From e7a6091e99eebd461125610a263fc3abb3f6133a Mon Sep 17 00:00:00 2001 From: Zhenhuan Chen Date: Sat, 14 Nov 2026 07:40:09 -0800 Subject: [PATCH 1/5] [None][feat] Qwen3.5 GB300 round 2: decode/prefill kernels, KVCM2 remote tier, disagg GEN admission Squash of PR #21997 (DCO cannot evaluate >250 commits); full history on dc3671/TensorRT-LLM branch user/zhenhuanc/q35-r2-upstream-history at bce171253c. Co-authored-by: Xiaoming Chen Signed-off-by: Zhenhuan Chen --- .github/CODEOWNERS | 3 + cpp/tensorrt_llm/batch_manager/CMakeLists.txt | 2 +- .../kv_cache_manager_v2/AGENTS.md | 49 +- .../kv_cache_manager_v2/CMakeLists.txt | 4 + .../kv_cache_manager_v2/common.h | 1 + .../kv_cache_manager_v2/config.cpp | 44 + .../kv_cache_manager_v2/config.h | 56 +- .../kv_cache_manager_v2/exceptions.h | 12 + .../kv_cache_manager_v2/kvCache.cpp | 92 +- .../kv_cache_manager_v2/kvCacheManager.cpp | 76 +- .../kv_cache_manager_v2/kvCacheManager.h | 15 +- .../kv_cache_manager_v2/page.cpp | 4 +- .../batch_manager/kv_cache_manager_v2/page.h | 6 +- .../kv_cache_manager_v2/storage/core.cpp | 95 +- .../kv_cache_manager_v2/storage/core.h | 88 +- .../kv_cache_manager_v2/storage/remoteMem.cpp | 712 +++++++ .../kv_cache_manager_v2/storage/remoteMem.h | 239 +++ .../storage/remoteTransfer.cpp | 52 + .../storage/remoteTransfer.h | 155 ++ .../storage/remoteTransferAgent.cpp | 325 ++++ .../storage/remoteTransferAgent.h | 91 + .../storage/remoteTransferFabric.cpp | 250 +++ .../storage/remoteTransferFabric.h | 93 + .../kv_cache_manager_v2/storageManager.cpp | 663 ++++++- .../kv_cache_manager_v2/storageManager.h | 94 +- .../kernels/customAllReduceKernels.cu | 116 +- .../kernels/customAllReduceKernels.h | 9 +- .../kernels/moe/trtllmGen/runner.cu | 25 + .../kernels/moe/trtllmGen/runner.h | 14 + .../batchedGemm/KernelRunner.cpp | 24 + .../batchedGemm/KernelRunner.h | 7 + ...ersistentContextStageKv256E4.cubin.tar.zst | 3 + ...128StaticContextStageKv256E4.cubin.tar.zst | 3 + ...ersistentContextStageKv256E4.cubin.tar.zst | 3 + ...128StaticContextStageKv256E4.cubin.tar.zst | 3 + .../fmha/cubin/kernelMetaInfoStageKv.h | 81 + .../trtllmGenKernels/fmha/fmhaKernels.h | 400 ++-- .../trtllmGenKernels/fmha/fmhaRunner.cpp | 11 + .../trtllmGenKernels/fmha/fmhaRunner.h | 4 + .../trtllmGenKernels/fmha/fmhaRunnerParams.h | 3 + .../batch_manager/kvCacheManagerV2.cpp | 65 + cpp/tensorrt_llm/thop/CMakeLists.txt | 4 + cpp/tensorrt_llm/thop/allreduceOp.cpp | 25 +- .../thop/moe/trtllmGen/fp4BlockScaleMoe.cpp | 176 +- .../thop/pagedFp8ContextFmhaOp.cpp | 189 ++ ...ent-guide-for-qwen3.8-qwen3.5-on-trtllm.md | 17 + docs/source/features/disagg-serving.md | 41 +- docs/source/features/kvcache.md | 141 ++ docs/source/features/subagent-routing.md | 18 +- .../disaggregated/slurm/benchmark/submit.py | 94 +- .../run_cache_transceiver_test.py | 3 + jenkins/L0_MergeRequest.groovy | 11 + scripts/generate_trtllm_serve_schemas.py | 175 +- .../export_kernel.cpp | 179 ++ .../gen_stage_kv_cubins.py | 809 ++++++++ .../spec_worker.py | 25 +- .../spec_worker.py | 6 +- .../spec_worker.py | 6 +- .../minimax_m3_nvfp4__sm_107__tp2/modeling.py | 6 +- .../attention/ATTENTION_DEVELOPER_GUIDE.md | 27 +- tensorrt_llm/_torch/attention/attention.py | 22 +- .../backends/fmha/flashinfer_trtllm_gen.py | 246 ++- .../attention/backends/fmha/gqa_decode.py | 333 +++- .../attention/backends/fmha/gqa_kv_replica.py | 77 +- .../backends/fmha/gqa_kv_replica_fused.py | 91 +- .../backends/fmha/gqa_segmented_decode.py | 40 +- .../_torch/attention/backends/fmha/manager.py | 7 +- .../_torch/attention/backends/interface.py | 5 + .../_torch/attention/backends/trtllm.py | 19 + .../_torch/attention/backends/utils.py | 4 + .../blackwell/gqa_kv_replica_partial_attn.py | 390 +++- .../kernels/fused_qk_norm_rope_gate.py | 593 +++++- .../_torch/attention/qk_norm_attention.py | 47 +- .../multi_stream/auto_multi_stream.py | 1 + .../_torch/custom_ops/cpp_custom_ops.py | 20 + .../_torch/custom_ops/cute_dsl_custom_ops.py | 41 +- .../custom_ops/trtllm_gen_custom_ops.py | 514 ++++- tensorrt_llm/_torch/cute_dsl_utils.py | 28 +- .../_torch/distributed/communicator.py | 63 +- .../_torch/distributed/ll_exchange.py | 878 +++++++-- .../distributed/mnnvl_fused_allreduce.py | 239 ++- tensorrt_llm/_torch/distributed/ops.py | 109 +- .../_torch/distributed/tp2_allreduce.py | 219 +++ .../kernels/blackwell/gate_add_rmsnorm_fp8.py | 299 +++ .../kernels/blackwell/gdn_verify_tcgen05.py | 1689 +++++++++++++++++ .../blackwell/gemm_twoshot_allreduce_norm.py | 887 +++++++++ .../kernels/blackwell/inproj_ba_splitk.py | 327 ++++ .../kernels/blackwell/low_m_mma_gemm.py | 12 +- .../kernels/blackwell/mnnvl_allreduce_norm.py | 82 +- .../blackwell/mnnvl_slot_allreduce_norm.py | 294 ++- .../kernels/blackwell/moe_bf16_engine.py | 1024 ++++++++++ .../_torch/kernels/blackwell/moe_lowm_fc2.py | 869 +++++++++ .../kernels/blackwell/moe_nvfp4_engine.py | 1689 +++++++++++++++++ .../blackwell/moe_persistent_engine.py | 337 ++++ .../kernels/blackwell/moe_route_front.py | 338 +++- .../kernels/blackwell/moe_router_gemm.py | 587 ++++++ .../_torch/kernels/blackwell/ptx_helpers.py | 196 ++ .../kernels/blackwell/resident_fp8_gemm.py | 720 +++++++ .../kernels/blackwell/tp2_allreduce_norm.py | 427 +++++ tensorrt_llm/_torch/kernels/nvfp4_quant.py | 56 +- tensorrt_llm/_torch/mmap_utils.py | 10 +- tensorrt_llm/_torch/models/modeling_qwen3.py | 9 + .../_torch/models/modeling_qwen3_5.py | 5 + .../_torch/models/modeling_qwen3_next.py | 973 +++++++++- .../_torch/models/modeling_speculative.py | 102 +- .../_torch/modules/expert_l2_prefetch.py | 328 ++++ .../_torch/modules/fla/flashinfer_chunk.py | 35 +- tensorrt_llm/_torch/modules/linear.py | 48 +- tensorrt_llm/_torch/modules/low_m_gemm.py | 60 +- tensorrt_llm/_torch/modules/low_m_mma_gemm.py | 193 +- .../modules/mamba/gdn_inforward_split.py | 374 ++++ .../_torch/modules/mamba/gdn_mixer.py | 395 +++- .../_torch/modules/mamba/gdn_prefill_conv.py | 688 +++++++ .../_torch/modules/mamba/layernorm_gated.py | 201 +- .../modules/mamba/recurrent_state_cache.py | 26 +- .../moe/fused_moe/MOE_DEVELOPER_GUIDE.md | 8 +- .../_torch/moe/fused_moe/configurable_moe.py | 5 + .../fused_moe/cutedsl/grouped_gemm/base.py | 8 + .../fused_moe/cutedsl/grouped_gemm/nvfp4.py | 6 + .../_torch/moe/fused_moe/impl_blocks.py | 6 + .../_torch/moe/fused_moe/impl_contract.py | 53 +- .../_torch/moe/fused_moe/interface.py | 4 + .../_torch/moe/fused_moe/moe_op_backend.py | 44 +- .../_torch/moe/fused_moe/moe_scheduler.py | 24 + .../_torch/moe/fused_moe/trtllm_gen/base.py | 11 +- .../moe/fused_moe/trtllm_gen/decode_front.py | 405 +++- .../moe/fused_moe/trtllm_gen/decode_moe.py | 474 +++++ .../fused_moe/trtllm_gen/decode_moe_bf16.py | 101 + .../fused_moe/trtllm_gen/fp4_block_scale.py | 49 +- .../moe/fused_moe/trtllm_gen/trtllm_bf16.py | 34 +- .../moe/fused_moe/trtllm_gen/trtllm_nvfp4.py | 3 + ...contiguous_grouped_gemm_finalize_fusion.py | 31 + tensorrt_llm/_torch/pyexecutor/_util.py | 152 +- .../_torch/pyexecutor/engine/model_setup.py | 5 +- .../engine/runners/decoder/graphs.py | 72 +- .../engine/runners/decoder/inputs.py | 33 +- .../engine/runners/decoder/metadata.py | 5 +- .../_torch/pyexecutor/kv_cache/host_memory.py | 327 ++++ .../kv_cache/kv_cache_manager_v2.py | 402 +++- .../pyexecutor/kv_cache/remote_donor.py | 995 ++++++++++ .../_torch/pyexecutor/model_engine.py | 5 + .../_torch/pyexecutor/model_loader.py | 27 +- .../_torch/pyexecutor/perf_metrics_manager.py | 36 +- tensorrt_llm/_torch/pyexecutor/py_executor.py | 116 +- .../_torch/pyexecutor/py_executor_creator.py | 111 +- .../_torch/pyexecutor/request_utils.py | 43 +- .../_torch/pyexecutor/runtime_hooks.py | 7 +- .../_torch/pyexecutor/scheduler/__init__.py | 2 + .../_torch/pyexecutor/scheduler/adp_router.py | 248 ++- .../_torch/pyexecutor/scheduler/scheduler.py | 12 + .../pyexecutor/scheduler/scheduler_v2.py | 171 +- .../pyexecutor/scheduler/waiting_queue.py | 239 ++- .../_torch/pyexecutor/steady_spec_prepare.py | 164 +- tensorrt_llm/_torch/speculative/eagle3.py | 225 ++- .../_torch/speculative/fused_accept.py | 326 +++- tensorrt_llm/_torch/speculative/interface.py | 180 +- tensorrt_llm/_torch/speculative/kept_rows.py | 150 ++ tensorrt_llm/_torch/utils.py | 1 + tensorrt_llm/functional.py | 9 + tensorrt_llm/llmapi/disagg_utils.py | 76 + tensorrt_llm/llmapi/llm_args.py | 303 +++ .../runtime/kv_cache_manager_v2/AGENTS.md | 2 +- .../runtime/kv_cache_manager_v2/__init__.py | 12 +- .../runtime/kv_cache_manager_v2/__init__.pyi | 32 + .../kv_cache_manager_v2/_introspection.py | 13 + .../schemas/trtllm-serve-config.schema.json | 475 +++++ .../trtllm-serve-disagg-config.schema.json | 647 ++++++- tensorrt_llm/serve/coordinator_server.py | 192 +- tensorrt_llm/serve/disagg_coordinator.py | 279 ++- tensorrt_llm/serve/openai_disagg_server.py | 36 +- tensorrt_llm/serve/openai_disagg_service.py | 86 +- tensorrt_llm/serve/openai_protocol.py | 17 +- tensorrt_llm/serve/openai_server.py | 7 + tensorrt_llm/serve/output_length_predictor.py | 1173 ++++++++++++ tensorrt_llm/serve/router.py | 576 +++++- tensorrt_llm/serve/seat_pool.py | 363 ++++ .../tools/layer_wise_benchmarks/runner.py | 24 +- .../usage/llm_args_golden_manifest.json | 69 + .../references/acceptance_length.yaml | 3 + .../defs/accuracy/test_llm_api_pytorch.py | 22 +- .../test_lists/qa/llm_function_core.txt | 1 + .../integration/test_lists/test-db/l0_a10.yml | 2 +- .../test_lists/test-db/l0_b200.yml | 10 +- .../test_lists/test-db/l0_b300.yml | 9 + .../integration/test_lists/test-db/l0_cpu.yml | 4 + .../test_lists/test-db/l0_dgx_b200.yml | 1 + .../test_lists/test-db/l0_dgx_b300.yml | 5 +- .../test_lists/test-db/l0_gb300.yml | 11 + .../test-db/l0_gb300_multi_gpus.yml | 8 +- .../test_lists/test-db/l0_h100.yml | 2 +- tests/integration/test_lists/waives.txt | 3 - .../kernels/test_fused_qk_norm_rope_gate.py | 215 +++ .../multi_gpu/test_gqa_kv_replica.py | 223 ++- .../attention/test_fmha_paged_context_fp8.py | 601 ++++++ .../_torch/attention/test_gqa_decode_fmha.py | 493 +++++ .../test_mixed_precision_backends.py | 1 + .../test_disagg_idle_cancellation.py | 2 + .../test_disagg_loop_transcript.py | 70 + .../test_mnnvl_fused_allreduce_dispatch.py | 48 +- .../test_torchdist_object_collectives.py | 25 + tests/unittest/_torch/helpers.py | 85 + .../kernels/parallel/test_nvfp4_quant.py | 29 +- .../test_quantization_for_cold_page.py | 1 + tests/unittest/_torch/misc/test_autotuner.py | 7 +- .../spec/test_modeling_v2_mtp_step.py | 4 +- .../test_modeling_v2_draft_loop.py | 34 + .../test_modeling_v2_m3_exact_numerics.py | 2 +- .../test_modeling_v2_m3_exact_numerics.py | 2 +- .../test_modeling_v2_m3_wide_draft_logits.py | 17 + .../test_modeling_v2_m3_exact_numerics.py | 2 +- .../test_modeling_v2_eagle3_worker_api.py | 3 +- .../models/test_qwen3_next_decode_gates.py | 540 ++++++ .../models/test_qwen3_next_eager_fusion.py | 380 +++- .../models/test_qwen3_next_moe_sm_reserve.py | 79 + .../test_qwen3next_moe_allreduce_guard.py | 1 + .../test_qwen3next_moe_input_dual_quant.py | 101 + .../modules/mamba/test_gdn_direct_launch.py | 136 ++ .../mamba/test_gdn_inforward_snapshot.py | 219 +++ .../modules/mamba/test_gdn_mixed_decode.py | 81 + .../modules/mamba/test_gdn_prefill_conv.py | 231 +++ .../modules/mamba/test_gdn_verify_tcgen05.py | 446 +++++ .../modules/mamba/test_layernorm_gated.py | 60 + .../_torch/modules/test_expert_l2_prefetch.py | 139 ++ .../modules/test_fused_add_rms_norm_quant.py | 78 +- .../modules/test_gate_add_rmsnorm_fp8.py | 79 + .../_torch/modules/test_inproj_ba_splitk.py | 105 + .../_torch/modules/test_low_m_gemm.py | 60 + .../_torch/modules/test_low_m_mma_gemm.py | 75 +- .../_torch/modules/test_resident_fp8_gemm.py | 278 +++ .../test_cutedsl_evict_first_tuning.py | 124 ++ .../moe/kernels/parallel/test_cute_dsl_moe.py | 75 + tests/unittest/_torch/moe/test_moe_backend.py | 190 ++ .../_torch/moe/test_moe_bf16_engine.py | 269 +++ .../_torch/moe/test_moe_decode_front.py | 367 +++- .../unittest/_torch/moe/test_moe_lowm_fc2.py | 393 ++++ .../_torch/moe/test_moe_nvfp4_engine.py | 1247 ++++++++++++ .../_torch/multi_gpu/test_ll_exchange.py | 590 +++++- .../test_mnnvl_fused_allreduce_norm.py | 485 ++++- .../engine/runners/decoder/test_graphs.py | 71 + .../kv_cache/test_kv_cache_budget_split.py | 389 ++++ .../test_kv_cache_compression_manager.py | 4 +- .../kv_cache/test_kv_cache_estimation.py | 57 + ...st_kv_cache_manager_v2_helix_superblock.py | 35 + .../test_kv_cache_v2_capacity_only.py | 2 + .../kv_cache/test_kv_cache_v2_scheduler.py | 452 ++++- .../kv_cache/test_kvcm2_integration.py | 352 +++- .../pyexecutor/test_adp_router_home_wait.py | 485 +++++ .../test_disagg_receive_ordering.py | 1 + .../test_executor_resource_rebind.py | 6 +- .../pyexecutor/test_fetch_request_hint.py | 2 + .../_torch/pyexecutor/test_gen_preemption.py | 3 + .../pyexecutor/test_hang_detector_kill.py | 22 + .../pyexecutor/test_multimodal_scheduler.py | 17 + .../pyexecutor/test_perf_metrics_manager.py | 44 + .../_torch/pyexecutor/test_py_executor.py | 28 + ...y_executor_creator_mla_cache_reuse_sync.py | 3 + .../pyexecutor/test_remote_tail_adp_phase.py | 2 + .../_torch/pyexecutor/test_request_utils.py | 106 +- .../pyexecutor/test_steady_spec_prepare.py | 143 +- .../_torch/pyexecutor/test_waiting_queue.py | 309 ++- .../test_draft_sampler_overrides.py | 165 ++ .../test_capture_sampling_params.py | 2 +- .../_torch/speculative/test_draft_row_pick.py | 19 +- .../_torch/speculative/test_eagle3.py | 38 + .../_torch/speculative/test_fused_accept.py | 103 + .../references/trtllm_serve_routes.yaml | 2 + .../test_cache_transceiver_single_process.py | 3 + .../disaggregated/test_coordinator_worker.py | 22 + .../disaggregated/test_kv_transfer.py | 4 +- .../test_openai_disagg_server.py | 33 + .../test_openai_disagg_service.py | 45 + .../disaggregated/test_openai_server_info.py | 28 +- .../test_output_length_predictor.py | 862 +++++++++ .../test_output_length_service.py | 538 ++++++ tests/unittest/disaggregated/test_peer.py | 60 + .../unittest/disaggregated/test_seat_pool.py | 1053 ++++++++++ .../remote_donor_cli.py | 111 ++ .../remote_test_utils.py | 85 + .../test_kv_cache_manager_v2.py | 8 + .../test_remote_capacity.py | 1043 ++++++++++ .../test_remote_donor_memory.py | 136 ++ .../test_remote_fabric_available.py | 49 + .../test_remote_level.py | 1432 ++++++++++++++ .../test_remote_ucx_devices.py | 172 ++ tests/unittest/llmapi/test_llm_args.py | 276 +++ .../llmapi/test_llm_multi_gpu_pytorch.py | 86 + tests/unittest/llmapi/test_llm_pytorch.py | 65 + .../test_trtllm_serve_config_schemas.py | 338 ++++ tests/unittest/scripts/test_perf_submit.py | 25 + .../test_layer_wise_benchmarks_runner_args.py | 39 + .../utils/post_transform_qualification.py | 2 + 291 files changed, 49262 insertions(+), 1809 deletions(-) create mode 100644 cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteMem.cpp create mode 100644 cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteMem.h create mode 100644 cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransfer.cpp create mode 100644 cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransfer.h create mode 100644 cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransferAgent.cpp create mode 100644 cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransferAgent.h create mode 100644 cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransferFabric.cpp create mode 100644 cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransferFabric.h create mode 100644 cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/FmhaSm100aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128PersistentContextStageKv256E4.cubin.tar.zst create mode 100644 cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/FmhaSm100aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128StaticContextStageKv256E4.cubin.tar.zst create mode 100644 cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/FmhaSm103aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128PersistentContextStageKv256E4.cubin.tar.zst create mode 100644 cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/FmhaSm103aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128StaticContextStageKv256E4.cubin.tar.zst create mode 100644 cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/kernelMetaInfoStageKv.h create mode 100644 cpp/tensorrt_llm/thop/pagedFp8ContextFmhaOp.cpp create mode 100644 scripts/trtllm_gen_fmha_stage_kv/export_kernel.cpp create mode 100644 scripts/trtllm_gen_fmha_stage_kv/gen_stage_kv_cubins.py create mode 100644 tensorrt_llm/_torch/distributed/tp2_allreduce.py create mode 100644 tensorrt_llm/_torch/kernels/blackwell/gate_add_rmsnorm_fp8.py create mode 100644 tensorrt_llm/_torch/kernels/blackwell/gdn_verify_tcgen05.py create mode 100644 tensorrt_llm/_torch/kernels/blackwell/gemm_twoshot_allreduce_norm.py create mode 100644 tensorrt_llm/_torch/kernels/blackwell/inproj_ba_splitk.py create mode 100644 tensorrt_llm/_torch/kernels/blackwell/moe_bf16_engine.py create mode 100644 tensorrt_llm/_torch/kernels/blackwell/moe_lowm_fc2.py create mode 100644 tensorrt_llm/_torch/kernels/blackwell/moe_nvfp4_engine.py create mode 100644 tensorrt_llm/_torch/kernels/blackwell/moe_persistent_engine.py create mode 100644 tensorrt_llm/_torch/kernels/blackwell/moe_router_gemm.py create mode 100644 tensorrt_llm/_torch/kernels/blackwell/ptx_helpers.py create mode 100644 tensorrt_llm/_torch/kernels/blackwell/resident_fp8_gemm.py create mode 100644 tensorrt_llm/_torch/kernels/blackwell/tp2_allreduce_norm.py create mode 100644 tensorrt_llm/_torch/modules/expert_l2_prefetch.py create mode 100644 tensorrt_llm/_torch/modules/mamba/gdn_inforward_split.py create mode 100644 tensorrt_llm/_torch/modules/mamba/gdn_prefill_conv.py create mode 100644 tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/decode_moe.py create mode 100644 tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/decode_moe_bf16.py create mode 100644 tensorrt_llm/_torch/pyexecutor/kv_cache/host_memory.py create mode 100644 tensorrt_llm/_torch/pyexecutor/kv_cache/remote_donor.py create mode 100644 tensorrt_llm/_torch/speculative/kept_rows.py create mode 100644 tensorrt_llm/serve/output_length_predictor.py create mode 100644 tensorrt_llm/serve/seat_pool.py create mode 100644 tests/unittest/_torch/attention/test_fmha_paged_context_fp8.py create mode 100644 tests/unittest/_torch/models/test_qwen3_next_decode_gates.py create mode 100644 tests/unittest/_torch/models/test_qwen3_next_moe_sm_reserve.py create mode 100644 tests/unittest/_torch/models/test_qwen3next_moe_input_dual_quant.py create mode 100644 tests/unittest/_torch/modules/mamba/test_gdn_prefill_conv.py create mode 100644 tests/unittest/_torch/modules/mamba/test_gdn_verify_tcgen05.py create mode 100644 tests/unittest/_torch/modules/test_expert_l2_prefetch.py create mode 100644 tests/unittest/_torch/modules/test_gate_add_rmsnorm_fp8.py create mode 100644 tests/unittest/_torch/modules/test_inproj_ba_splitk.py create mode 100644 tests/unittest/_torch/modules/test_resident_fp8_gemm.py create mode 100644 tests/unittest/_torch/moe/fused_moe/test_cutedsl_evict_first_tuning.py create mode 100644 tests/unittest/_torch/moe/test_moe_bf16_engine.py create mode 100644 tests/unittest/_torch/moe/test_moe_lowm_fc2.py create mode 100644 tests/unittest/_torch/moe/test_moe_nvfp4_engine.py create mode 100644 tests/unittest/_torch/pyexecutor/test_adp_router_home_wait.py create mode 100644 tests/unittest/_torch/speculative/hw_agnostic/test_draft_sampler_overrides.py create mode 100644 tests/unittest/disaggregated/test_output_length_predictor.py create mode 100644 tests/unittest/disaggregated/test_output_length_service.py create mode 100644 tests/unittest/disaggregated/test_seat_pool.py create mode 100644 tests/unittest/kv_cache_manager_v2_tests/remote_donor_cli.py create mode 100644 tests/unittest/kv_cache_manager_v2_tests/remote_test_utils.py create mode 100644 tests/unittest/kv_cache_manager_v2_tests/test_remote_capacity.py create mode 100644 tests/unittest/kv_cache_manager_v2_tests/test_remote_donor_memory.py create mode 100644 tests/unittest/kv_cache_manager_v2_tests/test_remote_fabric_available.py create mode 100644 tests/unittest/kv_cache_manager_v2_tests/test_remote_level.py create mode 100644 tests/unittest/kv_cache_manager_v2_tests/test_remote_ucx_devices.py diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 26995cec1b90..ce48caa82562 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -324,6 +324,7 @@ /tensorrt_llm/_torch/attention/backends/sparse/*/cache_manager.py @NVIDIA/trt-llm-kv-cache-manager-devs /tensorrt_llm/_torch/modules/fla @NVIDIA/trt-llm-torch-attention-devs /tests/microbenchmarks/cute_dsl_kernels/paged_mqa_logits @NVIDIA/trt-llm-torch-attention-devs +/scripts/trtllm_gen_fmha_stage_kv @NVIDIA/trt-llm-torch-attention-devs /tests/unittest/_torch/attention @NVIDIA/trt-llm-torch-attention-devs # The kernel-ownership question this test was waiting on is settled: the top-k # kernel has two production consumers (Attention and KV-cache compression), so it @@ -355,6 +356,8 @@ /cpp/tensorrt_llm/nanobind/runtime/moe* @NVIDIA/trt-llm-moe-devs /cpp/tensorrt_llm/runtime/moeLoadBalancer @NVIDIA/trt-llm-moe-devs /tensorrt_llm/_torch/moe @NVIDIA/trt-llm-moe-devs +/tensorrt_llm/_torch/kernels/blackwell/moe_* @NVIDIA/trt-llm-kernels-devs @NVIDIA/trt-llm-moe-devs +/tensorrt_llm/_torch/modules/expert_l2_prefetch.py @NVIDIA/trt-llm-models-devs @NVIDIA/trt-llm-moe-devs /tensorrt_llm/deep_ep @NVIDIA/trt-llm-moe-devs /tests/microbenchmarks/bench_moe @NVIDIA/trt-llm-moe-devs /tests/microbenchmarks/bench_moe_comm.py @NVIDIA/trt-llm-moe-devs diff --git a/cpp/tensorrt_llm/batch_manager/CMakeLists.txt b/cpp/tensorrt_llm/batch_manager/CMakeLists.txt index 3bd3a0978950..e529ad78f5df 100644 --- a/cpp/tensorrt_llm/batch_manager/CMakeLists.txt +++ b/cpp/tensorrt_llm/batch_manager/CMakeLists.txt @@ -88,7 +88,7 @@ target_link_libraries( tllm_kv_cache PUBLIC tllm::kv_cache_host_memory tllm::common_cuda tllm::executor_types CUDA::cuda_driver - PRIVATE tllm::common_environment) + PRIVATE tllm::common_environment tllm::executor_transfer_agent) add_library( tllm_kv_cache_legacy STATIC diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/AGENTS.md b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/AGENTS.md index 0dec43d2eed4..6a2590cce637 100644 --- a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/AGENTS.md +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/AGENTS.md @@ -6,7 +6,7 @@ SPDX-License-Identifier: Apache-2.0 # KVCacheManagerV2 C++ Guide This directory contains the C++ implementation of KVCacheManagerV2: allocation, -prefix reuse, eviction, GPU/host/disk movement, page locking, and KV-cache event +prefix reuse, eviction, GPU/host/disk/remote movement, page locking, and KV-cache event generation. Python accesses it through the nanobind bindings in `cpp/tensorrt_llm/nanobind/batch_manager/kvCacheManagerV2.cpp`. @@ -64,7 +64,9 @@ them before changing `batch.*`, `sparseCache.*` or the index conversion. -- act on which class they caught; throw those directly: `OutOfMemoryError` and its `Host`/`Disk`/`Cu` forms, `LogicError`, `AssertionError`, `CuError`, `CorruptedError`, `ResourceBusyError`, - `OutOfPagesError`. + `OutOfPagesError`, and `RemoteMemError` (a failed remote cache level: the + V2 scheduler and the prefetch path catch it by class to re-match, recompute + or fail only the affected requests). Validation at the binding boundary that throws `std::invalid_argument` or `std::out_of_range` is legacy and should migrate to `TLLM_CHECK*` as it is touched, so that KVCM2 ends up on the same footing as the rest of the repo. @@ -148,7 +150,7 @@ sizes match, which is what lets a sparse pool be backed by host memory while a dense pool of the same group and level is device memory; the group reports GPU_MEM either way. Compatible sparse buffers still coalesce. Sparse buffers place no requirement on the cold tiers. -`StorageManager` coordinates GPU, host, and disk cache levels. It allocates +`StorageManager` coordinates GPU, host, disk, and remote cache levels. It allocates slots, schedules pages for eviction, migrates pages between levels, and resizes pools. `CopyEngine` performs the actual batched transfers; C++ code calls it directly and must not round-trip through Python bindings. @@ -399,6 +401,33 @@ physically duplicate the whole prompt; ownership splits at the prompt tail: Keep allocation granularity, stream ordering, and source/destination lifetime valid through asynchronous copies. +### Remote cache levels + +A remote level (`RemoteCacheTierConfig`, `CacheTier::REMOTE`) keeps its slots in +host memory other processes donate (`tensorrt_llm/_torch/pyexecutor/kv_cache/remote_donor.py`). + +- `storage/remoteMem.*`: `RemoteMemClient`, one per rendezvous directory and + `StorageManager`: the donor table, the chunks claimed with O_EXCL claim files, + and the transfer backend. It opens and checks the directory once + (`openRendezvousDirectory`) and reads every donor file through that descriptor. + `RemoteRange` maps a pool's slots onto claimed chunks. +- `storage/remoteTransfer.h`: the backend interface; `remoteTransferAgent.*` + (NIXL, one-sided RDMA concluded on the host) and `remoteTransferFabric.*` + (fabric memory mapped into this process, copied on the caller's stream). +- Pages move through the pinned page staging ring. A host-concluded transfer + that misses its deadline fails the level, and its staging lease stays out of + use (`mUnquiescedRemoteTransfers`) until `quiesced()`; `destroy()` gives it one + more timeout, then leaks the lease, the claims and the backend + (`RemoteMemClient::abandon`). +- A failed client fails its levels for good: they take no pages and give none + back. `dropPagesOfFailedRemoteLevels()` drops their evictable pages, + `KvCacheManager::_unlinkPagesOfFailedRemoteLevels()` unlinks the held ones from + the radix tree (from `createKvCache` with tokens, `prefetchReuse` and the + probes), and `prepareFreeSlots()` retries an eviction past a level whose WRITE + failed. Callers tell this failure apart by `RemoteMemError`. +- A remote level cannot sit next to a file-backed disk level (rejected at + construction). + ## Testing a change here The Python suite (`tests/unittest/kv_cache_manager_v2_tests/`) does **not** build this @@ -442,6 +471,15 @@ from it: the radix tree, the storage manager, and the living-`KvCache` set. Mutating APIs take it exclusively; read-only queries take it shared, so several `probeReuse()` lookups run concurrently while a writer is excluded. +Remote levels add two exceptions. Each `RemoteMemClient` has its own `mMutex` +for its donor table, claims and backend; it is taken inside the manager lock +(the storage manager calls the client), never the other way round, and the +client never calls back into the manager. Its failure flag `mFailed` is an +atomic, read without any lock by `StorageManager::anyRemoteLevelFailed()` / +`numFailedRemoteClients()`: the `any_remote_level_failed` binding and the +probes' check for newly failed levels, which then take the lock exclusively to +unlink their pages before matching. + **What the lock does and does not cover.** It protects state *shared between* `KvCache`s, not the fields of an individual one, and it is a guarantee about the bound (Python-visible) API only -- see "Where the guarantee applies" below. @@ -496,7 +534,10 @@ Two exposed accessors look like they might leak shared state and do not: `get_life_cycle_pool_group_indices`, `get_page_stride`, `get_page_index_scale`, `get_page_index_converter`, `get_mem_pool_base_address`, `supports_index_mode`, `init_config`, and the - config flags. `get_page_index_upper_bound` resembles that group but reads a + config flags. `any_remote_level_failed` is lock-free too but reads runtime + state: each remote client's atomic `failed()` flag, walking `mRemoteClients`, + which `destroy()` clears; it is safe while no `shutdown()` runs concurrently. + `get_page_index_upper_bound` resembles that group but reads a pool's current `numSlots`, which `_adjustLevel()` changes, so it takes the shared lock. Anything added here that reads resize-mutable state must too. - `get_base_page_indices` returns a zero-copy numpy view, but into diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/CMakeLists.txt b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/CMakeLists.txt index 547b6e52693b..97572ab6efac 100644 --- a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/CMakeLists.txt +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/CMakeLists.txt @@ -54,6 +54,10 @@ set(KV_CACHE_MANAGER_V2_SRCS kv_cache_manager_v2/utils/optionalGilRelease.cpp kv_cache_manager_v2/storage/config.cpp kv_cache_manager_v2/storage/core.cpp + kv_cache_manager_v2/storage/remoteMem.cpp + kv_cache_manager_v2/storage/remoteTransfer.cpp + kv_cache_manager_v2/storage/remoteTransferAgent.cpp + kv_cache_manager_v2/storage/remoteTransferFabric.cpp kv_cache_manager_v2/evictionController.cpp kv_cache_manager_v2/stagingBuffer.cpp kv_cache_manager_v2/copyEngine.cpp diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/common.h b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/common.h index 3471804fcf47..57f9db108f98 100644 --- a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/common.h +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/common.h @@ -56,6 +56,7 @@ enum class CacheTier : int GPU_MEM = 0, HOST_MEM = 1, DISK = 2, + REMOTE = 3, }; // PageIndexMode — how converted page indices relate to layers within a layer group. diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/config.cpp b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/config.cpp index bafe2c1f7200..48ee59c8e493 100644 --- a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/config.cpp +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/config.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -153,6 +154,24 @@ void DiskCacheTierConfig::validate() const } } +void RemoteCacheTierConfig::validate() const +{ + TLLM_CHECK_WITH_INFO(quota > 0, "RemoteCacheTierConfig: quota must be > 0"); + TLLM_CHECK_WITH_INFO(std::filesystem::is_directory(path), + "RemoteCacheTierConfig: rendezvous directory '%s' is not a directory", path.c_str()); + TLLM_CHECK_WITH_INFO(0 < waitTimeoutMs && waitTimeoutMs <= kMaxRemoteTimeoutMs, + "RemoteCacheTierConfig: wait_timeout_ms (donor_wait_timeout_s) must be in (0, %lld], got %lld", + static_cast(kMaxRemoteTimeoutMs), static_cast(waitTimeoutMs)); + // The fabric transport's copies are stream-ordered and never timed. + TLLM_CHECK_WITH_INFO(transfer.transport != RemoteTransport::kNixl + || (0 < transfer.timeoutMs && transfer.timeoutMs <= kMaxRemoteTimeoutMs), + "RemoteCacheTierConfig: the NIXL transfer timeout_ms (transfer_timeout_s) must be in (0, %lld], got %lld", + static_cast(kMaxRemoteTimeoutMs), static_cast(transfer.timeoutMs)); + TLLM_CHECK_WITH_INFO(std::all_of(poolRatio.begin(), poolRatio.end(), + [](double weight) { return std::isfinite(weight) && weight > 0.0; }), + "RemoteCacheTierConfig: pool ratio entries must be positive and finite"); +} + namespace { @@ -306,6 +325,31 @@ void KVCacheManagerConfig::validate() const std::visit([](auto const& cfg) { cfg.validate(); }, tier); } + // Remote levels move pages through the page staging buffer, which cannot reach a file-backed disk level, and share + // one transport, so that their copies are either all stream-ordered or all host-synchronous. + std::optional remoteTransport; + bool hasFileDisk = false; + for (auto const& tier : cacheTiers) + { + if (std::holds_alternative(tier)) + { + hasFileDisk = true; + } + else if (auto const* remote = std::get_if(&tier)) + { + if (remoteTransport.value_or(remote->transfer.transport) != remote->transfer.transport) + { + throw AssertionError("KVCacheManagerConfig: remote cache levels must share one transport"); + } + remoteTransport = remote->transfer.transport; + } + } + if (remoteTransport.has_value() && hasFileDisk) + { + throw AssertionError( + "KVCacheManagerConfig: a remote cache level cannot be combined with a file-backed disk level"); + } + // Zero asks for host-backed pools with no room for a single slot. It is not a way to turn // them off: whether a pool is host-backed is a property of the buffer, not of this quota. if (hostSparsePoolQuota.has_value() && *hostSparsePoolQuota == 0) diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/config.h b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/config.h index 43096dee388e..d99d53a30188 100644 --- a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/config.h +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/config.h @@ -22,6 +22,7 @@ #include "tensorrt_llm/common/assert.h" #include #include +#include #include #include #include @@ -108,8 +109,59 @@ struct DiskCacheTierConfig void validate() const; }; -// Variant holding any tier config. -using CacheTierConfig = std::variant; +//! How a remote tier moves pages (storage/remoteTransfer.h). Donors must use the same one. +enum class RemoteTransport : int +{ + //! A NIXL transfer agent (executor::kv_cache::BaseTransferAgent): one-sided RDMA, concluded on the host. + kNixl = 0, + //! NVLink fabric memory mapped into this process, copied on the caller's stream. + kFabric = 1, +}; + +//! Upper bound of the remote tier's timeouts: 1e6 s, as RemoteCacheConfig allows. +inline constexpr int64_t kMaxRemoteTimeoutMs = 1'000'000'000; + +//! How a remote tier's pages move, apart from what memory it declares (RemoteCacheTierConfig). +struct RemoteTransferConfig +{ + RemoteTransport transport = RemoteTransport::kNixl; + //! NIXL: how long one batch of transfers may take before the level fails (transfer_timeout_s), in (0, + //! kMaxRemoteTimeoutMs]. Unused by FABRIC, whose copies run on the stream. + int64_t timeoutMs = 30'000; + //! NIXL only: the agent's backend parameters, passed as they are (e.g. UCX's {"device_list": "mlx5_0, mlx5_1"}); + //! empty uses the process's UCX environment. + std::map backendParams; + + bool operator==(RemoteTransferConfig const&) const = default; +}; + +//! Slots in host memory other processes donate (storage/remoteMem.h). Shares nothing with the disk tier. +struct RemoteCacheTierConfig +{ + size_t quota = 0; // bytes + std::string path; // the rendezvous directory the donors publish into + //! How long creating the level waits for donor capacity (RemoteCacheConfig.donor_wait_timeout_s), in (0, + //! kMaxRemoteTimeoutMs]. + int64_t waitTimeoutMs = 900'000; + //! Donors the job starts; once all have reported, a claim stops waiting. 0 if unknown. + uint32_t expectedDonors = 0; + //! Positive weights, one per layer group, that split the quota across layer groups instead of the hot level's + //! ratio; normalized by the storage manager. Empty follows the hot level. + std::vector poolRatio; + //! How the pages move. + RemoteTransferConfig transfer; + + [[nodiscard]] CacheTier tier() const noexcept + { + return CacheTier::REMOTE; + } + + void validate() const; +}; + +// Variant holding any tier config; an alternative's index is its CacheTier. +using CacheTierConfig + = std::variant; // Helper to extract tier from a variant. inline CacheTier cacheTierOf(CacheTierConfig const& cfg) diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/exceptions.h b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/exceptions.h index 3578ccb6fb42..cf18f55fa8e1 100644 --- a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/exceptions.h +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/exceptions.h @@ -223,6 +223,18 @@ class OutOfPagesError : public std::runtime_error } }; +// A remote cache level could not reach its donors, or a transfer to or from one failed or timed out +// (storage/remoteMem.h). Not an out-of-pages error: the level's contents can no longer be trusted, which no retry +// fixes. +class RemoteMemError : public std::runtime_error +{ +public: + explicit RemoteMemError(std::string const& msg) + : std::runtime_error(msg) + { + } +}; + // --------------------------------------------------------------------------- // Helper: unwrap a weak_ptr, throw LogicError on dangling reference. // Mirrors Python's unwrap_rawref(_utils.py:163). diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/kvCache.cpp b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/kvCache.cpp index 2ae8500a23b9..3e7a3d750cd3 100644 --- a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/kvCache.cpp +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/kvCache.cpp @@ -723,21 +723,31 @@ bool KvCache::resume(std::optional stream, std::optional(cudaStream()), std::move(scratchReadyEvents)); } - try - { - activate(); - } - catch (OutOfPagesError const&) + auto const releaseDeferredSlots = [&]() { for (LifeCycleId lc{0}; lc < numLc; ++lc) { if (deferredSlots[lc].has_value()) storageMgr.releaseSlot(lc, kHotLevel, std::move(*deferredSlots[lc])); } + }; + try + { + activate(); + } + catch (OutOfPagesError const&) + { + releaseDeferredSlots(); // Scratch slots stay in mScratchSlots — they'll be freed by close() inside // a recordEventScope, matching Python behavior. return false; } + catch (...) + { + // E.g. a RemoteMemError reading pages back: the same rollback, then the error. + releaseDeferredSlots(); + throw; + } // Private recovery pages have no reusable source. Their contents are // initialized by the caller before inference, after all allocations succeed. @@ -1356,10 +1366,33 @@ CommittedPage* KvCache::_copyPageToTreeBlock( { continue; } + catch (RemoteMemError const&) + { + continue; // a failed remote level holds no snapshot either + } CUstream stream = cudaStream(); newSlot.readyEvent.waitInStream(reinterpret_cast(stream)); - storageMgr.copySlotData(lcIdx, lvl, srcPage->cacheLevel, newSlot.slotId(), srcPage->slotId(), stream); + auto const releaseNewSlot = [&]() + { + // Whatever the copy enqueued finishes before the slot is reused. + newSlot.readyEvent = CachedCudaEvent(reinterpret_cast(stream)); + storageMgr.releaseSlot(lcIdx, lvl, std::move(newSlot)); + }; + try + { + storageMgr.copySlotData(lcIdx, lvl, srcPage->cacheLevel, newSlot.slotId(), srcPage->slotId(), stream); + } + catch (RemoteMemError const&) + { + releaseNewSlot(); + continue; // the snapshot is optional: a failed remote level holds none, as for the allocation above + } + catch (...) + { + releaseNewSlot(); + throw; + } newSlot.readyEvent = CachedCudaEvent(reinterpret_cast(stream)); auto committed = makeShared( @@ -1744,6 +1777,13 @@ bool KvCache::resize(std::optional capacity, std::optional historyLeng _lockHeldBlocks(backupHolders); return false; } + catch (...) + { + // E.g. a RemoteMemError evicting to a remote level: the same rollback, then the error. + _recoverExcessScratchSlots(excessScratchSlots); + _lockHeldBlocks(backupHolders); + throw; + } } else { @@ -2363,6 +2403,46 @@ void KvCache::_commitBlock(int ord, bool isLast, bool commitSsm, bool moveSsm) existingPage = nullptr; } bool isLocked = std::holds_alternative(bp); + if (existingPage != nullptr && existingPage->cacheLevel != kHotLevel + && mManager->storage().hasRemoteLevel()) + { + // The tree's copy is cold and ours, with the same tokens, is on the GPU: ours supersedes it. Moving the + // copy back would read it and take a GPU slot whose eviction can reach the remote level, synchronous + // transfers either way. A request still holding the cold copy keeps it until it lets go. + if (auto* lock = std::get_if(&bp)) + { + auto up = dynamicPointerCast(lock->page()); + if (up && up->cacheLevel == kHotLevel) + { + CacheLevel const coldLevel = existingPage->cacheLevel; + auto* superseded = newBlock->unlinkPage(lc, existingPage); + existingPage = nullptr; + // Kept until ours took over its retention, as reusing it would have kept it. + SharedPtr const supersededPage + = superseded != nullptr ? superseded->sharedFromThis() : SharedPtr{}; + if (superseded != nullptr && superseded->scheduledForEviction()) + { + superseded->manager->excludeFromEviction(*superseded); + } + bp = std::monostate{}; + auto committed + = up->convertToCommitted(newBlock, finishEvent(), numTokens, supersededPage.get()); + if (newBlock->eventSink) + { + newBlock->eventSink->addCacheLevelUpdated(newBlock->key, coldLevel, kHotLevel, lc); + } + bp = BlockPage{committed->lock(*this, kDefaultBeamIndex, static_cast(ord), lc)}; + continue; + } + } + else if (_getStaleRange(mHistoryLength, mManager->lifeCycles()[lc]).contains(BlockOrdinal{ord})) + { + // A stale block's page is held only to be committed, and the tree has a copy: ours is dropped. + // Locking that copy would read it back, a transfer the stale clear below then throws away. + bp = std::monostate{}; + continue; + } + } if (existingPage == nullptr) { // Existing page gone — put our uncommitted page into the tree block. diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/kvCacheManager.cpp b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/kvCacheManager.cpp index ef8f3f6d18bd..6b5098102729 100644 --- a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/kvCacheManager.cpp +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/kvCacheManager.cpp @@ -539,6 +539,7 @@ std::shared_ptr KvCacheManager::createKvCache(ReuseScope reuseScope, To std::optional reuseMatch; if (inputTokens.size() != 0) { + _unlinkPagesOfFailedRemoteLevels(); reuseMatch = matchReuse(reuseScope, inputTokens, textOnly.value_or(this->textOnly())); } @@ -546,6 +547,73 @@ std::shared_ptr KvCacheManager::createKvCache(ReuseScope reuseScope, To std::move(priorityCb), expectedPromptLength, textOnly, enableRequestStats, std::move(retentionConfig)); } +void KvCacheManager::_unlinkPagesIfARemoteLevelFailed() +{ + if (mStorage->numFailedRemoteClients() <= mNumFailedRemoteClientsUnlinked.load(std::memory_order_acquire)) + { + return; + } + auto const apiLock = lockExclusive(); + _unlinkPagesOfFailedRemoteLevels(); +} + +void KvCacheManager::_unlinkPagesOfFailedRemoteLevels() +{ + // Counted before the levels are taken: a client failing in between is unlinked by the next call. + auto const numFailed = mStorage->numFailedRemoteClients(); + auto const levels = mStorage->takeNewlyFailedRemoteLevels(); + mNumFailedRemoteClientsUnlinked.store(numFailed, std::memory_order_release); + if (levels.empty()) + { + return; + } + // The evictable pages there are dropped already; the rest are held by requests. Collect first: unlinking can + // detach subtrees. + std::vector, LifeCycleId>> onFailedLevel; + std::vector> pending; + for (auto const& [key, root] : mRadixTree->roots()) + { + for (auto const& [childKey, child] : root->next) + { + pending.push_back(child); + } + } + auto const onFailed = [&levels](CommittedPage const* page) + { return page != nullptr && std::find(levels.begin(), levels.end(), page->cacheLevel) != levels.end(); }; + while (!pending.empty()) + { + auto block = std::move(pending.back()); + pending.pop_back(); + for (auto const& [childKey, child] : block->next) + { + pending.push_back(child); + } + for (LifeCycleId lc{0}; lc < block->numLifeCycles(); ++lc) + { + if (onFailed(block->getPage(lc))) + { + onFailedLevel.emplace_back(block, lc); + } + } + } + // Detached blocks stay alive until every unlink is done. + std::vector> detached; + for (auto const& [block, lc] : onFailedLevel) + { + auto* const page = block->getPage(lc); + if (!onFailed(page)) + { + continue; + } + block->unlinkPage(lc, page); + auto cleared = Block::clearStaleBlocksAfterPageUnlink(*block, lc, mStorage->lifeCycles().getLifeCycle(lc)); + detached.insert( + detached.end(), std::make_move_iterator(cleared.begin()), std::make_move_iterator(cleared.end())); + } + TLLM_LOG_WARNING( + "KVCM2 remote level(s) failed: %zu page(s) requests hold there left the reuse tree", onFailedLevel.size()); +} + void KvCacheManager::refreshRetention() { KVCM2_API_GUARD(); @@ -559,6 +627,7 @@ bool KvCacheManager::prefetchReuse(ReuseScope reuseScope, TokenSpan inputTokens, auto const apiLock = lockExclusive(); if (target < kHotLevel || target >= mStorage->numCacheLevels()) throw std::out_of_range("Prefetch target is outside the configured cache tiers"); + _unlinkPagesOfFailedRemoteLevels(); auto reuseMatch = matchReuse(reuseScope, inputTokens, knownNoDigest); auto cache = std::make_shared(*this, std::move(reuseScope), std::move(reuseMatch), std::nullopt, KvCache::PriorityCb{}, std::nullopt, knownNoDigest, false, std::nullopt, /*isPrefetch=*/true); @@ -573,17 +642,20 @@ BlockRadixTree::ReuseMatch KvCacheManager::matchReuse( return mRadixTree->match(reuseScope, inputTokens, knownNoDigest, enablePartialMatch(), mConfig.reuseMatchBackoff); } -int KvCacheManager::probeReuse(ReuseScope reuseScope, TokenSpan inputTokens, bool knownNoDigest) const +int KvCacheManager::probeReuse(ReuseScope reuseScope, TokenSpan inputTokens, bool knownNoDigest) { KVCM2_REJECT_IF_POISONED(); + _unlinkPagesIfARemoteLevelFailed(); // Shared: the traversal is read-only and the matched Block* never escape this call. auto const apiLock = lockShared(); return matchReuse(reuseScope, inputTokens, knownNoDigest).numTokens; } std::optional KvCacheManager::probeFirstNewBlockKey( - ReuseScope reuseScope, TokenSpan inputTokens, bool knownNoDigest) const + ReuseScope reuseScope, TokenSpan inputTokens, bool knownNoDigest) { + KVCM2_REJECT_IF_POISONED(); + _unlinkPagesIfARemoteLevelFailed(); // The matched Block* remain protected until the key has been copied out. // Call matchReuse directly: probeReuse would nest shared-lock acquisitions. auto const apiLock = lockShared(); diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/kvCacheManager.h b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/kvCacheManager.h index 4eda55861d21..e4c5b537a6a4 100644 --- a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/kvCacheManager.h +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/kvCacheManager.h @@ -201,12 +201,14 @@ class KvCacheManager : public std::enable_shared_from_this // Defaults false (safe: the scanning path is taken). BlockRadixTree::ReuseMatch matchReuse( ReuseScope const& reuseScope, TokenSpan inputTokens, bool knownNoDigest = false) const; - int probeReuse(ReuseScope reuseScope = {}, TokenSpan inputTokens = {}, bool knownNoDigest = false) const; + // Matches under the shared lock. Once a remote level has failed, the first probe after it takes the exclusive lock + // to unlink that level's pages, as createKvCache does, so that no probe counts them. + int probeReuse(ReuseScope reuseScope = {}, TokenSpan inputTokens = {}, bool knownNoDigest = false); // Read-only, advisory key of the first full block past the reusable prefix. // Uses the same fresh, window-aware match as probeReuse without acquiring pages. std::optional probeFirstNewBlockKey( - ReuseScope reuseScope = {}, TokenSpan inputTokens = {}, bool knownNoDigest = false) const; + ReuseScope reuseScope = {}, TokenSpan inputTokens = {}, bool knownNoDigest = false); // ---- Memory pool queries ----------------------------------------------- @@ -567,6 +569,13 @@ class KvCacheManager : public std::enable_shared_from_this friend class Batch; private: + //! Unlink the committed pages of newly failed remote levels from the radix tree, so that no new match reads them; + //! a request still holding such a page fails its next resume (RemoteMemError). Caller holds the exclusive lock. + void _unlinkPagesOfFailedRemoteLevels(); + //! _unlinkPagesOfFailedRemoteLevels() under the exclusive lock if a remote client failed since the last unlink; for + //! the probes, which otherwise match under the shared lock. Without a failure it reads only atomics. + void _unlinkPagesIfARemoteLevelFailed(); + //! Units a step selects per buffer of this life cycle. The cache must hold a whole //! selection on top of everything in flight, so this is what the in-flight headroom is //! measured against. @@ -721,6 +730,8 @@ class KvCacheManager : public std::enable_shared_from_this std::shared_ptr mEventSink; std::shared_ptr mStorage; std::shared_ptr mRadixTree; + //! StorageManager::numFailedRemoteClients() as of the last _unlinkPagesOfFailedRemoteLevels(). + std::atomic mNumFailedRemoteClientsUnlinked{0}; // Weak references to all living KvCaches. std::set mLivingKvCaches; diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/page.cpp b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/page.cpp index 3d41f92e6e09..84e29c35dcfd 100644 --- a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/page.cpp +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/page.cpp @@ -222,7 +222,7 @@ UncommittedPage::~UncommittedPage() } SharedPtr UncommittedPage::convertToCommitted( - SharedPtr blk, CachedCudaEvent readyEv, int numTokensInBlock) + SharedPtr blk, CachedCudaEvent readyEv, int numTokensInBlock, Page const* retentionSource) { TLLM_CHECK_DEBUG(!scheduledForEviction()); // Check before building: replacePage() below drops the superseded page, so a failure @@ -245,7 +245,7 @@ SharedPtr UncommittedPage::convertToCommitted( } else { - committed->inheritRetention(*this); + committed->inheritRetention(retentionSource != nullptr ? *retentionSource : *this); } // Move slot id to the committed page; invalidate our slot. committed->setSlotId(slotId()); // asserts valid diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/page.h b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/page.h index 4fa34dc549a2..2f35bf8f8a63 100644 --- a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/page.h +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/page.h @@ -169,8 +169,10 @@ class UncommittedPage : public Page // // `numTokensInBlock` records the page's token count. See // CommittedPage::numTokensInBlock for its attention and SSM interpretations. - SharedPtr convertToCommitted( - SharedPtr block, CachedCudaEvent readyEvent, int numTokensInBlock); + // An attention page takes the retention of `retentionSource` if given (the block's page it supersedes), else its + // own. + SharedPtr convertToCommitted(SharedPtr block, CachedCudaEvent readyEvent, + int numTokensInBlock, Page const* retentionSource = nullptr); }; // --------------------------------------------------------------------------- diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/core.cpp b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/core.cpp index 359039bb0a4e..cbc44fe7592d 100644 --- a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/core.cpp +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/core.cpp @@ -57,6 +57,7 @@ size_t tierAllocationGranularity(CacheTier tier, size_t quota) // backing raises it to a page should a platform ever ask for more. case CacheTier::HOST_MEM: return hostMemSizeGranularity(); case CacheTier::DISK: return kDiskPoolSizeGranularity; + case CacheTier::REMOTE: return kRemotePoolSizeGranularity; default: throw std::invalid_argument("Invalid cache tier"); } } @@ -492,6 +493,47 @@ Address DiskSlotPool::slotAddress(SlotId slot) const return DiskAddress{mFd, static_cast(byteOffset)}; } +// --------------------------------------------------------------------------- +// RemoteSlotPool +// --------------------------------------------------------------------------- + +RemoteSlotPool::RemoteSlotPool(SharedPtr client, size_t slotSize, SlotCount numSlots) + : SlotPoolBase(slotSize) + , mRange(std::make_unique(std::move(client), slotSize)) +{ + resize(numSlots); +} + +RemoteSlotPool::~RemoteSlotPool() +{ + destroy(); +} + +void RemoteSlotPool::destroy() +{ + // Returns the chunks to the process's client; the claims stay with it. + mRange.reset(); + mNumSlots = SlotCount{0}; +} + +void RemoteSlotPool::resize(SlotCount newNumSlots) +{ + TLLM_CHECK_WITH_INFO(mRange != nullptr, "RemoteSlotPool::resize after destroy"); + mRange->reserve(newNumSlots); + mNumSlots = newNumSlots; +} + +Address RemoteSlotPool::slotAddress(SlotId /*slot*/) const +{ + throw LogicError("RemoteSlotPool::slotAddress: remote slots have no local address; use remoteRange()"); +} + +RemoteRange& RemoteSlotPool::remoteRange() const +{ + TLLM_CHECK_WITH_INFO(mRange != nullptr, "RemoteSlotPool::remoteRange after destroy"); + return *mRange; +} + // --------------------------------------------------------------------------- // PoolGroupBase // --------------------------------------------------------------------------- @@ -720,6 +762,25 @@ DiskPoolGroup::DiskPoolGroup( } } +// --------------------------------------------------------------------------- +// RemotePoolGroup +// --------------------------------------------------------------------------- + +RemotePoolGroup::RemotePoolGroup( + SlotCount numSlots, TypedVec const& slotSizeList, SharedPtr const& client) + : PoolGroupBase(numSlots) +{ + for (size_t sz : slotSizeList) + { + mPools.push_back(std::make_unique(client, sz, numSlots)); + } +} + +RemoteRange& RemotePoolGroup::remoteRange(PoolIndex poolIdx) const +{ + return static_cast(*mPools.at(poolIdx)).remoteRange(); +} + // --------------------------------------------------------------------------- // CacheLevelStorage // --------------------------------------------------------------------------- @@ -811,6 +872,29 @@ DiskCacheLevelStorage::DiskCacheLevelStorage(TypedVec } } +// --------------------------------------------------------------------------- +// RemoteCacheLevelStorage +// --------------------------------------------------------------------------- + +RemoteCacheLevelStorage::RemoteCacheLevelStorage(TypedVec const& slotDescList, + TypedVec const& slotCountList, SharedPtr client) + : mClient(std::move(client)) +{ + TLLM_CHECK(mClient != nullptr); + TLLM_CHECK_WITH_INFO(slotCountList.size() == slotDescList.size(), + "RemoteCacheLevelStorage: slotCountList and slotDescList must have the same length"); + for (PoolGroupIndex pgIdx{0}; pgIdx < slotDescList.size(); ++pgIdx) + { + mPoolGroups.push_back( + std::make_unique(slotCountList[pgIdx], slotDescList[pgIdx].slotSizeList(), mClient)); + } +} + +RemoteRange& RemoteCacheLevelStorage::remoteRange(PoolGroupIndex pgIdx, PoolIndex poolIdx) const +{ + return static_cast(*mPoolGroups.at(pgIdx)).remoteRange(poolIdx); +} + // --------------------------------------------------------------------------- // Factory // --------------------------------------------------------------------------- @@ -818,7 +902,7 @@ DiskCacheLevelStorage::DiskCacheLevelStorage(TypedVec std::unique_ptr createCacheLevelStorage(CacheTierConfig const& tierCfg, TypedVec const& slotDescList, TypedVec const& slotCountList, PooledPhysMemAllocator* gpuPhysMemAllocator, HostMemBackingOptions const& options, - std::optional sparseReservation) + std::optional sparseReservation, SharedPtr remoteClient) { TLLM_CHECK((cacheTierOf(tierCfg) == CacheTier::GPU_MEM) == (gpuPhysMemAllocator != nullptr)); return std::visit( @@ -834,10 +918,17 @@ std::unique_ptr createCacheLevelStorage(CacheTierConfig const { return std::make_unique(slotDescList, slotCountList, cfg.maxQuota, options); } - else + else if constexpr (std::is_same_v) { return std::make_unique(slotDescList, slotCountList, cfg.path); } + else + { + static_assert(std::is_same_v); + TLLM_CHECK_WITH_INFO(remoteClient != nullptr && remoteClient->directory() == cfg.path, + "A remote cache level needs the client of its rendezvous directory"); + return std::make_unique(slotDescList, slotCountList, std::move(remoteClient)); + } }, tierCfg); } diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/core.h b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/core.h index 56d9ccb33f3d..25cf4c678562 100644 --- a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/core.h +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/core.h @@ -21,6 +21,7 @@ #include "kv_cache_manager_v2/cudaVirtMem.h" #include "kv_cache_manager_v2/exceptions.h" #include "kv_cache_manager_v2/storage/config.h" +#include "kv_cache_manager_v2/storage/remoteMem.h" #include "kv_cache_manager_v2/utils/cudaEvent.h" #include "kv_cache_manager_v2/utils/hostMem.h" #include "kv_cache_manager_v2/utils/math.h" @@ -205,6 +206,10 @@ class SlotAllocator //! so this is just a rounding quantum. inline constexpr size_t kDiskPoolSizeGranularity = size_t{2} << 20; +//! Granularity a remote pool is sized in. Its slots come in whole donated chunks, which RemoteRange +//! claims as needed, so this is only a rounding quantum. +inline constexpr size_t kRemotePoolSizeGranularity = size_t{2} << 20; + //! The grain a hot-level pool of `medium` rounds its bytes to, where //! `deviceGranularity` is the VMM allocation granularity device pools grow in. //! @@ -397,6 +402,45 @@ class DiskSlotPool : public SlotPoolBase SlotCount mNumSlots{0}; }; +// --------------------------------------------------------------------------- +// RemoteSlotPool — slots in host memory other processes donate (remoteMem.h). +// The GPU cannot address them: their pages move through the page-staging buffer. +// --------------------------------------------------------------------------- +class RemoteSlotPool : public SlotPoolBase +{ +public: + RemoteSlotPool(SharedPtr client, size_t slotSize, SlotCount numSlots); + ~RemoteSlotPool() override; + + SlotCount numSlots() const noexcept override + { + return mNumSlots; + } + + [[nodiscard]] size_t sizeGranularity() const noexcept override + { + return kRemotePoolSizeGranularity; + } + + void destroy() override; + //! Growing claims more chunks and throws without resizing if none can be had; shrinking keeps them. + void resize(SlotCount newNumSlots) override; + //! Remote slots have no local address: their pages move through remoteRange(). Throws LogicError. + Address slotAddress(SlotId slot) const override; + + [[nodiscard]] CacheTier medium() const noexcept override + { + return CacheTier::REMOTE; + } + + [[nodiscard]] RemoteRange& remoteRange() const; + +private: + std::unique_ptr mRange; + // The slots resize() asked for; the range may hold more (whole chunks). + SlotCount mNumSlots{0}; +}; + // --------------------------------------------------------------------------- // PoolGroupBase — manages multiple pools with mirrored slot allocation. // Mirrors _storage/_core.py::PoolGroupBase. @@ -609,6 +653,21 @@ class DiskPoolGroup : public PoolGroupBase } }; +class RemotePoolGroup : public PoolGroupBase +{ +public: + RemotePoolGroup( + SlotCount numSlots, TypedVec const& slotSizeList, SharedPtr const& client); + + [[nodiscard]] CacheTier cacheTier() const noexcept override + { + return CacheTier::REMOTE; + } + + //! The remote slots of pool `poolIdx`. + [[nodiscard]] RemoteRange& remoteRange(PoolIndex poolIdx) const; +}; + //! A second medium's budget over a disjoint subset of each pool group's pools. //! //! A slot spans every pool of its group, so one slot count drives the bytes taken in every @@ -969,11 +1028,36 @@ class DiskCacheLevelStorage : public CacheLevelStorage std::string mDirectory; }; +//! A level whose slots are memory other processes donate, reached through one client (remoteMem.h). +class RemoteCacheLevelStorage : public CacheLevelStorage +{ +public: + RemoteCacheLevelStorage(TypedVec const& slotDescList, + TypedVec const& slotCountList, SharedPtr client); + + CacheTier cacheTier() const noexcept override + { + return CacheTier::REMOTE; + } + + [[nodiscard]] RemoteMemClient& client() const noexcept + { + return *mClient; + } + + //! The remote slots of one pool. + [[nodiscard]] RemoteRange& remoteRange(PoolGroupIndex pgIdx, PoolIndex poolIdx) const; + +private: + SharedPtr mClient; +}; + // Factory: create appropriate CacheLevelStorage for a given tier config. -// `sparseReservation` applies to a GPU tier only; see GpuPoolGroup. +// `sparseReservation` applies to a GPU tier only; see GpuPoolGroup. `remoteClient` is required by, and only used for, +// a remote tier: the client of its rendezvous directory. std::unique_ptr createCacheLevelStorage(CacheTierConfig const& tierCfg, TypedVec const& slotDescList, TypedVec const& slotCountList, PooledPhysMemAllocator* gpuPhysMemAllocator = nullptr, HostMemBackingOptions const& options = {}, - std::optional sparseReservation = std::nullopt); + std::optional sparseReservation = std::nullopt, SharedPtr remoteClient = nullptr); } // namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteMem.cpp b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteMem.cpp new file mode 100644 index 000000000000..7c74396b3cc8 --- /dev/null +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteMem.cpp @@ -0,0 +1,712 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "kv_cache_manager_v2/storage/remoteMem.h" +#include "kv_cache_manager_v2/exceptions.h" +#include "kv_cache_manager_v2/utils/funcGuard.h" + +#include "tensorrt_llm/common/assert.h" +#include "tensorrt_llm/common/logger.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 +{ + +namespace +{ + +std::string hostName() +{ + char buf[256] = {}; + if (::gethostname(buf, sizeof(buf) - 1) != 0) + { + return "unknown"; + } + return buf; +} + +//! The transport a donor's .failed file names, or nullopt when it names none (malformed: every donor names it). +std::optional failedDonorTransport(std::string const& text) +{ + std::istringstream lines(text); + std::string line; + while (std::getline(lines, line)) + { + std::istringstream fields(line); + std::string key; + std::string value; + fields >> key >> value; + if (key == "transport") + { + return value; + } + } + return std::nullopt; +} + +//! Bounds on what a donor's .meta may declare, so a malformed file cannot make a client allocate without limit. +constexpr uint64_t kMinChunkBytes = 1ULL << 20; +constexpr uint64_t kMaxChunksPerDonor = 1ULL << 20; + +constexpr std::string_view kDonorPrefix = "donor."; +constexpr std::string_view kReadySuffix = ".ready"; +constexpr std::string_view kFailedSuffix = ".failed"; +constexpr std::string_view kClaimPrefix = "claim."; +constexpr mode_t kOthersWrite = S_IWGRP | S_IWOTH; + +} // namespace + +OwnedFd::~OwnedFd() +{ + if (mFd != kBadFileDescriptor) + { + ::close(mFd); + } +} + +OwnedFd::OwnedFd(OwnedFd&& other) noexcept + : mFd(std::exchange(other.mFd, kBadFileDescriptor)) +{ +} + +OwnedFd openRendezvousDirectory(std::string const& path) +{ + // O_NOFOLLOW: a symlink in the directory's place could be pointed elsewhere after this check. + OwnedFd dir(::open(path.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)); + TLLM_CHECK_WITH_INFO(dir.get() != kBadFileDescriptor, + "KVCM2 remote level: cannot open rendezvous directory '%s' (a directory, not a symlink): %s", path.c_str(), + std::strerror(errno)); + struct stat st = {}; + TLLM_CHECK_WITH_INFO(::fstat(dir.get(), &st) == 0, "KVCM2 remote level: cannot stat rendezvous directory '%s': %s", + path.c_str(), std::strerror(errno)); + // Donor files hold memory registration keys and fabric handles: only this user may add or replace them. + TLLM_CHECK_WITH_INFO(st.st_uid == ::geteuid() && (st.st_mode & kOthersWrite) == 0, + "KVCM2 remote level: rendezvous directory '%s' must be owned by uid %u and not writable by group or others " + "(owner uid %u, mode %o)", + path.c_str(), static_cast(::geteuid()), static_cast(st.st_uid), + static_cast(st.st_mode & 0777)); + return dir; +} + +// --------------------------------------------------------------------------- +// RemoteMemClient +// --------------------------------------------------------------------------- + +RemoteMemClient::RemoteMemClient(std::string name, RemoteMemOptions options, OwnedFd directory, + RemoteTransferConfig transferConfig, std::unique_ptr backend) + : mName(std::move(name)) + , mOptions(std::move(options)) + , mDirectory(std::move(directory)) + , mTransferConfig(std::move(transferConfig)) + , mBackend(std::move(backend)) +{ + TLLM_CHECK(mBackend != nullptr); + mStreamOrdered = mBackend->streamOrdered(); + { + std::lock_guard lock(mMutex); + refreshDonors(); + } + TLLM_LOG_INFO("KVCM2 remote level: client %s, rendezvous %s, %zu donor(s) published, transport %s", mName.c_str(), + mOptions.directory.c_str(), mDonors.size(), mBackend->kind()); +} + +RemoteMemClient::~RemoteMemClient() +{ + if (mAbandoned) + { + // A transfer that never quiesced may still reach the chunks and the backend: both outlive this client. + static_cast(mBackend.release()); + TLLM_LOG_WARNING( + "KVCM2 remote level: %s keeps its %zu claim(s) in %s and its transport after transfers " + "that never quiesced", + mName.c_str(), mClaims.size(), mOptions.directory.c_str()); + return; + } + // The claims go last, after the backend's teardown: another client may write into a chunk as soon as its claim + // is gone. + mBackend.reset(); + for (auto const& claim : mClaims) + { + ::unlinkat(mDirectory.get(), claim.c_str(), 0); + } +} + +std::optional RemoteMemClient::readDonorFile(std::string const& file) const +{ + // Read through the directory checked at construction, never through a symlink, and only from this user's files. + OwnedFd const fd(::openat(mDirectory.get(), file.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)); + if (fd.get() == kBadFileDescriptor) + { + if (errno != ENOENT) + { + TLLM_LOG_WARNING("KVCM2 remote level: cannot read %s in %s (%s); passing over its donor", file.c_str(), + mOptions.directory.c_str(), std::strerror(errno)); + } + return std::nullopt; // ENOENT: withdrawn since the listing + } + struct stat st = {}; + if (::fstat(fd.get(), &st) != 0 || !S_ISREG(st.st_mode) || st.st_uid != ::geteuid()) + { + TLLM_LOG_WARNING("KVCM2 remote level: ignoring %s in %s: not a regular file of this user (owner uid %u)", + file.c_str(), mOptions.directory.c_str(), static_cast(st.st_uid)); + return std::nullopt; + } + std::string text; + constexpr size_t kReadChunkBytes = 4096; + std::array buf{}; + for (;;) + { + ssize_t const n = ::read(fd.get(), buf.data(), buf.size()); + if (n < 0 && errno == EINTR) + { + continue; + } + if (n < 0) + { + TLLM_LOG_WARNING("KVCM2 remote level: cannot read %s in %s (%s); passing over its donor", file.c_str(), + mOptions.directory.c_str(), std::strerror(errno)); + return std::nullopt; + } + if (n == 0) + { + return text; + } + text.append(buf.data(), static_cast(n)); + } +} + +void RemoteMemClient::refreshDonors() +{ + std::vector ready; + std::vector failedFiles; + // claim.. files: chunks some client holds. + std::unordered_map> claimedChunks; + { + // A fresh open of the checked directory: its own read position, closed by closedir. + int const listFd = ::openat(mDirectory.get(), ".", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + DIR* const listing = listFd == kBadFileDescriptor ? nullptr : ::fdopendir(listFd); + if (listing == nullptr) + { + int const error = errno; + if (listFd != kBadFileDescriptor) + { + ::close(listFd); + } + throw RemoteMemError( + "KVCM2 remote level: cannot list " + mOptions.directory + ": " + std::string(std::strerror(error))); + } + auto closeListing = FuncGuard([listing]() { ::closedir(listing); }); + for (;;) + { + errno = 0; + dirent const* const entry = ::readdir(listing); + if (entry == nullptr) + { + if (errno != 0) + { + throw RemoteMemError("KVCM2 remote level: cannot list " + mOptions.directory + ": " + + std::string(std::strerror(errno))); + } + break; + } + std::string_view const file(entry->d_name); + if (file.size() > kDonorPrefix.size() + kReadySuffix.size() && file.starts_with(kDonorPrefix) + && file.ends_with(kReadySuffix)) + { + ready.emplace_back( + file.substr(kDonorPrefix.size(), file.size() - kDonorPrefix.size() - kReadySuffix.size())); + } + else if (file.size() > kDonorPrefix.size() + kFailedSuffix.size() && file.starts_with(kDonorPrefix) + && file.ends_with(kFailedSuffix)) + { + failedFiles.emplace_back(file); + } + else if (file.starts_with(kClaimPrefix)) + { + auto const dot = file.rfind('.'); + if (dot > kClaimPrefix.size() && dot + 1 < file.size()) + { + uint64_t chunk = 0; + auto const digits = file.substr(dot + 1); + auto const [end, ec] = std::from_chars(digits.data(), digits.data() + digits.size(), chunk); + if (ec == std::errc() && end == digits.data() + digits.size()) + { + claimedChunks[std::string(file.substr(kClaimPrefix.size(), dot - kClaimPrefix.size()))] + .push_back(chunk); + } + } + } + } + } + // Each donor counts once: a listing taken while a donor exits can show its .ready and its .failed. + std::unordered_set reported; + for (auto const& file : failedFiles) + { + // A failed donor of another transport is not one of the donors this client counts on. + auto const text = readDonorFile(file); + auto const transport = text ? failedDonorTransport(*text) : std::nullopt; + if (transport && *transport == mBackend->kind()) + { + reported.emplace( + file.substr(kDonorPrefix.size(), file.size() - kDonorPrefix.size() - kFailedSuffix.size())); + } + } + std::sort(ready.begin(), ready.end()); + for (auto& donor : mDonors) + { + if (!std::binary_search(ready.begin(), ready.end(), donor.name)) + { + stillPublished(donor); + } + } + for (auto const& name : ready) + { + if (mDonorIndex.count(name) != 0 || mForeignDonors.count(name) != 0) + { + continue; + } + RemoteDonor donor; + // Donor files hold memory registration keys and fabric handles: only this user's files are read. + auto const metaText = readDonorFile("donor." + name + ".meta"); + if (!metaText) + { + continue; // withdrawn since the listing, or not trusted + } + std::istringstream meta(*metaText); + std::string line; + int version = 0; + std::string agentName; + std::string transport; + while (std::getline(meta, line)) + { + std::istringstream fields(line); + std::string key; + fields >> key; + if (key == "version") + { + fields >> version; + } + else if (key == "name") + { + fields >> agentName; + } + else if (key == "transport") + { + fields >> transport; + } + else if (key == "host") + { + fields >> donor.host; + } + else if (key == "chunk_bytes") + { + fields >> donor.chunkBytes; + } + else if (key == "segment") + { + uint64_t base = 0; + uint64_t bytes = 0; + fields >> base >> bytes; + donor.segments.emplace_back(base, bytes); + } + } + // Donors publish one segment (remote_donor.py): more could overlap or sum past the chunk bound. + if (version != 1 || agentName != name || transport.empty() || donor.chunkBytes == 0 + || donor.segments.size() != 1) + { + TLLM_LOG_WARNING( + "KVCM2 remote level: ignoring donor %s: malformed meta (version %d, name '%s', transport '%s')", + name.c_str(), version, agentName.c_str(), transport.c_str()); + continue; + } + if (transport != mBackend->kind()) + { + TLLM_LOG_WARNING( + "KVCM2 remote level: ignoring donor %s: it donates over %s, this client uses %s; it is not counted as " + "one of the expected donors", + name.c_str(), transport.c_str(), mBackend->kind()); + mForeignDonors.insert(name); + continue; + } + auto const [segmentBase, segmentBytes] = donor.segments.front(); + bool const segmentsValid = donor.chunkBytes >= kMinChunkBytes && segmentBase <= UINT64_MAX - segmentBytes; + uint64_t const numChunks = segmentsValid ? segmentBytes / donor.chunkBytes : 0; + if (!segmentsValid || numChunks > kMaxChunksPerDonor) + { + TLLM_LOG_WARNING("KVCM2 remote level: ignoring donor %s: chunk size %llu B or its segments out of bounds", + name.c_str(), static_cast(donor.chunkBytes)); + continue; + } + donor.name = name; + for (auto const& [base, bytes] : donor.segments) + { + for (uint64_t chunk = 0; chunk < bytes / donor.chunkBytes; ++chunk) + { + donor.chunks.emplace_back(base + chunk * donor.chunkBytes, donor.chunkBytes); + } + } + auto payload = readDonorFile("donor." + name + "." + mBackend->payloadSuffix()); + if (!payload) + { + continue; // withdrawn since the listing + } + donor.payload = std::move(*payload); + if (!mBackend->acceptPayload(donor)) + { + continue; + } + TLLM_LOG_INFO("KVCM2 remote level: found donor %s on %s, %zu chunk(s) of %.2f GiB", name.c_str(), + donor.host.c_str(), donor.chunks.size(), + static_cast(donor.chunkBytes) / static_cast(1ULL << 30)); + mDonorIndex.emplace(name, mDonors.size()); + mDonors.push_back(std::move(donor)); + } + // Counted once the new ready donors are parsed: a donor of another transport is not reported to this client. + for (auto const& name : ready) + { + if (mForeignDonors.count(name) == 0) + { + reported.insert(name); + } + } + mReportedDonors = reported.size(); + for (auto& donor : mDonors) + { + donor.claimed.assign(donor.chunks.size(), 0); + auto const it = claimedChunks.find(donor.name); + if (it != claimedChunks.end()) + { + for (auto const chunk : it->second) + { + if (chunk < donor.claimed.size()) + { + donor.claimed[chunk] = 1; + } + } + } + } +} + +bool RemoteMemClient::stillPublished(RemoteDonor& donor) +{ + if (!donor.withdrawn) + { + auto const ready = "donor." + donor.name + ".ready"; + struct stat st = {}; + if (::fstatat(mDirectory.get(), ready.c_str(), &st, AT_SYMLINK_NOFOLLOW) != 0 && errno == ENOENT) + { + // Donor names are unique per donor process, so a withdrawn one never comes back. + donor.withdrawn = true; + TLLM_LOG_WARNING("KVCM2 remote level: donor %s (%s) withdrew; no new claims from it", donor.name.c_str(), + donor.host.c_str()); + } + } + return !donor.withdrawn; +} + +void RemoteMemClient::throwIfFailed() const +{ + if (mFailed.load(std::memory_order_relaxed)) + { + throw RemoteMemError( + "KVCM2 remote level: " + mOptions.directory + " takes no transfers after an earlier failure: " + mFailure); + } +} + +void RemoteMemClient::fail(std::string const& message) +{ + { + std::lock_guard lock(mMutex); + if (!mFailed.load(std::memory_order_relaxed)) + { + mFailure = message; + mFailed.store(true, std::memory_order_release); + TLLM_LOG_ERROR( + "%s; the remote level in %s takes no further transfers", message.c_str(), mOptions.directory.c_str()); + } + } + throw RemoteMemError(message); +} + +bool RemoteMemClient::tryClaim(size_t minBytes, RemoteChunk& out) +{ + if (mDonors.empty()) + { + return false; + } + std::string const owner = mName + " " + hostName() + " " + std::to_string(::getpid()) + "\n"; + // Clients start at different donors, so the first claims of many clients spread out. + size_t const start = std::hash{}(mName) % mDonors.size(); + for (size_t k = 0; k < mDonors.size(); ++k) + { + uint32_t const index = static_cast((start + k) % mDonors.size()); + auto& donor = mDonors[index]; + if (donor.chunkBytes < minBytes || donor.full || !stillPublished(donor)) + { + continue; + } + // Chunks are probed from the last one this client claimed or found taken, wrapping around once, skipping + // those the last listing showed claimed: claims last as long as their client, so the shared file system sees + // about one exclusive create per free chunk per client, also while the client waits for capacity. + size_t const numChunks = donor.chunks.size(); + donor.claimed.resize(numChunks, 0); + for (size_t probe = 0; probe < numChunks; ++probe) + { + size_t const chunk = (donor.nextClaim + probe) % numChunks; + if (donor.claimed[chunk] != 0) + { + continue; + } + auto const claim = "claim." + donor.name + "." + std::to_string(chunk); + auto const path = mOptions.directory + "/" + claim; // for messages; files go through mDirectory + int const fd = ::openat(mDirectory.get(), claim.c_str(), O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC, 0600); + if (fd < 0) + { + if (errno == EEXIST) + { + donor.claimed[chunk] = 1; + continue; + } + throw RemoteMemError( + "KVCM2 remote level: creating claim " + path + " failed: " + std::string(std::strerror(errno))); + } + ssize_t const written = ::write(fd, owner.data(), owner.size()); + ::close(fd); + if (written != static_cast(owner.size())) + { + ::unlinkat(mDirectory.get(), claim.c_str(), 0); + throw RemoteMemError("KVCM2 remote level: writing claim " + path + " failed"); + } + uint64_t address = 0; + try + { + address = mBackend->attachChunk(donor, chunk); + } + catch (RemoteMemError const& e) + { + // E.g. a crashed donor whose .ready file stayed: no claims from it, the next donor is tried. + ::unlinkat(mDirectory.get(), claim.c_str(), 0); + donor.withdrawn = true; + mLastClaimError = e.what(); + TLLM_LOG_WARNING("KVCM2 remote level: no claims from donor %s (%s): %s", donor.name.c_str(), + donor.host.c_str(), e.what()); + break; + } + catch (...) + { + ::unlinkat(mDirectory.get(), claim.c_str(), 0); + throw; + } + out = RemoteChunk{index, address, donor.chunks[chunk].second}; + donor.claimed[chunk] = 1; + donor.nextClaim = chunk + 1; + mClaims.push_back(claim); + mClaimedBytes += out.bytes; + return true; + } + donor.full = !donor.withdrawn; + } + // No donor had a chunk: the next attempt probes the ones found full again, in case a client let go of one. + for (auto& donor : mDonors) + { + donor.full = false; + } + return false; +} + +RemoteChunk RemoteMemClient::acquireChunk(size_t minBytes) +{ + std::unique_lock lock(mMutex); + throwIfFailed(); + for (auto it = mFreeChunks.begin(); it != mFreeChunks.end(); ++it) + { + if (it->bytes >= minBytes && !mDonors[it->donor].withdrawn) + { + RemoteChunk chunk = std::move(*it); + mFreeChunks.erase(it); + return chunk; + } + } + auto const deadline = remoteDeadlineAfter(mOptions.waitTimeoutMs); + bool warned = false; + while (true) + { + RemoteChunk chunk; + if (tryClaim(minBytes, chunk)) + { + return chunk; + } + // Once every donor the job starts has reported, no chunk can appear: claims last as long as their client. + bool const allReported = mOptions.expectedDonors > 0 && mReportedDonors >= mOptions.expectedDonors; + if (allReported || std::chrono::steady_clock::now() >= deadline) + { + // The failed pass skipped donors found full while an earlier claim was served elsewhere, and chunks an + // older listing showed claimed: one more pass over a fresh listing probes them, as a peer that gave up + // (an abandoned construction) returns its chunks. + refreshDonors(); + if (tryClaim(minBytes, chunk)) + { + return chunk; + } + throw RemoteMemError("KVCM2 remote level: no donor in " + mOptions.directory + " has a free chunk of " + + std::to_string(minBytes) + " B or more " + + (allReported ? "and all " + std::to_string(mOptions.expectedDonors) + + " expected donors reported (each layer group of a rank claims whole chunks, so the " + "donation " + "must exceed the summed cache_size by up to one chunk per layer group per rank)" + : "after " + std::to_string(mOptions.waitTimeoutMs) + " ms") + + "; this process holds " + std::to_string(mClaimedBytes) + " B of " + std::to_string(mDonors.size()) + + " donor(s)" + (mLastClaimError.empty() ? "" : "; last donor withdrawn: " + mLastClaimError)); + } + if (!warned) + { + TLLM_LOG_INFO("KVCM2 remote level: waiting for donor capacity in %s (holding %.2f GiB, %zu donor(s))", + mOptions.directory.c_str(), static_cast(mClaimedBytes) / static_cast(1ULL << 30), + mDonors.size()); + warned = true; + } + lock.unlock(); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + lock.lock(); + refreshDonors(); + } +} + +void RemoteMemClient::checkUsable() const +{ + std::lock_guard lock(mMutex); + throwIfFailed(); +} + +void RemoteMemClient::releaseChunk(RemoteChunk chunk) noexcept +{ + std::lock_guard lock(mMutex); + mFreeChunks.push_back(std::move(chunk)); +} + +std::unique_ptr RemoteMemClient::submit( + bool write, std::vector const& ios, size_t bytes, CUstream stream) +{ + std::lock_guard lock(mMutex); + throwIfFailed(); + return mBackend->submit(write, mDonors, ios, bytes, stream); +} + +void RemoteMemClient::registerLocal(MemAddress base, size_t bytes) +{ + std::lock_guard lock(mMutex); + mBackend->registerLocal(base, bytes); +} + +void RemoteMemClient::deregisterLocal(MemAddress base, size_t bytes) noexcept +{ + std::lock_guard lock(mMutex); + if (!mAbandoned) + { + mBackend->deregisterLocal(base, bytes); + } +} + +void RemoteMemClient::drain() noexcept +{ + std::lock_guard lock(mMutex); + mBackend->drain(); +} + +void RemoteMemClient::abandon() noexcept +{ + std::lock_guard lock(mMutex); + mAbandoned = true; +} + +SharedPtr makeRemoteMemClient(RemoteMemOptions options, RemoteTransferConfig const& transferConfig) +{ + auto directory = openRendezvousDirectory(options.directory); + // Unique among the process's clients, past and present: it names the transfer agent and the owner of each claim. + static std::atomic sClients{0}; + std::string name = "kvcm2-remote-" + hostName() + "-" + std::to_string(::getpid()) + "-" + + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) + "-" + + std::to_string(sClients.fetch_add(1)); + auto backend = makeRemoteTransferBackend(transferConfig, name); + return makeShared( + std::move(name), std::move(options), std::move(directory), transferConfig, std::move(backend)); +} + +// --------------------------------------------------------------------------- +// RemoteRange +// --------------------------------------------------------------------------- + +RemoteRange::RemoteRange(SharedPtr client, size_t slotSize) + : mClient(std::move(client)) + , mSlotSize(slotSize) +{ + TLLM_CHECK(mClient != nullptr); + TLLM_CHECK_WITH_INFO(mSlotSize > 0, "KVCM2 remote level: zero slot size"); +} + +RemoteRange::~RemoteRange() +{ + for (auto& chunk : mChunks) + { + mClient->releaseChunk(std::move(chunk)); + } +} + +void RemoteRange::reserve(SlotCount numSlots) +{ + while (mCapacity < numSlots) + { + RemoteChunk chunk = mClient->acquireChunk(mSlotSize); + SlotCount const slots = static_cast(chunk.bytes / mSlotSize); + TLLM_CHECK(slots > 0); + mFirstSlot.push_back(mCapacity); + mCapacity += slots; + mChunks.push_back(std::move(chunk)); + } +} + +std::pair RemoteRange::locate(SlotId slot) const +{ + SlotCount const s = slot.value(); + TLLM_CHECK_WITH_INFO(s >= 0 && s < mCapacity, "KVCM2 remote level: slot %lld outside the %lld reserved", + static_cast(s), static_cast(mCapacity)); + auto const it = std::upper_bound(mFirstSlot.begin(), mFirstSlot.end(), s); + size_t const index = static_cast(std::distance(mFirstSlot.begin(), it)) - 1; + auto const& chunk = mChunks[index]; + return {chunk.donor, chunk.remoteAddr + static_cast(s - mFirstSlot[index]) * mSlotSize}; +} + +} // namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteMem.h b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteMem.h new file mode 100644 index 000000000000..77385bbf966e --- /dev/null +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteMem.h @@ -0,0 +1,239 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +// The memory behind a remote cache level: host memory that donors (remote_donor.py, which describes the files) +// publish in a rendezvous directory, claimed in whole chunks with O_EXCL claim.. files. Declaring and +// claiming it does not pick a transport: pages move through the client's RemoteTransferBackend (remoteTransfer.h), +// which makeRemoteMemClient makes from the tier's RemoteTransferConfig. + +#include "kv_cache_manager_v2/common.h" +#include "kv_cache_manager_v2/config.h" +#include "kv_cache_manager_v2/exceptions.h" +#include "kv_cache_manager_v2/storage/config.h" +#include "kv_cache_manager_v2/storage/remoteTransfer.h" +#include "kv_cache_manager_v2/utils/sharedPtr.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 +{ + +//! The memory a remote level declares: where donors publish it and how long to wait for them. +struct RemoteMemOptions +{ + //! Rendezvous directory the donors publish into. + std::string directory; + //! How long a claim waits for a donor with a free chunk (RemoteCacheTierConfig::waitTimeoutMs). + int64_t waitTimeoutMs = 0; + //! Donors the job starts (RemoteCacheTierConfig::expectedDonors); 0 if unknown. + uint32_t expectedDonors = 0; + + bool operator==(RemoteMemOptions const&) const = default; +}; + +//! A file descriptor, closed with its owner. +class OwnedFd +{ +public: + explicit OwnedFd(FileDescriptor fd = kBadFileDescriptor) noexcept + : mFd(fd) + { + } + + ~OwnedFd(); + OwnedFd(OwnedFd&& other) noexcept; + OwnedFd(OwnedFd const&) = delete; + OwnedFd& operator=(OwnedFd const&) = delete; + OwnedFd& operator=(OwnedFd&&) = delete; + + [[nodiscard]] FileDescriptor get() const noexcept + { + return mFd; + } + +private: + FileDescriptor mFd; +}; + +//! One chunk of donated memory this process owns. +struct RemoteChunk +{ + uint32_t donor = 0; // index into the client's donor table + uint64_t remoteAddr = 0; // the address transfers name the chunk by (RemoteTransferBackend::attachChunk) + uint64_t bytes = 0; +}; + +//! A connection to the donors of one rendezvous directory: the donor table and the claimed chunks, and the backend +//! that moves pages. Owned by a StorageManager and shared by its levels that name the directory; the last one to go +//! releases the claims. +class RemoteMemClient +{ +public: + //! Reads the donors published so far. `name` is unique among the process's clients and names each claim's owner. + //! `directory` is options.directory, opened and checked (openRendezvousDirectory): every later access goes through + //! it, so that the path is never resolved again. + RemoteMemClient(std::string name, RemoteMemOptions options, OwnedFd directory, RemoteTransferConfig transferConfig, + std::unique_ptr backend); + ~RemoteMemClient(); + + RemoteMemClient(RemoteMemClient const&) = delete; + RemoteMemClient& operator=(RemoteMemClient const&) = delete; + + //! A chunk that holds at least one slot of `minBytes`: from this process's free list, else claimed from a donor, + //! waiting up to waitTimeoutMs for one, or until all expectedDonors have reported. Throws RemoteMemError when + //! none appears. + [[nodiscard]] RemoteChunk acquireChunk(size_t minBytes); + //! Return a chunk to this process's free list. The claim is kept until the client is destroyed. + void releaseChunk(RemoteChunk chunk) noexcept; + + //! RemoteTransferBackend::streamOrdered(). + [[nodiscard]] bool streamOrdered() const noexcept + { + return mStreamOrdered; + } + + //! Register local memory transfers read from or write into with the backend (reference-counted by base). + void registerLocal(MemAddress base, size_t bytes); + //! Ignored once the client is abandoned: a transfer may still access the memory. + void deregisterLocal(MemAddress base, size_t bytes) noexcept; + + //! Start a transfer (RemoteTransferBackend::submit). Throws RemoteMemError when an earlier one failed: the + //! contents of the remote slots can no longer be trusted. + [[nodiscard]] std::unique_ptr submit( + bool write, std::vector const& ios, size_t bytes, CUstream stream); + + //! Record the first transfer failure and throw it as RemoteMemError; the client has failed() from then on. + [[noreturn]] void fail(std::string const& message); + + //! Throws RemoteMemError when an earlier transfer failed. Call it before leasing page staging for a transfer: a + //! failed level's unquiesced transfers may still hold all of it. + void checkUsable() const; + + //! Whether a transfer failed. A failed client throws RemoteMemError on every transfer and claim. + [[nodiscard]] bool failed() const noexcept + { + return mFailed.load(std::memory_order_acquire); + } + + //! Wait until every stream-ordered transfer enqueued so far has finished (teardown). + void drain() noexcept; + + //! A transfer that never quiesced may still access the claimed chunks, the backend's registrations and its + //! agent: keep the claims and leak the backend instead of releasing them. + void abandon() noexcept; + + [[nodiscard]] std::string const& directory() const noexcept + { + return mOptions.directory; + } + + [[nodiscard]] RemoteMemOptions const& options() const noexcept + { + return mOptions; + } + + [[nodiscard]] RemoteTransferConfig const& transferConfig() const noexcept + { + return mTransferConfig; + } + +private: + //! Add the donors newly published in the directory, mark the ones whose .ready file is gone as withdrawn, and + //! count the donors that reported (.ready or .failed). + void refreshDonors(); + //! Whether `donor` still publishes its .ready file; marks it withdrawn when not. + bool stillPublished(RemoteDonor& donor); + //! Claim a free chunk; a donor whose chunk cannot be attached (e.g. it crashed) is marked withdrawn. + bool tryClaim(size_t minBytes, RemoteChunk& out); + //! Caller holds mMutex. Throws RemoteMemError when an earlier transfer failed. + void throwIfFailed() const; + + //! The contents of the donor file `file` in the directory, or nullopt when it cannot be read or is not a regular + //! file of this user's: the donor withdrew after the listing, or the file is not trusted. + [[nodiscard]] std::optional readDonorFile(std::string const& file) const; + + std::string mName; + RemoteMemOptions mOptions; + OwnedFd mDirectory; + RemoteTransferConfig mTransferConfig; + std::unique_ptr mBackend; + bool mStreamOrdered = false; + std::vector mDonors; + mutable std::mutex mMutex; + std::unordered_map mDonorIndex; + std::vector mFreeChunks; + std::vector mClaims; // claim file names in the directory + uint64_t mClaimedBytes = 0; + size_t mReportedDonors = 0; // donors of this transport with a .ready or .failed file at the last refresh + std::unordered_set mForeignDonors; // ready donors of another transport, passed over + std::string mLastClaimError; // why the last donor was withdrawn at claim time + bool mAbandoned = false; + std::string mFailure; // the first transfer failure + std::atomic mFailed{false}; +}; + +//! Open `path` as a rendezvous directory: a directory, not a symlink, owned by this user and not writable by group or +//! others, as remote_donor.ensure_rendezvous_directory makes it. Throws otherwise. +[[nodiscard]] OwnedFd openRendezvousDirectory(std::string const& path); + +//! The client of `options.directory`, moving pages through the backend `transferConfig` selects. +[[nodiscard]] SharedPtr makeRemoteMemClient( + RemoteMemOptions options, RemoteTransferConfig const& transferConfig); + +//! A pool's slots in remote memory: whole chunks, each holding floor(chunk bytes / slot size) slots, in order. +class RemoteRange +{ +public: + RemoteRange(SharedPtr client, size_t slotSize); + ~RemoteRange(); + + RemoteRange(RemoteRange const&) = delete; + RemoteRange& operator=(RemoteRange const&) = delete; + + //! Hold enough chunks for `numSlots` slots. Growing claims chunks; shrinking keeps them (a later grow reuses them). + void reserve(SlotCount numSlots); + + //! Where slot `slot` lives: (donor index, remote address). + [[nodiscard]] std::pair locate(SlotId slot) const; + + [[nodiscard]] RemoteMemClient& client() const noexcept + { + return *mClient; + } + +private: + SharedPtr mClient; + size_t mSlotSize = 0; + std::vector mChunks; + std::vector mFirstSlot; // first slot of each chunk; mFirstSlot.size() == mChunks.size() + SlotCount mCapacity{0}; +}; + +} // namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransfer.cpp b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransfer.cpp new file mode 100644 index 000000000000..201313f7503b --- /dev/null +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransfer.cpp @@ -0,0 +1,52 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "kv_cache_manager_v2/storage/remoteTransfer.h" +#include "kv_cache_manager_v2/storage/remoteTransferAgent.h" +#include "kv_cache_manager_v2/storage/remoteTransferFabric.h" + +#include "tensorrt_llm/common/assert.h" +#include "tensorrt_llm/executor/transferAgent.h" + +namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 +{ + +std::unique_ptr makeRemoteTransferBackend( + RemoteTransferConfig const& config, std::string const& name) +{ + switch (config.transport) + { + case RemoteTransport::kNixl: + { + executor::kv_cache::BaseAgentConfig agentConfig{}; + agentConfig.mName = name; + // The progress thread completes connection set-up with donors that never call into NIXL themselves. + agentConfig.useProgThread = true; + agentConfig.multiThread = false; + agentConfig.useListenThread = false; + agentConfig.enableTelemetry = false; + // This agent's own devices, so the process-wide UCX_NET_DEVICES of the KV transceiver's agent stays. + agentConfig.backendParams.insert(config.backendParams.begin(), config.backendParams.end()); + return std::make_unique( + executor::kv_cache::makeTransferAgent("nixl", &agentConfig), "nixl"); + } + case RemoteTransport::kFabric: return std::make_unique(); + } + TLLM_THROW("KVCM2 remote level: unknown transport %d", static_cast(config.transport)); +} + +} // namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransfer.h b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransfer.h new file mode 100644 index 000000000000..cc0889a843ce --- /dev/null +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransfer.h @@ -0,0 +1,155 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +// How a remote cache level's pages move, apart from the memory it claims (remoteMem.h). A RemoteTransferBackend +// reaches the donors' chunks and moves pages; each submission returns a RemoteTransferAttempt whose outcome and +// quiescence are separate, as in _torch/disaggregation/base/backend.py's Attempt: memory a submission may still +// access (the local staging range, the remote chunk) is reused only once quiesced() is true. +// +// Backends: remoteTransferAgent.h (any executor::kv_cache::BaseTransferAgent, NIXL by default) and +// remoteTransferFabric.h (fabric memory mapped into this process; why it is not an agent is said there). + +#include "kv_cache_manager_v2/common.h" +#include "kv_cache_manager_v2/config.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 +{ + +//! `timeoutMs` from now on the steady clock, clamped to the clock's range: a timeout meant as "never" (e.g. +//! transfer_timeout_s 1e10) must not wrap the deadline into the past. +[[nodiscard]] inline std::chrono::steady_clock::time_point remoteDeadlineAfter(int64_t timeoutMs) noexcept +{ + auto const now = std::chrono::steady_clock::now(); + auto const maxMs + = std::chrono::duration_cast(std::chrono::steady_clock::time_point::max() - now) + .count(); + return now + std::chrono::milliseconds(std::clamp(timeoutMs, 0, maxMs)); +} + +//! A donor of one rendezvous directory, as RemoteMemClient read it from the donor's files. +struct RemoteDonor +{ + std::string name; + std::string host; + uint64_t chunkBytes = 0; + std::vector> segments; // (base, bytes) + std::vector> chunks; // (address, bytes), in claim-index order; fabric: offsets + std::string payload; // the donor's payloadSuffix() file: what the backend needs to reach it + bool attached = false; // the backend has reached it (attachChunk) + bool withdrawn = false; // its .ready file is gone: no new claims from it + size_t nextClaim = 0; // chunks before it were claimed (by anyone) when last probed: claims start here + bool full = false; // a probe found every chunk claimed; skipped until a claim finds no donor at all + //! Per chunk: its claim file was in the last directory listing, or a create since found it taken. Such a chunk is + //! not probed again until the next listing shows it free. + std::vector claimed; +}; + +//! One page to move: `bytes` between local memory at `local` and donor `donor` at `remoteAddr`. +struct RemoteIo +{ + MemAddress local; + uint32_t donor; + uint64_t remoteAddr; +}; + +//! How one submission ended: delivered whole, or why not. Says nothing about whether access has ended. +struct RemoteTransferOutcome +{ + std::string fault; // empty: every page delivered + + [[nodiscard]] bool ok() const noexcept + { + return fault.empty(); + } +}; + +//! The handle of one submission. Outcome (poll) and quiescence (quiesced) are independent: a submission that timed +//! out on the caller's deadline has no outcome yet and may still access its memory, which then stays out of use. +//! Destroying an attempt that is not quiesced leaks what the backend needs to finish it rather than release it. +class RemoteTransferAttempt +{ +public: + virtual ~RemoteTransferAttempt() = default; + + //! nullopt until concluded; the same outcome on every call after. Never blocks. + [[nodiscard]] virtual std::optional poll() = 0; + + //! True once the backend has evidence that no part of the submission still accesses its local or remote + //! memory; never turns false again. Never blocks. + [[nodiscard]] virtual bool quiesced() = 0; + + //! poll() until concluded or `timeoutMs` passed (the caller's deadline): nullopt at the deadline. + [[nodiscard]] virtual std::optional wait(int64_t timeoutMs) = 0; +}; + +//! Moves pages between local memory and donated chunks; one per RemoteMemClient, which serializes its calls. +class RemoteTransferBackend +{ +public: + virtual ~RemoteTransferBackend() = default; + + //! The transport's name, as donors write it in their .meta ("nixl" when absent). + [[nodiscard]] virtual char const* kind() const noexcept = 0; + //! The suffix of the donor file holding what this backend needs to reach a donor. + [[nodiscard]] virtual char const* payloadSuffix() const noexcept = 0; + //! Whether `donor`'s payload fits its chunks; logs why not. + [[nodiscard]] virtual bool acceptPayload(RemoteDonor const& donor) const = 0; + //! Make the newly claimed chunk `chunk` of `donor` reachable; returns the address transfers name it by. Throws + //! RemoteMemError when the donor cannot be reached, which passes over that donor; any other exception (a local + //! failure, such as mapping the chunk) fails the claim. + virtual uint64_t attachChunk(RemoteDonor& donor, size_t chunk) = 0; + + //! Whether transfers are enqueued on the caller's stream. Then the stream orders everything that touches the + //! submission's memory, and a stream-owned staging lease is its quiescence. Otherwise a transfer runs on the + //! host: its local memory must be ready, and free of stream work, before submit(). + [[nodiscard]] virtual bool streamOrdered() const noexcept = 0; + + //! Register local memory that transfers read from or write into, reference-counted by base address. A backend + //! that reaches local memory without registration ignores it. + virtual void registerLocal(MemAddress /*base*/, size_t /*bytes*/) {} + + virtual void deregisterLocal(MemAddress /*base*/, size_t /*bytes*/) noexcept {} + + //! Start moving `bytes` for every entry (`ios` non-empty), local -> remote (`write`) or remote -> local. Returns + //! without waiting on a donor; a failure after any page may have been accessed is the attempt's fault, never a + //! throw. + [[nodiscard]] virtual std::unique_ptr submit(bool write, + std::vector const& donors, std::vector const& ios, size_t bytes, CUstream stream) + = 0; + + //! Wait until every stream-ordered transfer enqueued so far has finished; a failure is logged (teardown). + virtual void drain() noexcept {} +}; + +//! The backend `config` selects; `name` names its agent (unique among the process's clients). +[[nodiscard]] std::unique_ptr makeRemoteTransferBackend( + RemoteTransferConfig const& config, std::string const& name); + +} // namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransferAgent.cpp b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransferAgent.cpp new file mode 100644 index 000000000000..f592452ade7b --- /dev/null +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransferAgent.cpp @@ -0,0 +1,325 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "kv_cache_manager_v2/storage/remoteTransferAgent.h" +#include "kv_cache_manager_v2/exceptions.h" + +#include "tensorrt_llm/common/assert.h" +#include "tensorrt_llm/common/logger.h" +#include "tensorrt_llm/executor/transferAgent.h" + +#include +#include +#include + +namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 +{ + +namespace kvc = tensorrt_llm::executor::kv_cache; + +namespace +{ + +//! The requests of one submission, one per donor. +class AgentTransferAttempt final : public RemoteTransferAttempt +{ +public: + struct Request + { + std::string donor; // " ()" + size_t pages = 0; + std::unique_ptr status; + bool concluded = false; + }; + + //! Room for `numRequests` requests and a fault message, so that add() and failSubmit() do not allocate. + AgentTransferAttempt(std::string opName, size_t bytes, size_t numRequests) + : mOpName(std::move(opName)) + , mBytes(bytes) + { + mRequests.reserve(numRequests); + mFault.reserve(kFaultCapacity); + } + + //! Take a posted request; never throws, within the reserved room. + void add(std::string donor, size_t pages, std::unique_ptr status) noexcept + { + TLLM_CHECK_DEBUG(mRequests.size() < mRequests.capacity()); + mRequests.push_back(Request{std::move(donor), pages, std::move(status), /*concluded=*/false}); + } + + //! Posting the request to `donor` failed; nothing more is posted. Never throws. + void failSubmit(std::string const& donor, char const* what) noexcept + { + try + { + mFault = "KVCM2 remote level: " + mOpName + " donor " + donor + ": submitting failed: " + what; + } + catch (...) + { + mFault.assign("KVCM2 remote level: submitting a transfer failed"); // within the reserved capacity + } + } + + ~AgentTransferAttempt() override + { + if (quiesced()) + { + return; + } + // Releasing a request in progress does not stop it: leave it to run, and its memory out of use. + size_t leaked = 0; + for (auto& request : mRequests) + { + if (!request.concluded) + { + static_cast(request.status.release()); + ++leaked; + } + } + TLLM_LOG_ERROR( + "KVCM2 remote level: %zu %s request(s) still in progress are left running", leaked, mOpName.c_str()); + } + + AgentTransferAttempt(AgentTransferAttempt const&) = delete; + AgentTransferAttempt& operator=(AgentTransferAttempt const&) = delete; + + std::optional poll() override + { + advance(); + return outcome(); + } + + //! A request that ended in kFAILURE counts as concluded, its access to the staging range ended: NIXL reports + //! no state after it, and keeping its lease out of use would leak the claims and staging of every dead donor. + bool quiesced() override + { + advance(); + return allConcluded(); + } + + std::optional wait(int64_t timeoutMs) override + { + auto const deadline = remoteDeadlineAfter(timeoutMs); + for (auto& request : mRequests) + { + if (!request.concluded) + { + auto const remaining = std::max(0, + std::chrono::duration_cast(deadline - std::chrono::steady_clock::now()) + .count()); + conclude(request, request.status->wait(remaining)); + } + } + return outcome(); + } + +private: + //! Query every request still in progress once, without waiting. + void advance() + { + for (auto& request : mRequests) + { + if (!request.concluded) + { + conclude(request, request.status->wait(0)); + } + } + } + + void conclude(Request& request, kvc::TransferState state) + { + if (state == kvc::TransferState::kIN_PROGRESS) + { + return; + } + request.concluded = true; + if (state == kvc::TransferState::kFAILURE && mFault.empty()) + { + mFault = "KVCM2 remote level: " + mOpName + " donor " + request.donor + " of " + + std::to_string(request.pages) + " page(s) x " + std::to_string(mBytes) + " B failed (" + + request.status->getLastStatusStr() + ")"; + } + } + + [[nodiscard]] bool allConcluded() const + { + return std::all_of(mRequests.begin(), mRequests.end(), [](Request const& r) { return r.concluded; }); + } + + [[nodiscard]] std::optional outcome() const + { + if (!allConcluded()) + { + return std::nullopt; + } + return RemoteTransferOutcome{mFault}; + } + + std::string mOpName; + size_t mBytes; + std::vector mRequests; + std::string mFault; // the first failure: the submission's, else a request's + + static constexpr size_t kFaultCapacity = 512; +}; + +} // namespace + +AgentTransferBackend::AgentTransferBackend(std::unique_ptr agent, std::string kind) + : mTransferAgent(std::move(agent)) + , mKind(std::move(kind)) +{ + TLLM_CHECK_WITH_INFO(mTransferAgent != nullptr, "KVCM2 remote level: creating the transfer agent failed"); +} + +AgentTransferBackend::~AgentTransferBackend() +{ + try + { + for (auto const& [base, info] : mLocalRegions) + { + mTransferAgent->deregisterMemory( + kvc::MemoryDescs(kvc::MemoryType::kDRAM, {kvc::MemoryDesc(base, info.first, /*deviceId=*/0)})); + } + for (auto const& donor : mLoadedDonors) + { + mTransferAgent->invalidateRemoteAgent(donor); + } + } + catch (std::exception const& e) + { + TLLM_LOG_WARNING("KVCM2 remote level: transfer agent teardown: %s", e.what()); + } +} + +uint64_t AgentTransferBackend::attachChunk(RemoteDonor& donor, size_t chunk) +{ + if (!donor.attached) + { + try + { + mTransferAgent->loadRemoteAgent(donor.name, kvc::AgentDesc::deserialize(donor.payload)); + } + catch (std::exception const& e) + { + throw RemoteMemError( + "KVCM2 remote level: loading donor " + donor.name + " (" + donor.host + ") failed: " + e.what()); + } + donor.attached = true; + mLoadedDonors.push_back(donor.name); + } + return donor.chunks[chunk].first; +} + +void AgentTransferBackend::registerLocal(MemAddress base, size_t bytes) +{ + auto it = mLocalRegions.find(base); + if (it != mLocalRegions.end()) + { + TLLM_CHECK_WITH_INFO(it->second.first == bytes, + "KVCM2 remote level: local region re-registered with %zu B, was %zu B", bytes, it->second.first); + ++it->second.second; + return; + } + mTransferAgent->registerMemory( + kvc::MemoryDescs(kvc::MemoryType::kDRAM, {kvc::MemoryDesc(base, bytes, /*deviceId=*/0)})); + mLocalRegions.emplace(base, std::make_pair(bytes, 1)); +} + +void AgentTransferBackend::deregisterLocal(MemAddress base, size_t bytes) noexcept +{ + auto it = mLocalRegions.find(base); + if (it == mLocalRegions.end() || --it->second.second > 0) + { + return; + } + try + { + mTransferAgent->deregisterMemory( + kvc::MemoryDescs(kvc::MemoryType::kDRAM, {kvc::MemoryDesc(base, bytes, /*deviceId=*/0)})); + } + catch (std::exception const& e) + { + TLLM_LOG_WARNING("KVCM2 remote level: deregistering local memory failed: %s", e.what()); + } + mLocalRegions.erase(it); +} + +std::unique_ptr AgentTransferBackend::submit(bool write, std::vector const& donors, + std::vector const& ios, size_t bytes, CUstream /*stream*/) +{ + std::vector> byDonor(donors.size()); + for (size_t i = 0; i < ios.size(); ++i) + { + TLLM_CHECK_DEBUG(ios[i].donor < donors.size()); + byDonor[ios[i].donor].push_back(i); + } + + // Everything that allocates is made before the first request is posted: from then on submit must return the + // attempt that owns the requests in flight, never throw (dropping a status does not stop its request). + struct Pending + { + std::string donor; // " ()" + size_t pages; + kvc::TransferRequest request; + }; + + std::vector pending; + for (uint32_t donorIdx = 0; donorIdx < byDonor.size(); ++donorIdx) + { + auto const& entries = byDonor[donorIdx]; + if (entries.empty()) + { + continue; + } + std::vector local; + std::vector remote; + local.reserve(entries.size()); + remote.reserve(entries.size()); + for (size_t i : entries) + { + local.emplace_back(ios[i].local, bytes, /*deviceId=*/0); + remote.emplace_back(static_cast(ios[i].remoteAddr), bytes, /*deviceId=*/0); + } + auto const& donor = donors[donorIdx]; + // The request names the local descriptors first and the remote ones second, whichever way data flows. + pending.push_back(Pending{donor.name + " (" + donor.host + ")", entries.size(), + kvc::TransferRequest(write ? kvc::TransferOp::kWRITE : kvc::TransferOp::kREAD, + kvc::MemoryDescs(kvc::MemoryType::kDRAM, std::move(local)), + kvc::MemoryDescs(kvc::MemoryType::kDRAM, std::move(remote)), donor.name)}); + } + auto attempt = std::make_unique(write ? "WRITE to" : "READ from", bytes, pending.size()); + for (auto& entry : pending) + { + std::unique_ptr status; + try + { + status = mTransferAgent->submitTransferRequests(entry.request); + } + catch (std::exception const& e) + { + // Nothing more is submitted; the requests already in flight conclude before the attempt does. + attempt->failSubmit(entry.donor, e.what()); + break; + } + attempt->add(std::move(entry.donor), entry.pages, std::move(status)); + } + return attempt; +} + +} // namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransferAgent.h b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransferAgent.h new file mode 100644 index 000000000000..78e097f7b8c2 --- /dev/null +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransferAgent.h @@ -0,0 +1,91 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "kv_cache_manager_v2/storage/remoteTransfer.h" + +#include +#include +#include +#include + +namespace tensorrt_llm::executor::kv_cache +{ +class BaseTransferAgent; +} // namespace tensorrt_llm::executor::kv_cache + +namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 +{ + +//! Transfers through a transfer agent (executor::kv_cache::BaseTransferAgent; makeRemoteTransferBackend makes a NIXL +//! one): one-sided READ / WRITE of DRAM, concluded on the host. Donors publish their agent's AgentDesc in +//! donor..desc. Only the BaseTransferAgent interface is used, so any agent that moves DRAM serves. +//! +//! A request is never released while in progress: releasing one does not stop it (NIXL 1.5.2 frees the backend +//! handle without cancelling or draining it), so an attempt holds its requests until they conclude, and one destroyed +//! before that leaks them. The owner of an attempt that has not quiesced keeps this backend alive too +//! (RemoteMemClient::abandon). +class AgentTransferBackend final : public RemoteTransferBackend +{ +public: + //! `kind` is the transport name donors of this agent write in their .meta. + AgentTransferBackend(std::unique_ptr agent, std::string kind); + //! Deregisters local memory, forgets the donors and destroys the agent. + ~AgentTransferBackend() override; + + AgentTransferBackend(AgentTransferBackend const&) = delete; + AgentTransferBackend& operator=(AgentTransferBackend const&) = delete; + + [[nodiscard]] char const* kind() const noexcept override + { + return mKind.c_str(); + } + + [[nodiscard]] char const* payloadSuffix() const noexcept override + { + return "desc"; + } + + [[nodiscard]] bool acceptPayload(RemoteDonor const& /*donor*/) const override + { + return true; + } + + uint64_t attachChunk(RemoteDonor& donor, size_t chunk) override; + + [[nodiscard]] bool streamOrdered() const noexcept override + { + return false; + } + + void registerLocal(MemAddress base, size_t bytes) override; + void deregisterLocal(MemAddress base, size_t bytes) noexcept override; + + //! One request per donor. A donor whose request cannot be submitted is the attempt's fault, which concludes once + //! the requests already submitted have. + [[nodiscard]] std::unique_ptr submit(bool write, std::vector const& donors, + std::vector const& ios, size_t bytes, CUstream stream) override; + +private: + std::unique_ptr mTransferAgent; + std::string mKind; + std::vector mLoadedDonors; + std::unordered_map> mLocalRegions; // base -> (bytes, refs) +}; + +} // namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransferFabric.cpp b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransferFabric.cpp new file mode 100644 index 000000000000..483886a7180f --- /dev/null +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransferFabric.cpp @@ -0,0 +1,250 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "kv_cache_manager_v2/storage/remoteTransferFabric.h" +#include "kv_cache_manager_v2/exceptions.h" +#include "kv_cache_manager_v2/utils/cudaContextScope.h" + +#include "tensorrt_llm/common/assert.h" +#include "tensorrt_llm/common/logger.h" + +#include +#include +#include +#include + +namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 +{ + +namespace +{ + +std::string cuErrorName(CUresult result) +{ + char const* name = nullptr; + if (cuGetErrorName(result, &name) != CUDA_SUCCESS || name == nullptr) + { + return "CUresult " + std::to_string(static_cast(result)); + } + return name; +} + +//! A submission's copies, enqueued on the caller's stream: concluded at once with the enqueue's outcome. +class FabricTransferAttempt final : public RemoteTransferAttempt +{ +public: + FabricTransferAttempt(std::string fault, CUstream stream) + : mOutcome{std::move(fault)} + , mStream(stream) + { + } + + std::optional poll() override + { + return mOutcome; + } + + //! The stream has run everything enqueued on it so far, these copies included. + bool quiesced() override + { + mQuiesced = mQuiesced || cuStreamQuery(mStream) == CUDA_SUCCESS; + return mQuiesced; + } + + std::optional wait(int64_t /*timeoutMs*/) override + { + return mOutcome; + } + +private: + RemoteTransferOutcome mOutcome; + CUstream mStream; + bool mQuiesced = false; +}; + +} // namespace + +FabricTransferBackend::FabricTransferBackend() +{ + CUcontext context = nullptr; + cuCheck(cuCtxGetCurrent(&context)); + if (context == nullptr) + { + throw RemoteMemError( + "KVCM2 remote level: the fabric transport needs a current CUDA context on the calling " + "thread"); + } + cuCheck(cuCtxGetDevice(&mDevice)); + // Callers enqueue copies in the device's primary context (as PyTorch does); teardown synchronizes it. + CUcontext primary = nullptr; + cuCheck(cuDevicePrimaryCtxRetain(&primary, mDevice)); + if (primary != context) + { + cuDevicePrimaryCtxRelease(mDevice); + throw RemoteMemError("KVCM2 remote level: the fabric transport needs the device's primary context current"); + } + mContext = primary; // released by release() +} + +FabricTransferBackend::~FabricTransferBackend() +{ + release(); +} + +void FabricTransferBackend::release() noexcept +{ + // Copies still queued on callers' streams must finish before their mappings go. + if (CUresult const result = synchronizeContext(); result != CUDA_SUCCESS) + { + TLLM_LOG_WARNING( + "KVCM2 remote level: fabric transport teardown: synchronizing failed: %s", cuErrorName(result).c_str()); + } + for (auto const& mapping : mMappings) + { + cuMemUnmap(mapping.address, mapping.bytes); + cuMemAddressFree(mapping.address, mapping.bytes); + cuMemRelease(mapping.handle); + } + mMappings.clear(); + mMappingEnd.clear(); + if (mContext != nullptr) + { + cuDevicePrimaryCtxRelease(mDevice); + mContext = nullptr; + } +} + +void FabricTransferBackend::drain() noexcept +{ + // Copies on callers' streams reach memory that is about to be released or reused. + if (CUresult const result = synchronizeContext(); result != CUDA_SUCCESS) + { + TLLM_LOG_ERROR("KVCM2 remote level: draining the fabric copies failed: %s", cuErrorName(result).c_str()); + } +} + +CUresult FabricTransferBackend::synchronizeContext() const noexcept +{ + if (mContext == nullptr) + { + return CUDA_SUCCESS; + } + CudaContextScope const scope(mContext); + return scope.usable() ? cuCtxSynchronize() : scope.error(); +} + +bool FabricTransferBackend::acceptPayload(RemoteDonor const& donor) const +{ + if (donor.payload.size() != donor.chunks.size() * sizeof(CUmemFabricHandle)) + { + TLLM_LOG_WARNING( + "KVCM2 remote level: ignoring donor %s: %zu B of fabric handles for %zu chunk(s), " + "expected %zu B each", + donor.name.c_str(), donor.payload.size(), donor.chunks.size(), sizeof(CUmemFabricHandle)); + return false; + } + return true; +} + +uint64_t FabricTransferBackend::attachChunk(RemoteDonor& donor, size_t chunk) +{ + // The chunk is its own fabric allocation, imported only as it is claimed. + uint64_t const bytes = donor.chunks[chunk].second; + CUmemFabricHandle fabricHandle{}; + std::memcpy(&fabricHandle, donor.payload.data() + chunk * sizeof(CUmemFabricHandle), sizeof(fabricHandle)); + CUmemGenericAllocationHandle handle = 0; + CUresult result = cuMemImportFromShareableHandle(&handle, &fabricHandle, CU_MEM_HANDLE_TYPE_FABRIC); + if (result != CUDA_SUCCESS) + { + throw RemoteMemError("KVCM2 remote level: importing chunk " + std::to_string(chunk) + " of donor " + + donor.name + " (" + donor.host + ") failed: " + cuErrorName(result) + + "; fabric memory needs both trays in one NVLink domain (NVL72 rack), the job's IMEX channel and a live " + "donor"); + } + CUdeviceptr address = 0; + result = cuMemAddressReserve(&address, bytes, 0, 0, 0); + if (result == CUDA_SUCCESS) + { + // An imported fabric allocation maps only whole: offset 0, its full size. + result = cuMemMap(address, bytes, 0, handle, 0); + if (result == CUDA_SUCCESS) + { + CUmemAccessDesc access{}; + access.location.type = CU_MEM_LOCATION_TYPE_DEVICE; + access.location.id = static_cast(mDevice); + access.flags = CU_MEM_ACCESS_FLAGS_PROT_READWRITE; + result = cuMemSetAccess(address, bytes, &access, 1); + if (result != CUDA_SUCCESS) + { + cuMemUnmap(address, bytes); + } + } + if (result != CUDA_SUCCESS) + { + cuMemAddressFree(address, bytes); + } + } + if (result != CUDA_SUCCESS) + { + cuMemRelease(handle); + // A local failure (e.g. out of GPU address space or memory), not the donor's: it fails the claim instead of + // passing over a live donor. + throw std::runtime_error("KVCM2 remote level: mapping chunk " + std::to_string(chunk) + " (" + + std::to_string(bytes) + " B) of donor " + donor.name + " (" + donor.host + + ") into this GPU failed: " + cuErrorName(result)); + } + mMappings.push_back(FabricMapping{address, bytes, handle}); + mMappingEnd.emplace(address, address + bytes); + donor.attached = true; + return address; +} + +std::unique_ptr FabricTransferBackend::submit(bool write, + std::vector const& /*donors*/, std::vector const& ios, size_t bytes, CUstream stream) +{ + // Runs of pages that are contiguous on both sides go as one copy, within one mapped chunk: two chunks' separate + // mappings may happen to be adjacent in the address space. + size_t i = 0; + while (i < ios.size()) + { + auto const mapping = mMappingEnd.upper_bound(static_cast(ios[i].remoteAddr)); + TLLM_CHECK_WITH_INFO(mapping != mMappingEnd.begin(), "KVCM2 remote level: fabric address outside every chunk"); + CUdeviceptr const mappingEnd = std::prev(mapping)->second; + size_t j = i + 1; + while (j < ios.size() && ios[j].local == ios[j - 1].local + bytes + && ios[j].remoteAddr == ios[j - 1].remoteAddr + bytes && ios[j].remoteAddr + bytes <= mappingEnd) + { + ++j; + } + auto const local = static_cast(ios[i].local); + auto const remote = static_cast(ios[i].remoteAddr); + size_t const n = (j - i) * bytes; + CUresult const result + = write ? cuMemcpyAsync(remote, local, n, stream) : cuMemcpyAsync(local, remote, n, stream); + if (result != CUDA_SUCCESS) + { + // The copies enqueued before it run on; the stream orders them before anything reuses their memory. + return std::make_unique(std::string("KVCM2 remote level: enqueuing a fabric ") + + (write ? "WRITE" : "READ") + " of " + std::to_string(n) + " B failed: " + cuErrorName(result), + stream); + } + i = j; + } + return std::make_unique(std::string{}, stream); +} + +} // namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransferFabric.h b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransferFabric.h new file mode 100644 index 000000000000..3039370a2880 --- /dev/null +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storage/remoteTransferFabric.h @@ -0,0 +1,93 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "kv_cache_manager_v2/storage/remoteTransfer.h" + +#include +#include +#include + +namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 +{ + +//! The NVLink fabric transport: each claimed chunk (one fabric allocation of the donor) is imported and mapped into +//! this process's device, and pages are copied on the caller's stream. Donors publish one CUmemFabricHandle per chunk +//! in donor..fabric. +//! +//! Not a BaseTransferAgent: a TransferRequest and its TransferStatus carry no CUDA stream, so a copy behind one would +//! conclude on the host, and every batch would synchronize the stream between the cold-page codec and the copy. Once +//! mapped, a chunk is device-addressable memory with no remote agent to load (MemoryType has no fabric kind either). +class FabricTransferBackend final : public RemoteTransferBackend +{ +public: + //! Needs the device's primary context current on the calling thread. + FabricTransferBackend(); + //! Synchronizes the context, then unmaps and releases every chunk. + ~FabricTransferBackend() override; + + FabricTransferBackend(FabricTransferBackend const&) = delete; + FabricTransferBackend& operator=(FabricTransferBackend const&) = delete; + + [[nodiscard]] char const* kind() const noexcept override + { + return "fabric"; + } + + [[nodiscard]] char const* payloadSuffix() const noexcept override + { + return "fabric"; + } + + [[nodiscard]] bool acceptPayload(RemoteDonor const& donor) const override; + //! Imports the chunk and maps it whole, readable and writable by this device; returns the device address. + uint64_t attachChunk(RemoteDonor& donor, size_t chunk) override; + + [[nodiscard]] bool streamOrdered() const noexcept override + { + return true; + } + + //! Enqueues the copies on `stream`, merging runs that are contiguous on both sides within one mapped chunk; the + //! attempt concludes at once, with the enqueue's outcome, and quiesces when the stream has run them. + [[nodiscard]] std::unique_ptr submit(bool write, std::vector const& donors, + std::vector const& ios, size_t bytes, CUstream stream) override; + + void drain() noexcept override; + +private: + //! One imported, mapped fabric chunk: unmapped, its address range freed and its handle released on close. + struct FabricMapping + { + CUdeviceptr address = 0; + size_t bytes = 0; + CUmemGenericAllocationHandle handle = 0; + }; + + //! Unmap and release what the constructor and the claims acquired; the destructor and a failed constructor run it. + void release() noexcept; + //! Synchronize mContext, where callers enqueue their copies. + [[nodiscard]] CUresult synchronizeContext() const noexcept; + + CUdevice mDevice = 0; + CUcontext mContext = nullptr; // mDevice's primary context, retained + std::vector mMappings; // every mapped chunk + std::map mMappingEnd; // start -> end of every mapped chunk +}; + +} // namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storageManager.cpp b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storageManager.cpp index 9588f392ed46..c7b1924ecd7d 100644 --- a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storageManager.cpp +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storageManager.cpp @@ -23,6 +23,8 @@ #include "kv_cache_manager_v2/exceptions.h" #include "kv_cache_manager_v2/page.h" #include "kv_cache_manager_v2/stagingBuffer.h" +#include "kv_cache_manager_v2/storage/remoteMem.h" +#include "kv_cache_manager_v2/utils/copyUtils.h" #include "kv_cache_manager_v2/utils/funcGuard.h" #include "kv_cache_manager_v2/utils/hostMem.h" #include "kv_cache_manager_v2/utils/math.h" @@ -30,14 +32,18 @@ #include "tensorrt_llm/common/assert.h" #include +#include #include #include #include #include +#include #include #include +#include #include #include +#include namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 { @@ -105,14 +111,15 @@ PoolGroupIndex LifeCyclePoolGroupMapping::numPoolGroups() const noexcept CacheLevelManager::CacheLevelManager(TypedVec const& lifeCycleGrouping, CacheLevel cl, CacheTierConfig const& tierConfig, TypedVec const& slotDescList, TypedVec const& slotCountList, PooledPhysMemAllocator* gpuPhysMemAllocator, - HostMemBackingOptions const& options, std::optional sparseReservation) + HostMemBackingOptions const& options, std::optional sparseReservation, + SharedPtr remoteClient) : cacheLevel(cl) - , cacheTier(CacheTier(tierConfig.index())) + , cacheTier(cacheTierOf(tierConfig)) , controller(lifeCycleGrouping, cl) { TLLM_CHECK((cacheTier == CacheTier::GPU_MEM) == (gpuPhysMemAllocator != nullptr)); - storage = createCacheLevelStorage( - tierConfig, slotDescList, slotCountList, gpuPhysMemAllocator, options, sparseReservation); + storage = createCacheLevelStorage(tierConfig, slotDescList, slotCountList, gpuPhysMemAllocator, options, + sparseReservation, std::move(remoteClient)); } // --------------------------------------------------------------------------- @@ -127,6 +134,32 @@ bool isGpuAccessibleMemory(CacheTier tier) noexcept return tier == CacheTier::GPU_MEM || tier == CacheTier::HOST_MEM; } +bool isRemoteTier(CacheTierConfig const& tier) noexcept +{ + return std::holds_alternative(tier); +} + +//! A remote level's own split of its quota across layer groups (RemoteCacheTierConfig::poolRatio), normalized; +//! nullopt where the level follows the hot level's ratio. Throws when the entry count is not one per layer group. +std::optional> remotePoolRatioOf(CacheTierConfig const& tier, LifeCycleId numLifeCycles) +{ + auto const* remote = std::get_if(&tier); + if (remote == nullptr || remote->poolRatio.empty()) + { + return std::nullopt; + } + auto const& weights = remote->poolRatio; + TLLM_CHECK_WITH_INFO(weights.size() == toSizeT(numLifeCycles), + "remote pool ratio: %zu entries for %zu layer groups", weights.size(), toSizeT(numLifeCycles)); + double const sum = std::accumulate(weights.begin(), weights.end(), 0.0); + TypedVec ratio(numLifeCycles, 0.F); + for (LifeCycleId lc{0}; lc < numLifeCycles; ++lc) + { + ratio[lc] = static_cast(weights[toSizeT(lc)] / sum); + } + return ratio; +} + // The host sparse pool quota an unset configuration gets: 80% of the host memory the host // tiers' quotas leave. Host tiers configured past physical memory leave none. size_t defaultHostSparsePoolQuota(TypedVec const& cacheTiers) @@ -176,6 +209,22 @@ TypedVec> computeSlotToPageIndices(Storage return result; } +SlotId toSlotId(int32_t pageIndex) +{ + TLLM_CHECK_DEBUG(pageIndex >= 0); + return SlotId{pageIndex}; +} + +//! Drop a page-index buffer kept across calls (thread_local) once a large batch has grown it past 1 MiB. +void trimRetainedPageIndices(std::vector& pageIndices) +{ + constexpr size_t kMaxRetainedPageIndexPairs = (1u << 20u) / sizeof(PageIndexPair); + if (pageIndices.capacity() > kMaxRetainedPageIndexPairs) + { + std::vector().swap(pageIndices); + } +} + void sortFallenPagesByPriority(TypedVec>>& fallenPages) { for (auto& pages : fallenPages) @@ -391,6 +440,14 @@ StorageManager::StorageManager(LifeCycleRegistry const& lifeCycles, StorageConfi auto const hotRatio = toPoolGroupRatio(kHotLevel, lifeCycleRatio); + // Checked before any level exists, so a malformed ratio fails construction before remote memory is claimed. + mHasRemoteLevel = std::any_of(config.cacheTiers.begin(), config.cacheTiers.end(), isRemoteTier); + TypedVec>> remotePoolRatios; + for (auto const& tier : config.cacheTiers) + { + remotePoolRatios.push_back(remotePoolRatioOf(tier, numLifeCycles())); + } + mLevels.reserve(config.cacheTiers.size()); // A sparse pool's hot pages are host memory. Its bytes are excluded from the GPU quota @@ -529,10 +586,24 @@ StorageManager::StorageManager(LifeCycleRegistry const& lifeCycles, StorageConfi } } + // A remote level with its own pool ratio takes that share of its own bytes per layer group (layer groups that + // share a cold pool group add up); it is a ratio of this level's bytes, so it is not projected from the hot level. + auto const levelShareRatio = [this](CacheLevel level, TypedVec const& shares) + { + TypedVec weights(numPoolGroups(level), 0.0); + for (LifeCycleId lc{0}; lc < numLifeCycles(); ++lc) + { + weights[getPoolGroupIndex(level, lc)] += static_cast(shares[lc]); + } + return normalizeToRatio(weights); + }; + for (CacheLevel level{1}; level < config.cacheTiers.size(); ++level) { TLLM_CHECK(appendLevelSlotDescList(coldSlotDescList) == level); - auto const coldRatio = projectPoolGroupRatio(kHotLevel, level, lifeCycleRatio); + auto const& remotePoolRatio = remotePoolRatios[level]; + auto const coldRatio = remotePoolRatio.has_value() ? levelShareRatio(level, *remotePoolRatio) + : projectPoolGroupRatio(kHotLevel, level, lifeCycleRatio); // No second budget: a cold group is a single pool holding whatever the codec packs // into it, dense and sparse buffers alike, so its quota pays for all of it. auto slotCounts = computeSlotCountForLevel( @@ -540,7 +611,8 @@ StorageManager::StorageManager(LifeCycleRegistry const& lifeCycles, StorageConfi auto* gpuPhysMemAllocator = cacheTierOf(config.cacheTiers[level]) == CacheTier::GPU_MEM ? mGpuPhysMemAllocator.get() : nullptr; mLevels.emplace_back(lifeCycleGrouping(level), level, config.cacheTiers[level], slotDescList(level), slotCounts, - gpuPhysMemAllocator, tierBackingOptions(config.cacheTiers[level], gpuGranularity)); + gpuPhysMemAllocator, tierBackingOptions(config.cacheTiers[level], gpuGranularity), std::nullopt, + remoteClientFor(config.cacheTiers[level])); } for (CacheLevel level{0}; level < mLevels.size(); ++level) @@ -556,6 +628,126 @@ StorageManager::StorageManager(LifeCycleRegistry const& lifeCycles, StorageConfi } mCopyEngine = std::make_unique(mPageStagingManager.get()); + + // A remote level moves its pages between the page staging buffer and remote memory, so the staging buffer is + // registered with each client once, for the life of this manager. + for (auto const& client : mRemoteClients) + { + TLLM_CHECK_WITH_INFO(mPageStagingManager != nullptr, "A remote cache level needs page staging"); + client->registerLocal(mPageStagingManager->baseAddress(), mPageStagingManager->totalSize()); + } + mLastLiveLevel = numCacheLevels() - 1; +} + +SharedPtr StorageManager::remoteClientFor(CacheTierConfig const& tier) +{ + auto const* remote = std::get_if(&tier); + if (remote == nullptr) + { + return nullptr; + } + RemoteMemOptions options{remote->path, remote->waitTimeoutMs, remote->expectedDonors}; + for (auto const& client : mRemoteClients) + { + if (client->directory() != remote->path) + { + continue; + } + TLLM_CHECK_WITH_INFO(client->options() == options && client->transferConfig() == remote->transfer, + "remote cache levels sharing rendezvous directory '%s' must use the same timeouts, transport, devices and " + "expected donors", + remote->path.c_str()); + return client; + } + return mRemoteClients.emplace_back(makeRemoteMemClient(std::move(options), remote->transfer)); +} + +RemoteCacheLevelStorage* StorageManager::remoteLevel(CacheLevel level) const +{ + auto const& lvl = mLevels.at(level); + return lvl.cacheTier == CacheTier::REMOTE ? static_cast(lvl.storage.get()) : nullptr; +} + +bool StorageManager::anyRemoteLevelFailed() const noexcept +{ + return std::any_of( + mRemoteClients.begin(), mRemoteClients.end(), [](auto const& client) { return client->failed(); }); +} + +size_t StorageManager::numFailedRemoteClients() const noexcept +{ + return static_cast(std::count_if( + mRemoteClients.begin(), mRemoteClients.end(), [](auto const& client) { return client->failed(); })); +} + +bool StorageManager::remoteLevelFailed(CacheLevel level) const +{ + // One flag per client while none has failed: this runs whenever a page is scheduled for eviction. + if (std::none_of(mRemoteClients.begin(), mRemoteClients.end(), [](auto const& client) { return client->failed(); })) + { + return false; + } + auto const* const remote = remoteLevel(level); + return remote != nullptr && remote->client().failed(); +} + +std::vector> StorageManager::queuedPages(CacheLevel level, PageStatus status) +{ + auto& controller = mLevels.at(level).controller; + std::vector> pages; + for (PoolGroupIndex pgIdx{0}; pgIdx < controller.numPoolGroups(); ++pgIdx) + { + auto next = controller.pageGenerator(pgIdx); + while (auto const* page = next()) + { + if ((*page)->status() == status) + { + pages.push_back(*page); + } + } + } + return pages; +} + +void StorageManager::dropPagesOfFailedRemoteLevels() +{ + if (!mUnquiescedRemoteTransfers.empty()) + { + reapQuiescedRemoteTransfers(); + } + for (CacheLevel level{1}; level < numCacheLevels(); ++level) + { + if (!remoteLevelFailed(level)) + { + continue; + } + auto const dropped = queuedPages(level, PageStatus::DROPPABLE); + for (auto const& page : dropped) + { + excludeFromEviction(*page); + } + if (!dropped.empty()) + { + TLLM_LOG_WARNING( + "KVCM2 remote level %d failed: dropped its %zu cached page(s)", level.value(), dropped.size()); + } + // `dropped` holds the last references: the pages leave the radix tree and release their slots here. + } + // Trailing failed levels take no pages, so held pages above them stop being evictable: they would only fall + // into a level that cannot hold them. + CacheLevel lastLive = numCacheLevels() - 1; + while (lastLive > kHotLevel && remoteLevelFailed(lastLive)) + { + --lastLive; + } + if (lastLive < mLastLiveLevel) + { + mLastLiveLevel = lastLive; + for (auto const& page : queuedPages(lastLive, PageStatus::HELD)) + { + excludeFromEviction(*page); + } + } } StorageManager::~StorageManager() @@ -565,6 +757,36 @@ StorageManager::~StorageManager() void StorageManager::destroy() { + // A transfer that missed its deadline gets one more transfer timeout to quiesce. One that still has not may yet + // access its staging lease, its chunks and its client's registrations: all of them are leaked rather than reused. + bool leakStaging = false; + for (auto& transfer : mUnquiescedRemoteTransfers) + { + auto const deadline = remoteDeadlineAfter(transfer.client->transferConfig().timeoutMs); + while (!transfer.attempt->quiesced() && std::chrono::steady_clock::now() < deadline) + { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + if (!transfer.attempt->quiesced()) + { + TLLM_LOG_ERROR( + "KVCM2 remote level %s: a transfer never quiesced; its staging, claims and transport are leaked", + transfer.client->directory().c_str()); + transfer.client->abandon(); + static_cast(transfer.attempt.release()); + static_cast(transfer.staging.release()); + leakStaging = true; + } + } + mUnquiescedRemoteTransfers.clear(); + // Before the levels go: the last level holding a client destroys it, and the staging must be deregistered first, + // after every stream-ordered transfer that uses it has finished. + for (auto const& client : mRemoteClients) + { + client->drain(); + client->deregisterLocal(mPageStagingManager->baseAddress(), mPageStagingManager->totalSize()); + } + mRemoteClients.clear(); for (auto& lvl : mLevels) { TLLM_CHECK_DEBUG(lvl.storage); @@ -575,9 +797,54 @@ void StorageManager::destroy() mIndexStagingManager.reset(); mCopyEngine.reset(); + if (leakStaging) + { + static_cast(mPageStagingManager.release()); + } mPageStagingManager.reset(); } +size_t StorageManager::reapQuiescedRemoteTransfers() noexcept +{ + auto const quiesced = [](UnquiescedRemoteTransfer& transfer) { return transfer.attempt->quiesced(); }; + mUnquiescedRemoteTransfers.erase( + std::remove_if(mUnquiescedRemoteTransfers.begin(), mUnquiescedRemoteTransfers.end(), quiesced), + mUnquiescedRemoteTransfers.end()); + return mUnquiescedRemoteTransfers.size(); +} + +void StorageManager::runRemoteTransfer(RemoteMemClient& client, bool write, std::vector const& ios, + size_t bytes, CUstream stream, std::unique_ptr& staging) +{ + auto attempt = client.submit(write, ios, bytes, stream); + if (client.streamOrdered()) + { + // Concluded at once; the staging lease, retired on the stream, is reused only after the copies have run. + auto const outcome = attempt->poll(); + if (!outcome.has_value() || !outcome->ok()) + { + client.fail(outcome.has_value() ? outcome->fault : "KVCM2 remote level: a transfer did not conclude"); + } + return; + } + int64_t const timeoutMs = client.transferConfig().timeoutMs; + auto const outcome = attempt->wait(timeoutMs); + if (!attempt->quiesced()) + { + mUnquiescedRemoteTransfers.push_back({std::move(attempt), std::move(staging), &client}); + } + if (!outcome.has_value()) + { + client.fail("KVCM2 remote level: a " + std::string(write ? "WRITE" : "READ") + " of " + + std::to_string(ios.size()) + " page(s) x " + std::to_string(bytes) + " B timed out after " + + std::to_string(timeoutMs) + " ms"); + } + if (!outcome->ok()) + { + client.fail(outcome->fault); + } +} + // --------------------------------------------------------------------------- // newSlots // --------------------------------------------------------------------------- @@ -678,6 +945,28 @@ Address StorageManager::slotAddress(CacheLevel level, PoolGroupIndex pgIdx, Slot return mLevels.at(level).storage->slotAddress(pgIdx, slotId).at(poolIdx); } +bool StorageManager::encodeColdPages( + LayerGroupId layerGroup, void* dstBase, PageIndexPair const* pageIndices, size_t numPages, CUstream stream) +{ + return submitColdPageCodec(mPageIndexLocations.at(layerGroup), pageIndices, numPages, stream, + [this, layerGroup, dstBase](PageIndexPair const* submitted, size_t submittedPages, CUstream submittedStream) + { + return mColdPageCodec->encode( + layerGroup, dstBase, submitted, submittedPages, reinterpret_cast(submittedStream)); + }); +} + +bool StorageManager::decodeColdPages( + LayerGroupId layerGroup, void const* srcBase, PageIndexPair const* pageIndices, size_t numPages, CUstream stream) +{ + return submitColdPageCodec(mPageIndexLocations.at(layerGroup), pageIndices, numPages, stream, + [this, layerGroup, srcBase](PageIndexPair const* submitted, size_t submittedPages, CUstream submittedStream) + { + return mColdPageCodec->decode( + layerGroup, srcBase, submitted, submittedPages, reinterpret_cast(submittedStream)); + }); +} + void StorageManager::submitMigrationBatch(CacheLevel dstLevel, CacheLevel srcLevel, LayerGroupId batchingLayerGroupId, PageIndexPair const* pageIndices, size_t numPages, CUstream stream) { @@ -689,14 +978,13 @@ void StorageManager::submitMigrationBatch(CacheLevel dstLevel, CacheLevel srcLev auto& srcPoolGroup = poolGroup(srcLevel, srcPgIdx); auto& dstPoolGroup = poolGroup(dstLevel, dstPgIdx); - auto toSlotId = [](int32_t pageIndex) - { - TLLM_CHECK_DEBUG(pageIndex >= 0); - return SlotId{pageIndex}; - }; - if (srcIsHot == dstIsHot) { + if (!srcIsHot && (remoteLevel(srcLevel) != nullptr || remoteLevel(dstLevel) != nullptr)) + { + submitRemoteColdMigration(dstLevel, srcLevel, dstPgIdx, srcPgIdx, pageIndices, numPages, stream); + return; + } auto const srcSizes = slotSize(srcLevel, srcPgIdx); TLLM_CHECK_DEBUG(srcSizes == slotSize(dstLevel, dstPgIdx)); for (PoolIndex poolIdx{0}; poolIdx < srcSizes.size(); ++poolIdx) @@ -719,35 +1007,24 @@ void StorageManager::submitMigrationBatch(CacheLevel dstLevel, CacheLevel srcLev return; } + if (remoteLevel(srcIsHot ? dstLevel : srcLevel) != nullptr) + { + submitRemoteHotMigration(dstLevel, srcLevel, batchingLayerGroupId, pageIndices, numPages, stream); + return; + } + CacheLevel const coldLevel = srcIsHot ? dstLevel : srcLevel; PoolGroupIndex const coldPgIdx = srcIsHot ? dstPgIdx : srcPgIdx; // Only a GPU-tier pool is ever host-backed, so for a cold level cacheTier() and // poolMedium() agree. CacheTier const coldTier = cacheTier(coldLevel); size_t const coldPageBytes = slotSize(coldLevel, coldPgIdx).at(PoolIndex{0}); - PageIndexLocation const pageIndexLocation = mPageIndexLocations.at(batchingLayerGroupId); - auto encodeBatch = [this, batchingLayerGroupId, pageIndexLocation]( + auto encodeBatch = [this, batchingLayerGroupId]( void* dstBasePtr, PageIndexPair const* indices, size_t count, CUstream batchStream) - { - return submitColdPageCodec(pageIndexLocation, indices, count, batchStream, - [this, batchingLayerGroupId, dstBasePtr]( - PageIndexPair const* submittedIndices, size_t submittedPages, CUstream submittedStream) - { - return mColdPageCodec->encode(batchingLayerGroupId, dstBasePtr, submittedIndices, submittedPages, - reinterpret_cast(submittedStream)); - }); - }; - auto decodeBatch = [this, batchingLayerGroupId, pageIndexLocation]( + { return encodeColdPages(batchingLayerGroupId, dstBasePtr, indices, count, batchStream); }; + auto decodeBatch = [this, batchingLayerGroupId]( void const* srcBasePtr, PageIndexPair const* indices, size_t count, CUstream batchStream) - { - return submitColdPageCodec(pageIndexLocation, indices, count, batchStream, - [this, batchingLayerGroupId, srcBasePtr]( - PageIndexPair const* submittedIndices, size_t submittedPages, CUstream submittedStream) - { - return mColdPageCodec->decode(batchingLayerGroupId, srcBasePtr, submittedIndices, submittedPages, - reinterpret_cast(submittedStream)); - }); - }; + { return decodeColdPages(batchingLayerGroupId, srcBasePtr, indices, count, batchStream); }; if (isGpuAccessibleMemory(coldTier)) { @@ -817,10 +1094,216 @@ void StorageManager::submitMigrationBatch(CacheLevel dstLevel, CacheLevel srcLev remaining -= batchSize; } - constexpr size_t kMaxRetainedPageIndexPairs = (1u << 20u) / sizeof(PageIndexPair); - if (stagingPageIndices.capacity() > kMaxRetainedPageIndexPairs) + trimRetainedPageIndices(stagingPageIndices); +} + +void StorageManager::submitRemoteHotMigration(CacheLevel dstLevel, CacheLevel srcLevel, + LayerGroupId batchingLayerGroupId, PageIndexPair const* pageIndices, size_t numPages, CUstream stream) +{ + TLLM_CHECK_WITH_INFO(mPageStagingManager != nullptr, "A remote cache level needs page staging"); + bool const srcIsHot = srcLevel == kHotLevel; + CacheLevel const coldLevel = srcIsHot ? dstLevel : srcLevel; + PoolGroupIndex const coldPgIdx = getPoolGroupIndex(coldLevel, batchingLayerGroupId); + size_t const coldPageBytes = slotSize(coldLevel, coldPgIdx).at(PoolIndex{0}); + auto encodeBatch = [this, batchingLayerGroupId]( + void* dstBasePtr, PageIndexPair const* indices, size_t count, CUstream batchStream) + { return encodeColdPages(batchingLayerGroupId, dstBasePtr, indices, count, batchStream); }; + auto decodeBatch = [this, batchingLayerGroupId]( + void const* srcBasePtr, PageIndexPair const* indices, size_t count, CUstream batchStream) + { return decodeColdPages(batchingLayerGroupId, srcBasePtr, indices, count, batchStream); }; + + // Kept across calls, as the disk path's: a migration batch reuses the previous one's allocation. + thread_local std::vector stagingPageIndices; + size_t remaining = numPages; + size_t offset = 0; + // Remote level: the codec runs against the page staging buffer, and the client moves the bytes between + // staging and the remote slots, on the stream or on the host (a failure then throws before _batchedMigrate + // points any page at its new slot). + RemoteRange& range = remoteLevel(coldLevel)->remoteRange(coldPgIdx, PoolIndex{0}); + RemoteMemClient& client = range.client(); + // Before any staging lease: a failed level's unquiesced transfer may hold all of it, and the lease would then fail + // with a plain exception instead of the RemoteMemError that costs only this request. + client.checkUsable(); + bool const streamOrdered = client.streamOrdered(); + std::vector ios; + while (remaining > 0) { - std::vector().swap(stagingPageIndices); + size_t const maxStagingBytes = remaining > std::numeric_limits::max() / coldPageBytes + ? std::numeric_limits::max() + : coldPageBytes * remaining; + ios.clear(); + if (srcIsHot) + { + // Hot -> remote: encode into staging on the stream, then WRITE once the encode is done. + auto staging = std::make_unique(*mPageStagingManager, coldPageBytes, maxStagingBytes, + coldPageBytes, 16, std::optional{stream}); + MemAddress const base = staging->address(); + size_t const batchSize = std::min(remaining, staging->size() / coldPageBytes); + stagingPageIndices.resize(batchSize); + for (size_t index = 0; index < batchSize; ++index) + { + stagingPageIndices[index] = PageIndexPair{static_cast(index), pageIndices[offset + index].src}; + } + TLLM_CHECK_WITH_INFO( + encodeBatch(reinterpret_cast(base), stagingPageIndices.data(), batchSize, stream), + "Cold-page codec rejected a migration batch"); + for (size_t index = 0; index < batchSize; ++index) + { + auto const [donor, remoteAddr] = range.locate(toSlotId(pageIndices[offset + index].dst)); + ios.push_back(RemoteIo{base + index * coldPageBytes, donor, remoteAddr}); + } + // Stream-ordered, the WRITE starts when the stream has encoded the batch and the lease retires after + // it; on the host, it waits for the encode. + if (!streamOrdered) + { + cuCheck(cuStreamSynchronize(stream)); + } + runRemoteTransfer(client, /*write=*/true, ios, coldPageBytes, stream, staging); + offset += batchSize; + remaining -= batchSize; + } + else + { + // Remote -> hot: READ into staging, then decode on the stream. Stream-ordered, the lease is the + // stream's from the start and the READ begins when the stream reaches it; on the host, the lease is + // host-synchronous and moves to the stream only after the READ has finished. + auto staging = std::make_unique(*mPageStagingManager, coldPageBytes, maxStagingBytes, + coldPageBytes, 16, streamOrdered ? std::optional{stream} : std::nullopt); + MemAddress const base = staging->address(); + size_t const batchSize = std::min(remaining, staging->size() / coldPageBytes); + for (size_t index = 0; index < batchSize; ++index) + { + auto const [donor, remoteAddr] = range.locate(toSlotId(pageIndices[offset + index].src)); + ios.push_back(RemoteIo{base + index * coldPageBytes, donor, remoteAddr}); + } + runRemoteTransfer(client, /*write=*/false, ios, coldPageBytes, stream, staging); + if (!streamOrdered) + { + staging->setStream(stream); + } + stagingPageIndices.resize(batchSize); + for (size_t index = 0; index < batchSize; ++index) + { + stagingPageIndices[index] = PageIndexPair{pageIndices[offset + index].dst, static_cast(index)}; + } + TLLM_CHECK_WITH_INFO( + decodeBatch(reinterpret_cast(base), stagingPageIndices.data(), batchSize, stream), + "Cold-page codec rejected a migration batch"); + offset += batchSize; + remaining -= batchSize; + } + } + trimRetainedPageIndices(stagingPageIndices); +} + +void StorageManager::submitRemoteColdMigration(CacheLevel dstLevel, CacheLevel srcLevel, PoolGroupIndex dstPgIdx, + PoolGroupIndex srcPgIdx, PageIndexPair const* pageIndices, size_t numPages, CUstream stream) +{ + TLLM_CHECK_WITH_INFO(mPageStagingManager != nullptr, "A remote cache level needs page staging"); + auto* const srcRemote = remoteLevel(srcLevel); + auto* const dstRemote = remoteLevel(dstLevel); + auto const sizes = slotSize(srcLevel, srcPgIdx); + TLLM_CHECK_DEBUG(sizes == slotSize(dstLevel, dstPgIdx)); + auto& srcGroup = poolGroup(srcLevel, srcPgIdx); + auto& dstGroup = poolGroup(dstLevel, dstPgIdx); + // Cold levels hold one pool per group (the codec's single cold page), but nothing here depends on it. + for (PoolIndex poolIdx{0}; poolIdx < sizes.size(); ++poolIdx) + { + size_t const pageBytes = sizes.at(poolIdx); + RemoteRange* const srcRange = srcRemote != nullptr ? &srcRemote->remoteRange(srcPgIdx, poolIdx) : nullptr; + RemoteRange* const dstRange = dstRemote != nullptr ? &dstRemote->remoteRange(dstPgIdx, poolIdx) : nullptr; + // The local side is copied to or from staging by the GPU's batched copy kernel, which needs memory the GPU + // can address (the host level's pinned pages are). + TLLM_CHECK_WITH_INFO(srcRange != nullptr || isGpuAccessibleMemory(poolMedium(srcLevel, srcPgIdx, poolIdx)), + "Remote level: unsupported source medium"); + TLLM_CHECK_WITH_INFO(dstRange != nullptr || isGpuAccessibleMemory(poolMedium(dstLevel, dstPgIdx, poolIdx)), + "Remote level: unsupported destination medium"); + // Stream-ordered only if every remote side's transfers are: the legs (and the local copies) then follow one + // another on the stream. + bool const streamOrdered = (srcRange == nullptr || srcRange->client().streamOrdered()) + && (dstRange == nullptr || dstRange->client().streamOrdered()); + // Before any staging lease, as in submitRemoteHotMigration. + for (RemoteRange const* remoteRange : {srcRange, dstRange}) + { + if (remoteRange != nullptr) + { + remoteRange->client().checkUsable(); + } + } + std::vector ios; + std::vector> tasks; + size_t remaining = numPages; + size_t offset = 0; + while (remaining > 0) + { + size_t const maxStagingBytes = remaining > std::numeric_limits::max() / pageBytes + ? std::numeric_limits::max() + : pageBytes * remaining; + // Stream-ordered: the stream's lease, so every leg below is ordered after the range's previous users. + // On the host: a host-synchronous lease, nothing else is using this range of staging once acquire returns. + auto staging = std::make_unique(*mPageStagingManager, pageBytes, maxStagingBytes, pageBytes, + 16, streamOrdered ? std::optional{stream} : std::nullopt); + size_t const batchSize = std::min(remaining, staging->size() / pageBytes); + MemAddress const base = staging->address(); + + // 1. Source pages into staging. + if (srcRange != nullptr) + { + ios.clear(); + for (size_t index = 0; index < batchSize; ++index) + { + auto const [donor, remoteAddr] = srcRange->locate(toSlotId(pageIndices[offset + index].src)); + ios.push_back(RemoteIo{base + index * pageBytes, donor, remoteAddr}); + } + runRemoteTransfer(srcRange->client(), /*write=*/false, ios, pageBytes, stream, staging); + } + else + { + tasks.clear(); + for (size_t index = 0; index < batchSize; ++index) + { + tasks.push_back({base + index * pageBytes, + std::get( + srcGroup.slotAddress(toSlotId(pageIndices[offset + index].src)).at(poolIdx))}); + } + // The stream already waits for the source pages' writers; the copy kernel reads host memory over C2C. + staging->setStream(stream); + cuCheck(copyHostToDevice(tasks, static_cast(pageBytes), stream)); + if (!streamOrdered) + { + cuCheck(cuStreamSynchronize(stream)); + } + } + + // 2. Staging into the destination pages. + if (dstRange != nullptr) + { + ios.clear(); + for (size_t index = 0; index < batchSize; ++index) + { + auto const [donor, remoteAddr] = dstRange->locate(toSlotId(pageIndices[offset + index].dst)); + ios.push_back(RemoteIo{base + index * pageBytes, donor, remoteAddr}); + } + // Stream-ordered, starts when the stream has the source bytes in staging; on the host, they are there. + runRemoteTransfer(dstRange->client(), /*write=*/true, ios, pageBytes, stream, staging); + } + else + { + tasks.clear(); + for (size_t index = 0; index < batchSize; ++index) + { + tasks.push_back({std::get( + dstGroup.slotAddress(toSlotId(pageIndices[offset + index].dst)).at(poolIdx)), + base + index * pageBytes}); + } + // On the host: the READ above has finished, so handing the lease to the stream needs no + // synchronization. Stream-ordered: the lease is the stream's already, and the copy waits for the READ. + staging->setStream(stream); + cuCheck(copyHostToDevice(tasks, static_cast(pageBytes), stream)); + } + offset += batchSize; + remaining -= batchSize; + } } } @@ -873,7 +1356,8 @@ bool StorageManager::isEvictable(Page const& page, std::optional lev auto const& committed = static_cast(page); return committed.block && !committed.block->isOrphan() && committed.block->holdsPage(committed); } - return s == PageStatus::HELD && lvl < numCacheLevels() - 1; + // A held page cannot drop, so it is evictable only with a level below it that still takes pages. + return s == PageStatus::HELD && lvl < mLastLiveLevel; } // --------------------------------------------------------------------------- @@ -882,7 +1366,8 @@ bool StorageManager::isEvictable(Page const& page, std::optional lev void StorageManager::scheduleForEviction(Page& page) { - if (isEvictable(page)) + // A droppable page on a failed remote level is left unscheduled, so it drops with its last reference. + if (isEvictable(page) && !(page.status() == PageStatus::DROPPABLE && remoteLevelFailed(page.cacheLevel))) { mLevels.at(page.cacheLevel).controller.scheduleForEviction(page); scheduleRetentionExpiry(page); @@ -993,7 +1478,46 @@ void StorageManager::prepareFreeSlots(CacheLevel level, TypedVec StorageManager::takeNewlyFailedRemoteLevels() +{ + std::vector levels; + if (std::none_of(mRemoteClients.begin(), mRemoteClients.end(), [](auto const& client) { return client->failed(); })) + { + return levels; + } + dropPagesOfFailedRemoteLevels(); + for (CacheLevel level{1}; level < numCacheLevels(); ++level) + { + if (remoteLevelFailed(level) + && std::find(mRetiredRemoteLevels.begin(), mRetiredRemoteLevels.end(), level) == mRetiredRemoteLevels.end()) + { + mRetiredRemoteLevels.push_back(level); + levels.push_back(level); + } + } + return levels; } void StorageManager::_prepareFreeSlots(CacheLevel level, TypedVec const& requirements, @@ -1010,16 +1534,20 @@ void StorageManager::_prepareFreeSlots(CacheLevel level, TypedVec> keepAlive; + _prepareFreeSlots(goals, level, fallenPages, keepAlive, migrationRecorder, dropRecorder); } void StorageManager::forceEvict( CacheLevel level, TypedVec const& minNumPages, DropRecorder const& dropRecorder) { + // Declared before the rollback guard, so that the pages they hold outlive it on failure. + PagesByLifeCycle fallen(numLifeCycles()); + std::vector> keepAlive; auto evicted = mLevels.at(level).controller.evict(minNumPages); auto rescheduleEvictedPagesOnFailure = makeEvictionRollbackGuard(evicted); - if (isLastLevel(level)) + if (isLastLiveLevel(level)) { // Last level: all evicted pages must be DROPPABLE (they get dropped, not migrated). for (auto const& pages : evicted) @@ -1050,7 +1578,6 @@ void StorageManager::forceEvict( } CacheLevel nextLvl = level + 1; - PagesByLifeCycle fallen(numLifeCycles()); for (PoolGroupIndex pgIdx{0}; pgIdx < evicted.size(); ++pgIdx) { for (auto& sp : evicted.at(pgIdx)) @@ -1060,7 +1587,7 @@ void StorageManager::forceEvict( } } sortFallenPagesByPriority(fallen); - _prepareFreeSlots(goals, nextLvl, fallen, MigrationRecorder{}, dropRecorder); + _prepareFreeSlots(goals, nextLvl, fallen, keepAlive, MigrationRecorder{}, dropRecorder); rescheduleEvictedPagesOnFailure.cancel(); } @@ -1069,8 +1596,8 @@ void StorageManager::forceEvict( // --------------------------------------------------------------------------- void StorageManager::_prepareFreeSlots(TypedVec>& goals, - CacheLevel lvlId, PagesByLifeCycle& fallenPages, MigrationRecorder const& migrationRecorder, - DropRecorder const& dropRecorder) + CacheLevel lvlId, PagesByLifeCycle& fallenPages, std::vector>& keepAlive, + MigrationRecorder const& migrationRecorder, DropRecorder const& dropRecorder) { TypedVec>> belowOffloadThreshold(numLifeCycles()); auto restoreBelowThreshold = FuncGuard( @@ -1130,7 +1657,11 @@ void StorageManager::_prepareFreeSlots(TypedVec oldFree ? required - oldFree : 0; numToEvict.at(pgIdx) = std::min(shortage, evictableCount); @@ -1228,7 +1759,7 @@ void StorageManager::_prepareFreeSlots(TypedVec= numEvicted + oldFree); TLLM_CHECK_DEBUG_WITH_INFO( countPages(pgIdx, heldPages) <= freeAfterEviction, "held_pages count exceeds new free slot count"); @@ -1269,7 +1800,23 @@ void StorageManager::_prepareFreeSlots(TypedVec>> byLevel; + for (auto const& page : rejected) + { + byLevel[page->cacheLevel].push_back(page); + } + for (auto const& [fromLevel, pages] : byLevel) + { + dropRecorder(pages, fromLevel); + } + } + rejected.clear(); } } else @@ -1284,10 +1831,16 @@ void StorageManager::_prepareFreeSlots(TypedVec> StorageManager::_batchedMigrate(CacheLevel dstL } updateReadyEvents.run(); - constexpr size_t kMaxRetainedPageIndexPairs = (1u << 20u) / sizeof(PageIndexPair); - if (pageIndices.capacity() > kMaxRetainedPageIndexPairs) - { - std::vector().swap(pageIndices); - } + trimRetainedPageIndices(pageIndices); if (migrationRecorder && !defrag) { migrationRecorder(srcPages, dstSlots, srcLevel, dstLevel); diff --git a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storageManager.h b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storageManager.h index ef1c4099c75d..4668cb772acf 100644 --- a/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storageManager.h +++ b/cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/storageManager.h @@ -43,6 +43,7 @@ namespace tensorrt_llm::batch_manager::kv_cache_manager_v2 class Page; class KvCache; class CopyEngine; +class StagingBuffer; class StagingBufferManager; using MigrationRecorder @@ -101,7 +102,8 @@ class CacheLevelManager CacheLevelManager(TypedVec const& lifeCycleGrouping, CacheLevel cacheLevel, CacheTierConfig const& tierConfig, TypedVec const& slotDescList, TypedVec const& slotCountList, PooledPhysMemAllocator* gpuPhysMemAllocator = nullptr, - HostMemBackingOptions const& options = {}, std::optional sparseReservation = std::nullopt); + HostMemBackingOptions const& options = {}, std::optional sparseReservation = std::nullopt, + SharedPtr remoteClient = nullptr); CacheLevel cacheLevel; CacheTier cacheTier; @@ -177,10 +179,20 @@ class StorageManager : public std::enable_shared_from_this // Check if a page is evictable (optionally at a target level). bool isEvictable(Page const& page, std::optional level = std::nullopt) const noexcept; - // Ensure the requested free slots exist at this level (evicting pages as needed). + // Ensure the requested free slots exist at this level (evicting pages as needed). A remote level that fails an + // eviction WRITE is retired and the eviction retried past it. void prepareFreeSlots(CacheLevel level, TypedVec const& requirements, MigrationRecorder const& migrationRecorder = {}, DropRecorder const& dropRecorder = {}); + //! Remote levels that failed since the last call, each returned once, after their evictable pages are dropped. + //! The caller unlinks the pages still held there from the radix tree, so that reuse no longer finds them. + [[nodiscard]] std::vector takeNewlyFailedRemoteLevels(); + //! Whether any remote level failed (a transfer, or a claim from a donor that went away). Cheap: one atomic flag + //! per client, read without the manager lock. + [[nodiscard]] bool anyRemoteLevelFailed() const noexcept; + //! How many remote clients have failed; only grows. Lock-free, like anyRemoteLevelFailed(). + [[nodiscard]] size_t numFailedRemoteClients() const noexcept; + // Force-evict pages from a level to free space. void forceEvict(CacheLevel level, TypedVec const& minNumPages, DropRecorder const& dropRecorder = {}); @@ -201,7 +213,8 @@ class StorageManager : public std::enable_shared_from_this // Best-effort migration of grouped pages to a destination cache level. Returns how many pages // it moved off the disk tier, counted per migrated batch rather than per page. A throw reports - // nothing, which in practice means slot preparation failed before anything moved. + // nothing, which in practice means slot preparation failed before anything moved. Pages moved + // off a remote level are not counted: the disk prefetch statistic stays disk-only. int64_t prefetch( CacheLevel dstLevel, TypedVec>>> const& pages); @@ -254,6 +267,22 @@ class StorageManager : public std::enable_shared_from_this return lvl == numCacheLevels() - 1; } + //! Whether evicted pages stop at `lvl`: the last level, or the last one above trailing failed remote levels. + bool isLastLiveLevel(CacheLevel lvl) const noexcept + { + return lvl >= mLastLiveLevel; + } + + //! Whether a cold level keeps its slots in remote memory (RemoteCacheTierConfig). + [[nodiscard]] bool hasRemoteLevel() const noexcept + { + return mHasRemoteLevel; + } + + //! Release the staging leases of remote transfers that have quiesced since their deadline; returns how many + //! remain out of use. + size_t reapQuiescedRemoteTransfers() noexcept; + PoolGroupIndex getPoolGroupIndex(CacheLevel level, LifeCycleId lc) const; PoolGroupIndex getPoolGroupIndex(LifeCycleId lc) const; PoolIndex numPools(CacheLevel level, PoolGroupIndex pgIdx) const; @@ -450,9 +479,12 @@ class StorageManager : public std::enable_shared_from_this void _prepareFreeSlots(CacheLevel level, TypedVec const& requirements, MigrationRecorder const& migrationRecorder, DropRecorder const& dropRecorder); + //! `keepAlive` collects the pages each level accepts for migration. A frame's own containers die as an exception + //! unwinds it, before the rollback guards of the frames above run; whoever owns `keepAlive` keeps those pages + //! alive until then, so that the guards can put them back. void _prepareFreeSlots(TypedVec>& goals, CacheLevel lvlId, - PagesByLifeCycle& fallenPages, MigrationRecorder const& migrationRecorder = {}, - DropRecorder const& dropRecorder = {}); + PagesByLifeCycle& fallenPages, std::vector>& keepAlive, + MigrationRecorder const& migrationRecorder = {}, DropRecorder const& dropRecorder = {}); std::optional> _batchedMigrate(CacheLevel dstLevel, CacheLevel srcLevel, std::vector> const& srcPages, bool updateSrc, MigrationRecorder const& migrationRecorder = {}, @@ -462,9 +494,41 @@ class StorageManager : public std::enable_shared_from_this void submitMigrationBatch(CacheLevel dstLevel, CacheLevel srcLevel, LayerGroupId batchingLayerGroupId, PageIndexPair const* pageIndices, size_t numPages, CUstream stream); + //! The level's storage when it is a remote level (storage/remoteMem.h), else null. + [[nodiscard]] RemoteCacheLevelStorage* remoteLevel(CacheLevel level) const; + //! Whether `level` is a remote level whose client failed a transfer: it takes and gives up no pages. + [[nodiscard]] bool remoteLevelFailed(CacheLevel level) const; + //! Drop the evictable pages of every failed remote level, which could not be read back, so reuse no longer finds + //! them. Pages a request holds stay until it lets go of them (scheduleForEviction then drops them). + void dropPagesOfFailedRemoteLevels(); + //! The pages of `level`'s eviction queues with `status`, collected before any leaves a queue. + [[nodiscard]] std::vector> queuedPages(CacheLevel level, PageStatus status); + //! Run one remote transfer of a migration batch and act on its outcome: stream-ordered, the enqueue's; on the + //! host, waited for up to the transfer timeout, and a transfer not quiesced by then keeps `staging` out of use. + //! A fault or timeout fails the client (RemoteMemError). + void runRemoteTransfer(RemoteMemClient& client, bool write, std::vector const& ios, size_t bytes, + CUstream stream, std::unique_ptr& staging); + //! The client of a remote tier's rendezvous directory, created on first use; null for any other tier. + SharedPtr remoteClientFor(CacheTierConfig const& tier); + //! A hot-to-remote or remote-to-hot migration: the cold-page codec runs against the page-staging buffer and the + //! remote level's client moves the bytes. Separate from the disk path. + void submitRemoteHotMigration(CacheLevel dstLevel, CacheLevel srcLevel, LayerGroupId batchingLayerGroupId, + PageIndexPair const* pageIndices, size_t numPages, CUstream stream); + //! A cold-to-cold migration where either side is a remote level, through the page-staging buffer. A failed + //! transfer on the host throws RemoteMemError before any page is pointed at its new slot. + void submitRemoteColdMigration(CacheLevel dstLevel, CacheLevel srcLevel, PoolGroupIndex dstPgIdx, + PoolGroupIndex srcPgIdx, PageIndexPair const* pageIndices, size_t numPages, CUstream stream); + template bool submitColdPageCodec(PageIndexLocation location, PageIndexPair const* pageIndices, size_t numPages, CUstream stream, Submit&& submit); + //! Encode hot pages (PageIndexPair::src) of `layerGroup` into cold pages at `dstBase` (PageIndexPair::dst), the + //! cold level's base or a staging buffer; false if the codec rejects the batch. + bool encodeColdPages( + LayerGroupId layerGroup, void* dstBase, PageIndexPair const* pageIndices, size_t numPages, CUstream stream); + //! The reverse of encodeColdPages: cold pages at `srcBase` (src) into hot pages (dst). + bool decodeColdPages(LayerGroupId layerGroup, void const* srcBase, PageIndexPair const* pageIndices, + size_t numPages, CUstream stream); PoolGroupBase& poolGroup(CacheLevel lvl, PoolGroupIndex pgIdx); @@ -501,6 +565,26 @@ class StorageManager : public std::enable_shared_from_this // Optional model-sized page staging is owned here and borrowed by CopyEngine. std::unique_ptr mPageStagingManager; std::unique_ptr mCopyEngine; + // One remote-memory client per rendezvous directory, shared by this manager's levels that name it. The page + // staging buffer is registered with each and deregistered before the staging is freed. + std::vector> mRemoteClients; + + //! A host-concluded remote transfer that had not quiesced by its deadline, and the staging lease it may still + //! access: kept out of use until it quiesces (reapQuiescedRemoteTransfers), leaked with its client at teardown + //! if it never does. + struct UnquiescedRemoteTransfer + { + std::unique_ptr attempt; + std::unique_ptr staging; + RemoteMemClient* client; + }; + + std::vector mUnquiescedRemoteTransfers; + bool mHasRemoteLevel = false; + // The deepest level that still takes pages: the last level, until trailing remote levels fail. + CacheLevel mLastLiveLevel{0}; + // Failed remote levels takeNewlyFailedRemoteLevels() has returned. + std::vector mRetiredRemoteLevels; // Get buffer attributes for a (LayerId, DataRole) pair. Throws std::out_of_range if not found. // Mirrors Python's get_buffer_attr(). diff --git a/cpp/tensorrt_llm/kernels/customAllReduceKernels.cu b/cpp/tensorrt_llm/kernels/customAllReduceKernels.cu index ea217d465be1..cdf1480b0974 100644 --- a/cpp/tensorrt_llm/kernels/customAllReduceKernels.cu +++ b/cpp/tensorrt_llm/kernels/customAllReduceKernels.cu @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024, NVIDIA CORPORATION. All rights reserved. + * Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ #include "tensorrt_llm/common/tllmDataType.h" #include #include +#include #include #include @@ -272,11 +273,25 @@ inline __device__ int4 rms_norm(float denom, PackedStruct& vec, PackedStruct& we return ret.packed; } -template -__global__ void rms_norm_kernel(AllReduceParams params) +// The optional per-tensor E4M3 epilogue of rms_norm_kernel (QuantFp8): quant_out [tokens, hidden] and the device +// scale [1]; each output is scaleMatrixPerTensorVec's, satfinite(FP32(norm) x (1 / scale)). +struct RmsNormQuantFp8Params +{ + __nv_fp8_e4m3* quant_out = nullptr; + float const* scale = nullptr; +}; + +// Residual add + RMSNorm, one CTA per token. QuantFp8: also the norm's per-tensor E4M3 quantization (BF16 only), so +// the outputs equal this kernel's norm followed by the static per-tensor quantize bit for bit; WriteNorm: store the +// norm output (only a QuantFp8 launch may skip it). +template +__global__ void rms_norm_kernel(AllReduceParams params, RmsNormQuantFp8Params quant) { static constexpr int kPackedSize = details::kBytesPerAccess / sizeof(T); using PackedStruct = typename PackedOn16Bytes::Type; + static_assert(WriteNorm || QuantFp8, "a launch without the norm output must quantize"); + static_assert(!QuantFp8 || std::is_same_v, "the FP8 epilogue takes BF16"); extern __shared__ uint8_t smem_ptr[]; T* smem = reinterpret_cast(smem_ptr); @@ -289,7 +304,7 @@ __global__ void rms_norm_kernel(AllReduceParams params) T* local_final_output_buffer = reinterpret_cast(params.local_output_buffer_ptr); T* intermediate_buffer = reinterpret_cast(params.fusion_params.intermediate_buffer); - int block_offset = bid * params.fusion_params.hidden_size; + size_t block_offset = static_cast(bid) * params.fusion_params.hidden_size; int thread_offset = tid * kPackedSize; if constexpr (Residual) @@ -340,7 +355,26 @@ __global__ void rms_norm_kernel(AllReduceParams params) weight_vec.packed = *reinterpret_cast(weight_buffer + offset); } inter_vec.packed = rms_norm(denom, inter_vec, weight_vec); - *reinterpret_cast(&local_final_output_buffer[offset]) = inter_vec.packed; + if constexpr (WriteNorm) + { + *reinterpret_cast(&local_final_output_buffer[offset]) = inter_vec.packed; + } + if constexpr (QuantFp8) + { + float const factor = 1.0f / quant.scale[0]; + __nv_bfloat162 const* pairs = reinterpret_cast<__nv_bfloat162 const*>(&inter_vec.packed); + __nv_fp8x2_storage_t fp8_pairs[kPackedSize / 2]; +#pragma unroll + for (int p = 0; p < kPackedSize / 2; ++p) + { + float2 f2 = __bfloat1622float2(pairs[p]); + f2.x *= factor; + f2.y *= factor; + fp8_pairs[p] = __nv_cvt_float2_to_fp8x2(f2, __NV_SATFINITE, __NV_E4M3); + } + *reinterpret_cast(quant.quant_out + block_offset + offset) + = *reinterpret_cast(fp8_pairs); + } } #if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900) && (__CUDA_ARCH__ < 1200)) cudaTriggerProgrammaticLaunchCompletion(); @@ -431,11 +465,15 @@ __global__ void rms_pre_post_norm_kernel(AllReduceParams params) // for gemma2 p #endif } -template -void rms_norm_kernel_launcher(AllReduceParams& params, cudaStream_t stream, AllReduceFusionOp fusionOp) +// QuantFp8 / WriteNorm: rms_norm_kernel's FP8 epilogue (into ``quant``) and norm store, for RESIDUAL_RMS_NORM only. +template +void rms_norm_kernel_launcher( + AllReduceParams& params, cudaStream_t stream, AllReduceFusionOp fusionOp, RmsNormQuantFp8Params quant = {}) { static constexpr int kPackedSize = details::kBytesPerAccess / sizeof(T); TLLM_CHECK(params.fusion_params.hidden_size % kPackedSize == 0); + TLLM_CHECK((!QuantFp8 && WriteNorm) || fusionOp == AllReduceFusionOp::RESIDUAL_RMS_NORM); if (fusionOp == AllReduceFusionOp::RESIDUAL_RMS_PREPOST_NORM) { TLLM_CHECK(params.fusion_params.hidden_size <= 8192); @@ -472,8 +510,8 @@ void rms_norm_kernel_launcher(AllReduceParams& params, cudaStream_t stream, AllR if (fusionOp == AllReduceFusionOp::RESIDUAL_RMS_NORM) { - TLLM_CUDA_CHECK( - cudaLaunchKernelEx(&kernelConfig, rms_norm_kernel, params)); + TLLM_CUDA_CHECK(cudaLaunchKernelEx(&kernelConfig, + rms_norm_kernel, params, quant)); } else { // AllReduceFusionOp::RESIDUAL_RMS_PREPOST_NORM @@ -485,7 +523,8 @@ void rms_norm_kernel_launcher(AllReduceParams& params, cudaStream_t stream, AllR { if (fusionOp == AllReduceFusionOp::RESIDUAL_RMS_NORM) { - rms_norm_kernel<<>>(params); + rms_norm_kernel + <<>>(params, quant); } else { // AllReduceFusionOp::RESIDUAL_RMS_PREPOST_NORM @@ -512,8 +551,8 @@ void rms_norm_kernel_launcher(AllReduceParams& params, cudaStream_t stream, AllR if (fusionOp == AllReduceFusionOp::RESIDUAL_RMS_NORM) { - TLLM_CUDA_CHECK( - cudaLaunchKernelEx(&kernelConfig, rms_norm_kernel, params)); + TLLM_CUDA_CHECK(cudaLaunchKernelEx(&kernelConfig, + rms_norm_kernel, params, quant)); } else { // AllReduceFusionOp::RESIDUAL_RMS_PREPOST_NORM @@ -525,7 +564,8 @@ void rms_norm_kernel_launcher(AllReduceParams& params, cudaStream_t stream, AllR { if (fusionOp == AllReduceFusionOp::RESIDUAL_RMS_NORM) { - rms_norm_kernel<<>>(params); + rms_norm_kernel + <<>>(params, quant); } else { // AllReduceFusionOp::RESIDUAL_RMS_PREPOST_NORM @@ -1342,6 +1382,7 @@ void lamport_initialize_kernel_launcher(void* buffer, size_t size, cudaStream_t int grid_size = (size + 1024 * kPackedSize - 1) / (1024 * kPackedSize); lamport_initialize_kernel<<>>(reinterpret_cast(buffer), size); } + }; // namespace reduce_fusion template @@ -2007,6 +2048,55 @@ void residualRmsNorm( sync_check_cuda_error(stream); } +bool residualRmsNormQuantFp8Supported(tensorrt_llm::DataType dataType, int hidden_size) +{ +#ifdef ENABLE_BF16 + // One 16-byte pack per thread: hidden = 8 x threads, threads a multiple of 32 and at most kMaxCtaSize. + return dataType == tensorrt_llm::DataType::kBF16 && hidden_size % (8 * reduce_fusion::details::kWarpSize) == 0 + && hidden_size / 8 <= reduce_fusion::details::kMaxCtaSize; +#else + return false; +#endif +} + +void residualRmsNormQuantFp8(kernels::AllReduceParams& params, tensorrt_llm::DataType dataType, void* quant_out, + float const* scale, bool write_norm_out, cudaStream_t stream) +{ + TLLM_CHECK_WITH_INFO(residualRmsNormQuantFp8Supported(dataType, params.fusion_params.hidden_size), + "residualRmsNormQuantFp8: unsupported dtype / hidden size"); + TLLM_CHECK_WITH_INFO(params.fusion_params.weight_buffer != nullptr && params.fusion_params.bias_buffer == nullptr, + "residualRmsNormQuantFp8: a norm weight and no bias"); + if (params.elts_total / params.fusion_params.hidden_size == 0) + { + return; + } + sync_check_cuda_error(stream); +#ifdef ENABLE_BF16 + // rms_norm_kernel with its FP8 epilogue: one CTA per token, one 16-byte pack per thread at these hidden sizes. + reduce_fusion::RmsNormQuantFp8Params const quant{reinterpret_cast<__nv_fp8_e4m3*>(quant_out), scale}; + auto const op = AllReduceFusionOp::RESIDUAL_RMS_NORM; + using T = __nv_bfloat16; + bool const residual = params.fusion_params.residual_buffer != nullptr; + if (residual && write_norm_out) + { + reduce_fusion::rms_norm_kernel_launcher(params, stream, op, quant); + } + else if (residual) + { + reduce_fusion::rms_norm_kernel_launcher(params, stream, op, quant); + } + else if (write_norm_out) + { + reduce_fusion::rms_norm_kernel_launcher(params, stream, op, quant); + } + else + { + reduce_fusion::rms_norm_kernel_launcher(params, stream, op, quant); + } +#endif + sync_check_cuda_error(stream); +} + void lamportInitialize(void* buffer, size_t size, tensorrt_llm::DataType dataType, cudaStream_t stream) { sync_check_cuda_error(stream); diff --git a/cpp/tensorrt_llm/kernels/customAllReduceKernels.h b/cpp/tensorrt_llm/kernels/customAllReduceKernels.h index 93f67ffdd911..7bf8ec971e70 100644 --- a/cpp/tensorrt_llm/kernels/customAllReduceKernels.h +++ b/cpp/tensorrt_llm/kernels/customAllReduceKernels.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024, NVIDIA CORPORATION. All rights reserved. + * Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -190,6 +190,13 @@ void customAllReduce(kernels::AllReduceParams& params, tensorrt_llm::DataType da void residualRmsNorm( kernels::AllReduceParams& params, tensorrt_llm::DataType dataType, cudaStream_t stream, AllReduceFusionOp fusionOp); +//! Residual add + RMSNorm + per-tensor FP8 quantization in one pass (the NCCL-fallback path of +//! RESIDUAL_RMS_NORM_[OUT_]QUANT_FP8); same outputs as residualRmsNorm followed by the static per-tensor +//! quantize. +bool residualRmsNormQuantFp8Supported(tensorrt_llm::DataType dataType, int hidden_size); +void residualRmsNormQuantFp8(kernels::AllReduceParams& params, tensorrt_llm::DataType dataType, void* quant_out, + float const* scale, bool write_norm_out, cudaStream_t stream); + void lamportInitialize(void* buffer, size_t size, tensorrt_llm::DataType dataType, cudaStream_t stream); namespace reduce_fusion diff --git a/cpp/tensorrt_llm/kernels/moe/trtllmGen/runner.cu b/cpp/tensorrt_llm/kernels/moe/trtllmGen/runner.cu index 1d54c324d4f0..eb4acc7bca58 100644 --- a/cpp/tensorrt_llm/kernels/moe/trtllmGen/runner.cu +++ b/cpp/tensorrt_llm/kernels/moe/trtllmGen/runner.cu @@ -666,6 +666,11 @@ std::string Runner::getKernelNameFromConfigIndex(int32_t configIndex) const return mRunner.getKernelNameFromConfigIndex(configIndex); } +std::map Runner::getKernelOptionsFromConfigIndex(int32_t configIndex) const +{ + return mRunner.getKernelOptionsFromConfigIndex(configIndex); +} + } // namespace Gemm2 namespace MoE @@ -825,6 +830,20 @@ int64_t Runner::getDefaultValidConfigIndex(int32_t topK, int32_t hiddenSize, int return std::distance(mPassingConfigs.begin(), it); } +std::string Runner::getGemm2KernelName(int64_t configIndex) const +{ + TLLM_CHECK_WITH_INFO(configIndex >= 0 && configIndex < static_cast(mPassingConfigs.size()), + "Invalid MoE config index %ld.", static_cast(configIndex)); + return mGemm2.getKernelNameFromConfigIndex(static_cast(mPassingConfigs[configIndex].gemm2Config)); +} + +std::map Runner::getGemm2KernelOptions(int64_t configIndex) const +{ + TLLM_CHECK_WITH_INFO(configIndex >= 0 && configIndex < static_cast(mPassingConfigs.size()), + "Invalid MoE config index %ld.", static_cast(configIndex)); + return mGemm2.getKernelOptionsFromConfigIndex(static_cast(mPassingConfigs[configIndex].gemm2Config)); +} + void Runner::run( MoERunnerArgs const& args, MoEWorkspace const& workspace, int device, cudaStream_t stream, int64_t configIndex) { @@ -853,6 +872,7 @@ void Runner::run( args.valid_intermediate_size.value_or(args.intermediate_size)); // We do not fuse activation with FC1 for DeepSeek FP8 due to the weights shuffling constraint. + TLLM_CHECK_WITH_INFO(!args.skip_gemm2 || !args.do_finalize, "skip_gemm2 requires do_finalize == false."); void* gemm2_input = workspace.gemm1_output; void* gemm2_input_scale = workspace.gemm1_output_scale; // We do activation only for DeepSeek FP8, as cubins do not have fused activation. @@ -864,6 +884,11 @@ void Runner::run( gemm2_input_scale = workspace.activation_output_scale; } + if (args.skip_gemm2) + { + return; + } + // Run gemm2 mGemm2.run(gemm2_input, gemm2_input_scale, args.gemm2_weights, args.gemm2_weights_scale, args.output2_scales_scalar, args.gemm2_bias, workspace.gemm2_output, workspace.gemm2_output_scale, totalExpertsPerToken, diff --git a/cpp/tensorrt_llm/kernels/moe/trtllmGen/runner.h b/cpp/tensorrt_llm/kernels/moe/trtllmGen/runner.h index 453a29671f4a..a01fa7beb5cd 100644 --- a/cpp/tensorrt_llm/kernels/moe/trtllmGen/runner.h +++ b/cpp/tensorrt_llm/kernels/moe/trtllmGen/runner.h @@ -24,6 +24,7 @@ #include "tensorrt_llm/kernels/trtllmGenKernels/batchedGemm/KernelRunner.h" #include "tensorrt_llm/kernels/trtllmGenKernels/batchedGemm/trtllmGen_bmm_export/trtllm/gen/DtypeDecl.h" #include "tensorrt_llm/thop/thUtils.h" +#include #include #include @@ -259,6 +260,9 @@ class Runner [[nodiscard]] std::string getKernelNameFromConfigIndex(int32_t configIndex) const; + // See TrtllmGenBatchedGemmRunner::getKernelOptionsFromConfigIndex. + [[nodiscard]] std::map getKernelOptionsFromConfigIndex(int32_t configIndex) const; + void run(void* permutedHiddenState, void* permutedHiddenStateScale, void* weight, void* weightScale, float* outputScalesScalar, float* ptrBias, void* output, void* outputScale, int32_t topK, int32_t hiddenSize, int32_t intermediateSize, int32_t numExperts, int32_t numTokens, int32_t* ptrNumNonExitingCtas, @@ -352,6 +356,10 @@ struct MoERunnerArgs // finalize bool do_finalize{true}; + + // Stop after FC1 (+ activation): the caller runs FC2 on workspace.gemm1_output / gemm1_output_scale with the + // routing tables. Requires do_finalize == false. + bool skip_gemm2{false}; }; struct MoEWorkspace @@ -430,6 +438,12 @@ class Runner int32_t numLocalExperts, int32_t numTokens, int32_t validHiddenSize = -1, int32_t validIntermediateSize = -1) const; + // Kernel name of the FC2 (gemm2) cubin of MoE config configIndex. + [[nodiscard]] std::string getGemm2KernelName(int64_t configIndex) const; + + // Arithmetic options of the FC2 (gemm2) cubin of MoE config configIndex (getKernelOptionsFromConfigIndex). + [[nodiscard]] std::map getGemm2KernelOptions(int64_t configIndex) const; + private: void setOpsData(MoERunnerArgs const& args, MoEWorkspace const& workspace, moe::dev::convertsf::Data& convertSfData, moe::dev::activation::Data& activationData, moe::dev::finalize::Data& finalizeData); diff --git a/cpp/tensorrt_llm/kernels/trtllmGenKernels/batchedGemm/KernelRunner.cpp b/cpp/tensorrt_llm/kernels/trtllmGenKernels/batchedGemm/KernelRunner.cpp index 05d9daab04d6..1828be4d30eb 100644 --- a/cpp/tensorrt_llm/kernels/trtllmGenKernels/batchedGemm/KernelRunner.cpp +++ b/cpp/tensorrt_llm/kernels/trtllmGenKernels/batchedGemm/KernelRunner.cpp @@ -532,6 +532,30 @@ std::string TrtllmGenBatchedGemmRunner::getKernelNameFromConfigIndex(int32_t con return configs[configIndex].mFunctionName; } +std::map TrtllmGenBatchedGemmRunner::getKernelOptionsFromConfigIndex( + int32_t configIndex) const +{ + auto const bmm = BatchedGemmInterface(); + auto const configs = bmm.getBatchedGemmConfigs(); + auto const& options = configs[configIndex].mOptions; + return { + {"dtypeA", dtypeToString(options.mDtypeA)}, + {"dtypeB", dtypeToString(options.mDtypeB)}, + {"dtypeC", dtypeToString(options.mDtypeC)}, + {"dtypeAcc", dtypeToString(options.mDtypeAcc)}, + {"tileM", std::to_string(options.mTileM)}, + {"tileN", std::to_string(options.mTileN)}, + {"tileK", std::to_string(options.mTileK)}, + {"mmaM", std::to_string(options.mMmaM)}, + {"mmaN", std::to_string(options.mMmaN)}, + {"mmaK", std::to_string(options.mMmaK)}, + {"clusterDimX", std::to_string(options.mClusterDimX)}, + {"clusterDimY", std::to_string(options.mClusterDimY)}, + {"clusterDimZ", std::to_string(options.mClusterDimZ)}, + {"numSlicesForSplitK", std::to_string(options.mNumSlicesForSplitK)}, + }; +} + std::vector TrtllmGenBatchedGemmRunner::getValidConfigIndices(int32_t m, int32_t n, int32_t k, std::vector const& batchedTokens, int32_t numTokens, int32_t numBatches, int32_t maxNumCtasInBatchDim, int32_t validM, int32_t validN, int32_t validK) const diff --git a/cpp/tensorrt_llm/kernels/trtllmGenKernels/batchedGemm/KernelRunner.h b/cpp/tensorrt_llm/kernels/trtllmGenKernels/batchedGemm/KernelRunner.h index 2699c46126e0..fca84fe0d5a5 100644 --- a/cpp/tensorrt_llm/kernels/trtllmGenKernels/batchedGemm/KernelRunner.h +++ b/cpp/tensorrt_llm/kernels/trtllmGenKernels/batchedGemm/KernelRunner.h @@ -19,6 +19,8 @@ #include "tensorrt_llm/common/config.h" #include #include +#include +#include #include #include "trtllmGen_bmm_export/trtllm/gen/DtypeDecl.h" @@ -153,6 +155,11 @@ class TrtllmGenBatchedGemmRunner // Get the kernel name from the config index [[nodiscard]] std::string getKernelNameFromConfigIndex(int32_t configIndex) const; + // The options of the kernel a config index names that decide its arithmetic: "dtypeA", "dtypeB", "dtypeC", + // "dtypeAcc" (dtype names), "tileM", "tileN", "tileK", "mmaM", "mmaN", "mmaK", "clusterDimX", "clusterDimY", + // "clusterDimZ" and "numSlicesForSplitK" (decimal). + [[nodiscard]] std::map getKernelOptionsFromConfigIndex(int32_t configIndex) const; + // Get the list of config indices that are valid for the given problem shape [[nodiscard]] std::vector getValidConfigIndices(int32_t m, int32_t n, int32_t k, std::vector const& batchedTokens, int32_t numTokens, int32_t numBatches, int32_t maxNumCtasInBatchDim, diff --git a/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/FmhaSm100aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128PersistentContextStageKv256E4.cubin.tar.zst b/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/FmhaSm100aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128PersistentContextStageKv256E4.cubin.tar.zst new file mode 100644 index 000000000000..0fef5eac1f36 --- /dev/null +++ b/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/FmhaSm100aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128PersistentContextStageKv256E4.cubin.tar.zst @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26646e9458110704a39c7a9eb0da4dc839141231e1a009a1568a2515c681bb0b +size 70332 diff --git a/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/FmhaSm100aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128StaticContextStageKv256E4.cubin.tar.zst b/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/FmhaSm100aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128StaticContextStageKv256E4.cubin.tar.zst new file mode 100644 index 000000000000..30de86194daf --- /dev/null +++ b/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/FmhaSm100aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128StaticContextStageKv256E4.cubin.tar.zst @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01f84e78a8883994a4c7a5cbb632a1bd7b47b2f0500b27e940d7c727c36fa699 +size 66607 diff --git a/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/FmhaSm103aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128PersistentContextStageKv256E4.cubin.tar.zst b/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/FmhaSm103aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128PersistentContextStageKv256E4.cubin.tar.zst new file mode 100644 index 000000000000..eb8ffd705acc --- /dev/null +++ b/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/FmhaSm103aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128PersistentContextStageKv256E4.cubin.tar.zst @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bb5188e3d2dd8e9f6198bafd1da5c56ae3ad0f67fe5f409cac3e6055156f9f2e +size 70141 diff --git a/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/FmhaSm103aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128StaticContextStageKv256E4.cubin.tar.zst b/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/FmhaSm103aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128StaticContextStageKv256E4.cubin.tar.zst new file mode 100644 index 000000000000..a1df91152b04 --- /dev/null +++ b/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/FmhaSm103aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128StaticContextStageKv256E4.cubin.tar.zst @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:10a61fa3b166bc6132ff2e734a1cceee8c221c6168ef041bb63d9e966b2a5277 +size 67064 diff --git a/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/kernelMetaInfoStageKv.h b/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/kernelMetaInfoStageKv.h new file mode 100644 index 000000000000..83915ce606cd --- /dev/null +++ b/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/kernelMetaInfoStageKv.h @@ -0,0 +1,81 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Generated by scripts/trtllm_gen_fmha_stage_kv/gen_stage_kv_cubins.py; do not edit. +#pragma once + +#include "kernelMetaInfo.h" + +#include + +TRTLLM_NAMESPACE_BEGIN + +namespace kernels +{ + +// trtllm-gen FMHA kernels generated for a caller-fixed head dim per K/V shared-memory stage +// (TllmGenFmhaRunnerParams::mHeadDimPerStageKv). The kernel hash does not cover that option, so the runner keeps these +// apart from sTllmGenFmhaKernelMetaInfos and matches them only for callers that fix the stage. +struct TllmGenFmhaStageKvKernelMetaInfo +{ + int mHeadDimPerStageKv; + TllmGenFmhaKernelMetaInfo mMeta; +}; + +// clang-format off +// BEGIN decls sm100 h256p64s256 +#ifndef EXCLUDE_SM_100 +// Kernel inputs sha256: 3e76c3ff74f8430380bef415162164c9b00cd10636164e1d17ce49a10bdc93e0 +extern unsigned char const FmhaSm100aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128PersistentContextStageKv256E4_cubin[]; +extern unsigned int const FmhaSm100aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128PersistentContextStageKv256E4_cubin_len; +extern unsigned char const FmhaSm100aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128StaticContextStageKv256E4_cubin[]; +extern unsigned int const FmhaSm100aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128StaticContextStageKv256E4_cubin_len; +#endif +// END decls sm100 h256p64s256 +// BEGIN decls sm103 h256p64s256 +#ifndef EXCLUDE_SM_103 +// Kernel inputs sha256: 3e76c3ff74f8430380bef415162164c9b00cd10636164e1d17ce49a10bdc93e0 +extern unsigned char const FmhaSm103aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128PersistentContextStageKv256E4_cubin[]; +extern unsigned int const FmhaSm103aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128PersistentContextStageKv256E4_cubin_len; +extern unsigned char const FmhaSm103aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128StaticContextStageKv256E4_cubin[]; +extern unsigned int const FmhaSm103aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128StaticContextStageKv256E4_cubin_len; +#endif +// END decls sm103 h256p64s256 + +inline std::vector const& getTllmGenFmhaStageKvKernelMetaInfos() +{ + static std::vector const sInfos = { +// BEGIN entries sm100 h256p64s256 +#ifndef EXCLUDE_SM_100 +{ 256, { DATA_TYPE_E4M3, DATA_TYPE_E4M3, DATA_TYPE_E4M3, DATA_TYPE_E4M3, DATA_TYPE_BF16, 128, 128, 128, 128, 256, 256, 256, kSM_100, FmhaSm100aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128PersistentContextStageKv256E4_cubin, FmhaSm100aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128PersistentContextStageKv256E4_cubin_len, "fmhaSm100aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128PersistentContextStageKv256E4", 198016, 384, 2, 64, 1, 0, 1, 0, 0, 0, 0, 0, false, false, false, false, 0, false, false, false, false, false, false, false, "0588ddb8fce8c1a699503b67a8f9a84735dbd4e25d6d58dd7ba4f2a78e8e848b", false } }, +{ 256, { DATA_TYPE_E4M3, DATA_TYPE_E4M3, DATA_TYPE_E4M3, DATA_TYPE_E4M3, DATA_TYPE_BF16, 128, 128, 128, 128, 256, 256, 256, kSM_100, FmhaSm100aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128StaticContextStageKv256E4_cubin, FmhaSm100aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128StaticContextStageKv256E4_cubin_len, "fmhaSm100aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128StaticContextStageKv256E4", 197904, 384, 2, 64, 1, 0, 0, 0, 0, 0, 0, 0, false, false, false, false, 0, false, false, false, false, false, false, false, "a3944cc754c4ab3969df1812d98b96ed067b88ea414b42245c7e43ed3904f905", false } }, +#endif +// END entries sm100 h256p64s256 +// BEGIN entries sm103 h256p64s256 +#ifndef EXCLUDE_SM_103 +{ 256, { DATA_TYPE_E4M3, DATA_TYPE_E4M3, DATA_TYPE_E4M3, DATA_TYPE_E4M3, DATA_TYPE_BF16, 128, 128, 128, 128, 256, 256, 256, kSM_103, FmhaSm103aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128PersistentContextStageKv256E4_cubin, FmhaSm103aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128PersistentContextStageKv256E4_cubin_len, "fmhaSm103aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128PersistentContextStageKv256E4", 198016, 384, 2, 64, 1, 0, 1, 0, 0, 0, 0, 0, false, false, false, false, 0, false, false, false, false, false, false, false, "0ee976b55d36a81d5f0cd110fa67c1f74c596d8db30fec61718b084dcca64dad", false } }, +{ 256, { DATA_TYPE_E4M3, DATA_TYPE_E4M3, DATA_TYPE_E4M3, DATA_TYPE_E4M3, DATA_TYPE_BF16, 128, 128, 128, 128, 256, 256, 256, kSM_103, FmhaSm103aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128StaticContextStageKv256E4_cubin, FmhaSm103aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128StaticContextStageKv256E4_cubin_len, "fmhaSm103aKernel_QkvE4m3OBfloat16H256PagedKvCausalP64VarSeqQ128Kv128StaticContextStageKv256E4", 197904, 384, 2, 64, 1, 0, 0, 0, 0, 0, 0, 0, false, false, false, false, 0, false, false, false, false, false, false, false, "9fc0140692fc562c39a2bc99e8fd07d6ce483dc6cb8630c9baadad076eef81ae", false } }, +#endif +// END entries sm103 h256p64s256 + }; + return sInfos; +} + +// clang-format on + +} // namespace kernels + +TRTLLM_NAMESPACE_END diff --git a/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaKernels.h b/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaKernels.h index 81f8cf002519..5deac7dea28a 100644 --- a/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaKernels.h +++ b/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaKernels.h @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -41,6 +42,7 @@ #include "tensorrt_llm/kernels/multiHeadAttentionCommon.h" #include "cubin/kernelMetaInfo.h" +#include "cubin/kernelMetaInfoStageKv.h" #include "fmhaReduction.h" #include "fmhaRunnerParams.h" #include "prepareCustomMask.h" @@ -156,11 +158,21 @@ class TllmGenFmhaKernel using FmhaConfig = fmha::FmhaConfig; using FmhaData = fmha::FmhaData; using KernelParams = fmha::KernelParams; + using StageKvKernelMeta = TllmGenFmhaStageKvKernelMetaInfo; +private: + struct KernelInfo + { + KernelMeta const* mMeta; + CUfunction mDeviceFunction; + }; + +public: // Ctor. TllmGenFmhaKernel(KernelMeta const* pMetaStart, unsigned int nMetaCount, Data_type dtypeQ, Data_type dtypeK, Data_type dtypeV, Data_type dtypeOut, unsigned int smArch, int numEltsPerSageAttnBlkQ = 0, - int numEltsPerSageAttnBlkK = 0, int numEltsPerSageAttnBlkP = 0, int numEltsPerSageAttnBlkV = 0) + int numEltsPerSageAttnBlkK = 0, int numEltsPerSageAttnBlkP = 0, int numEltsPerSageAttnBlkV = 0, + StageKvKernelMeta const* pStageKvMetaStart = nullptr, unsigned int nStageKvMetaCount = 0) : mDtypeQ(dtypeQ) , mDtypeK(dtypeK) , mDtypeV(dtypeV) @@ -168,6 +180,8 @@ class TllmGenFmhaKernel , mDriver(tensorrt_llm::common::CUDADriverWrapper::getInstance()) , mKernelMeta(pMetaStart) , mKernelMetaCount(nMetaCount) + , mStageKvKernelMeta(pStageKvMetaStart) + , mStageKvKernelMetaCount(nStageKvMetaCount) , mSM(smArch) , mNumEltsPerSageAttnBlkQ(numEltsPerSageAttnBlkQ) , mNumEltsPerSageAttnBlkK(numEltsPerSageAttnBlkK) @@ -182,79 +196,108 @@ class TllmGenFmhaKernel for (unsigned int i = 0; i < mKernelMetaCount; ++i) { auto const& kernelMeta = mKernelMeta[i]; - if (isSMCompatible(mSM, kernelMeta.mSM) && kernelMeta.mDataTypeQ == mDtypeQ - && kernelMeta.mDataTypeK == mDtypeK && kernelMeta.mDataTypeV == mDtypeV - && kernelMeta.mDataTypeO == mDtypeOut && kernelMeta.mNumEltsPerSageAttnBlkQ == mNumEltsPerSageAttnBlkQ - && kernelMeta.mNumEltsPerSageAttnBlkK == mNumEltsPerSageAttnBlkK - && kernelMeta.mNumEltsPerSageAttnBlkP == mNumEltsPerSageAttnBlkP - && kernelMeta.mNumEltsPerSageAttnBlkV == mNumEltsPerSageAttnBlkV) + KernelInfo funcInfo; + if (!loadKernel(kernelMeta, funcInfo)) { - // Load CUmodules - CUmodule hmod{0}; - auto findModuleIter = mModules.find(kernelMeta.mCubin); - if (findModuleIter != mModules.end()) - { - hmod = findModuleIter->second; - } - else - { - TLLM_CU_CHECK(mDriver->cuModuleLoadData(&hmod, kernelMeta.mCubin)); - mModules.insert(std::make_pair(kernelMeta.mCubin, hmod)); - } - // Build a hash map, which maps from kernel meta info to kernel index - KernelInfo funcInfo; - funcInfo.mMetaInfoIndex = i; - TLLM_CU_CHECK(mDriver->cuModuleGetFunction(&funcInfo.mDeviceFunction, hmod, kernelMeta.mFuncName)); -#if defined(CUDA_VERSION) && CUDA_VERSION >= 13040 - if (kernelMeta.mSharedMemBytes + 1024 > 228 * 1024) + continue; + } + // Make sure the hashIds are not duplicated. + // Except for the case where we have both family version and specific version of the same config. + auto const hash = hashID(kernelMeta); + auto& functions = getFunctions(kernelMeta.mFusesDsv4InvRopeFp8Quant, kernelMeta.mUsesDsv4Ue8m0ScaleO); + auto it = functions.find(hash); + if (it != functions.end()) + { + auto const& existingKernelMeta = *it->second.mMeta; + TLLM_CHECK_WITH_INFO(isFamilySpecificSMPair(existingKernelMeta.mSM, kernelMeta.mSM), + "The kernel's hashId conflicts with another kernel in the same variant: existing=%s, new=%s.", + existingKernelMeta.mFuncName, kernelMeta.mFuncName); + // Prefer specific SM version over family version + if (existingKernelMeta.mSM == kSM_100f) { - TLLM_CU_CHECK(mDriver->cuFuncSetAttribute(funcInfo.mDeviceFunction, - CU_FUNC_ATTRIBUTE_SHARED_MEMORY_MODE, CU_SHARED_MEMORY_MODE_ALLOW_OVERSIZED_SHARED_MEMORY)); + it->second = funcInfo; } - else -#endif - if (kernelMeta.mSharedMemBytes >= 48 * 1024) + } + else + { + functions[hash] = funcInfo; + } + } + } + + // Kernels generated for a caller-fixed head dim per K/V stage, keyed by (hash, stage): the hash does not cover + // the stage, so they are only found by callers that fix it (RunnerParams::mHeadDimPerStageKv). Loaded on the first + // such call; a kernel that fails to load is left to NVRTC. + void loadStageKvKernels() + { + std::call_once(mStageKvLoaded, + [this] + { + for (unsigned int i = 0; i < mStageKvKernelMetaCount; ++i) { - auto const result = mDriver->cuFuncSetAttribute(funcInfo.mDeviceFunction, - CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, kernelMeta.mSharedMemBytes); - if (result != CUDA_SUCCESS) + auto const& stageKvMeta = mStageKvKernelMeta[i]; + KernelInfo funcInfo; + try { - char const* errorName = nullptr; - char const* errorString = nullptr; - mDriver->cuGetErrorName(result, &errorName); - mDriver->cuGetErrorString(result, &errorString); - TLLM_LOG_WARNING("Skipping FMHA kernel due to cuFuncSetAttribute failure: " - + std::string(kernelMeta.mFuncName) + ", smem=" + std::to_string(kernelMeta.mSharedMemBytes) - + ", error=" + std::string(errorName != nullptr ? errorName : "unknown") + ": " - + std::string(errorString != nullptr ? errorString : "unknown")); - continue; + if (!loadKernel(stageKvMeta.mMeta, funcInfo)) + { + continue; + } } - } - // Make sure the hashIds are not duplicated. - // Except for the case where we have both family version and specific version of the same config. - auto const hash = hashID(kernelMeta); - auto& functions = getFunctions(kernelMeta.mFusesDsv4InvRopeFp8Quant, kernelMeta.mUsesDsv4Ue8m0ScaleO); - auto it = functions.find(hash); - if (it != functions.end()) - { - auto const& existingKernelMeta = mKernelMeta[it->second.mMetaInfoIndex]; - TLLM_CHECK_WITH_INFO(isFamilySpecificSMPair(existingKernelMeta.mSM, kernelMeta.mSM), - "The kernel's hashId conflicts with another kernel in the same variant: existing=%s, new=%s.", - existingKernelMeta.mFuncName, kernelMeta.mFuncName); - // Prefer specific SM version over family version - if (existingKernelMeta.mSM == kSM_100f) + catch (std::exception const& e) { - it->second = funcInfo; + TLLM_LOG_WARNING( + "Stage-KV FMHA kernel %s not loaded: %s", stageKvMeta.mMeta.mFuncName, e.what()); + continue; } + auto const key = std::make_pair(hashID(stageKvMeta.mMeta), stageKvMeta.mHeadDimPerStageKv); + TLLM_CHECK_WITH_INFO(mStageKvFunctions.emplace(key, funcInfo).second, + "Two stage-KV FMHA kernels share a hashId and head dim per K/V stage: %s.", + stageKvMeta.mMeta.mFuncName); } - else - { - functions[hash] = funcInfo; - } - } + }); + } + + // Options the caller fixes, applied before the autotuner (marked as set, so it keeps them) and again after it. + static void applyCallerOptions( + RunnerParams const& params, FmhaOptions& options, FmhaOptionsFromArgs& optionsFromArgs) + { + if (params.mHeadDimPerStageKv > 0) + { + options.mHeadDimPerStageKv = params.mHeadDimPerStageKv; + optionsFromArgs.mIsHeadDimPerStageKvSet = true; } } + // NVRTC for the configurations shouldUseNvrtc picks and for caller-fixed options the cubin tables do not hold. + bool usesNvrtc(RunnerParams const& params, FmhaOptions const& options) const + { + if (shouldUseNvrtc(options)) + { + return true; + } + return params.mHeadDimPerStageKv > 0 && findCubinKernel(options, params.mHeadDimPerStageKv) == nullptr; + } + + // Whether run() would compile the kernel it selects for these params (their batch, lengths and SM count) with + // NVRTC instead of launching a precompiled one. + bool usesNvrtc(RunnerParams const& params) + { + if (params.mHeadDimPerStageKv > 0) + { + loadStageKvKernels(); + } + auto const [options, ctaDim, grid] = selectOptions(params); + return usesNvrtc(params, options); + } + + // The NVRTC configuration run() compiles for these params (also used offline to export the generated kernel). + FmhaConfig nvrtcConfig(RunnerParams const& params) const + { + auto const [options, ctaDim, grid] = selectOptions(params); + return makeNvrtcConfig(options, ctaDim, grid); + } + bool shouldUseNvrtc(FmhaOptions const& options) const { #ifdef TLLM_RUBIN_FEATURES @@ -322,29 +365,10 @@ class TllmGenFmhaKernel return std::make_pair(false, "Empty batch or zero sequence length"); } - // The selectKernelParams that might be updated. - SelectKernelParams selectKernelParams{params}; + // The options run() selects (its CTA counts included), so the check answers for the kernel it dispatches. + auto const [options, ctaDim, grid] = selectOptions(params); - int32_t ctaDim = 512; - FmhaOptions options; - FmhaOptionsFromArgs optionsFromArgs; - parseOptionsFromRunnerParams(params, options); - options.mCudaArch = intToCudaArch(mSM); - - std::tie(options, optionsFromArgs, ctaDim) - = selectKernelAutotuned(options, optionsFromArgs, params.mMultiProcessorCount); - - // Check if the options are valid or not. - checkFmhaOptions(options, optionsFromArgs); - // Update the options if needed. - updateFmhaOptions(options, optionsFromArgs); - checkTrtllmSkipCorrThreshold(options, params.mSkipCorrThreshold); - - // The number of CtasQ and CtasKv per sequence, Ctas in the Y dimension, and Ctas in the Z - // dimension. - computeNumCtas(options, params.mMultiProcessorCount); - - if (shouldUseNvrtc(options)) + if (usesNvrtc(params, options)) { // For the NVRTC path, we return supported as long as autotuner successfully selected a kernel config. return std::make_pair(true, "NVRTC path is supported"); @@ -352,11 +376,8 @@ class TllmGenFmhaKernel // Check if a precompiled cubin exists for this configuration (same lookup as run()). // If not, return (false, info) so the dispatcher can fall back to unfused MHA like on main. - algoFilterForCubinPath(options); - auto [hashId, info] = hashFromFmhaOptions(options); - - auto const& functions = getFunctions(options.mFusesDsv4InvRopeFp8Quant, options.mUsesDsv4Ue8m0ScaleO); - if (functions.find(hashId) == functions.end()) + std::string info; + if (findCubinKernel(options, params.mHeadDimPerStageKv, &info) == nullptr) { TLLM_LOG_WARNING("Trtllm-gen kernels not found: " + info); return std::make_pair(false, info); @@ -429,23 +450,21 @@ class TllmGenFmhaKernel return candidateSizes; } - void warmupOneKernel(RunnerParams const& params) + // The options and CTA size run() selects for these params, before computeNumCtas. + std::pair selectKernelOptions(RunnerParams const& params) const { - if (params.mMaxSeqLenQ == 0 || params.mBatchSize == 0 - || (!isContextKernel(params.mKernelType) && params.mMaxSeqLenKv == 0)) - { - return; - } - int32_t ctaDim = 512; FmhaOptions options; FmhaOptionsFromArgs optionsFromArgs; parseOptionsFromRunnerParams(params, options); + applyCallerOptions(params, options, optionsFromArgs); options.mCudaArch = intToCudaArch(mSM); std::tie(options, optionsFromArgs, ctaDim) = selectKernelAutotuned(options, optionsFromArgs, params.mMultiProcessorCount); - // Same override as run(), so the warmed config matches the dispatched one. + applyCallerOptions(params, options, optionsFromArgs); + // Overwrite AutoTuner decision: SageAttention with SfsPV is known to cause regression to persistent scheduler. + // Remove this overwritten once we refresh the cubin kernels that containing the related fix. if (mNumEltsPerSageAttnBlkP + mNumEltsPerSageAttnBlkV > 0) { options.mTileScheduler = TileScheduler::Static; @@ -454,23 +473,31 @@ class TllmGenFmhaKernel checkFmhaOptions(options, optionsFromArgs); updateFmhaOptions(options, optionsFromArgs); checkTrtllmSkipCorrThreshold(options, params.mSkipCorrThreshold); + return {options, ctaDim}; + } + // The options, CTA size and grid run() selects for these params. + std::tuple selectOptions(RunnerParams const& params) const + { + auto selected = selectKernelOptions(params); + FmhaOptions& options = selected.first; auto [numCtasX, numCtasY, numCtasZ] = computeNumCtas(options, params.mMultiProcessorCount); - tg::CudaRunner::Grid grid{numCtasX, numCtasY, numCtasZ}; + return {options, selected.second, tg::CudaRunner::Grid{numCtasX, numCtasY, numCtasZ}}; + } - if (shouldUseNvrtc(options)) + void warmupOneKernel(RunnerParams const& params) + { + if (params.mMaxSeqLenQ == 0 || params.mBatchSize == 0 + || (!isContextKernel(params.mKernelType) && params.mMaxSeqLenKv == 0)) + { + return; + } + + auto const [options, ctaDim, grid] = selectOptions(params); + if (usesNvrtc(params, options)) { // Compile exactly what run() compiles (same target arch), so the warmed kernel is the one run() hits. - FmhaOptions const nvrtcOptions = nvrtcCompileOptions(options); - FmhaConfig fmhaConfig; - fmhaConfig.mOptions = nvrtcOptions; - std::ostringstream sstream; - populateJsonConfig(nvrtcOptions, sstream); - fmhaConfig.mGenCfgJsonStr = sstream.str(); - - fmhaConfig.mExecPath = getExecPath().c_str(); - fmhaConfig.mCtaDim = ctaDim; - fmhaConfig.mGrid = grid; + FmhaConfig fmhaConfig = makeNvrtcConfig(options, ctaDim, grid); auto const compileStart = std::chrono::steady_clock::now(); mFmhaInterface.generateAndCompileKernel(fmhaConfig); auto const compileElapsed = std::chrono::steady_clock::now() - compileStart; @@ -633,29 +660,15 @@ class TllmGenFmhaKernel TLLM_CHECK_WITH_INFO(params.mDsv4EpilogueFusion.cosSinCache != nullptr, "SM107 DSV4 FMHA epilogue fusion requires a non-null inverse-RoPE cos/sin cache."); } - runJITWarmupGridIfRequested(params); - - int32_t ctaDim = 512; - FmhaOptions options; - FmhaOptionsFromArgs optionsFromArgs; - parseOptionsFromRunnerParams(params, options); - options.mCudaArch = intToCudaArch(mSM); - - std::tie(options, optionsFromArgs, ctaDim) - = selectKernelAutotuned(options, optionsFromArgs, params.mMultiProcessorCount); - - // Overwrite AutoTuner decision: SageAttention with SfsPV is known to cause regression to persistent scheduler. - // Remove this overwritten once we refresh the cubin kernels that containing the related fix. - if (mNumEltsPerSageAttnBlkP + mNumEltsPerSageAttnBlkV > 0) + if (params.mHeadDimPerStageKv > 0) { - options.mTileScheduler = TileScheduler::Static; + loadStageKvKernels(); } + runJITWarmupGridIfRequested(params); - // Check if the options are valid or not. - checkFmhaOptions(options, optionsFromArgs); - // Update the options if needed. - updateFmhaOptions(options, optionsFromArgs); - checkTrtllmSkipCorrThreshold(options, params.mSkipCorrThreshold); + auto selected = selectKernelOptions(params); + FmhaOptions& options = selected.first; + int32_t const ctaDim = selected.second; // Any caller that selects MultiCtasKvMode must supply the partial-reduction scratch pool // and per-CTA counter; fail fast here instead of silently falling back to Disabled. @@ -692,20 +705,10 @@ class TllmGenFmhaKernel setFmhaData(params, options, fmhaData); fmha::checkSkipCorrThreshold(options, fmhaData.mMetaData.skipCorrThreshold); - if (shouldUseNvrtc(options)) + if (usesNvrtc(params, options)) { // nvrtc path - uses mFmhaInterface member for kernel caching - FmhaOptions const nvrtcOptions = nvrtcCompileOptions(options); - - FmhaConfig fmhaConfig; - fmhaConfig.mOptions = nvrtcOptions; - std::ostringstream sstream; - populateJsonConfig(nvrtcOptions, sstream); - fmhaConfig.mGenCfgJsonStr = sstream.str(); - - fmhaConfig.mExecPath = getExecPath().c_str(); - fmhaConfig.mCtaDim = ctaDim; - fmhaConfig.mGrid = grid; + FmhaConfig fmhaConfig = makeNvrtcConfig(options, ctaDim, grid); auto const compileStart = std::chrono::steady_clock::now(); mFmhaInterface.generateAndCompileKernel(fmhaConfig); auto const compileElapsed = std::chrono::steady_clock::now() - compileStart; @@ -723,16 +726,15 @@ class TllmGenFmhaKernel else { algoFilterForCubinPath(options); - auto [hashId, info] = hashFromFmhaOptions(options); // load from cubin - auto const& functions = getFunctions(options.mFusesDsv4InvRopeFp8Quant, options.mUsesDsv4Ue8m0ScaleO); - auto const findIter = functions.find(hashId); + std::string info; + KernelInfo const* kernelInfo = findCubinKernel(options, params.mHeadDimPerStageKv, &info); // Add debug info when kernels are not found. - TLLM_CHECK_WITH_INFO(findIter != functions.end(), "Trtllm-gen kernels not found: " + info); + TLLM_CHECK_WITH_INFO(kernelInfo != nullptr, "Trtllm-gen kernels not found: " + info); - auto const& kernelMeta = mKernelMeta[findIter->second.mMetaInfoIndex]; - const CUfunction func = findIter->second.mDeviceFunction; + auto const& kernelMeta = *kernelInfo->mMeta; + const CUfunction func = kernelInfo->mDeviceFunction; // mGroupsHeadsQ, mGroupsTokensHeadsQ, and mNumInsts{Q,Kv} are part of the hashID, so the // matched cubin already agrees with the AutoTuner decision. Re-assign from kernelMeta @@ -802,6 +804,95 @@ class TllmGenFmhaKernel return nvrtcOptions; } + // The NVRTC config for the selected options; shared by run() and warmupOneKernel() so both produce the same kernel. + FmhaConfig makeNvrtcConfig(FmhaOptions const& options, int32_t ctaDim, tg::CudaRunner::Grid const& grid) const + { + FmhaOptions const nvrtcOptions = nvrtcCompileOptions(options); + FmhaConfig fmhaConfig; + fmhaConfig.mOptions = nvrtcOptions; + std::ostringstream sstream; + populateJsonConfig(nvrtcOptions, sstream); + fmhaConfig.mGenCfgJsonStr = sstream.str(); + fmhaConfig.mExecPath = getExecPath().c_str(); + fmhaConfig.mCtaDim = ctaDim; + fmhaConfig.mGrid = grid; + return fmhaConfig; + } + + // Loads the kernel of a table entry that matches this runner's SM and data types; false if it does not apply. + bool loadKernel(KernelMeta const& kernelMeta, KernelInfo& funcInfo) + { + if (!(isSMCompatible(mSM, kernelMeta.mSM) && kernelMeta.mDataTypeQ == mDtypeQ + && kernelMeta.mDataTypeK == mDtypeK && kernelMeta.mDataTypeV == mDtypeV + && kernelMeta.mDataTypeO == mDtypeOut && kernelMeta.mNumEltsPerSageAttnBlkQ == mNumEltsPerSageAttnBlkQ + && kernelMeta.mNumEltsPerSageAttnBlkK == mNumEltsPerSageAttnBlkK + && kernelMeta.mNumEltsPerSageAttnBlkP == mNumEltsPerSageAttnBlkP + && kernelMeta.mNumEltsPerSageAttnBlkV == mNumEltsPerSageAttnBlkV)) + { + return false; + } + // Load CUmodules + CUmodule hmod{0}; + auto findModuleIter = mModules.find(kernelMeta.mCubin); + if (findModuleIter != mModules.end()) + { + hmod = findModuleIter->second; + } + else + { + TLLM_CU_CHECK(mDriver->cuModuleLoadData(&hmod, kernelMeta.mCubin)); + mModules.insert(std::make_pair(kernelMeta.mCubin, hmod)); + } + funcInfo.mMeta = &kernelMeta; + TLLM_CU_CHECK(mDriver->cuModuleGetFunction(&funcInfo.mDeviceFunction, hmod, kernelMeta.mFuncName)); +#if defined(CUDA_VERSION) && CUDA_VERSION >= 13040 + if (kernelMeta.mSharedMemBytes + 1024 > 228 * 1024) + { + TLLM_CU_CHECK(mDriver->cuFuncSetAttribute(funcInfo.mDeviceFunction, CU_FUNC_ATTRIBUTE_SHARED_MEMORY_MODE, + CU_SHARED_MEMORY_MODE_ALLOW_OVERSIZED_SHARED_MEMORY)); + } + else +#endif + if (kernelMeta.mSharedMemBytes >= 48 * 1024) + { + auto const result = mDriver->cuFuncSetAttribute( + funcInfo.mDeviceFunction, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, kernelMeta.mSharedMemBytes); + if (result != CUDA_SUCCESS) + { + char const* errorName = nullptr; + char const* errorString = nullptr; + mDriver->cuGetErrorName(result, &errorName); + mDriver->cuGetErrorString(result, &errorString); + TLLM_LOG_WARNING("Skipping FMHA kernel due to cuFuncSetAttribute failure: " + + std::string(kernelMeta.mFuncName) + ", smem=" + std::to_string(kernelMeta.mSharedMemBytes) + + ", error=" + std::string(errorName != nullptr ? errorName : "unknown") + ": " + + std::string(errorString != nullptr ? errorString : "unknown")); + return false; + } + } + return true; + } + + // The precompiled kernel for the selected options, or nullptr. A caller-fixed head dim per K/V stage is only + // matched against the kernels generated for exactly that stage. + KernelInfo const* findCubinKernel(FmhaOptions options, int headDimPerStageKv, std::string* info = nullptr) const + { + algoFilterForCubinPath(options); + auto [hashId, hashInfo] = hashFromFmhaOptions(options); + if (info != nullptr) + { + *info = hashInfo + ", headDimPerStageKv=" + std::to_string(headDimPerStageKv); + } + if (headDimPerStageKv > 0) + { + auto const it = mStageKvFunctions.find(std::make_pair(hashId, headDimPerStageKv)); + return it == mStageKvFunctions.end() ? nullptr : &it->second; + } + auto const& functions = getFunctions(options.mFusesDsv4InvRopeFp8Quant, options.mUsesDsv4Ue8m0ScaleO); + auto const it = functions.find(hashId); + return it == functions.end() ? nullptr : &it->second; + } + // Autotuner entry for checkIfKernelExist, warmupOneKernel, and run. SM107 may select // CgaSmemReduction configs where clusterDimX * mMaxNumCtasPerSeqKv must stay <= 16; // the pre/post clamps below enforce that. Other architectures keep the legacy path. @@ -1648,6 +1739,8 @@ class TllmGenFmhaKernel std::shared_ptr mDriver; KernelMeta const* mKernelMeta; unsigned int mKernelMetaCount; + StageKvKernelMeta const* mStageKvKernelMeta; + unsigned int mStageKvKernelMetaCount; unsigned int mSM; int mNumEltsPerSageAttnBlkQ; int mNumEltsPerSageAttnBlkK; @@ -1655,12 +1748,6 @@ class TllmGenFmhaKernel int mNumEltsPerSageAttnBlkV; std::unordered_map mModules; - struct KernelInfo - { - unsigned int mMetaInfoIndex; - CUfunction mDeviceFunction; - }; - using KernelMap = std::unordered_map; // Route each kernel to the map matching its DSv4 fused inverse-RoPE FP8 epilogue variant. @@ -1691,6 +1778,9 @@ class TllmGenFmhaKernel KernelMap mFunctions; KernelMap mDsv4FusedFunctions; KernelMap mDsv4FusedUe8m0Functions; + // Kernels for a caller-fixed head dim per K/V stage, keyed by (hashId, headDimPerStageKv); see loadStageKvKernels. + std::map, KernelInfo> mStageKvFunctions; + std::once_flag mStageKvLoaded; FmhaInterface mFmhaInterface{false, 1}; }; @@ -1718,8 +1808,10 @@ class TllmFmhaKernelFactory auto const findIter = mKernels.find(id); if (findIter == mKernels.end()) { + auto const& stageKvKernels = getTllmGenFmhaStageKvKernelMetaInfos(); KernelType* newKernel = new KernelType{pKernelList, nbKernels, dtypeQ, dtypeK, dtypeV, dtypeOut, sm, - numEltsPerSageAttnBlkQ, numEltsPerSageAttnBlkK, numEltsPerSageAttnBlkP, numEltsPerSageAttnBlkV}; + numEltsPerSageAttnBlkQ, numEltsPerSageAttnBlkK, numEltsPerSageAttnBlkP, numEltsPerSageAttnBlkV, + stageKvKernels.data(), static_cast(stageKvKernels.size())}; newKernel->loadKernels(); mKernels.insert(std::make_pair(id, std::unique_ptr(newKernel))); return newKernel; diff --git a/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaRunner.cpp b/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaRunner.cpp index b25ee45cf9ea..5e0110d9c1d5 100644 --- a/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaRunner.cpp +++ b/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaRunner.cpp @@ -104,6 +104,17 @@ std::pair TllmGenFmhaRunner::isSupportedWithInfo(TllmGenFmhaR return mKernel->checkIfKernelExist(runnerParams); } +//////////////////////////////////////////////////////////////////////////////////////////////////// + +bool TllmGenFmhaRunner::usesNvrtc(TllmGenFmhaRunnerParams const& runnerParams) +{ + if (mKernel == nullptr) + { + TLLM_THROW("TRTLLM-GEN: mKernel is null. Cannot select an FMHA kernel."); + } + return mKernel->usesNvrtc(runnerParams); +} + size_t TllmGenFmhaRunner::getTotalDeviceMemory() const { return mTotalDeviceMemory; diff --git a/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaRunner.h b/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaRunner.h index 3f23d0cc2056..f10003881131 100644 --- a/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaRunner.h +++ b/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaRunner.h @@ -44,6 +44,10 @@ class TllmGenFmhaRunner // Check if fmha is supported with additional info. std::pair isSupportedWithInfo(TllmGenFmhaRunnerParams const& runnerParams) const; + // Whether run() would compile the kernel it selects for these params with NVRTC instead of launching a + // precompiled one. + bool usesNvrtc(TllmGenFmhaRunnerParams const& runnerParams); + // Get the total device memory. size_t getTotalDeviceMemory() const; diff --git a/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaRunnerParams.h b/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaRunnerParams.h index df4815da40bf..7e0a6aa95027 100644 --- a/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaRunnerParams.h +++ b/cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaRunnerParams.h @@ -387,6 +387,9 @@ struct TllmGenFmhaRunnerParams bool mFp16Softmax{false}; // Whether the kernel consumes 2:4 structured-sparse (compressed) inputs (Rubin FMHA feature). bool mUsesSpcompress{false}; + // Head dimension per K/V shared-memory stage; 0 lets the autotuner choose. A caller-chosen value is kept; its + // kernel comes from the stage-KV cubin table (kernelMetaInfoStageKv.h) when one matches, else from NVRTC. + int mHeadDimPerStageKv{0}; // set the attention mask type TllmGenFmhaRunnerParams& setAttentionMaskType(std::int8_t maskType) diff --git a/cpp/tensorrt_llm/nanobind/batch_manager/kvCacheManagerV2.cpp b/cpp/tensorrt_llm/nanobind/batch_manager/kvCacheManagerV2.cpp index 440ea4f362e8..42514c55078a 100644 --- a/cpp/tensorrt_llm/nanobind/batch_manager/kvCacheManagerV2.cpp +++ b/cpp/tensorrt_llm/nanobind/batch_manager/kvCacheManagerV2.cpp @@ -53,10 +53,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include @@ -931,6 +933,7 @@ void KvCacheManagerV2Bindings::initBindings(nb::module_& m) static nb::object sOutOfPagesError = nb::exception(m, "OutOfPagesError"); static nb::object sCuError = nb::exception(m, "CuError"); static nb::object sCorruptedError = nb::exception(m, "CorruptedError"); + static nb::object sRemoteMemError = nb::exception(m, "RemoteMemError"); // Default attribute so the class mirrors the pure-Python CuError surface. sCuError.attr("error_code") = nb::none(); @@ -998,8 +1001,13 @@ void KvCacheManagerV2Bindings::initBindings(nb::module_& m) .value("GPU_MEM", kv::CacheTier::GPU_MEM) .value("HOST_MEM", kv::CacheTier::HOST_MEM) .value("DISK", kv::CacheTier::DISK) + .value("REMOTE", kv::CacheTier::REMOTE) .export_values(); + nb::enum_(m, "RemoteTransport") + .value("NIXL", kv::RemoteTransport::kNixl) + .value("FABRIC", kv::RemoteTransport::kFabric); + // ---- KvCache::Status enum (also accessible as _KVCache.Status) --------- auto kvCacheStatus = nb::enum_(m, "KvCacheStatus") .value("ACTIVE", kv::KvCache::Status::ACTIVE) @@ -1760,6 +1768,29 @@ void KvCacheManagerV2Bindings::initBindings(nb::module_& m) .def_prop_ro("tier", &kv::DiskCacheTierConfig::tier) .def("validate", &kv::DiskCacheTierConfig::validate) DEF_COPY(kv::DiskCacheTierConfig); + nb::class_(m, "RemoteTransferConfig") + .def(nb::init>(), + nb::arg("transport") = kv::RemoteTransport::kNixl, + nb::arg("timeout_ms") = kv::RemoteTransferConfig{}.timeoutMs, + nb::arg("backend_params") = std::map{}) + .def_rw("transport", &kv::RemoteTransferConfig::transport) + .def_rw("timeout_ms", &kv::RemoteTransferConfig::timeoutMs) + .def_rw("backend_params", &kv::RemoteTransferConfig::backendParams) DEF_COPY(kv::RemoteTransferConfig); + + nb::class_(m, "RemoteCacheTierConfig") + .def(nb::init, kv::RemoteTransferConfig>(), + nb::arg("quota"), nb::arg("path"), nb::arg("wait_timeout_ms") = kv::RemoteCacheTierConfig{}.waitTimeoutMs, + nb::arg("expected_donors") = 0, nb::arg("pool_ratio") = std::vector{}, + nb::arg("transfer") = kv::RemoteTransferConfig{}) + .def_rw("quota", &kv::RemoteCacheTierConfig::quota) + .def_rw("path", &kv::RemoteCacheTierConfig::path) + .def_rw("wait_timeout_ms", &kv::RemoteCacheTierConfig::waitTimeoutMs) + .def_rw("expected_donors", &kv::RemoteCacheTierConfig::expectedDonors) + .def_rw("pool_ratio", &kv::RemoteCacheTierConfig::poolRatio) + .def_rw("transfer", &kv::RemoteCacheTierConfig::transfer) + .def_prop_ro("tier", &kv::RemoteCacheTierConfig::tier) + .def("validate", &kv::RemoteCacheTierConfig::validate) DEF_COPY(kv::RemoteCacheTierConfig); + nb::class_(m, "SparseCacheConfig") .def(nb::init>(), nb::arg("num_selected_blocks"), nb::arg("max_cached_units"), nb::arg("unit_tokens"), nb::arg("selection_id").none() = nb::none()) @@ -2774,6 +2805,37 @@ void KvCacheManagerV2Bindings::initBindings(nb::module_& m) return std::move(utilization.raw()); }, nb::arg("manager"), nb::arg("cache_level") = kv::kHotLevel.value(), nb::call_guard()); + mIntrospection.def( + "remote_unquiesced_transfers", + // Remote transfers past their deadline whose staging is still out of use, after releasing the quiesced ones. + [](kv::KvCacheManager& manager) { return manager.storage().reapQuiescedRemoteTransfers(); }, nb::arg("manager"), + nb::call_guard()); + mIntrospection.def( + "level_pool_groups", + [](kv::KvCacheManager& manager, int cacheLevel) + { + // Per pool group of one cache level: slot count, bytes per slot, and the layer groups it holds. + auto const& storage = manager.storage(); + kv::CacheLevel const level{cacheLevel}; + TLLM_CHECK_WITH_INFO( + cacheLevel >= 0 && level < storage.numCacheLevels(), "cache_level %d is out of range", cacheLevel); + std::vector>> groups( + static_cast(storage.numPoolGroups(level).value())); + for (kv::PoolGroupIndex pg{0}; pg < storage.numPoolGroups(level); ++pg) + { + auto const& sizes = storage.slotSize(level, pg); + auto& group = groups[static_cast(pg.value())]; + std::get<0>(group) = static_cast(storage.numSlots(pg, level)); + std::get<1>(group) = std::accumulate(sizes.begin(), sizes.end(), size_t{0}); + } + for (kv::LifeCycleId lc{0}; lc < storage.numLifeCycles(); ++lc) + { + std::get<2>(groups[static_cast(storage.getPoolGroupIndex(level, lc).value())]) + .push_back(lc.value()); + } + return groups; + }, + nb::arg("manager"), nb::arg("cache_level"), nb::call_guard()); mIntrospection.def( "grains_for_slots", [](kv::SlotCount numSlots, std::vector const& slotSizeList, size_t granularity, @@ -3689,6 +3751,9 @@ void KvCacheManagerV2Bindings::initBindings(nb::module_& m) { return std::dynamic_pointer_cast(self.eventSink()); }) .def_prop_ro("init_config", [](kv::KvCacheManager const& self) { return self.config(); }) .def_prop_ro("cache_tier_list", [](kv::KvCacheManager const& self) { return self.cacheTierList().raw(); }) + .def_prop_ro("any_remote_level_failed", + // A lock-step scheduler stops once any remote level failed on this rank. Lock-free (atomic flags). + [](kv::KvCacheManager& self) { return self.storage().anyRemoteLevelFailed(); }) .def_prop_ro("all_buffer_ids", &kv::KvCacheManager::allBufferIds) .def_prop_ro("pool_group_descs", [](kv::KvCacheManager const& self) diff --git a/cpp/tensorrt_llm/thop/CMakeLists.txt b/cpp/tensorrt_llm/thop/CMakeLists.txt index 2810611b5725..d30ffb9488ed 100644 --- a/cpp/tensorrt_llm/thop/CMakeLists.txt +++ b/cpp/tensorrt_llm/thop/CMakeLists.txt @@ -68,9 +68,13 @@ add_th_common_family( dsv3RopeOp.cpp convertReqIndexToGlobalOp.cpp nvfp4MlaKvCacheGatherOp.cpp + pagedFp8ContextFmhaOp.cpp trtllmGenQKVProcessOp.cpp) target_include_directories(th_common_attention PRIVATE ${TRTLLM_FMHA_PARAMS_GENERATED_INCLUDE_DIR}) +# pagedFp8ContextFmhaOp.cpp includes the trtllm-gen FMHA runner headers (see +# th_common_visual_gen below). +target_link_libraries(th_common_attention PRIVATE trtllm_gen_fmha_interface) # MiniMax-M3 torch ops live in minimaxM3/; that directory adds them to # th_common_attention with target_sources() so the list stays next to the files. diff --git a/cpp/tensorrt_llm/thop/allreduceOp.cpp b/cpp/tensorrt_llm/thop/allreduceOp.cpp index eb54eb32620d..75f3293860e2 100644 --- a/cpp/tensorrt_llm/thop/allreduceOp.cpp +++ b/cpp/tensorrt_llm/thop/allreduceOp.cpp @@ -886,13 +886,22 @@ class AllreduceOp auto const hidden_size = input.size(-1); auto const stream = at::cuda::getCurrentCUDAStream(input.get_device()); - torch::Tensor norm_out = torch::empty_like(input); + // RESIDUAL_RMS_NORM_[OUT_]QUANT_FP8 with a float per-tensor scale on the device: residual + norm + FP8 + // quantization in one kernel, bitwise equal to residualRmsNorm + the static per-tensor quantize. + bool const fusedQuantFp8 = (mOp == AllReduceFusionOp::RESIDUAL_RMS_NORM_QUANT_FP8 + || mOp == AllReduceFusionOp::RESIDUAL_RMS_NORM_OUT_QUANT_FP8) + && scale && scale.value().is_cuda() && scale.value().scalar_type() == torch::kFloat32 && norm_weight + && !bias && tensorrt_llm::kernels::residualRmsNormQuantFp8Supported(mType, static_cast(hidden_size)); + bool const fusedNormOut = fusedQuantFp8 && mOp == AllReduceFusionOp::RESIDUAL_RMS_NORM_OUT_QUANT_FP8; + + // The fused QUANT_FP8 path does not return the norm output, so it does not allocate one. + torch::Tensor norm_out = (!fusedQuantFp8 || fusedNormOut) ? torch::empty_like(input) : torch::Tensor(); tensorrt_llm::kernels::AllReduceParams params; params.fusion_params.bias_buffer = bias ? bias.value().data_ptr() : nullptr; params.fusion_params.residual_buffer = residual ? residual.value().data_ptr() : nullptr; params.fusion_params.weight_buffer = norm_weight ? norm_weight.value().data_ptr() : nullptr; - params.local_output_buffer_ptr = norm_out.mutable_data_ptr(); + params.local_output_buffer_ptr = norm_out.defined() ? norm_out.mutable_data_ptr() : nullptr; params.elts_total = size; params.fusion_params.hidden_size = hidden_size; @@ -908,6 +917,18 @@ class AllreduceOp return {norm_out}; } + if (fusedQuantFp8) + { + torch::Tensor quant_out = torch::empty(input.sizes(), input.options().dtype(torch::kFloat8_e4m3fn)); + tensorrt_llm::kernels::residualRmsNormQuantFp8( + params, mType, quant_out.mutable_data_ptr(), scale.value().data_ptr(), fusedNormOut, stream); + if (fusedNormOut) + { + return {norm_out, quant_out, reduce_output}; + } + return {quant_out, reduce_output}; + } + // All remaining patterns use residual + rmsnorm. tensorrt_llm::kernels::residualRmsNorm(params, mType, stream, AllReduceFusionOp::RESIDUAL_RMS_NORM); diff --git a/cpp/tensorrt_llm/thop/moe/trtllmGen/fp4BlockScaleMoe.cpp b/cpp/tensorrt_llm/thop/moe/trtllmGen/fp4BlockScaleMoe.cpp index 14ec703300d3..d061caed6eff 100644 --- a/cpp/tensorrt_llm/thop/moe/trtllmGen/fp4BlockScaleMoe.cpp +++ b/cpp/tensorrt_llm/thop/moe/trtllmGen/fp4BlockScaleMoe.cpp @@ -59,8 +59,13 @@ std::vector run_fp4_block_scale_moe_runner(torch::optional const routed_scaling_factor, int64_t const tile_tokens_dim, int64_t const routing_method_type, bool const do_finalize, btg::Dtype const dtype, MoeRunnerType& moe_runner, int64_t const moeConfigIndex, torch::optional const& topk_weights, torch::optional const& topk_ids, - torch::optional const& out_tensor = torch::nullopt, PreRoutedBuffers const* prerouted = nullptr) + torch::optional const& out_tensor = torch::nullopt, PreRoutedBuffers const* prerouted = nullptr, + bool const fc1_only = false) { + // fc1_only: routing (unless pre-routed) and FC1 only; the caller runs FC2 into the returned gemm2 output, which + // keeps the do_finalize == false contract (gemm2 output, expert weights, expanded -> permuted index). + TORCH_CHECK(!fc1_only || (!do_finalize && !out_tensor.has_value() && dtype == btg::Dtype::E2m1), + "fc1_only requires do_finalize == false, no output tensor and E2m1 activations."); TORCH_CHECK(dtype == btg::Dtype::E4m3 || dtype == btg::Dtype::E2m1, "dtype can only be e4m3 or e2m1."); TORCH_CHECK(tensorrt_llm::common::isSM100Family(), "Only SM100f is supported by FP4 block scale MOE"); TORCH_CHECK(tile_tokens_dim == 8 || tile_tokens_dim == 16 || tile_tokens_dim == 32 || tile_tokens_dim == 64 @@ -534,6 +539,7 @@ std::vector run_fp4_block_scale_moe_runner(torch::optional(); args.output2_scales_scalar = output2_scales_scalar.data_ptr(); args.do_finalize = do_finalize; + args.skip_gemm2 = fc1_only; auto const workspace_sizes = moe_runner.getWorkspaceSizeInBytes(args, moeConfigIndex); @@ -546,11 +552,17 @@ std::vector run_fp4_block_scale_moe_runner(torch::optional permuted index, CTA -> batch, CTA -> row limit, CTAs]. + [[nodiscard]] std::vector runFc1(torch::optional const& routing_logits, + torch::optional const& routing_bias, torch::Tensor const& hidden_states, + torch::Tensor const& hidden_states_scale, torch::Tensor const& gemm1_weights, + torch::Tensor const& gemm1_weights_scale, std::optional const& gemm1_bias, + std::optional const& gemm1_alpha, std::optional const& gemm1_beta, + std::optional const& gemm1_clamp_limit, torch::Tensor const& gemm2_weights, + torch::Tensor const& gemm2_weights_scale, torch::Tensor const& output1_scales_scalar, + torch::Tensor const& output1_scales_gate_scalar, torch::Tensor const& output2_scales_scalar, + int64_t const num_experts, int64_t const top_k, std::optional const n_group, + std::optional const topk_group, int64_t const intermediate_size, int64_t const local_expert_offset, + int64_t const local_num_experts, std::optional const routed_scaling_factor, + int64_t const routing_method_type, std::vector moeConfigIndex, + torch::optional const& topk_weights, torch::optional const& topk_ids) + { + return runImpl(routing_logits, routing_bias, hidden_states, hidden_states_scale, gemm1_weights, + gemm1_weights_scale, gemm1_bias, gemm1_alpha, gemm1_beta, gemm1_clamp_limit, gemm2_weights, + gemm2_weights_scale, std::nullopt, output1_scales_scalar, output1_scales_gate_scalar, output2_scales_scalar, + num_experts, top_k, n_group, topk_group, intermediate_size, local_expert_offset, local_num_experts, + routed_scaling_factor, routing_method_type, /*do_finalize=*/false, moeConfigIndex, topk_weights, topk_ids, + torch::nullopt, /*prerouted=*/nullptr, /*routing_tile_n=*/-1, /*fc1_only=*/true); } // run() with caller-computed routing tables for tile routing_tile_n (see PreRoutedBuffers), used in place of the @@ -678,10 +715,95 @@ class FP4BlockScaleMoeRunner : public torch::CustomClassHolder gemm2_weights_scale, gemm2_bias, output1_scales_scalar, output1_scales_gate_scalar, output2_scales_scalar, num_experts, top_k, n_group, topk_group, intermediate_size, local_expert_offset, local_num_experts, routed_scaling_factor, routing_method_type, do_finalize, moeConfigIndex, topk_weights, topk_ids, output, - &prerouted, routing_tile_n); + &prerouted, routing_tile_n, /*fc1_only=*/false); + } + + // runPrerouted() up to FC1 + activation, with the arguments and outputs of runFc1. + [[nodiscard]] std::vector runPreroutedFc1(torch::optional const& routing_logits, + torch::optional const& routing_bias, torch::Tensor const& hidden_states, + torch::Tensor const& hidden_states_scale, torch::Tensor const& gemm1_weights, + torch::Tensor const& gemm1_weights_scale, std::optional const& gemm1_bias, + std::optional const& gemm1_alpha, std::optional const& gemm1_beta, + std::optional const& gemm1_clamp_limit, torch::Tensor const& gemm2_weights, + torch::Tensor const& gemm2_weights_scale, torch::Tensor const& output1_scales_scalar, + torch::Tensor const& output1_scales_gate_scalar, torch::Tensor const& output2_scales_scalar, + int64_t const num_experts, int64_t const top_k, std::optional const n_group, + std::optional const topk_group, int64_t const intermediate_size, int64_t const local_expert_offset, + int64_t const local_num_experts, std::optional const routed_scaling_factor, + int64_t const routing_method_type, std::vector moeConfigIndex, + torch::optional const& topk_weights, torch::optional const& topk_ids, + torch::Tensor const& expanded_idx_to_permuted_idx, torch::Tensor const& permuted_idx_to_token_idx, + torch::Tensor const& cta_idx_xy_to_batch_idx, torch::Tensor const& cta_idx_xy_to_mn_limit, + torch::Tensor const& num_non_exiting_ctas, torch::Tensor const& total_num_padded_tokens, + int64_t const routing_tile_n) + { + PreRoutedBuffers const prerouted{expanded_idx_to_permuted_idx, permuted_idx_to_token_idx, + cta_idx_xy_to_batch_idx, cta_idx_xy_to_mn_limit, num_non_exiting_ctas, total_num_padded_tokens}; + return runImpl(routing_logits, routing_bias, hidden_states, hidden_states_scale, gemm1_weights, + gemm1_weights_scale, gemm1_bias, gemm1_alpha, gemm1_beta, gemm1_clamp_limit, gemm2_weights, + gemm2_weights_scale, std::nullopt, output1_scales_scalar, output1_scales_gate_scalar, output2_scales_scalar, + num_experts, top_k, n_group, topk_group, intermediate_size, local_expert_offset, local_num_experts, + routed_scaling_factor, routing_method_type, /*do_finalize=*/false, moeConfigIndex, topk_weights, topk_ids, + torch::nullopt, &prerouted, routing_tile_n, /*fc1_only=*/true); + } + + // Kernel name of the FC2 cubin a tactic [tileN, config] runs (non-FineGrained runner). + [[nodiscard]] std::string getGemm2KernelName(int64_t tileN, int64_t config) + { + return getRunner(static_cast(tileN), /*useFineGrained=*/false).getGemm2KernelName(config); + } + + // Arithmetic options of the FC2 cubin a tactic [tileN, config] runs (non-FineGrained runner), as strings + // (TrtllmGenBatchedGemmRunner::getKernelOptionsFromConfigIndex). + [[nodiscard]] c10::Dict getGemm2KernelOptions(int64_t tileN, int64_t config) + { + c10::Dict result; + for (auto const& [key, value] : + getRunner(static_cast(tileN), /*useFineGrained=*/false).getGemm2KernelOptions(config)) + { + result.insert(key, value); + } + return result; + } + + // Whether a call of this shape on tile tileN runs the fine-grained-sync FC1 / FC2 pair instead of the tuned + // tactic: TLLM_USE_FINE_GRAINED_SYNC is set and a fine-grained cubin with a valid config exists for it. + [[nodiscard]] bool usesFineGrainedSync(int64_t tileN, int64_t topK, int64_t hiddenSize, int64_t intermediateSize, + int64_t numLocalExperts, int64_t numTokens) + { + int64_t config = -1; + return fineGrainedRunner(tileN, topK, hiddenSize, intermediateSize, numLocalExperts, numTokens, config) + != nullptr; } private: + // The fine-grained-sync runner a call of this shape prefers on tile tileN, with its default config in + // configOut, or nullptr (TLLM_USE_FINE_GRAINED_SYNC unset, no fine-grained cubin for the tile, or none valid for + // the shape): the call then runs the tuned tactic on the non-fine-grained runner. + RunnerType* fineGrainedRunner(int64_t tileN, int64_t topK, int64_t hiddenSize, int64_t intermediateSize, + int64_t numLocalExperts, int64_t numTokens, int64_t& configOut) + { + if (!tensorrt_llm::common::getEnvUseFineGrainedSync()) + { + return nullptr; + } + auto* runner = getRunnerOrNull(static_cast(tileN), /*useFineGrained=*/true); + if (runner == nullptr) + { + return nullptr; + } + try + { + configOut + = runner->getDefaultValidConfigIndex(topK, hiddenSize, intermediateSize, numLocalExperts, numTokens); + return runner; + } + catch (std::exception const&) + { + return nullptr; // no valid config for this shape + } + } + [[nodiscard]] std::vector runImpl(torch::optional const& routing_logits, torch::optional const& routing_bias, torch::Tensor const& hidden_states, torch::Tensor const& hidden_states_scale, torch::Tensor const& gemm1_weights, @@ -696,11 +818,10 @@ class FP4BlockScaleMoeRunner : public torch::CustomClassHolder std::optional const routed_scaling_factor, int64_t const routing_method_type, bool const do_finalize, std::vector moeConfigIndex, torch::optional const& topk_weights, torch::optional const& topk_ids, torch::optional const& output, - PreRoutedBuffers const* prerouted, int64_t const routing_tile_n) + PreRoutedBuffers const* prerouted, int64_t const routing_tile_n, bool const fc1_only) { int64_t tileN = moeConfigIndex[0]; int64_t config = moeConfigIndex[1]; - bool const useFineGrained = tensorrt_llm::common::getEnvUseFineGrainedSync(); auto const num_tokens = hidden_states.sizes()[0]; // 2x FP4 per byte element @@ -712,7 +833,7 @@ class FP4BlockScaleMoeRunner : public torch::CustomClassHolder float const avg_tokens_per_expert = static_cast(num_tokens * top_k) / local_num_experts; tileN = std::clamp(nextPowerOfTwo(avg_tokens_per_expert), mSupportedTileN.front(), mSupportedTileN.back()); config - = getRunner(tileN, /* useFineGrained */ false) + = getRunner(tileN, /*useFineGrained=*/false) .getDefaultValidConfigIndex(top_k, hidden_size, intermediate_size, local_num_experts, num_tokens); } @@ -720,29 +841,15 @@ class FP4BlockScaleMoeRunner : public torch::CustomClassHolder // passes local expert counts, global expert ids and no logits). TORCH_CHECK(prerouted == nullptr || tileN == routing_tile_n, "pre-routed call built for tile ", routing_tile_n, " cannot run with tile ", tileN); - // Prefer the fine-grained runner for the tuned tile when it has a valid config for this shape. - RunnerType* runner = nullptr; + // Prefer the fine-grained runner for the tuned tile when it has a valid config for this shape; only that + // pair has no FC1-only entry (without a fine-grained cubin the call runs the tuned tactic). int64_t configToRun = config; - if (useFineGrained) - { - auto* fineGrainedRunner = getRunnerOrNull(tileN, /* useFineGrained */ true); - if (fineGrainedRunner != nullptr) - { - try - { - configToRun = fineGrainedRunner->getDefaultValidConfigIndex( - top_k, hidden_size, intermediate_size, local_num_experts, num_tokens); - runner = fineGrainedRunner; - } - catch (std::exception const&) - { - runner = nullptr; // no valid config for this shape; fall back to the tuned tactic - } - } - } + RunnerType* runner = fineGrainedRunner( + tileN, top_k, hidden_size, intermediate_size, local_num_experts, num_tokens, configToRun); + TORCH_CHECK(!fc1_only || runner == nullptr, "fc1_only does not support FineGrained sync."); if (runner == nullptr) { - runner = &getRunner(tileN, /* useFineGrained */ false); + runner = &getRunner(tileN, /*useFineGrained=*/false); configToRun = config; } return run_fp4_block_scale_moe_runner(routing_logits, routing_bias, hidden_states, hidden_states_scale, @@ -750,7 +857,7 @@ class FP4BlockScaleMoeRunner : public torch::CustomClassHolder gemm2_weights_scale, gemm2_bias, output1_scales_scalar, output1_scales_gate_scalar, output2_scales_scalar, num_experts, top_k, n_group, topk_group, intermediate_size, local_expert_offset, local_num_experts, routed_scaling_factor, tileN, routing_method_type, do_finalize, mDtypeElt, *runner, configToRun, - topk_weights, topk_ids, output, prerouted); + topk_weights, topk_ids, output, prerouted, fc1_only); } std::vector const mSupportedTileN; @@ -871,7 +978,12 @@ TORCH_LIBRARY_FRAGMENT(trtllm, m) .def(torch::init()) .def("get_valid_configs", &tensorrt_llm::torch_ext::FP4BlockScaleMoeRunner::getValidConfigs) .def("run_moe", &tensorrt_llm::torch_ext::FP4BlockScaleMoeRunner::run) - .def("run_moe_prerouted", &tensorrt_llm::torch_ext::FP4BlockScaleMoeRunner::runPrerouted); + .def("run_moe_prerouted", &tensorrt_llm::torch_ext::FP4BlockScaleMoeRunner::runPrerouted) + .def("run_moe_fc1", &tensorrt_llm::torch_ext::FP4BlockScaleMoeRunner::runFc1) + .def("run_moe_prerouted_fc1", &tensorrt_llm::torch_ext::FP4BlockScaleMoeRunner::runPreroutedFc1) + .def("get_gemm2_kernel_name", &tensorrt_llm::torch_ext::FP4BlockScaleMoeRunner::getGemm2KernelName) + .def("get_gemm2_kernel_options", &tensorrt_llm::torch_ext::FP4BlockScaleMoeRunner::getGemm2KernelOptions) + .def("uses_fine_grained_sync", &tensorrt_llm::torch_ext::FP4BlockScaleMoeRunner::usesFineGrainedSync); m.class_("FP8FP4BlockScaleMoERunner") .def(torch::init()) .def("get_valid_configs", &tensorrt_llm::torch_ext::FP8FP4BlockScaleMoeRunner::getValidConfigs) diff --git a/cpp/tensorrt_llm/thop/pagedFp8ContextFmhaOp.cpp b/cpp/tensorrt_llm/thop/pagedFp8ContextFmhaOp.cpp new file mode 100644 index 000000000000..927ae95c5aab --- /dev/null +++ b/cpp/tensorrt_llm/thop/pagedFp8ContextFmhaOp.cpp @@ -0,0 +1,189 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Causal FP8 context attention over TRT-LLM's paged HND KV pool through the trtllm-gen FMHA runner, with a caller-fixed +// head dimension per K/V stage: a precompiled stage-KV kernel when one matches the selected config; otherwise the op +// declines (NVRTC only with the test-only allow_nvrtc). + +#include "tensorrt_llm/kernels/multiHeadAttentionCommon.h" +#include "tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaRunner.h" +#include "tensorrt_llm/thop/thUtils.h" + +#include +#include +#include + +#include +#include +#include +#include +#include + +TRTLLM_NAMESPACE_BEGIN + +namespace torch_ext +{ + +namespace +{ + +namespace tk = tensorrt_llm::kernels; + +// One E4M3-in / BF16-out runner per device; the runner holds the loaded cubins and the NVRTC kernel cache. +tk::TllmGenFmhaRunner& runnerFor(int device) +{ + static std::mutex mutex; + static std::map> runners; + std::lock_guard lock(mutex); + auto it = runners.find(device); + if (it == runners.end()) + { + it = runners + .emplace(device, + std::make_unique( + tk::DATA_TYPE_E4M3, tk::DATA_TYPE_E4M3, tk::DATA_TYPE_E4M3, tk::DATA_TYPE_BF16)) + .first; + } + return *it->second; +} + +// The shape-independent part of the runner params: layout, mask, kernel type, head dims, page size and stage. +tk::TllmGenFmhaRunnerParams makeParams(int64_t headDim, int64_t tokensPerPage, int64_t headDimPerStageKv) +{ + tk::TllmGenFmhaRunnerParams p{}; + p.mQkvLayout = tk::QkvLayout::PagedKv; + p.mMaskType = tk::TrtllmGenAttentionMaskType::Causal; + p.mKernelType = tk::FmhaKernelType::Context; + p.mTileScheduler = tk::TileScheduler::Persistent; + p.mHeadDimQk = static_cast(headDim); + p.mHeadDimV = static_cast(headDim); + p.mNumTokensPerPage = static_cast(tokensPerPage); + p.mHeadDimPerStageKv = static_cast(headDimPerStageKv); + return p; +} + +} // namespace + +// q: e4m3 [T, Hq, D]; kv_pool: e4m3 [pages, Hkv, tokens_per_page, D]; block_tables: int32 [B, 2, max_pages] (K and V +// page indices); seq_lens_kv: int32 [B]; cu_seqlens_q / cu_seqlens_kv: int32 [B + 1]; out: bf16 [T, Hq * D], written. +// scale_bmm1: fp32 [2] on device, [softmax scale, softmax scale * log2(e)] with the Q / K descales folded in. +// scale_out: fp32 [1] on device, the V descale. head_dim_per_stage_kv: the head dim per K/V stage (> 0). +// Returns false, launching nothing, when the kernel the runner selects for this call has no precompiled cubin and +// allow_nvrtc is false (the caller then runs another kernel instead of compiling one inside the step). +bool fmha_paged_context_fp8(torch::Tensor const& q, torch::Tensor const& kv_pool, torch::Tensor const& block_tables, + torch::Tensor const& seq_lens_kv, torch::Tensor const& cu_seqlens_q, torch::Tensor const& cu_seqlens_kv, + torch::Tensor& out, torch::Tensor const& scale_bmm1, torch::Tensor const& scale_out, int64_t max_q_len, + int64_t max_kv_len, int64_t head_dim_per_stage_kv, bool allow_nvrtc) +{ + TORCH_CHECK(q.scalar_type() == c10::ScalarType::Float8_e4m3fn && kv_pool.scalar_type() == q.scalar_type(), + "fmha_paged_context_fp8: q and kv_pool must be float8_e4m3fn"); + TORCH_CHECK(q.dim() == 3 && q.is_contiguous(), "fmha_paged_context_fp8: q must be a contiguous [T, H, D] tensor"); + TORCH_CHECK(kv_pool.dim() == 4 && kv_pool.is_contiguous() && kv_pool.size(3) == q.size(2), + "fmha_paged_context_fp8: kv_pool must be a contiguous [pages, Hkv, tokens_per_page, D] tensor"); + // && short-circuits: the multiple check divides by the KV heads only once there are some. + TORCH_CHECK(kv_pool.size(1) > 0 && q.size(1) % kv_pool.size(1) == 0, + "fmha_paged_context_fp8: kv_pool must have KV heads and Q heads must be a multiple of them"); + TORCH_CHECK(out.scalar_type() == c10::ScalarType::BFloat16 && out.is_contiguous() && out.numel() == q.numel(), + "fmha_paged_context_fp8: out must be a contiguous bf16 tensor with q's element count"); + TORCH_CHECK(block_tables.scalar_type() == c10::ScalarType::Int && block_tables.dim() == 3 + && block_tables.size(1) == 2 && block_tables.is_contiguous(), + "fmha_paged_context_fp8: block_tables must be a contiguous int32 [B, 2, max_pages] tensor"); + int64_t const batch = block_tables.size(0); + for (auto const* t : {&seq_lens_kv, &cu_seqlens_q, &cu_seqlens_kv}) + { + TORCH_CHECK(t->scalar_type() == c10::ScalarType::Int && t->dim() == 1, + "fmha_paged_context_fp8: sequence lengths must be int32 vectors"); + } + TORCH_CHECK(seq_lens_kv.numel() >= batch && cu_seqlens_q.numel() > batch && cu_seqlens_kv.numel() > batch, + "fmha_paged_context_fp8: sequence length vectors are shorter than the batch"); + TORCH_CHECK(scale_bmm1.scalar_type() == c10::ScalarType::Float && scale_bmm1.numel() >= 2, + "fmha_paged_context_fp8: scale_bmm1 must be float32 [2]"); + TORCH_CHECK(scale_out.scalar_type() == c10::ScalarType::Float && scale_out.numel() >= 1, + "fmha_paged_context_fp8: scale_out must be float32 [1]"); + TORCH_CHECK(max_q_len > 0 && max_kv_len >= max_q_len, "fmha_paged_context_fp8: invalid max sequence lengths"); + TORCH_CHECK(head_dim_per_stage_kv > 0, "fmha_paged_context_fp8: head_dim_per_stage_kv must be > 0"); + for (at::Tensor const* t : std::initializer_list{ + &kv_pool, &block_tables, &seq_lens_kv, &cu_seqlens_q, &cu_seqlens_kv, &out, &scale_bmm1, &scale_out}) + { + TORCH_CHECK(t->device() == q.device(), "fmha_paged_context_fp8: all tensors must be on the device of q"); + } + + c10::cuda::CUDAGuard const deviceGuard(q.device()); + int const device = q.get_device(); + int64_t const numTokens = q.size(0); + int64_t const numHeadsQ = q.size(1); + int64_t const numHeadsKv = kv_pool.size(1); + int64_t const headDim = q.size(2); + + tk::TllmGenFmhaRunnerParams p = makeParams(headDim, kv_pool.size(2), head_dim_per_stage_kv); + p.mMultiCtasKvMode = false; + p.qPtr = q.data_ptr(); + p.kvPtr = kv_pool.data_ptr(); + p.kvPageIdxPtr = block_tables.data_ptr(); + p.seqLensKvPtr = seq_lens_kv.data_ptr(); + p.cumSeqLensQPtr = cu_seqlens_q.data_ptr(); + p.cumSeqLensKvPtr = cu_seqlens_kv.data_ptr(); + p.oPtr = out.data_ptr(); + // No softmax stats: the kernels skip that store for a null pointer, as in the regular context dispatch. + p.softmaxStatsPtr = nullptr; + // The kernels read both scales from device memory. + p.scaleSoftmaxLog2Ptr = scale_bmm1.data_ptr() + tk::kIdxScaleSoftmaxLog2Ptr; + p.outputScalePtr = scale_out.data_ptr(); + p.mNumHeadsQ = static_cast(numHeadsQ); + p.mNumHeadsKv = static_cast(numHeadsKv); + p.mNumHeadsQPerKv = static_cast(numHeadsQ / numHeadsKv); + p.mBatchSize = static_cast(batch); + p.mMaxSeqLenQ = static_cast(max_q_len); + p.mMaxSeqLenKv = static_cast(max_kv_len); + p.mMaxSeqLenCacheKv = static_cast(max_kv_len); + p.mSumOfSeqLensQ = static_cast(numTokens); + p.mSumOfSeqLensKv = static_cast(std::min(batch * max_kv_len, INT_MAX)); + p.mMaxNumPagesPerSeqKv = static_cast(block_tables.size(2)); + p.mNumPagesInMemPool = static_cast(std::min(kv_pool.size(0), INT_MAX)); + p.mChunkedAttentionSize = INT_MAX; + p.mLeftSlidingWindow = -1; + p.mRightSlidingWindow = -1; + p.mScaleQ = 1.0f; + int smCount = 0; + TLLM_CUDA_CHECK(cudaDeviceGetAttribute(&smCount, cudaDevAttrMultiProcessorCount, device)); + p.mMultiProcessorCount = smCount; + p.stream = at::cuda::getCurrentCUDAStream(device); + tk::TllmGenFmhaRunner& runner = runnerFor(device); + if (!allow_nvrtc && runner.usesNvrtc(p)) + { + return false; + } + runner.run(p); + return true; +} + +} // namespace torch_ext + +TRTLLM_NAMESPACE_END + +TORCH_LIBRARY_FRAGMENT(trtllm, m) +{ + m.def( + "fmha_paged_context_fp8(Tensor q, Tensor kv_pool, Tensor block_tables, Tensor seq_lens_kv, " + "Tensor cu_seqlens_q, Tensor cu_seqlens_kv, Tensor(a!) out, Tensor scale_bmm1, Tensor scale_out, " + "int max_q_len, int max_kv_len, int head_dim_per_stage_kv, bool allow_nvrtc=False) -> bool"); +} + +TORCH_LIBRARY_IMPL(trtllm, CUDA, m) +{ + m.impl("fmha_paged_context_fp8", &tensorrt_llm::torch_ext::fmha_paged_context_fp8); +} diff --git a/docs/source/deployment-guide/deployment-guide-for-qwen3.8-qwen3.5-on-trtllm.md b/docs/source/deployment-guide/deployment-guide-for-qwen3.8-qwen3.5-on-trtllm.md index c82f480416d5..07f89d5d5526 100644 --- a/docs/source/deployment-guide/deployment-guide-for-qwen3.8-qwen3.5-on-trtllm.md +++ b/docs/source/deployment-guide/deployment-guide-for-qwen3.8-qwen3.5-on-trtllm.md @@ -210,6 +210,15 @@ source system has 840 GiB of host memory per four-GPU node. A fully occupied four-rank node reserves 512 GiB for host KV cache. Check the remaining host-memory budget before increasing worker count or cache size. +These profiles do not use the +[remote KV cache level](../features/kvcache.md#remote-cache-level-in-donated-host-memory-prototype). +If you add it, every rank with `remote_cache_config.donor.size` also holds that +many bytes of host memory for the life of its process, on top of its +`host_cache_size`. For example, decode ranks that donate 100 GiB each on a full +four-rank node with 128 GiB host caches use 912 GiB, which exceeds the 840 GiB of +the source system. Lower `host_cache_size` or `donor.size` on the donating ranks +so that host cache plus donation fits each node's budget. + Use a GB300 NVL72 system with working GPU peer access and NIXL/UCX transport. For workers spanning nodes, the hosts must share the required NVLink fabric and have compatible MPI, drivers, networking, and container mounts. Have reachable @@ -304,6 +313,14 @@ mpirun --allow-run-as-root -np 2 --bind-to none \ --publish-metrics ``` +If you also enable MTP (`speculative_config`) on the prefill worker, add +`export TRTLLM_DISAGG_ROLE=context` to the prefill shell. Ranks started by +`trtllm-llmapi-launch` do not receive a server role, so without it the prefill +worker reserves the GDN replay-state KV region that only decode uses. With +`pool_ratio` set, startup then fails with `initial_pool_ratio length must match +number of layer groups`. The profile above runs MTP on decode only and needs no +role setting. + The container runs as root; omit `--allow-run-as-root` when using a non-root user. The rank counts must match `tensor_parallel_size * pipeline_parallel_size` for each worker; launch a diff --git a/docs/source/features/disagg-serving.md b/docs/source/features/disagg-serving.md index a6001d2913d2..f4251b76b41d 100644 --- a/docs/source/features/disagg-serving.md +++ b/docs/source/features/disagg-serving.md @@ -300,7 +300,7 @@ A single disaggregated server process is itself a single-threaded orchestrator a The two roles split as follows: -- **Coordinator** — a single process that owns all cluster state: the ctx/gen routers, worker readiness, and (for the KV-cache-aware router) the single ZMQ event-ingest endpoint. It exposes an internal coordination API (`/select`, `/finish`, `/cluster_info`, `/health`). +- **Coordinator** — a single process that owns all cluster state: the ctx/gen routers, worker readiness, and (for the KV-cache-aware router) the single ZMQ event-ingest endpoint. It exposes an internal coordination API (`/select`, `/finish`, `/renew`, `/cluster_info`, `/health`, `/version`, and `/output_length` for [output-length prediction](#generation-admission-by-predicted-output-length)). The API has no authentication: any client that reaches the coordinator's port can reserve and release servers, and through `/output_length` record arbitrary in-range reply lengths, with or without a conversation ID. Such records change the named conversation's later predictions and also train the global models (median, ridge, trees) that predict every request, so they change the generation priority of all clients' requests, and the effect outlasts them (the ridge statistics cover all history). Keep the port reachable only from the fleet workers. - **Fleet workers** — `num_workers` stateless disaggregated servers that share the public port via `SO_REUSEPORT` (each worker is its own process binding the same port, so the kernel load-balances incoming connections across them by 4-tuple hash). Each holds a lightweight delegating client: it computes the routing key locally (e.g. block hashes) and delegates the placement decision to the coordinator over HTTP. Workers own no routing state, so routing stays globally consistent no matter which worker terminates a connection. Each worker also gets a distinct `process_id` for the [global request ID](#unique-global-request-id). This is controlled by two fields in the disaggregated config: @@ -320,6 +320,16 @@ The three resulting topologies: The fleet delegates `load_balancing`, `kv_cache_aware`, and `conversation` routing to the coordinator, so their placement and in-flight load state are globally consistent across workers. `round_robin` remains local to each worker and does not make a coordinator round-trip. ``` +#### Generation admission by predicted output length + +With `output_length_prediction: {}` (predictor `ridge`, the default) or `{predictor: ridge_gbm}` at the top level of the disaggregated config, the coordinator learns reply lengths online and the orchestrator sets the `priority` of every completion and chat completion generation request from the predicted length (shorter first; `max_tokens` is never read). `/v1/responses` requests have no `priority` field and are not predicted: with pooled dispatch (below) they wait for a seat at the prior's priority, any `priority` the client sends with them is ignored, and generation servers give them the default priority. A reply with `n` sequences is learned as the length of one sequence. Replies without a conversation ID train the global models (median, ridge, trees) but have no per-conversation history (see the conversation-ID note below). A streamed request's generation leg always asks for usage, which is how its length is learned; if the client did not ask for it, the final usage chunk is dropped from its stream, and a stream that ends without that chunk is not learned. In a fleet, a generation router placed by the coordinator gets the prediction inside `/select`, without an extra round trip; other fleets ask the coordinator's `/output_length`, which also takes the finished replies' lengths in batches and rejects lengths that are not numbers of tokens in [0, 2^24]. A request the coordinator fails to predict gets the prior's priority, and so does a request that conditional disaggregation serves without a context phase. Prediction needs `schedule_style: context_first` (the prompt length comes from the context phase); the server refuses to start with `generation_first`. `ridge_gbm` adds a gradient-boosted tree ensemble, fitted in a separate process with scikit-learn, which is not a TensorRT-LLM dependency: the server checks at startup that it can fit and export the trees, and refuses to start otherwise. Generation servers order their waiting queue by the priority with `scheduler_config: {waiting_queue_policy: priority, waiting_queue_max_wait_s: 60}`; the cap lets a request that waited that long go first. + +This priority queue and main's GEN admission by original arrival (`TLLM_GEN_ADMISSION_TTFT_PERCENTILE` > 0, see [generation slot preemption](#generation-slot-preemption-prototype)) are alternatives. With `waiting_queue_max_wait_s` set, a generation server that also has `TLLM_GEN_ADMISSION_TTFT_PERCENTILE` > 0 refuses to start; without the cap, the admission by arrival replaces the priority queue and the predicted priorities are ignored (a warning says so). GEN slot preemption needs the admission by arrival in its auto mode (`0 < TLLM_GEN_ADMISSION_TTFT_PERCENTILE < 99`), so it is not available with the priority queue. Use the priority queue with output-length prediction to run short predicted replies first; use the admission by arrival, optionally with preemption, to order by arrival at the orchestrator toward a TTFT percentile. + +`generation_servers.router: {type: load_balancing, max_requests_per_server: 64, max_queue_wait_s: 60}` additionally holds generation requests in the orchestrator until a server has a free seat (fewer than `max_requests_per_server` active requests), in the same order, with the cap also counted from the arrival at the orchestrator. Set `max_requests_per_server` to the number of requests a generation server runs at once: its `max_batch_size` × `pipeline_parallel_size`, times `tensor_parallel_size` with `enable_attention_dp` (a seat counts requests per server URL, and an attention-DP server spreads them over its ranks). A smaller value leaves decode batch slots unused; with attention DP, `max_batch_size` alone caps the server at one rank's share. `max_queue_wait_s` requires `max_requests_per_server`. A request held there longer than the context servers' `cache_transceiver_config.kv_transfer_timeout_ms`, less a 5% margin, fails with HTTP 503. A context server with the C++ transceiver (`transceiver_runtime: CPP`) counts that timeout from its KV send, a little before the request joins the queue, and has dropped the transfer by then (the margin covers that gap); the Python transceiver (the default) holds a send that its generation peer has not asked for up to three timeouts from the send, so there the bound is conservative (with `schedule_style: generation_first` the context server waits as long for the generation side); keep `max_queue_wait_s` at or below it. The orchestrator takes the smallest value the context servers report in `/server_info` (their own `--config`), and waits without a bound when they report `null` (no timeout); until a context server reports the key, it uses `context_servers.cache_transceiver_config.kv_transfer_timeout_ms` from the disaggregated config (`null` included), default 60000, and logs a warning. A seat is released when its request finishes. In a fleet, the worker sends that release to the coordinator in the background and retries it, with backoff of up to 5 s, until the coordinator accepts it: a full release queue or an unreachable coordinator delays it but does not drop it. The coordinator reclaims a seat by itself only after 6 hours (or `TRTLLM_DISAGG_COORDINATOR_RESERVATION_TIMEOUT`, if longer; that variable cannot shorten it, since a shorter expiry would hand on the seat of a generation still streaming). A seat waits for that expiry only when its release never arrives: the orchestrator worker died or was stopped before sending it (on shutdown a worker waits 5 s for pending releases), or the coordinator rejected it as malformed. A worker that gets no reply to a `/select` sends that release too, and a `/select` still waiting for a seat when its worker's connection closes leaves the queue. The Slurm benchmark launcher (`examples/disaggregated/slurm/benchmark/submit.py`) copies its `router_config` to both roles without the generation-only keys for the context servers, and copies the context workers' `kv_transfer_timeout_ms` (`null` included) into `context_servers`. + +With prediction on, the client's conversation ID sets the generation priority. The orchestrator replaces any `priority` the client sent with the predicted one. The prediction comes from the earlier replies of the conversation named by the request's `conversation_params.conversation_id`, either sent in the body or taken from the session header (see [request headers](subagent-routing.md#request-headers)). A request without a conversation ID, or the first request of a conversation, is predicted from its prompt length and the replies of all conversations. A client that reuses another conversation's ID therefore takes that conversation's predicted priority, and its replies change that conversation's later predictions. Treat the conversation ID as untrusted input: when untrusted clients reach the server, a gateway in front of it should set or validate the ID. + #### Example: implicit coordinator + 4-worker fleet Extend the `disagg_config.yaml` from the [trtllm-serve](#trtllm-serve) example with `num_workers` and a router type: @@ -450,6 +460,35 @@ Pool headroom belongs to each executor. Configuring preemption on a context worker also reserves headroom. `target_output_tps` has simulation coverage only; GPU validation is limited to `tpot_budget`. +### Deferred KV cache release on generation servers (prototype) + +On a generation server, releasing a finished request's KV cache is host work on +the executor's critical path. With + +```yaml +kv_cache_config: + use_kv_cache_manager_v2: true + defer_generation_only_release: true +``` + +the overlap executor releases the KV cache of finished generation-only requests +after the next forward is enqueued, so that the release overlaps GPU work. The +request itself finishes as before; its pages return one iteration later: + +- When the next iteration's scheduler runs out of KV cache pages, it releases + the pending caches before it suspends or recompute-pauses a running request. + Until then, new requests are admitted as if those pages were still in use. +- KV cache events for the released pages are published one iteration later, or + in the same iteration when the server goes idle. +- An idle server, an iteration that skips its forward, and a KV pool rebalance + release the pending caches before they continue. + +The option requires KV cache manager V2 and the overlap scheduler +(`disable_overlap_scheduler: false`) without pipeline parallelism; other +configurations are rejected at startup. It affects only generation-only +requests, so it has no effect on context servers or aggregated serving (startup +logs a warning when the server has no cache transceiver). + ### Bounding the graceful stop of a server A server can still have request handlers running when it is told to stop, for diff --git a/docs/source/features/kvcache.md b/docs/source/features/kvcache.md index 3ed1adbb2d14..ec324fdd3598 100644 --- a/docs/source/features/kvcache.md +++ b/docs/source/features/kvcache.md @@ -358,6 +358,147 @@ configured separately from `KvCacheConfig`; see [KV Cache Compression](kv-cache-compression.md) for the available methods and their activation points. +### Remote Cache Level in Donated Host Memory (Prototype) + +KV cache manager V2 can add a cache level below the host tier whose pages live in +host memory that other ranks of the same job donate. In disaggregated serving, +generation ranks typically donate host memory they do not use, and context ranks +use it to keep more reusable prefixes. `kv_cache_config.remote_cache_config` +configures it; it requires `use_kv_cache_manager_v2: true`. + +Each rank takes one or both of two roles: + +- **Donor** (`donor`): at startup, before the KV cache estimation, the rank + allocates and registers `donor.size` bytes of host memory in whole 1 GiB + chunks (a remainder below one chunk is not donated; the rank logs the size it + donates) and publishes it in the rendezvous directory. The memory stays donated + for the lifetime of the process. The donor does no work after publishing; the + claiming ranks move pages themselves. +- **Claimant** (`level`): the rank gets a remote cache level of `level.size` + bytes, and claims whole chunks of the donors' memory for it. + +For example, with eight generation ranks that donate 100 GiB each: + +```yaml +kv_cache_config: + use_kv_cache_manager_v2: true + remote_cache_config: + directory: /shared/kv_rendezvous/${SLURM_JOB_ID} + donor: + size: 107374182400 +``` + +and four context ranks with a 96 GiB remote level each below their host tier: + +```yaml +kv_cache_config: + use_kv_cache_manager_v2: true + host_cache_size: 137438953472 + remote_cache_config: + directory: /shared/kv_rendezvous/${SLURM_JOB_ID} + level: + size: 103079215104 + expected: + num_donors: 8 # donating ranks the job starts + claim_size: 412316860416 # level.size summed over all claimants +``` + +`transport` selects how pages move (below); it defaults to `{kind: nixl}`. The +Slurm launcher in `examples/disaggregated/slurm/benchmark` fills in `directory` +(when unset) and `level.expected` from the job's layout. + +**Rendezvous directory.** `directory` must be on a file system that every rank of +the job sees; environment variables in it are expanded, and one that is not set +is an error (every run without it would share one directory). Use a new +directory for each job. Donor files hold NIXL memory registration keys or fabric +handles, so the directory and its missing parents are created with mode 0700, +every file in it is 0600, and a rank refuses a directory that another user owns, +that group or others can write, or that is a symlink (also when the path ends in +`/`). When it claims, a claimant opens the directory once, checks it, and reads +every donor file through that handle, only from files the job's user owns. The +capacity check that runs before the claim (with `level.expected.num_donors` set) +does not: it checks the directory by path, then lists it and reads the donor +`.meta` and `.failed` files by path every 2 s, with no owner, file-type or size +check, so a non-regular file planted in the directory (for example a FIFO) can +block it. Put the directory where only users you trust can rename or replace it +or write into it: a user who can write one of its parent directories can move it +aside before a rank opens it. + +**Transport.** `transport: {kind: nixl}` (the default) moves pages with one-sided +NIXL RDMA; its `ucx_devices` selects the UCX devices of the agents. +`transport: {kind: fabric}` donates CUDA fabric memory, which claimants in the +same multi-node NVLink domain copy over NVLink. A fabric donation fills the GPU's +host NUMA node first, then the other nodes, keeping `donor_reserve_size` bytes +free on each node, and is published short when it does not fit; with +`compact_host_memory: true` a node that refuses a chunk first gets +reclaim-and-compact passes (one donor per node at a time), otherwise that is left +to the job prolog. Every rank that shares a directory must use the same +transport. Both move pages through a pinned host staging ring. A NIXL batch is +waited for on the scheduling thread (up to `transfer_timeout_s`), so offloading +to a NIXL level under host-memory pressure adds that wait to the step that +evicts; fabric copies are queued on the caller's stream. The cost of the NIXL wait +on decode step time has not been measured. + +**Sizing.** The donors' published memory must cover the claims. A claimant splits +`level.size` across layer groups (by the hot tier's split, or `level.pool_ratio`) +and rounds each up to whole chunks, so it can claim slightly more than +`level.size`. +Donated memory is host memory in addition to `host_cache_size`; include it in the +host-memory budget of every donating node. Donors publish while their own servers +start, so a claimant waits for them: up to `level.donor_wait_timeout_s` (default +900 seconds) for each chunk claim. With `level.expected`, it first waits, within +the same bound, until +those donors have reported, and fails at once when they cannot cover the job's +claims instead of after a claim wait. + +**Disk tier and pool rebalance.** The remote level takes the disk level's place: +`level` cannot be combined with `disk_cache_size`. It cannot be combined with +`enable_kv_pool_rebalance` either. + +**Failure behavior.** + +- At startup, a donor that cannot start publishes a failure marker that claimants + count as reported. A claimant that cannot claim its chunks fails KV cache + manager construction, so its server does not start; with `level.expected`, the + error names the failed and short donors. +- At runtime, a NIXL transfer that fails or exceeds `transfer_timeout_s` (default + 30 seconds), for example because its donor died, retires the remote level for + the rest of the process. Its pages leave the reuse tree, nothing more is written + to it, and the tiers above it keep serving. A NIXL request that NIXL reports as + failed is taken to have ended its access to the staging buffer, which is then + reused; one still in progress at the timeout keeps its staging out of use. +- Donors send no heartbeat: a claimant treats a donor as live while its `.ready` + file exists, and notices that the donor went away only at its next transfer to + or from that donor's chunks. Every exit of a donor process takes its donated + memory with it. A graceful shutdown or scale-down withdraws its files and + deregisters the memory; a process killed by `SIGKILL` or `MPI_Abort` (such as a + lock-step rank stopped as described below) leaves its files in place. With NIXL, + the claimants' next transfer to the exited donor's chunks fails and retires + their level, and a claimant that starts later can still claim chunks from a + killed donor's leftover files and fails at its first transfer to them. With + `kind: fabric`, a claimant passes over a donor whose chunks it cannot + import, and what a copy from an already mapped chunk of an exited donor does is + up to the CUDA driver. +- A request whose KV cache pages were on a retired level does not fail if its + pages can be recomputed. If it has not computed anything yet (including a + disaggregated generation request being admitted), it is matched against the + cache again. If it has started, it computes its context again when the + executor supports recompute pause; otherwise it fails with an error. +- This per-request recovery applies where each rank schedules its own requests: + a single rank, or attention data parallelism. Ranks that schedule the same + requests in lock step (tensor parallelism without attention data parallelism, + context parallelism, pipeline parallelism) cannot recover a failure only some + of them saw: a rank whose remote level retires stops its executor with + `RemoteMemError`, whether or not a request lost pages, and the server fails. + A donor process that exits or restarts therefore stops every lock-step + claimant holding chunks from it, and, where those ranks donate too, their own + lock-step claimants in turn; claimants with per-request recovery keep serving + from the tiers above. Share a rendezvous directory only among workers that start + and stop together (no independent restarts or scale-down of donating workers), + or give the claimants a single-rank or attention-data-parallel layout. +- A transfer that never completes keeps its staging buffers and chunk claims + until the process exits. + ### Partial Reuse Partial reuse of a block can happen when some but not all tokens are matched. It is enabled by default. Set `enable_partial_reuse=False` to stop matching part of a cached block. diff --git a/docs/source/features/subagent-routing.md b/docs/source/features/subagent-routing.md index 466cda87e155..2e9cd0f1dbe8 100644 --- a/docs/source/features/subagent-routing.md +++ b/docs/source/features/subagent-routing.md @@ -91,8 +91,22 @@ workers as well. Use `context` scope with conditional disaggregation, which requ a KV-cache-aware generation router. Placement follows the existing conversation routers' behavior. Affinity is best -effort: a saturated ADP rank can overflow to another rank, and affinity bindings can -be evicted. Cache reuse depends on matching prompt prefixes and cache availability. +effort: affinity bindings can be evicted, and by default a request whose home ADP +rank has no free request slot overflows at once to another rank chosen by +`kv_cache_routing_new_conv_placement`. Cache reuse depends on matching prompt +prefixes and cache availability. + +To trade queueing delay for reuse on the home rank, set +`attention_dp_config.kv_cache_routing_home_wait_rounds` (prototype; requires +`kv_cache_routing_conversation_affinity: true`). A returning conversation (or a +sub-agent routed by its parent's key) whose home rank is full then stays in the +waiting queue until a slot frees there, for up to that many scheduling rounds in +which another rank had room. After that it overflows as above; its conversation +stays bound to the home rank. While it waits, later requests can be admitted +ahead of it. With `scheduler_config.waiting_queue_policy: priority`, later +requests of the same priority can take any rank, and lower-priority requests +can take other ranks but not the held request's home rank, so each rank still +admits in priority order. ## Gateway trust boundary diff --git a/examples/disaggregated/slurm/benchmark/submit.py b/examples/disaggregated/slurm/benchmark/submit.py index 8783c27e827c..7694d830df13 100644 --- a/examples/disaggregated/slurm/benchmark/submit.py +++ b/examples/disaggregated/slurm/benchmark/submit.py @@ -127,6 +127,64 @@ def save_mooncake_worker_config(worker_config, log_dir, role, instance_id): return config_path +#: Rendezvous directory of the KV cache manager v2 remote level, under log_dir. +REMOTE_CACHE_DIR_NAME = 'kvcm2_remote' + + +def resolve_remote_cache(worker_config: Dict[str, Any], + num_ranks: Dict[str, int], directory: str) -> None: + """Fill the job-wide fields of the KV cache remote level from the layout. + + Each role's kv_cache_config.remote_cache_config gets the job's rendezvous + directory; a role with a `level` also gets `level.expected`: the number of + donating ranks and the bytes all ranks with a level claim, which only the + launcher can count. The claim is the sum of level.size: ranks round each + layer group up to whole chunks, which the launcher cannot see, so a claim + that runs out stops once every expected donor has reported. An explicit + `level.expected` is left alone. + + Args: + worker_config: {'ctx': ..., 'gen': ...} worker configs, edited in place. + num_ranks: {'ctx': ..., 'gen': ...} ranks of each role in the job. + directory: Rendezvous directory to use when none is set. + + Raises: + ValueError: Roles sharing a directory set different transports. + """ + remote = {} + for role in ('ctx', 'gen'): + kv_cache_config = worker_config[role].get('kv_cache_config') or {} + if kv_cache_config.get('remote_cache_config'): + remote[role] = kv_cache_config['remote_cache_config'] + remote[role].setdefault('directory', directory) + # Donors and claims are counted per rendezvous directory, whose ranks must + # share one transport: a client passes over donors of another transport. + by_directory = {} + for role, config in remote.items(): + by_directory.setdefault(config['directory'], []).append(role) + for shared, roles in by_directory.items(): + transports = { + role: (remote[role].get('transport') or {}).get('kind', 'nixl') + for role in roles + } + if len(set(transports.values())) > 1: + raise ValueError( + f"remote_cache_config of roles {', '.join(roles)} share " + f"directory {shared!r} with different transports {transports}; " + "use one transport, or a directory per role") + num_donors = sum(num_ranks[role] for role in roles + if remote[role].get('donor')) + claim_size = sum(num_ranks[role] * remote[role]['level']['size'] + for role in roles if remote[role].get('level')) + for role in roles: + level = remote[role].get('level') + if level and num_donors and 'expected' not in level: + level['expected'] = { + 'num_donors': num_donors, + 'claim_size': claim_size + } + + def calculate_nodes(world_size, num_servers, gpus_per_node): """Required node count under per-worker whole-node ownership. @@ -228,9 +286,21 @@ def assign_servers( return allocations -def convert_allocations_to_server_config(allocations, - server_port=8333, - router_config=None): +# Router options of pooled generation dispatch; a context router rejects them. +GEN_ONLY_ROUTER_KEYS = ("max_requests_per_server", "max_queue_wait_s") + + +def convert_allocations_to_server_config( + allocations: dict, + server_port: int = 8333, + router_config: dict | None = None, + ctx_cache_transceiver_config: dict | None = None) -> dict: + """Build the disaggregated server config. + + ``router_config`` applies to both roles, without its generation-only keys for the context + servers. The context workers' ``kv_transfer_timeout_ms`` (from + ``ctx_cache_transceiver_config``, null included) bounds the pooled generation wait. + """ generation_servers = {} context_servers = {} server_hostname = None @@ -246,6 +316,15 @@ def convert_allocations_to_server_config(allocations, server_config_entry = {'num_instances': num_servers, 'urls': urls} if router_config: server_config_entry['router'] = router_config.copy() + if server_type == "CTX": + for key in GEN_ONLY_ROUTER_KEYS: + server_config_entry['router'].pop(key, None) + if (server_type == "CTX" and ctx_cache_transceiver_config + and 'kv_transfer_timeout_ms' in ctx_cache_transceiver_config): + server_config_entry['cache_transceiver_config'] = { + 'kv_transfer_timeout_ms': + ctx_cache_transceiver_config['kv_transfer_timeout_ms'] + } if server_type == "GEN": generation_servers = server_config_entry @@ -639,6 +718,10 @@ def submit_job(config, log_dir, dry_run): mooncake_pool_file) gen_uses_mooncake = resolve_mooncake_pool(worker_config['gen'], mooncake_pool_file) + resolve_remote_cache(worker_config, { + 'ctx': ctx_num * ctx_world_size, + 'gen': gen_num * gen_world_size + }, os.path.join(log_dir, REMOTE_CACHE_DIR_NAME)) save_worker_config(worker_config['ctx'], ctx_config_path) save_worker_config(worker_config['gen'], gen_config_path) @@ -658,7 +741,10 @@ def submit_job(config, log_dir, dry_run): # Generate disagg server config router_config = config.get('router_config', None) server_config = convert_allocations_to_server_config( - allocations, router_config=router_config) + allocations, + router_config=router_config, + ctx_cache_transceiver_config=worker_config['ctx'].get( + 'cache_transceiver_config')) # Merge server_config_extra into disagg server config if 'server_config_extra' in config: server_config.update(config['server_config_extra']) diff --git a/examples/disaggregated/slurm/cache_transceiver_test/run_cache_transceiver_test.py b/examples/disaggregated/slurm/cache_transceiver_test/run_cache_transceiver_test.py index 2cb691e86716..134fffae1bfa 100644 --- a/examples/disaggregated/slurm/cache_transceiver_test/run_cache_transceiver_test.py +++ b/examples/disaggregated/slurm/cache_transceiver_test/run_cache_transceiver_test.py @@ -63,6 +63,7 @@ BlockReuseConfig, CacheTransceiverConfig, KvPoolRebalanceConfig, + RemoteCacheConfig, ) from tensorrt_llm.mapping import Mapping from tensorrt_llm.sampling_params import SamplingParams @@ -120,6 +121,8 @@ class KvCacheConfigV2: # tensorrt_llm/llmapi/llm_args.py; KVCacheManagerV2._build_base_config() # reads it unconditionally. kv_pool_rebalance_config: KvPoolRebalanceConfig = field(default_factory=KvPoolRebalanceConfig) + # Mirrors KvCacheConfig.remote_cache_config; read by KVCacheManagerV2.__init__. + remote_cache_config: Optional[RemoteCacheConfig] = None enable_kv_pool_rebalance: bool = False diff --git a/jenkins/L0_MergeRequest.groovy b/jenkins/L0_MergeRequest.groovy index 4673e93acebc..d87fc2186628 100644 --- a/jenkins/L0_MergeRequest.groovy +++ b/jenkins/L0_MergeRequest.groovy @@ -2030,11 +2030,20 @@ def getMultiGpuFileChanged(pipeline, testFilter, globalVars) "tensorrt_llm/_torch/custom_ops/torch_custom_ops.py", "tensorrt_llm/_torch/custom_ops/userbuffers_custom_ops.py", "tensorrt_llm/_torch/distributed/", + // GQA KV-replica decode and the MNNVL / TP2 all-reduce + norm kernels: their tests run only in + // l0_gb300's 4-GPU pre-merge block. + "tensorrt_llm/_torch/attention/backends/fmha/gqa_", + "tensorrt_llm/_torch/kernels/blackwell/gemm_allreduce_norm.py", + "tensorrt_llm/_torch/kernels/blackwell/gemm_twoshot_allreduce_norm.py", + "tensorrt_llm/_torch/kernels/blackwell/mnnvl_", + "tensorrt_llm/_torch/kernels/blackwell/tp2_allreduce_norm.py", "tensorrt_llm/_torch/models/modeling_llama.py", "tensorrt_llm/_torch/models/modeling_qwen3_next.py", "tensorrt_llm/_torch/moe/", "tensorrt_llm/_torch/pyexecutor/_util.py", "tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py", + // KVCM2 remote tier: its fabric-transport tests run only on GB300 (l0_gb300). + "tensorrt_llm/_torch/pyexecutor/kv_cache/remote_donor.py", "tensorrt_llm/_torch/pyexecutor/model_engine.py", "tensorrt_llm/_torch/pyexecutor/py_executor.py", "tensorrt_llm/_torch/weight_sharing/", @@ -2098,8 +2107,10 @@ def getMultiGpuFileChanged(pipeline, testFilter, globalVars) "tests/integration/test_lists/test-db/l0_gb300_multi_nodes_node4_gpu16.yml", "tests/integration/test_lists/test-db/l0_model_express.yml", "tests/integration/test_lists/test-db/l0_rtx_pro_6000.yml", + "tests/unittest/_torch/attention/multi_gpu/", "tests/unittest/_torch/multi_gpu/", "tests/unittest/_torch/moe/multi_gpu/", + "tests/unittest/kv_cache_manager_v2_tests/", "tests/unittest/_torch/multi_gpu_modeling/", "tests/unittest/_torch/visual_gen/multi_gpu/", "tests/unittest/disaggregated/", diff --git a/scripts/generate_trtllm_serve_schemas.py b/scripts/generate_trtllm_serve_schemas.py index 2ad16a5d4994..03d90f71b04b 100644 --- a/scripts/generate_trtllm_serve_schemas.py +++ b/scripts/generate_trtllm_serve_schemas.py @@ -193,8 +193,100 @@ def dwdp_fields(required: tuple[str, ...] = (), **values: object) -> dict: ] +def _is_set_to(name: str, schema: dict) -> dict: + """The mapping sets ``name`` (it is required) to a value that matches ``schema``.""" + return {"properties": {name: schema}, "required": [name]} + + +def _launch_rules() -> list[dict]: + """Top-level ``if``/``then`` rules: DWDP and ``validate_defer_generation_only_release()``. + + ``_dwdp_launch_rules()``, plus ``TorchLlmArgs.validate_defer_generation_only_release()`` (the overlap loop + without pipeline parallelism). As there, values the YAML does not set are left to runtime validation. + """ + defer = {"type": "object", **_is_set_to("defer_generation_only_release", {"const": True})} + return _dwdp_launch_rules() + [ + { + "if": _is_set_to("kv_cache_config", defer), + "then": { + "properties": { + "disable_overlap_scheduler": {"not": {"const": True}}, + "pipeline_parallel_size": {"maximum": 1}, + } + }, + } + ] + + +def _cross_field_rules(definitions: dict) -> None: + """Mirror the model validators of the KV cache, scheduler and attention-DP options. + + They hold only for values the YAML sets; defaults are taken from the models. + """ + from tensorrt_llm.llmapi.llm_args import SchedulerConfig, WaitingQueuePolicy + + def default(model: type, name: str) -> dict: + return {"const": model.model_fields[name].default} + + def when(condition: dict, then: dict) -> dict: + return {"if": condition, "then": then} + + # RemoteCacheConfig.validate_remote_cache(). + definitions["RemoteCacheConfig"]["anyOf"] = [ + {"required": ["donor"], "properties": {"donor": {"type": "object"}}}, + {"required": ["level"], "properties": {"level": {"type": "object"}}}, + ] + # KvCacheConfig.validate_remote_cache_config() and validate_defer_generation_only_release(). + kv_v2 = {"properties": {"use_kv_cache_manager_v2": {"not": {"const": False}}}} + definitions["KvCacheConfig"].setdefault("allOf", []).extend( + [ + when(_is_set_to("remote_cache_config", {"type": "object"}), kv_v2), + when(_is_set_to("defer_generation_only_release", {"const": True}), kv_v2), + when( + _is_set_to("remote_cache_config", _is_set_to("level", {"type": "object"})), + { + "properties": { + "disk_cache_size": {"enum": [0, None]}, + "enable_kv_pool_rebalance": {"not": {"const": True}}, + } + }, + ), + ] + ) + # AttentionDpConfig.validate_attention_dp_config(). + definitions["AttentionDpConfig"].setdefault("allOf", []).append( + when( + _is_set_to("kv_cache_routing_home_wait_rounds", {"type": "integer"}), + _is_set_to("kv_cache_routing_conversation_affinity", {"const": True}), + ) + ) + # SchedulerConfig.validate_waiting_queue_max_wait_s(). + definitions["SchedulerConfig"].setdefault("allOf", []).append( + when( + { + "not": _is_set_to( + "waiting_queue_policy", + {"const": WaitingQueuePolicy.PRIORITY.value}, + ) + }, + { + "properties": { + "waiting_queue_max_wait_s": default(SchedulerConfig, "waiting_queue_max_wait_s") + } + }, + ) + ) + + def generate_serve_schema() -> dict: """Describe the YAML fragment merged with ordinary serving CLI arguments.""" + schema = _serve_schema() + _cross_field_rules(schema["$defs"]) + return schema + + +def _serve_schema() -> dict: + """The serve schema without ``_cross_field_rules``, so that later merges see unmodified definitions.""" from tensorrt_llm.llmapi.disagg_utils import DisaggClusterConfig, InternalRequestAuthKey from tensorrt_llm.llmapi.llm_args import ( SERVE_CONFIG_ALIASES, @@ -293,7 +385,7 @@ def generate_serve_schema() -> dict: "type": "null", "description": "Live objects require the Python LLM API.", } - schema["allOf"] = _dwdp_launch_rules() + schema["allOf"] = _launch_rules() schema["$defs"]["RayPlacementConfig"]["properties"]["placement_groups"] = {"type": "null"} user_draft = schema["$defs"]["UserProvidedDecodingConfig"]["properties"] user_draft["drafter"] = {"not": {}, "description": "A Drafter requires the Python LLM API."} @@ -303,6 +395,53 @@ def generate_serve_schema() -> dict: return schema +def _router_schema(router_type: dict) -> dict: + """A disaggregated server block's ``router`` mapping, with pooled generation dispatch's startup rules. + + Mirrors extract_disagg_cfg() (``max_queue_wait_s`` needs ``max_requests_per_server``), create_router() + (pooling needs the ``load_balancing`` type, matched case-insensitively), PooledLoadBalancingRouter (no + ``use_tokens``) and SeatPool (seats an integer >= 1, wait > 0). A null value is unset, as at runtime. + """ + pooled_type = "load_balancing" + any_case = "".join(f"[{c.lower()}{c.upper()}]" if c.isalpha() else c for c in pooled_type) + falsy = [False, None, 0, "", [], {}] + return { + "type": "object", + "properties": { + "type": router_type, + "max_requests_per_server": { + "type": ["integer", "null"], + "minimum": 1, + "description": "Pooled generation dispatch: requests each generation server runs at once " + "(load_balancing generation router only).", + }, + "max_queue_wait_s": { + "type": ["number", "null"], + "exclusiveMinimum": 0, + "description": "Pooled generation dispatch: seconds after which a waiting request goes " + "first (needs max_requests_per_server).", + }, + }, + "additionalProperties": True, + "allOf": [ + { + "if": _is_set_to("max_queue_wait_s", {"type": "number"}), + "then": _is_set_to("max_requests_per_server", {"type": "integer"}), + }, + { + "if": _is_set_to("max_requests_per_server", {"type": "integer"}), + "then": { + "properties": { + "type": {"type": "string", "pattern": f"^{any_case}$"}, + "use_tokens": {"enum": falsy}, + }, + "required": ["type"], + }, + }, + ], + } + + def generate_disagg_schema() -> dict: """Describe orchestrator options and the inherited per-role worker options.""" from tensorrt_llm.llmapi.disagg_utils import ( @@ -315,7 +454,7 @@ def generate_disagg_schema() -> dict: ) from tensorrt_llm.llmapi.llm_args import SERVE_CLI_CONFIG_FIELDS, TorchLlmArgs - schema = generate_serve_schema() + schema = _serve_schema() properties = schema["properties"] for config_name, aliases in SERVE_CLI_CONFIG_FIELDS.items(): config = _schema_for(TorchLlmArgs.model_fields[config_name].annotation, schema) @@ -326,20 +465,30 @@ def generate_disagg_schema() -> dict: worker["properties"].pop("type") worker.pop("required", None) worker["properties"] = properties | worker["properties"] - # YAML flattens router-specific args alongside the shared type field. - worker["properties"]["router"] = { - "type": "object", - "properties": {"type": _schema_for(RouterConfig, schema)["properties"]["type"]}, - "additionalProperties": True, - } + # YAML flattens router-specific args alongside the shared type field. Unknown args stay accepted; + # the pooled generation dispatch keys are typed. + worker["properties"]["router"] = _router_schema( + _schema_for(RouterConfig, schema)["properties"]["type"] + ) worker["additionalProperties"] = False - worker["allOf"] = _dwdp_launch_rules() + worker["allOf"] = _launch_rules() schema["$defs"]["DisaggServerBlock"] = worker orchestrator = _schema_for(extract_disagg_cfg, schema)["properties"] # Update these refinements when extract_disagg_cfg() changes its untyped mapping inputs. for name in ("context_servers", "generation_servers"): orchestrator[name] = _nullable({"$ref": "#/$defs/DisaggServerBlock"}) + # PooledLoadBalancingRouter refuses the context role. + orchestrator["context_servers"]["anyOf"][0] = { + "allOf": [ + {"$ref": "#/$defs/DisaggServerBlock"}, + { + "properties": { + "router": {"properties": {"max_requests_per_server": {"type": "null"}}} + } + }, + ] + } orchestrator["conditional_disagg_config"] = _nullable( _schema_for(ConditionalDisaggConfig, schema) ) @@ -353,6 +502,14 @@ def generate_disagg_schema() -> dict: "maximum": (1 << DISAGG_NODE_ID_BITS) - 1, } properties.update(orchestrator) + # Mirror extract_disagg_cfg(): output-length prediction needs the context-first schedule. + schema.setdefault("allOf", []).append( + { + "if": _is_set_to("output_length_prediction", {"type": "object"}), + "then": {"properties": {"schedule_style": {"not": {"const": "generation_first"}}}}, + } + ) + _cross_field_rules(schema["$defs"]) return schema diff --git a/scripts/trtllm_gen_fmha_stage_kv/export_kernel.cpp b/scripts/trtllm_gen_fmha_stage_kv/export_kernel.cpp new file mode 100644 index 000000000000..c74b3148bde4 --- /dev/null +++ b/scripts/trtllm_gen_fmha_stage_kv/export_kernel.cpp @@ -0,0 +1,179 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Python extension for gen_stage_kv_cubins.py: selects the trtllm-gen FMHA kernel the runner would JIT for an E4M3 +// Q/KV, BF16-out paged causal context call with a caller-fixed head dim per K/V stage, and has the generator +// (exported by libtensorrt_llm.so) dump that kernel's source and cubin. + +#include + +#include "tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaKernels.h" + +#include +#include +#include +#include +#include + +namespace tk = tensorrt_llm::kernels; + +namespace +{ + +tk::TllmGenFmhaRunnerParams makeParams(int64_t numSms, int64_t numHeadsQ, int64_t numHeadsKv, int64_t headDim, + int64_t batch, int64_t maxQ, int64_t maxKv, int64_t tokensPerPage, int64_t headDimPerStageKv) +{ + tk::TllmGenFmhaRunnerParams p{}; + p.mQkvLayout = tk::QkvLayout::PagedKv; + p.mMaskType = tk::TrtllmGenAttentionMaskType::Causal; + p.mKernelType = tk::FmhaKernelType::Context; + p.mTileScheduler = tk::TileScheduler::Persistent; + p.mMultiCtasKvMode = false; + p.mHeadDimQk = static_cast(headDim); + p.mHeadDimV = static_cast(headDim); + p.mNumHeadsQ = static_cast(numHeadsQ); + p.mNumHeadsKv = static_cast(numHeadsKv); + p.mNumHeadsQPerKv = static_cast(numHeadsQ / numHeadsKv); + p.mBatchSize = static_cast(batch); + p.mMaxSeqLenQ = static_cast(maxQ); + p.mMaxSeqLenKv = static_cast(maxKv); + p.mMaxSeqLenCacheKv = static_cast(maxKv); + p.mSumOfSeqLensQ = static_cast(std::min(batch * maxQ, INT_MAX)); + p.mSumOfSeqLensKv = static_cast(std::min(batch * maxKv, INT_MAX)); + p.mMaxNumPagesPerSeqKv = static_cast((maxKv + tokensPerPage - 1) / tokensPerPage); + p.mNumTokensPerPage = static_cast(tokensPerPage); + p.mNumPagesInMemPool = INT_MAX; + p.mChunkedAttentionSize = INT_MAX; + p.mLeftSlidingWindow = -1; + p.mRightSlidingWindow = -1; + p.mScaleQ = 1.0f; + p.mMultiProcessorCount = static_cast(numSms); + p.mHeadDimPerStageKv = static_cast(headDimPerStageKv); + return p; +} + +tk::TllmGenFmhaKernel& kernelFor(int64_t sm) +{ + // No cubin tables: only the selection and the NVRTC config are used. + static std::map> kernels; + auto& k = kernels[sm]; + if (k == nullptr) + { + k = std::make_unique(nullptr, 0, tk::DATA_TYPE_E4M3, tk::DATA_TYPE_E4M3, + tk::DATA_TYPE_E4M3, tk::DATA_TYPE_BF16, static_cast(sm)); + } + return *k; +} + +// The kernel-table fields of the selected config (see TllmGenFmhaKernelMetaInfo), plus its name and JSON config. +py::dict describe(fmha::FmhaConfig const& cfg, std::string const& name) +{ + auto const& o = cfg.mOptions; + TORCH_CHECK(o.mDtypeQ == trtllm::gen::Dtype::E4m3 && o.mDtypeKv == trtllm::gen::Dtype::E4m3 + && o.mDtypeOut == trtllm::gen::Dtype::Bfloat16, + "export_kernel: unexpected dtypes"); + py::dict d; + d["name"] = name; + d["json"] = cfg.mGenCfgJsonStr; + d["ctaDim"] = cfg.mCtaDim; + d["tileSizeQ"] = o.mTileSizeQ; + d["tileSizeKv"] = o.mTileSizeKv; + d["stepQ"] = o.mTileSizeQ * o.mNumInstsQ; + d["stepKv"] = o.mTileSizeKv * o.mNumInstsKv; + d["headDimPerCtaV"] = o.mHeadDimPerCtaV; + d["headDimQk"] = o.mHeadDimQk; + d["headDimV"] = o.mHeadDimV; + d["headDimPerStageKv"] = o.mHeadDimPerStageKv; + d["qkvLayout"] = static_cast(o.mQkvLayout); + d["numTokensPerPage"] = o.mNumTokensPerPage; + d["maskType"] = static_cast(o.mMaskType); + d["kernelType"] = static_cast(o.mFmhaKernelType); + d["tileScheduler"] = static_cast(o.mTileScheduler); + d["multiCtasKvMode"] = static_cast(o.mMultiCtasKvMode); + d["groupsHeadsQ"] = o.mGroupsHeadsQ; + d["groupsTokensHeadsQ"] = o.mGroupsTokensHeadsQ; + d["reuseSmemKForV"] = o.mReuseSmemKForV; + d["uses2CtaMma"] = o.mClusterDimX == 2; + d["sparseAttn"] = static_cast(o.mSparseType); + d["skipsSoftmax"] = o.mSkipsSoftmaxWhenPossible; + d["fp16Softmax"] = o.mEnablesFp16Softmax; + d["usesSpcompress"] = o.mUsesSpcompress; + d["enablesBf16QFp8KvKOnlyTransform"] = o.mEnablesBf16QFp8KvKOnlyTransform; + d["separateTransformedKv"] = o.mSeparateTransformedKv; + d["fusesDsv4InvRopeFp8Quant"] = o.mFusesDsv4InvRopeFp8Quant; + d["usesDsv4Ue8m0ScaleO"] = o.mUsesDsv4Ue8m0ScaleO; + d["clusterDimX"] = o.mClusterDimX; + return d; +} + +} // namespace + +// The config the runner selects for these shapes, without generating anything. +py::dict selectKernel(int64_t sm, int64_t numSms, int64_t numHeadsQ, int64_t numHeadsKv, int64_t headDim, int64_t batch, + int64_t maxQ, int64_t maxKv, int64_t tokensPerPage, int64_t headDimPerStageKv) +{ + auto const params + = makeParams(numSms, numHeadsQ, numHeadsKv, headDim, batch, maxQ, maxKv, tokensPerPage, headDimPerStageKv); + auto& kernel = kernelFor(sm); + fmha::FmhaConfig cfg = kernel.nvrtcConfig(params); + fmha::FmhaInterface const fmhaInterface{false, 1}; + return describe(cfg, fmhaInterface.getKernelNameFromConfigs(cfg)); +} + +// Generates and compiles the selected kernel with source and cubin export on. execPath stands in for the runner's +// exec path (the fmha build dir with the kernel headers); the generator writes .nvrtc.cu / .nvrtc.cubin there. +py::dict generateKernel(int64_t sm, int64_t numSms, int64_t numHeadsQ, int64_t numHeadsKv, int64_t headDim, + int64_t batch, int64_t maxQ, int64_t maxKv, int64_t tokensPerPage, int64_t headDimPerStageKv, + std::string const& execPath) +{ + auto const params + = makeParams(numSms, numHeadsQ, numHeadsKv, headDim, batch, maxQ, maxKv, tokensPerPage, headDimPerStageKv); + auto& kernel = kernelFor(sm); + fmha::FmhaConfig cfg = kernel.nvrtcConfig(params); + // Generator switches that only write the NVRTC source and cubin next to the compile; the kernel is unchanged. + std::string const open = "{\n"; + TORCH_CHECK(cfg.mGenCfgJsonStr.rfind(open, 0) == 0, "export_kernel: unexpected generator config"); + cfg.mGenCfgJsonStr.insert(open.size(), "\"emitsNvRtcSource\": true,\n\"emitsCubin\": true,\n"); + // The generator reads the kernel headers from, and writes its dumps to, the exec path. + cfg.mExecPath = execPath.c_str(); + fmha::FmhaInterface const fmhaInterface{/*exportsCubin=*/true, /*numRotations=*/1, /*verbose=*/true}; + fmhaInterface.generateAndCompileKernel(cfg); + py::dict d = describe(cfg, cfg.mFunctionName); + return d; +} + +// The standard-header stand-ins the generator's NVRTC front end (jitify2) compiles with, read from its function-local +// map in libtensorrt_llm.so once a generation has initialized it. +py::dict jitifyHeaders(uintptr_t mapAddress) +{ + TORCH_CHECK(mapAddress != 0, "export_kernel: null jitify2 header map address"); + auto const& headers = *reinterpret_cast const*>(mapAddress); + TORCH_CHECK(!headers.empty(), "export_kernel: the jitify2 header map is empty"); + py::dict d; + for (auto const& [name, source] : headers) + { + d[py::str(name)] = py::bytes(source); + } + return d; +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) +{ + m.def("jitify_headers", &jitifyHeaders, "Read the generator's built-in NVRTC header map at the given address"); + m.def("select_kernel", &selectKernel, "Select the trtllm-gen FMHA context kernel config the runner would JIT"); + m.def("generate_kernel", &generateKernel, "Generate the selected kernel with source and cubin export"); +} diff --git a/scripts/trtllm_gen_fmha_stage_kv/gen_stage_kv_cubins.py b/scripts/trtllm_gen_fmha_stage_kv/gen_stage_kv_cubins.py new file mode 100644 index 000000000000..c62b8dc9c7cc --- /dev/null +++ b/scripts/trtllm_gen_fmha_stage_kv/gen_stage_kv_cubins.py @@ -0,0 +1,809 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +r"""Build the stage-KV trtllm-gen FMHA cubins (E4M3 Q/KV, BF16 out, paged causal context, fixed K/V stage). + +Run on a GPU of the target arch (GB200 -> sm100a, GB300 -> sm103a) with TensorRT-LLM installed. The shipped cubins +(Qwen3.5 full attention, 32 / 2 heads under TP 1..8 and attention DP) come from: + + python3 scripts/trtllm_gen_fmha_stage_kv/gen_stage_kv_cubins.py --work-dir \ + --heads 32:2,16:1,8:1,4:1,64:4 --head-dim 256 --tokens-per-page 64 --stage 256 + +For each kernel the runner selects over the context warmup grid (``TllmGenFmhaKernel::nvrtcConfig``), the generator in +libtensorrt_llm.so writes its source and cubin; the source gets the E4 edit below, is compiled with NVRTC and the +generator's options, and lands in ``cubin/`` as ``StageKvE4.cubin.tar.zst`` with its entry in +``cubin/kernelMetaInfoStageKv.h``. The unedited source is compiled the same way and must reproduce the generator's +cubin byte for byte, which shows that the offline compile matches the runner's JIT. + +E4 (no arithmetic change): in the softmax task's per-KV-tile loop, release the S tile (the "P ready" signal to the MMA +warp) before acquiring the next softmax-stats slot. That acquire waits on the correction task and guards nothing the MMA +needs, yet the generated order puts it between P(j) and the MMA of tile j + 1. +""" + +import argparse +import ctypes +import hashlib +import importlib.util +import itertools +import os +import re +import shutil +import subprocess +import sys +import tempfile +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path +from types import ModuleType +from typing import Any, NoReturn + +REPO = Path(__file__).resolve().parents[2] +FMHA_DIR = REPO / "cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha" +CUBIN_DIR = FMHA_DIR / "cubin" +META_HEADER = CUBIN_DIR / "kernelMetaInfoStageKv.h" +EXPORT_DIR = FMHA_DIR / "trtllmGen_fmha_export" +# What the cubins are built against and the runner sets their parameters with: the kernel parameter block and its +# host-side setup (KernelParams.h takes FmhaOptions and KernelTraits), and the device headers the generated source +# compiles with (trtllm/). Their hash is recorded per block in META_HEADER and checked by +# tests/unittest/_torch/attention/test_fmha_paged_context_fp8.py, so a change to any of them forces a regeneration. +KERNEL_INPUT_HEADERS = ( + "KernelParams.h", + "KernelParamsDecl.h", + "KernelTraits.h", + "KernelConfigBase.h", + "FmhaOptions.h", + "Dsv4Constants.h", +) +STAGE_KV_ARCHIVE_GLOB = "FmhaSm{sm}*StageKv*E4.cubin.tar.zst" + +# Context-warmup grid of fmhaKernels.h (kContextWarmup* / kDefaultWarmupSeqLenKvCandidates), up to 128k tokens. +BATCH_SIZES = [1, 2, 4, 8, 16, 32, 64, 128, 256] +SEQ_LENS_Q = [ + 1, + 128, + 129, + 256, + 257, + 512, + 513, + 1024, + 1025, + 2048, + 2049, + 4096, + 4097, + 8192, + 8193, + 16384, + 16385, + 32768, + 32769, + 65536, + 65537, + 131072, +] +SEQ_LENS_KV = [ + 1, + 128, + 256, + 384, + 512, + 640, + 768, + 896, + 1024, + 1152, + 1280, + 1408, + 1536, + 1664, + 1792, + 1920, + 2048, + 2176, + 2304, + 2432, + 2560, + 2688, + 2816, + 2944, + 3072, + 3328, + 3584, + 3840, + 4096, + 4352, + 4608, + 4864, + 5120, + 5376, + 5632, + 5888, + 6144, + 6656, + 7168, + 7680, + 8192, + 8704, + 9216, + 9728, + 10240, + 10752, + 11264, + 11776, + 12288, + 13312, + 14336, + 16384, + 20480, + 24576, + 32768, + 40960, + 49152, + 65536, + 98304, + 131072, +] +# E4: the block that acquires the next softmax-stats slot, then releases the S tile; swapped. Matched on the source +# with comment-only lines ignored; each comment line moves with the code line after it, so the line count is unchanged. +ACQUIRE = """{ +if ((loopOffsetN)>=(int32_t{0})) { +tmemSoftmaxLocal0ProdToken = tmemSoftmaxLocal0DstStack.mPipeline.producer_try_acquire(tmemSoftmaxLocal0ProdState); +} +} +{ +tmemSoftmaxLocal0DstStack.mPipeline.producer_acquire(tmemSoftmaxLocal0ProdState, tmemSoftmaxLocal0ProdToken); +}""".split("\n") +RELEASE = """if (!(isLastLoopIter)) { +if ((loopOffsetN)>=(int32_t{0})) { +{ +tmemS0SrcStack.mPipeline.consumer_release(tmemS0ConsReleaseState); +} +++tmemS0ConsReleaseState; +} +}""".split("\n") + +HEADER_TEMPLATE = """/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Generated by scripts/trtllm_gen_fmha_stage_kv/gen_stage_kv_cubins.py; do not edit. +#pragma once + +#include "kernelMetaInfo.h" + +#include + +TRTLLM_NAMESPACE_BEGIN + +namespace kernels +{ + +// trtllm-gen FMHA kernels generated for a caller-fixed head dim per K/V shared-memory stage +// (TllmGenFmhaRunnerParams::mHeadDimPerStageKv). The kernel hash does not cover that option, so the runner keeps these +// apart from sTllmGenFmhaKernelMetaInfos and matches them only for callers that fix the stage. +struct TllmGenFmhaStageKvKernelMetaInfo +{ + int mHeadDimPerStageKv; + TllmGenFmhaKernelMetaInfo mMeta; +}; + +// clang-format off +@DECLS@ +inline std::vector const& getTllmGenFmhaStageKvKernelMetaInfos() +{ + static std::vector const sInfos = { +@ENTRIES@ }; + return sInfos; +} + +// clang-format on + +} // namespace kernels + +TRTLLM_NAMESPACE_END +""" + + +def log(*args: object) -> None: + print("[gen_stage_kv]", *args, flush=True) + + +def kernel_input_files(export_dir: Path = EXPORT_DIR) -> list[Path]: + """The files kernel_inputs_sha256 covers, in hashing order.""" + files = [export_dir / name for name in KERNEL_INPUT_HEADERS] + files += sorted(p for p in (export_dir / "trtllm").rglob("*") if p.is_file()) + return files + + +def kernel_inputs_sha256(export_dir: Path = EXPORT_DIR) -> str: + """sha256 over the path (relative to export_dir) and bytes of every kernel_input_files entry.""" + h = hashlib.sha256() + for path in kernel_input_files(export_dir): + rel = path.relative_to(export_dir).as_posix().encode() + data = path.read_bytes() + h.update(len(rel).to_bytes(8, "little") + rel + len(data).to_bytes(8, "little") + data) + return h.hexdigest() + + +def fail(msg: str) -> NoReturn: + sys.exit(f"gen_stage_kv: {msg}") + + +@contextmanager +def redirect_fds(path: Path) -> Iterator[None]: + """Send the process's stdout / stderr (C++ logging included) to a file.""" + sys.stdout.flush() + sys.stderr.flush() + saved = [os.dup(1), os.dup(2)] + with open(path, "w") as f: + os.dup2(f.fileno(), 1) + os.dup2(f.fileno(), 2) + try: + yield + finally: + sys.stdout.flush() + sys.stderr.flush() + os.dup2(saved[0], 1) + os.dup2(saved[1], 2) + for fd in saved: + os.close(fd) + + +def trtllm_package_dir() -> Path: + spec = importlib.util.find_spec("tensorrt_llm") + if spec is None or not spec.submodule_search_locations: + fail("tensorrt_llm is not installed") + return Path(list(spec.submodule_search_locations)[0]) + + +def build_extension(build_dir: Path, fmha_build_dir: Path) -> ModuleType: + import torch.utils.cpp_extension as ce + + pkg = trtllm_package_dir() + cuda_home = Path(ce.CUDA_HOME or "/usr/local/cuda") + json_include = REPO / "cpp/build/_deps/json-src/include" + if not json_include.is_dir(): + # The fmha build dir of the installed package always exists; its CMake tree has the same _deps layout. + json_include = ( + Path(os.path.realpath(fmha_build_dir / "cutlass")).parent / "json-src/include" + ) + if not json_include.is_dir(): + fail(f"nlohmann json headers not found (looked in the repo and next to {fmha_build_dir})") + includes = [ + REPO / "cpp", + REPO / "cpp/include", + FMHA_DIR, + FMHA_DIR / "trtllmGen_fmha_export", + json_include, + cuda_home / "include", + cuda_home / "include/cccl", + fmha_build_dir / "cutlass/include", + fmha_build_dir, + ] + flags = [ + "-O2", + "-std=c++20", + "-fvisibility=hidden", + "-DTLLM_GEN_EXPORT_INTERFACE", + "-DTLLM_FMHA_TRTLLM_COMPAT", + "-DTLLM_RUBIN_FEATURES", + "-DTLLM_ENABLE_CUDA", + "-DENABLE_BF16", + "-DENABLE_FP8", + "-DENABLE_FP4", + "-DEXCLUDE_SM_100F", + "-DTRTLLM_ABI_NAMESPACE=_v1", + "-Wno-deprecated-declarations", + ] + libdir = pkg / "libs" + os.makedirs(build_dir, exist_ok=True) + return ce.load( + name="trtllm_gen_fmha_stage_kv_export", + sources=[str(Path(__file__).with_name("export_kernel.cpp"))], + extra_include_paths=[str(p) for p in includes], + extra_cflags=flags, + extra_ldflags=[f"-L{libdir}", "-ltensorrt_llm", f"-Wl,-rpath,{libdir}", "-lcuda"], + build_directory=str(build_dir), + verbose=False, + ) + + +IDENTITY_KEYS = [ + "ctaDim", + "tileSizeQ", + "tileSizeKv", + "stepQ", + "stepKv", + "headDimPerCtaV", + "headDimQk", + "headDimV", + "headDimPerStageKv", + "qkvLayout", + "numTokensPerPage", + "maskType", + "kernelType", + "tileScheduler", + "multiCtasKvMode", + "groupsHeadsQ", + "groupsTokensHeadsQ", + "reuseSmemKForV", + "uses2CtaMma", + "sparseAttn", + "skipsSoftmax", + "fp16Softmax", + "usesSpcompress", + "enablesBf16QFp8KvKOnlyTransform", + "separateTransformedKv", + "fusesDsv4InvRopeFp8Quant", + "usesDsv4Ue8m0ScaleO", + "clusterDimX", + "json", +] + + +def enumerate_kernels( + ext: ModuleType, + sm: int, + num_sms: int, + heads: list[tuple[int, int]], + head_dim: int, + page: int, + stage: int, +) -> dict[str, tuple[dict[str, object], list[tuple[int, ...]]]]: + """Kernel name -> (identity, [shape args...]) over the grid; every shape of a name must give the same identity.""" + kernels = {} + for (hq, hkv), b, q, kv in itertools.product(heads, BATCH_SIZES, SEQ_LENS_Q, SEQ_LENS_KV): + if kv < q: + continue + args = (sm, num_sms, hq, hkv, head_dim, b, q, kv, page, stage) + d = ext.select_kernel(*args) + ident = {k: d[k] for k in IDENTITY_KEYS} + if d["name"] not in kernels: + kernels[d["name"]] = (ident, [args]) + continue + if kernels[d["name"]][0] != ident: + diff = { + k: (kernels[d["name"]][0][k], ident[k]) + for k in IDENTITY_KEYS + if kernels[d["name"]][0][k] != ident[k] + } + fail(f"{d['name']} has two configs over the grid: {diff}") + kernels[d["name"]][1].append(args) + return kernels + + +def make_exec_dir(exec_dir: Path, fmha_build_dir: Path) -> Path: + """Create a stand-in for the runner's exec path. + + It links to the kernel headers of the installed build, so the generator reads the same headers but writes its + dumps here instead of into the build tree. + """ + exec_dir.mkdir(parents=True, exist_ok=True) + for entry in ("cuda", "cuda_ptx", "cutlass", "trtllm", "KernelParams.h", "KernelParamsDecl.h"): + if not (fmha_build_dir / entry).exists(): + fail(f"{fmha_build_dir / entry} is missing: the generator's kernel headers moved") + link = exec_dir / entry + if not link.is_symlink(): + link.symlink_to(os.path.realpath(fmha_build_dir / entry)) + return exec_dir + + +def generate( + ext: ModuleType, args: tuple[int, ...], exec_dir: Path, out_dir: Path +) -> tuple[dict[str, object], Path, Path, str]: + """Generator source, cubin and NVRTC options of the kernel selected for args, moved into out_dir.""" + out_dir.mkdir(parents=True, exist_ok=True) + with redirect_fds(out_dir / "generator.log"): + d = ext.generate_kernel(*args, f"{exec_dir}/") + text = (out_dir / "generator.log").read_text(errors="replace") + src = re.findall(r"Dumped NVRTC kernel source to: (\S+)", text) + cub = re.findall(r"Dumped NVRTC CUBIN to: (\S+)", text) + m = re.findall(r"NVRTC Compiler options: (.*)", text) + if len(src) != 1 or len(cub) != 1 or not m: + fail( + f"generator output not found (sources {src}, cubins {cub}, options logged {len(m)}): the " + f"emitsNvRtcSource / emitsCubin switches or the log format changed; see {out_dir / 'generator.log'}" + ) + src, cub = [Path(shutil.move(p, out_dir / Path(p).name)) for p in (src[0], cub[0])] + return d, src, cub, m[-1].strip() + + +def split_options(line: str) -> list[str]: + """The generator logs its NVRTC options space-separated.""" + return [o for o in line.split(" ") if o] + + +# Local static of jitify2::detail::get_jitsafe_headers_map() and its guard variable. +JITIFY_MAP = "_ZZN7jitify26detailL23get_jitsafe_headers_mapEvE19jitsafe_headers_map" +JITIFY_MAP_GUARD = "_ZGVZN7jitify26detailL23get_jitsafe_headers_mapEvE19jitsafe_headers_map" + + +def jitify_headers(ext: ModuleType) -> dict[bytes, bytes]: + """The built-in headers the generator's NVRTC front end (jitify2) supplies for etc. + + They are part of the generator's compile: the offline compile reproduces its cubin only with the same set. Read + in-process from libtensorrt_llm.so after the first generation initialized the map. + """ + lib = trtllm_package_dir() / "libs/libtensorrt_llm.so" + syms = {} + try: + nm = subprocess.run( + ["nm", "--defined-only", str(lib)], check=True, capture_output=True, text=True + ) + except (OSError, subprocess.CalledProcessError) as err: + fail(f"cannot list the symbols of {lib}: {err}") + for line in nm.stdout.splitlines(): + parts = line.split() + if len(parts) == 3 and parts[2] in (JITIFY_MAP, JITIFY_MAP_GUARD): + syms.setdefault(parts[2], []).append(int(parts[0], 16)) + if any(len(syms.get(k, [])) != 1 for k in (JITIFY_MAP, JITIFY_MAP_GUARD)): + fail(f"expected one jitify2 header map in {lib}, found {syms}: jitify2's symbols changed") + real = os.path.realpath(lib) + base = None + for line in Path("/proc/self/maps").read_text().splitlines(): + parts = line.split() + if len(parts) >= 6 and os.path.realpath(parts[5]) == real and int(parts[2], 16) == 0: + base = int(parts[0].split("-")[0], 16) + break + if base is None: + fail(f"{lib} is not mapped in this process") + if ctypes.c_uint8.from_address(base + syms[JITIFY_MAP_GUARD][0]).value == 0: + fail("the jitify2 header map is not initialized yet") + headers = {k.encode(): v for k, v in ext.jitify_headers(base + syms[JITIFY_MAP][0]).items()} + if not any(name.endswith(b"type_traits") for name in headers): + fail( + f"the jitify2 header map holds no ({len(headers)} entries): wrong symbol or layout" + ) + return headers + + +# jitify2 adds these to the generator's options. +JITIFY_OPTIONS = ["-include=jitify_preinclude.h", "-default-device"] + + +def nvrtc_compile( + source: str, name: str, options: list[str], headers: dict[bytes, bytes], log_path: Path +) -> bytes: + """NVRTC compile as the generator does it: program name = kernel name, jitify2's headers in memory.""" + from cuda.bindings import nvrtc + + names, sources = list(headers), list(headers.values()) + err, prog = nvrtc.nvrtcCreateProgram( + source.encode(), name.encode(), len(sources), sources, names + ) + if err != nvrtc.nvrtcResult.NVRTC_SUCCESS: + fail(f"nvrtcCreateProgram failed for {name}: {err}") + opts = [o.encode() for o in options + JITIFY_OPTIONS] + (err,) = nvrtc.nvrtcCompileProgram(prog, len(opts), opts) + _, n = nvrtc.nvrtcGetProgramLogSize(prog) + buf = b" " * n + nvrtc.nvrtcGetProgramLog(prog, buf) + Path(log_path).write_bytes(buf) + if err != nvrtc.nvrtcResult.NVRTC_SUCCESS: + fail(f"NVRTC failed for {name} ({err}); log {log_path}") + _, n = nvrtc.nvrtcGetCUBINSize(prog) + cubin = b" " * n + nvrtc.nvrtcGetCUBIN(prog, cubin) + nvrtc.nvrtcDestroyProgram(prog) + return cubin + + +def apply_e4(source: str) -> str: + lines = source.split("\n") + code = [i for i, ln in enumerate(lines) if not ln.lstrip().startswith("//")] + # The loop counter's generated name (loopOffset) differs between kernels; it must be one name in the block. + norm = [re.sub(r"\bloopOffset\d+\b", "loopOffsetN", lines[i]) for i in code] + pattern = ACQUIRE + RELEASE + hits = [k for k in range(len(code) - len(pattern) + 1) if norm[k : k + len(pattern)] == pattern] + if len(hits) != 1: + fail( + f"expected one stats-acquire / S-release block, found {len(hits)}; the generator changed, re-derive " + "the E4 edit" + ) + k = hits[0] + counters = { + m for j in range(len(pattern)) for m in re.findall(r"\bloopOffset\d+\b", lines[code[k + j]]) + } + if len(counters) != 1: + fail(f"the E4 block uses several loop counters {counters}") + # Each comment line belongs to the code line after it. + first = code[k - 1] + 1 if k > 0 else 0 + split = code[k + len(ACQUIRE) - 1] + 1 + last = code[k + len(pattern) - 1] + 1 + edited = lines[:first] + lines[split:last] + lines[first:split] + lines[last:] + assert len(edited) == len(lines) + return "\n".join(edited) + + +def smem_bytes(cubin: bytes, func_name: str) -> int: + """Dynamic shared memory of the kernel, from the GetSmemSize helper the generator emits.""" + import torch + from cuda.bindings import driver as cu + + def check(res: tuple[Any, ...]) -> Any: + if res[0] != cu.CUresult.CUDA_SUCCESS: + fail(f"CUDA driver call failed reading the shared memory of {func_name}: {res[0]}") + return res[1] if len(res) > 1 else None + + torch.cuda.init() + mod = check(cu.cuModuleLoadData(cubin)) + fn = check(cu.cuModuleGetFunction(mod, f"{func_name}GetSmemSize".encode())) + out = torch.zeros(1, dtype=torch.int32, device="cuda") + ptr = ctypes.c_void_p(out.data_ptr()) + params = (ctypes.c_void_p * 1)(ctypes.addressof(ptr)) + check(cu.cuLaunchKernel(fn, 1, 1, 1, 1, 1, 1, 0, 0, ctypes.addressof(params), 0)) + torch.cuda.synchronize() + check(cu.cuModuleUnload(mod)) + return int(out.item()) + + +def write_archive(stem: str, cubin: bytes) -> None: + with tempfile.TemporaryDirectory(dir=CUBIN_DIR.parent) as tmp: + (Path(tmp) / f"{stem}.cubin").write_bytes(cubin) + subprocess.run( + [ + "cmake", + "-E", + "tar", + "cf", + str(CUBIN_DIR / f"{stem}.cubin.tar.zst"), + "--zstd", + "--mtime=1970-01-01UTC", + "--", + f"{stem}.cubin", + ], + cwd=tmp, + check=True, + ) + + +def meta_entry(sm: int, stem: str, func: str, ident: dict[str, object], smem: int, sha: str) -> str: + b = lambda v: "true" if v else "false" # noqa: E731 + i = ident + return ( + "{ %d, { DATA_TYPE_E4M3, DATA_TYPE_E4M3, DATA_TYPE_E4M3, DATA_TYPE_E4M3, DATA_TYPE_BF16, %d, %d, %d, %d, " + '%d, %d, %d, kSM_%d, %s_cubin, %s_cubin_len, "%s", %d, %d, %d, %d, %d, %d, %d, %d, 0, 0, 0, 0, ' + '%s, %s, %s, %s, %d, %s, %s, %s, %s, %s, %s, %s, "%s", false } },\n' + ) % ( + i["headDimPerStageKv"], + i["tileSizeQ"], + i["tileSizeKv"], + i["stepQ"], + i["stepKv"], + i["headDimPerCtaV"], + i["headDimQk"], + i["headDimV"], + sm, + stem, + stem, + func, + smem, + i["ctaDim"], + i["qkvLayout"], + i["numTokensPerPage"], + i["maskType"], + i["kernelType"], + i["tileScheduler"], + i["multiCtasKvMode"], + b(i["groupsHeadsQ"]), + b(i["groupsTokensHeadsQ"]), + b(i["reuseSmemKForV"]), + b(i["uses2CtaMma"]), + i["sparseAttn"], + b(i["skipsSoftmax"]), + b(i["fp16Softmax"]), + b(i["usesSpcompress"]), + b(i["enablesBf16QFp8KvKOnlyTransform"]), + b(i["separateTransformedKv"]), + b(i["fusesDsv4InvRopeFp8Quant"]), + b(i["usesDsv4Ue8m0ScaleO"]), + sha, + ) + + +_BLOCK_RE = r"// BEGIN %s sm(\d+) (\S+)\n#ifndef EXCLUDE_SM_\d+\n(.*?)#endif\n// END %s sm\1 \2\n" +_STEM_RE = r"extern unsigned char const (\w+)_cubin\[\];" + + +def config_key(head_dim: int, tokens_per_page: int, stage: int) -> str: + """Header block key of one generator configuration (the kernels of other page sizes / stages live apart).""" + return f"h{head_dim}p{tokens_per_page}s{stage}" + + +def write_header(sm: int, config: str, decls: str, entries: str) -> set[str]: + """Replace this SM's blocks of this configuration in the header; keep the other SMs' and configurations'. + + Returns the cubin stems the header references for this SM afterwards. + """ + blocks = {"decls": {}, "entries": {}} + text = META_HEADER.read_text() if META_HEADER.exists() else "" + for kind in blocks: + for m in re.finditer(_BLOCK_RE % (kind, kind), text, re.S): + blocks[kind][(int(m.group(1)), m.group(2))] = m.group(3) + blocks["decls"][(sm, config)] = f"// Kernel inputs sha256: {kernel_inputs_sha256()}\n" + decls + blocks["entries"][(sm, config)] = entries + render = { + kind: "".join( + f"// BEGIN {kind} sm{s} {c}\n#ifndef EXCLUDE_SM_{s}\n{body}#endif\n// END {kind} sm{s} {c}\n" + for (s, c), body in sorted(blocks[kind].items()) + ) + for kind in blocks + } + META_HEADER.write_text( + HEADER_TEMPLATE.replace("@DECLS@", render["decls"]).replace("@ENTRIES@", render["entries"]) + ) + return { + stem + for (s, _), body in blocks["decls"].items() + if s == sm + for stem in re.findall(_STEM_RE, body) + } + + +def remove_stale_archives(sm: int, keep: set[str]) -> list[Path]: + """Delete this SM's stage-KV archives in cubin/ that no header entry references; return their paths. + + Those are kernels a regeneration no longer selects, which CMake would still link (it globs the directory). + """ + stale = [ + path + for path in sorted(CUBIN_DIR.glob(STAGE_KV_ARCHIVE_GLOB.format(sm=sm))) + if path.name[: -len(".cubin.tar.zst")] not in keep + ] + for path in stale: + path.unlink() + return stale + + +def parse_heads(text: str) -> list[tuple[int, int]]: + """'32:2,16:1' -> [(32, 2), (16, 1)]: (Q heads, KV heads) per rank of every layout the cubins serve.""" + heads = [] + for item in text.split(","): + hq, sep, hkv = item.partition(":") + if not sep or not hq.isdigit() or not hkv.isdigit() or int(hkv) == 0 or int(hq) % int(hkv): + raise argparse.ArgumentTypeError( + f"bad --heads entry {item!r}: want :" + ) + heads.append((int(hq), int(hkv))) + return heads + + +def main() -> None: + ap = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + ap.add_argument( + "--work-dir", required=True, type=Path, help="generator output, extension build, logs" + ) + ap.add_argument( + "--heads", + required=True, + type=parse_heads, + help="(Q heads):(KV heads) per rank of every layout, comma-separated, e.g. 32:2,16:1", + ) + ap.add_argument("--head-dim", type=int, required=True) + ap.add_argument("--tokens-per-page", type=int, required=True) + ap.add_argument( + "--stage", type=int, required=True, help="head dim per K/V stage the caller fixes" + ) + ap.add_argument( + "--dry-run", + action="store_true", + help="select and generate, but write nothing into the repo", + ) + a = ap.parse_args() + + # The runner launches these kernels with PDL unless TRTLLM_ENABLE_PDL=0, so they must wait on their grid + # dependency: generate them with PDL regardless of the caller's environment (read before the library loads). + os.environ["TRTLLM_ENABLE_PDL"] = "1" + import torch + + major, minor = torch.cuda.get_device_capability() + sm = major * 10 + minor + if sm not in (100, 103): + fail(f"run on SM100 / SM103, got SM{sm}") + num_sms = torch.cuda.get_device_properties(0).multi_processor_count + work = a.work_dir.resolve() / f"sm{sm}" + work.mkdir(parents=True, exist_ok=True) + fmha_build_dir = ( + trtllm_package_dir().parent / "cpp/build/tensorrt_llm/kernels/trtllmGenKernels/fmha" + ) + if not fmha_build_dir.is_dir(): + fail(f"{fmha_build_dir} not found: run from an editable install with its C++ build tree") + ext = build_extension(work / "ext", fmha_build_dir) + exec_dir = make_exec_dir(work / "exec", fmha_build_dir) + + kernels = enumerate_kernels(ext, sm, num_sms, a.heads, a.head_dim, a.tokens_per_page, a.stage) + log( + f"SM{sm} ({num_sms} SMs): {len(kernels)} kernel(s) over the grid:", + ", ".join(f"{n} ({len(v[1])} shapes)" for n, v in sorted(kernels.items())), + ) + + decls, entries, headers = "", "", None + for name, (ident, shapes) in sorted(kernels.items()): + # Two shapes far apart in the grid must generate the same source. + outs = [ + generate(ext, shapes[i], exec_dir, work / "gen" / name / f"shape{i}") + for i in sorted({0, len(shapes) - 1}) + ] + d, src_path, gen_cubin_path, opt_line = outs[0] + source = src_path.read_text() + for _, other_src, _, other_opts in outs[1:]: + if other_src.read_text() != source or other_opts != opt_line: + fail(f"{name}: shapes {shapes[0]} and {shapes[-1]} generate different kernels") + options = split_options(opt_line) + (work / "gen" / name / "nvrtc_options.txt").write_text("\n".join(options) + "\n") + log( + f"{name}: generator source {src_path} ({len(source)} bytes), options: {' '.join(options)}" + ) + + headers = headers or jitify_headers(ext) + plain = nvrtc_compile(source, name, options, headers, work / "gen" / name / "plain.log") + gen_cubin = gen_cubin_path.read_bytes() + if plain != gen_cubin: + fail( + f"{name}: the offline compile does not reproduce the generator's cubin " + f"({len(plain)} vs {len(gen_cubin)} bytes); fix the compile before trusting the E4 cubin" + ) + log( + f"{name}: offline compile reproduces the generator cubin ({len(plain)} bytes, " + f"sha256 {hashlib.sha256(plain).hexdigest()[:16]})" + ) + + func = f"{name}StageKv{a.stage}E4" + e4_source = apply_e4(source).replace(name, func) + (work / "gen" / name / f"{func}.cu").write_text(e4_source) + e4 = nvrtc_compile(e4_source, func, options, headers, work / "gen" / name / "e4.log") + smem_plain, smem_e4 = smem_bytes(plain, name), smem_bytes(e4, func) + if smem_plain != smem_e4: + fail(f"{name}: smem differs after E4 ({smem_plain} vs {smem_e4})") + sha = hashlib.sha256(e4).hexdigest() + stem = func[0].upper() + func[1:] + (work / "gen" / name / f"{stem}.cubin").write_bytes(e4) + log( + f"{func}: {len(e4)} bytes, smem {smem_e4}, {ident['ctaDim']} threads, sha256 {sha[:16]}" + ) + decls += ( + f"extern unsigned char const {stem}_cubin[];\n" + f"extern unsigned int const {stem}_cubin_len;\n" + ) + entries += meta_entry(sm, stem, func, ident, smem_e4, sha) + if not a.dry_run: + write_archive(stem, e4) + + if not a.dry_run: + config = config_key(a.head_dim, a.tokens_per_page, a.stage) + keep = write_header(sm, config, decls, entries) + log( + f"wrote {len(kernels)} archive(s) to {CUBIN_DIR} and the SM{sm} {config} entries of {META_HEADER}" + ) + for path in remove_stale_archives(sm, keep): + log(f"removed {path.name}: no header entry references it") + + +if __name__ == "__main__": + main() diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/models/glm_moe_dsa/glm_5_2_nvfp4__sm_103__tep4/spec_worker.py b/tensorrt_llm/_torch/_experimental/modeling_v2/models/glm_moe_dsa/glm_5_2_nvfp4__sm_103__tep4/spec_worker.py index 43e80fab59cd..12c63e881c42 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/models/glm_moe_dsa/glm_5_2_nvfp4__sm_103__tep4/spec_worker.py +++ b/tensorrt_llm/_torch/_experimental/modeling_v2/models/glm_moe_dsa/glm_5_2_nvfp4__sm_103__tep4/spec_worker.py @@ -559,8 +559,11 @@ def __init__( # torch.argmax. self._glm_argmax_on = os.environ.get("TRTLLM_GLM52_GREEDY_ARGMAX", "1") == "1" - def _glm_pick(self, logits: torch.Tensor, route: str) -> torch.Tensor | None: - """int32 argmax tokens of `logits` on the CuTe DSL kernel, or None for the built-in.""" + def _glm_pick( + self, logits: torch.Tensor, route: str, out: torch.Tensor | None = None + ) -> torch.Tensor | None: + """int32 argmax tokens of `logits` on the CuTe DSL kernel, or None for the built-in. + `out` (int32 `[rows]`, contiguous), when given, receives them and is returned.""" rows = self._glm_argmax_rows() if self._glm_argmax_on else None if rows is None: return None @@ -568,17 +571,25 @@ def _glm_pick(self, logits: torch.Tensor, route: str) -> torch.Tensor | None: self._glm_count(route, hit) if not hit: return None - tokens = torch.empty([logits.shape[0]], dtype=torch.int32, device=logits.device) - return cute_dsl_argmax(logits, tokens, rows) + if out is None: + out = torch.empty([logits.shape[0]], dtype=torch.int32, device=logits.device) + return cute_dsl_argmax(logits, out, rows) def greedy_sample_draft_with_tp_gather( - self, logits: torch.Tensor, spec_metadata=None, mapping_lm_head_tp=None + self, + logits: torch.Tensor, + spec_metadata=None, + mapping_lm_head_tp=None, + tokens_out: torch.Tensor | None = None, ) -> torch.Tensor: + """The base contract: with `tokens_out` the tokens are written there and it is returned.""" if mapping_lm_head_tp is None: - tokens = self._glm_pick(logits, "greedy_draft") + tokens = self._glm_pick(logits, "greedy_draft", out=tokens_out) if tokens is not None: return tokens - return super().greedy_sample_draft_with_tp_gather(logits, spec_metadata, mapping_lm_head_tp) + return super().greedy_sample_draft_with_tp_gather( + logits, spec_metadata, mapping_lm_head_tp, tokens_out=tokens_out + ) def _sample_tokens_for_batch( self, logits: torch.Tensor, spec_metadata, num_contexts: int, batch_size: int diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/models/kimi_k3_vl/kimi_k3_mxfp4__sm_100__tp16_moetp16ep1/spec_worker.py b/tensorrt_llm/_torch/_experimental/modeling_v2/models/kimi_k3_vl/kimi_k3_mxfp4__sm_100__tp16_moetp16ep1/spec_worker.py index 9691ff052dc6..585408ca1e41 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/models/kimi_k3_vl/kimi_k3_mxfp4__sm_100__tp16_moetp16ep1/spec_worker.py +++ b/tensorrt_llm/_torch/_experimental/modeling_v2/models/kimi_k3_vl/kimi_k3_mxfp4__sm_100__tp16_moetp16ep1/spec_worker.py @@ -1291,18 +1291,21 @@ def sample_draft_tokens( num_contexts=0, draft_step=None, mapping_lm_head_tp=None, + out=None, ): """Greedy block drafts straight from ``k3_markov``. When ``logits`` are the corrected logits the kernel just returned, its per-position global argmax (first maximum, lowest vocabulary index among equal values) is the token the - TP-gathered greedy sampler would pick. Anything else goes to the base sampler. + TP-gathered greedy sampler would pick. Anything else, and any call with ``out``, goes to + the base sampler. """ chain = getattr(self, "_k3_markov", None) if ( chain is not None and chain[0] is logits and mapping_lm_head_tp is None + and out is None and not spec_metadata.wants_advanced_draft_sampling ): self._k3_markov_next = (chain[1], chain[2], chain[3], chain[4]) @@ -1315,6 +1318,7 @@ def sample_draft_tokens( num_contexts=num_contexts, draft_step=draft_step, mapping_lm_head_tp=mapping_lm_head_tp, + out=out, ) def _prepare_next_new_tokens( diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/models/kimi_k3_vl/kimi_k3_mxfp4__sm_100__tp16_moetp4ep4/spec_worker.py b/tensorrt_llm/_torch/_experimental/modeling_v2/models/kimi_k3_vl/kimi_k3_mxfp4__sm_100__tp16_moetp4ep4/spec_worker.py index 9691ff052dc6..585408ca1e41 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/models/kimi_k3_vl/kimi_k3_mxfp4__sm_100__tp16_moetp4ep4/spec_worker.py +++ b/tensorrt_llm/_torch/_experimental/modeling_v2/models/kimi_k3_vl/kimi_k3_mxfp4__sm_100__tp16_moetp4ep4/spec_worker.py @@ -1291,18 +1291,21 @@ def sample_draft_tokens( num_contexts=0, draft_step=None, mapping_lm_head_tp=None, + out=None, ): """Greedy block drafts straight from ``k3_markov``. When ``logits`` are the corrected logits the kernel just returned, its per-position global argmax (first maximum, lowest vocabulary index among equal values) is the token the - TP-gathered greedy sampler would pick. Anything else goes to the base sampler. + TP-gathered greedy sampler would pick. Anything else, and any call with ``out``, goes to + the base sampler. """ chain = getattr(self, "_k3_markov", None) if ( chain is not None and chain[0] is logits and mapping_lm_head_tp is None + and out is None and not spec_metadata.wants_advanced_draft_sampling ): self._k3_markov_next = (chain[1], chain[2], chain[3], chain[4]) @@ -1315,6 +1318,7 @@ def sample_draft_tokens( num_contexts=num_contexts, draft_step=draft_step, mapping_lm_head_tp=mapping_lm_head_tp, + out=out, ) def _prepare_next_new_tokens( diff --git a/tensorrt_llm/_torch/_experimental/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/modeling.py b/tensorrt_llm/_torch/_experimental/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/modeling.py index 5e4b8b9532f6..4e5e2eef7154 100644 --- a/tensorrt_llm/_torch/_experimental/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/modeling.py +++ b/tensorrt_llm/_torch/_experimental/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/modeling.py @@ -5868,7 +5868,7 @@ def _m3_wide_draft_logits_ok(self, spec_metadata, draft_model: Optional[nn.Modul ) def greedy_sample_draft_with_tp_gather( - self, logits: torch.Tensor, spec_metadata=None, mapping_lm_head_tp=None + self, logits: torch.Tensor, spec_metadata=None, mapping_lm_head_tp=None, tokens_out=None ) -> torch.Tensor: """W2b (``WIDE_SPEC_TAIL``): the in-tree draft loop's greedy top-1 over this rank's vocab shard of the drafter logits, from the fused shard argmax + cross-rank key exchange (ops/m3_shard_accept at draft length 0, at @@ -5900,9 +5900,9 @@ def greedy_sample_draft_with_tp_gather( _log_engaged("m3_draft_shard_top1", self.mapping) if tokens is None: return super().greedy_sample_draft_with_tp_gather( - logits, spec_metadata, mapping_lm_head_tp + logits, spec_metadata, mapping_lm_head_tp, tokens_out=tokens_out ) - return tokens + return self._tokens_into(tokens, tokens_out) def _m3_fused_draft_loop( self, diff --git a/tensorrt_llm/_torch/attention/ATTENTION_DEVELOPER_GUIDE.md b/tensorrt_llm/_torch/attention/ATTENTION_DEVELOPER_GUIDE.md index d1bbc4fc810b..4e0d6c64e7a5 100644 --- a/tensorrt_llm/_torch/attention/ATTENTION_DEVELOPER_GUIDE.md +++ b/tensorrt_llm/_torch/attention/ATTENTION_DEVELOPER_GUIDE.md @@ -337,7 +337,10 @@ full arena capacity alongside the profiled peak: a decode arena may first be allocated after peak prefill, so its final retained bytes cannot safely be subtracted from that earlier peak. The attended-KV admission cap applies to the prefix gather, independently of -the fixed graph arena. Projection, native/provider scratch and transient logits +the fixed graph arena. The attention-DP minimum-KV-split scratch of +`fmha/gqa_decode.py` needs no declaration: it is sized by the largest +generation CUDA-graph batch, which graph warmup runs before KV-cache sizing, +and larger eager batches keep FlashInfer's split heuristic. Projection, native/provider scratch and transient logits still require representative peak-memory profiling. ### 2.4 Capability reference @@ -522,6 +525,28 @@ silently drop the routing semantics. Likewise a generation call whose QK-norm / RoPE / KV-append prologue the attention module deferred (`AttentionForwardArgs.kv_append.fold`, query = raw QKV projection) reaches only libraries that declare `supports_deferred_prologue`. + +Two per-forward arguments and one layer field let a library return less than +a full BF16 `output`; callers that set them must read the result accordingly: + +- `output_gate`: a library that multiplies `sigmoid(gate)` into the output sets + `output_gate_applied`; otherwise the caller applies the gate. +- `gated_out_scale` / `output_fp8` (offered only with `output_gate`): a library + that applies the gate may write the gated output as E4M3 at o_proj's static + input scale into `output_fp8` and leave `output` unwritten. The caller then + feeds `output_fp8` to o_proj; `output` holds stale data. +- `context_last_rows_only` (a `TrtllmAttention` field the model sets, e.g. the + Qwen3.5 MTP layer): in a context-only step `FlashInferTrtllmGenFmha` computes + only each request's last output row, against the full KV, and writes zeros to + the other rows; every row's K / V is still appended. Mixed steps run the full + call. + +`trtllm::fmha_paged_context_fp8` (the stage-KV context path of +`FlashInferTrtllmGenFmha`, `context_fmha_head_dim_per_stage_kv > 0`) runs only +a precompiled kernel: when the config the runner selects for the call has no +cubin, the op returns `False` without launching and the library runs +FlashInfer's kernel, so no step compiles with NVRTC. + For mixed non-MLA batches, the manager checks each active phase independently with `is_supported(..., phase=...)`; a phased library accepts only phases backed by its corresponding `run_*()` entry point. diff --git a/tensorrt_llm/_torch/attention/attention.py b/tensorrt_llm/_torch/attention/attention.py index fa585132f3b2..5e9306696faf 100644 --- a/tensorrt_llm/_torch/attention/attention.py +++ b/tensorrt_llm/_torch/attention/attention.py @@ -496,6 +496,9 @@ def maybe_allgather_for_helix_cp( class Attention(nn.Module): + # A gated layer offers o_proj's static FP8 input scale to the KV-replica GQA decode, whose merge then writes + # o_proj's E4M3 input (AttentionForwardArgs.gated_out_scale). + offers_gated_fp8_out: bool = False def __init__( self, @@ -521,6 +524,8 @@ def __init__( head_dim: Optional[int] = None, use_gqa_decode_fmha: bool = False, cache_context_plan: bool = False, + context_fmha_head_dim_per_stage_kv: int = 0, + context_last_rows_only: bool = False, ): """ Initialize the Attention module. @@ -545,6 +550,8 @@ def __init__( use_gqa_decode_fmha (bool): With the TRTLLM backend, serve generation calls with the GQA decode FMHA library (backends/fmha/gqa_decode.py), offering it the output gate and the prologue's FP8 KV append. cache_context_plan (bool): Let the TRTLLM backend plan a context-only forward once for all layers. + context_fmha_head_dim_per_stage_kv (int): See TrtllmAttention; 0 keeps the default context kernel. + context_last_rows_only (bool): See TrtllmAttention; the layer reads only each context request's last row. """ super().__init__() self.layer_idx = layer_idx @@ -667,11 +674,13 @@ def __init__( # Ray); without it the rank decodes its whole KV head. if not TPGroupExchange.is_supported(self.mapping, kv_replicas): kv_replicas = 1 + self.offers_gated_fp8_out = kv_replicas > 1 gqa_decode = GqaDecodeSetup( kv_replicas=kv_replicas, mapping=self.mapping, tokens_per_gen_step=(config.spec_config.tokens_per_gen_step - if config.spec_config is not None else 1)) + if config.spec_config is not None else 1), + max_graph_batch=max(config.cuda_graph_batch_sizes, default=0)) self.q_size = self.num_heads * self.head_dim self.kv_size = self.num_key_value_heads * self.head_dim @@ -834,6 +843,9 @@ def __init__( sparse_params=sparse_params, gqa_decode=gqa_decode, cache_context_plan=cache_context_plan, + context_fmha_head_dim_per_stage_kv= + context_fmha_head_dim_per_stage_kv, + context_last_rows_only=context_last_rows_only, ) self.cache_context_plan = cache_context_plan # (_use_quantize_output(), FP4 KV cache) once the weights are loaded, with cache_context_plan. @@ -1091,6 +1103,10 @@ def _attn_impl( variable_window_token_starts=variable_window_token_starts, variable_window_token_ends=variable_window_token_ends, ) + if (self.offers_gated_fp8_out and output_gate is not None + and out_scale is None and not has_lora): + forward_args.gated_out_scale = self.o_proj.static_fp8_input_scale( + num_tokens) with attn_metadata.mixed_precision_kv_staging(self.attn.layer_idx): attn_output = self.attn.forward(q, k, @@ -1103,6 +1119,10 @@ def _attn_impl( attn_output ) == 2, "attn_output should be a tuple of (output, output_sf)" attn_output, attn_output_sf = attn_output + if forward_args.output_fp8 is not None: + # the library applied the gate and wrote o_proj's FP8 input itself (gated_out_scale) + assert forward_args.output_gate_applied and attn_output_sf is None + return forward_args.output_fp8, None if output_gate is not None and not forward_args.output_gate_applied: attn_output = self.apply_output_gate(attn_output, output_gate) return attn_output, attn_output_sf diff --git a/tensorrt_llm/_torch/attention/backends/fmha/flashinfer_trtllm_gen.py b/tensorrt_llm/_torch/attention/backends/fmha/flashinfer_trtllm_gen.py index bab3490c85bb..acf20b69b89c 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/flashinfer_trtllm_gen.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/flashinfer_trtllm_gen.py @@ -39,8 +39,9 @@ """ import math +import re from functools import lru_cache -from typing import TYPE_CHECKING, List, Optional, Tuple +from typing import TYPE_CHECKING, List, Optional, Tuple, Union import torch @@ -224,6 +225,120 @@ def _get_bmm1_scale_log2(bmm1_scale: torch.Tensor) -> torch.Tensor: return bmm1_scale.narrow(0, 1, 1) +# The typed signature of FlashInfer's private trtllm-gen decode op that trtllm_gen_paged_decode's positional call is +# written for (FlashInfer 0.7), as the op's TVM-FFI wrapper reports it. +_PAGED_DECODE_SIGNATURE = ( + "trtllm_paged_attention_decode(0: DLTensor*, 1: Optional, 2: DLTensor*, 3: DLTensor*, 4: DLTensor*, " + "5: DLTensor*, 6: DLTensor*, 7: DLTensor*, 8: DLTensor*, 9: int, 10: int, 11: Variant, " + "12: Variant, 13: float, 14: int, 15: int, 16: int, 17: int, 18: int, 19: int, 20: bool, " + "21: int, 22: Optional, 23: Optional, 24: Optional, 25: Optional, " + "26: Optional, 27: Optional, 28: Optional, 29: float, 30: int, 31: int, 32: bool, " + "33: Optional, 34: int, 35: Optional) -> void" +) + + +@lru_cache(maxsize=1) +def trtllm_gen_paged_decode_supported() -> bool: + """Whether FlashInfer's private positional ``trtllm_paged_attention_decode`` has the signature + trtllm_gen_paged_decode passes its arguments for; callers decline otherwise (FlashInfer's public decode runs). + + Probed once by calling the op without arguments: its TVM-FFI wrapper checks the argument count before running + anything and names its typed signature in the TypeError. Another signature, another error, or a module that + does not load all decline. + """ + if not IS_FLASHINFER_AVAILABLE: + return False + try: + op = flashinfer.decode.get_trtllm_gen_fmha_module().trtllm_paged_attention_decode + except (AttributeError, ImportError, OSError, RuntimeError) as e: + logger.warning( + f"FlashInfer's trtllm-gen decode op is unavailable ({e}); its direct calls are declined" + ) + return False + try: + op() + except TypeError as e: + found = re.search(r"`([^`]*)`", str(e)) + if found is not None and found.group(1) == _PAGED_DECODE_SIGNATURE: + return True + logger.warning( + "FlashInfer's trtllm_paged_attention_decode does not have the signature trtllm_gen_paged_decode was " + f"written for ({e}); its direct calls are declined" + ) + return False + except (RuntimeError, ValueError) as e: + logger.warning( + f"FlashInfer's trtllm_paged_attention_decode did not report its signature ({e}); its direct calls are " + "declined" + ) + return False + return False + + +def trtllm_gen_paged_decode( + out: torch.Tensor, + query: torch.Tensor, + kv_pool: torch.Tensor, + workspace: torch.Tensor, + counter: torch.Tensor, + block_tables: torch.Tensor, + seq_lens: torch.Tensor, + max_q_len: int, + max_kv_len: int, + bmm1_scale: Union[float, torch.Tensor], + bmm2_scale: Union[float, torch.Tensor], + batch_size: int, + window_left: int, + sm_count: int, + enable_pdl: bool, + sinks: Optional[torch.Tensor] = None, + cum_seq_lens_q: Optional[torch.Tensor] = None, + lse: Optional[torch.Tensor] = None, +) -> None: + """FlashInfer's trtllm-gen paged decode op (behind ``trtllm_batch_decode_with_kv_cache``) with an explicit SM count, + from which the kernel derives its KV split. Query and KV of one dtype, HND pool, a [requests, 2, pages] page table; + bmm1_scale a float or the [raw, raw * log2e] tensor; lse (base 2) optional. Callers check + trtllm_gen_paged_decode_supported() first.""" + flashinfer.decode.get_trtllm_gen_fmha_module().trtllm_paged_attention_decode( + out, + None, # out_scale_factor + query, + kv_pool, + kv_pool, + workspace, + counter, + block_tables, + seq_lens, + max_q_len, + max_kv_len, + _get_bmm1_scale_log2(bmm1_scale) if isinstance(bmm1_scale, torch.Tensor) else bmm1_scale, + bmm2_scale, + -1.0, # o_sf_scale + -1, # o_sf_vec_size + 0, # o_sf_start_index + batch_size, + window_left, + 0, # sparse_mla_top_k + sm_count, + enable_pdl, + workspace.numel() * workspace.element_size(), + sinks, + cum_seq_lens_q, + None, # k_block_scales + None, # v_block_scales + None, # skip_softmax_threshold_scale_factor + False, # uses_shared_paged_kv_idx + lse, + 1.0, # lse_scale + lse.stride(0) if lse is not None else 0, + lse.stride(1) if lse is not None else 0, + False, # enable_block_sparse_attention + None, # sparse_mla_top_k_lens + 0, # bf16q_fp8kv_transform_mode (query and KV of one dtype) + None, # use_fp16_softmax + ) + + @lru_cache(maxsize=128) def _get_generation_workspace_layout( dtype: torch.dtype, @@ -938,6 +1053,41 @@ def _missing_fused_nanobind_ops() -> List[str]: ) return [op for op in required_ops if not hasattr(thop, op)] + def _uses_paged_context_fp8( + self, + fp8_context_fmha: bool, + query: torch.Tensor, + kv_pool: torch.Tensor, + block_tables: torch.Tensor, + bmm1_scale: Optional[torch.Tensor], + kv_scale_pool: Optional[torch.Tensor], + causal: bool, + attention_sinks: Optional[torch.Tensor], + window_left: int, + output: torch.Tensor, + ) -> bool: + """Whether a context call offers trtllm::fmha_paged_context_fp8 the layer's declared + ``context_fmha_head_dim_per_stage_kv``: causal E4M3 Q / KV (no KV scale factors, sinks or window), BF16 + output, TRT-LLM's contiguous paged KV pool with separate K / V page indices. The op declines a call whose + selected kernel has no precompiled cubin, which then runs FlashInfer's kernel.""" + return ( + self.attn.context_fmha_head_dim_per_stage_kv > 0 + and fp8_context_fmha + and causal + and isinstance(bmm1_scale, torch.Tensor) + and kv_scale_pool is None + and attention_sinks is None + and window_left < 0 + and query.dtype == torch.float8_e4m3fn + and kv_pool.dtype == torch.float8_e4m3fn + and kv_pool.dim() == 4 + and kv_pool.is_contiguous() + and block_tables.dim() == 3 + and block_tables.size(1) == 2 + and output.dtype == torch.bfloat16 + and output.is_contiguous() + ) + def run_context( self, params: FmhaParams, @@ -1032,30 +1182,80 @@ def run_context( if params.is_cross else AttentionMaskType(fwd.mask_type) == AttentionMaskType.causal ) - flashinfer.prefill.trtllm_batch_context_with_kv_cache( - query=q_processed, - kv_cache=(kv_pool, kv_pool), - workspace_buffer=fmha_workspace, - block_tables=block_tables, - seq_lens=params.sequence_lengths, - max_q_len=max_q_len, - max_kv_len=max_kv_len, - bmm1_scale=ctx_bmm1_scale, - bmm2_scale=ctx_bmm2_scale, - batch_size=params.batch_size, - cum_seq_lens_q=cu_q_seqlens, - cum_seq_lens_kv=cu_kv_seqlens, - window_left=window_left, - out=params.output, - kv_layout=self._layout, - enable_pdl=self._enable_pdl, - sinks=fwd.attention_sinks, - kv_cache_sf=(kv_scale_pool, kv_scale_pool) if kv_scale_pool is not None else None, - uses_shared_paged_kv_idx=self.USE_SHARED_PAGED_KV_IDX, - causal=causal, - multi_ctas_kv_counter_buffer=self._get_multi_ctas_kv_counter_buffer(), + paged_context_fp8 = self._uses_paged_context_fp8( + fp8_context_fmha, + q_processed, + kv_pool, + block_tables, + bmm1_scale, + kv_scale_pool, + causal, + fwd.attention_sinks, + window_left, + params.output, ) + def fmha(query, out, cu_q, max_q): + if paged_context_fp8 and torch.ops.trtllm.fmha_paged_context_fp8( + query, + kv_pool, + block_tables, + params.sequence_lengths, + cu_q, + cu_kv_seqlens, + out, + bmm1_scale, + bmm2_scale, + max_q, + max_kv_len, + attn.context_fmha_head_dim_per_stage_kv, + ): + return + flashinfer.prefill.trtllm_batch_context_with_kv_cache( + query=query, + kv_cache=(kv_pool, kv_pool), + workspace_buffer=fmha_workspace, + block_tables=block_tables, + seq_lens=params.sequence_lengths, + max_q_len=max_q, + max_kv_len=max_kv_len, + bmm1_scale=ctx_bmm1_scale, + bmm2_scale=ctx_bmm2_scale, + batch_size=params.batch_size, + cum_seq_lens_q=cu_q, + cum_seq_lens_kv=cu_kv_seqlens, + window_left=window_left, + out=out, + kv_layout=self._layout, + enable_pdl=self._enable_pdl, + sinks=fwd.attention_sinks, + kv_cache_sf=(kv_scale_pool, kv_scale_pool) if kv_scale_pool is not None else None, + uses_shared_paged_kv_idx=self.USE_SHARED_PAGED_KV_IDX, + causal=causal, + multi_ctas_kv_counter_buffer=self._get_multi_ctas_kv_counter_buffer(), + ) + + if ( + attn.context_last_rows_only + and not params.is_cross + and meta.num_generations == 0 + and params.num_tokens > params.batch_size + ): + # Each request's last row only, against the full KV (preprocess appended every row's K / V). + # The PDL-launched FMHA may read its sequence offsets before its dependency wait, so they are not + # written by the kernel right before it (the query gather, which it reads after the wait). + cu_q_last = torch.arange( + params.batch_size + 1, dtype=cu_q_seqlens.dtype, device=cu_q_seqlens.device + ) + last = (cu_q_seqlens[1 : params.batch_size + 1] - 1).long() + q_last = q_processed.index_select(0, last) + out_last = params.output.new_empty((params.batch_size, *params.output.shape[1:])) + fmha(q_last, out_last, cu_q_last, 1) + params.output.zero_() + params.output.index_copy_(0, last, out_last) + else: + fmha(q_processed, params.output, cu_q_seqlens, max_q_len) + if params.is_cross: return diff --git a/tensorrt_llm/_torch/attention/backends/fmha/gqa_decode.py b/tensorrt_llm/_torch/attention/backends/fmha/gqa_decode.py index c07ff2880f45..1ddd2d44b332 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/gqa_decode.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/gqa_decode.py @@ -30,12 +30,13 @@ import math from dataclasses import dataclass -from typing import TYPE_CHECKING, Optional, Tuple +from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union import torch from tensorrt_llm._torch.attention.backends.interface import AttentionForwardArgs from tensorrt_llm._torch.cute_dsl_utils import IS_CUTLASS_DSL_AVAILABLE +from tensorrt_llm._torch.memory_buffer_utils import get_memory_buffers from tensorrt_llm._torch.pyexecutor.trace_log_utils import log_tensor_size from tensorrt_llm.bindings.internal import thop from tensorrt_llm.logger import logger @@ -47,12 +48,20 @@ FlashInferTrtllmGenFmha, _get_generation_workspace_layout, _get_generation_workspace_size, + trtllm_gen_paged_decode, + trtllm_gen_paged_decode_supported, +) +from .gqa_kv_replica import ( + ROPE_GATHER_CHANNEL, + exchange_channels, + kv_replica_decode, + kv_replica_fused_decode, ) -from .gqa_kv_replica import EXCHANGE_CHANNELS, kv_replica_decode, kv_replica_fused_decode from .gqa_kv_replica_fused import kv_replica_fused_state, kv_replica_fused_supported from .gqa_segmented_decode import ( MAX_FOLDED_ROWS, MAX_Q_LEN, + load_trtllm_gen_decode_module, segment_attention_softmax_bytes, segmented_decode, segmented_decode_supported, @@ -84,6 +93,17 @@ # Smallest sizes of the KV-replica exchange: per-pair payload bytes, rows of one all-to-all merge. _MIN_EXCHANGE_BYTES = 1 << 20 _MIN_MERGE_ROWS = 2048 +# trtllm-gen splits each sequence's KV over at most sm_count // (CTAs of one split) CTAs, so a large decode batch +# streams each sequence on one CTA. Attention-DP decode keeps at least this many splits per sequence. +_ATTENTION_DP_MIN_KV_SPLITS = 8 +# Largest Q tile of trtllm-gen's generation kernels; a split CTA keeps one tile of partials (FP32 O + softmax stats). +_MAX_GEN_TILE_ROWS = 128 + + +def min_kv_split_scratch_bytes(max_sm_count: int, head_dim: int) -> int: + """Scratch bytes of a forced-split trtllm-gen decode launched with up to max_sm_count CTAs: per CTA one Q tile of + at most _MAX_GEN_TILE_ROWS rows of FP32 partial O and an FP32 (max, sum) softmax-stats pair.""" + return max_sm_count * _MAX_GEN_TILE_ROWS * (8 + 4 * head_dim) @dataclass(frozen=True) @@ -96,6 +116,8 @@ class GqaDecodeSetup: mapping: Optional[Mapping] = None # Largest q_len of a generation call (1 + draft tokens). tokens_per_gen_step: int = 1 + # Largest CUDA-graph decode batch (requests per rank); 0 without generation CUDA graphs. + max_graph_batch: int = 0 @dataclass @@ -137,6 +159,12 @@ class KvAppendPlan: # then runs the folded kernel or the prologue, which fills q_fp8, scales and the contiguous gate. fold: Optional[FoldInputs] = None gate: Optional[torch.Tensor] = None + # The KV group's FP8 query [num_tokens, group * num_heads * head_dim], when the prologue all-gathered it + # (GqaKvReplicaFusedFmha). + q_gathered: Optional[torch.Tensor] = None + # The q all-gather arguments of GqaKvReplicaFusedFmha when it takes the call (peer table, epochs, member index, + # group size, slot words, PDL); its run_prologue gathers only with a resident grid. + rope_gather: Optional[tuple] = None def _kv_replica_exchange_sizes( @@ -158,12 +186,38 @@ class GqaDecodeFmha(FlashInferTrtllmGenFmha): """trtllm-gen for a layer built with a ``GqaDecodeSetup``; base of the dedicated GQA decode libraries.""" supports_deferred_prologue = True + # Whether a generation call of this library loaded FlashInfer's trtllm-gen decode module. + _decode_module_loaded = False + # Minimum KV splits per sequence of a trtllm-gen decode call; 0: FlashInfer's heuristic. + _min_kv_splits: int = 0 + # Largest decode batch that takes the minimum (the largest CUDA-graph decode batch); sizes its scratch. + _min_kv_split_batch: int = 0 def __init__(self, attn: "TrtllmAttention") -> None: super().__init__(attn) self._counter_buffer: Optional[torch.Tensor] = None # max_num_requests -> _segment_stats_bytes self._segment_stats_bytes_cache: dict[int, int] = {} + setup = attn.gqa_decode + if ( + setup.mapping is not None + and setup.mapping.enable_attention_dp + and setup.max_graph_batch > 0 + ): + # Bounded by the largest CUDA-graph batch: graph warmup allocates the scratch before KV-cache sizing, + # and larger eager batches keep FlashInfer's heuristic. + self._min_kv_splits = self._min_kv_splits_for( + attn.num_heads, attn.num_kv_heads, setup.tokens_per_gen_step + ) + self._min_kv_split_batch = setup.max_graph_batch + + @staticmethod + def _min_kv_splits_for(num_heads: int, num_kv_heads: int, tokens_per_gen_step: int) -> int: + """_ATTENTION_DP_MIN_KV_SPLITS when the forced split fits the counter buffer (splits x KV heads <= heads) and + one Q tile (group x q_len rows), else 0.""" + splits = _ATTENTION_DP_MIN_KV_SPLITS + rows = num_heads // num_kv_heads * tokens_per_gen_step + return splits if splits * num_kv_heads <= num_heads and rows <= _MAX_GEN_TILE_ROWS else 0 @classmethod def _is_available(cls, attn: "TrtllmAttention") -> bool: @@ -269,6 +323,20 @@ def _run_generation_decode( ) ): return + if kv_scale_pool is None and self._run_min_kv_split( + params, + q, + kv_pool, + block_tables, + max_kv_len, + window_left, + q_len_per_req, + max_q_len, + cu_seqlens, + bmm1_scale, + bmm2_scale, + ): + return super()._run_generation_decode( params, q, @@ -299,6 +367,68 @@ def _run_dedicated( """Run this library's kernel on a uniform-q_len generation call with an FP8 query; False: trtllm-gen.""" return False + def _run_min_kv_split( + self, + params: FmhaParams, + q: torch.Tensor, + kv_pool: torch.Tensor, + block_tables: torch.Tensor, + max_kv_len: int, + window_left: int, + q_len_per_req: Optional[int], + max_q_len: Optional[int], + cu_seqlens: Optional[torch.Tensor], + bmm1_scale: Union[float, torch.Tensor], + bmm2_scale: Union[float, torch.Tensor], + ) -> bool: + """trtllm-gen decode with _min_kv_splits KV splits per sequence where the device's SM count gives fewer: the + same kernel launched with the SM count that gives them, and a scratch for their partials. False: the stock + call (no minimum, query and KV dtypes differ, enough SMs, or a batch above _min_kv_split_batch).""" + splits = self._min_kv_splits + if splits == 0 or self._multi_processor_count is None or q.dtype != kv_pool.dtype: + return False + if q_len_per_req is not None: + batch, max_q_len, cu_seqlens = q.size(0) // q_len_per_req, q_len_per_req, None + elif cu_seqlens is not None: + batch = cu_seqlens.size(0) - 1 + else: + return False + attn = self.attn + sm_count = splits * attn.num_kv_heads * batch + if sm_count <= self._multi_processor_count or batch > self._min_kv_split_batch: + return False + if not trtllm_gen_paged_decode_supported(): + return False + # Split CTAs <= sm_count, one Q tile of partials each; sized for the largest batch, so every call and captured + # graph shares one block. + max_sm_count = splits * attn.num_kv_heads * self._min_kv_split_batch + scratch = get_memory_buffers().get_buffer( + [min_kv_split_scratch_bytes(max_sm_count, attn.head_dim)], + torch.uint8, + buffer_name="trtllm_gen_min_kv_split_scratch", + reserve_buffer=True, + ) + trtllm_gen_paged_decode( + params.output, + q, + kv_pool, + scratch, + self._get_multi_ctas_kv_counter_buffer(), + block_tables, + params.sequence_lengths, + max_q_len, + max_kv_len, + bmm1_scale, + bmm2_scale, + batch, + window_left, + sm_count, + self._enable_pdl, + sinks=params.fwd.attention_sinks, + cum_seq_lens_q=cu_seqlens, + ) + return True + @staticmethod def _gate(params: FmhaParams) -> Optional[torch.Tensor]: """The offered output gate of a generation-only call (it covers every token of the forward), else None.""" @@ -357,6 +487,11 @@ def prepare_workspace( ) -> None: self._reserve_segment_stats(q, metadata, workspace) super().prepare_workspace(q, k, v, metadata, forward_args, workspace) + if not self._decode_module_loaded and metadata.num_generations > 0: + # On the first generation call (warmup's), which a dedicated kernel may serve: the segmented and + # trtllm-gen decodes that need the module may come only with mixed or larger batches. + load_trtllm_gen_decode_module() + self._decode_module_loaded = True def _reserve_segment_stats( self, q: torch.Tensor, metadata: "TrtllmAttentionMetadata", workspace: torch.Tensor @@ -427,29 +562,55 @@ def _segment_workspace_if_fits( ) return None - @staticmethod - def _run_fold_prologue(params: FmhaParams, plan: KvAppendPlan) -> None: + def run_prologue( + self, + plan: KvAppendPlan, + qkv: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + cos_sin: torch.Tensor, + positions: torch.Tensor, + eps: float, + rotary_dim: int, + mrope_section: Optional[tuple], + ) -> Tuple[torch.Tensor, torch.Tensor]: + """The prologue kernel of a call with KV-append ``plan`` (fused_qkv_rope_gate_fp8_append): sets plan.q_fp8 + and plan.scales, returns the packed QKV and the gate. The module's unfolded prologue runs it too.""" + from ...kernels.fused_qk_norm_rope_gate import fused_qkv_rope_gate_fp8_append + + attn = self.attn + qkv_out, gate_out, plan.q_fp8, plan.scales = fused_qkv_rope_gate_fp8_append( + qkv, + q_weight, + k_weight, + cos_sin, + positions, + eps, + attn.num_heads, + attn.num_kv_heads, + attn.head_dim, + rotary_dim, + mrope_section, + plan, + ) + return qkv_out, gate_out + + def _run_fold_prologue(self, params: FmhaParams, plan: KvAppendPlan) -> None: """Run the prologue kernel the module skipped for a folded call that misses the folded kernel. Sets the packed QKV of this call as params.qkv_input and the prologue outputs on the plan. """ - from ...kernels.fused_qk_norm_rope_gate import fused_qkv_rope_gate_fp8_append - - attn = params.attn f = plan.fold - qkv_out, gate_out, plan.q_fp8, plan.scales = fused_qkv_rope_gate_fp8_append( + qkv_out, gate_out = self.run_prologue( + plan, f.qkv, f.q_weight, f.k_weight, f.cos_sin, f.positions, f.eps, - attn.num_heads, - attn.num_kv_heads, - attn.head_dim, f.rotary_dim, f.mrope_section, - plan, ) params.qkv_input = qkv_out[: params.num_tokens] if params.fwd.output_gate is not None: @@ -751,7 +912,12 @@ def prepare_workspace( metadata.max_num_requests, self._tokens_per_gen_step, attn.num_heads, attn.head_dim ) self._exchange = get_tp_group_exchange( - self._mapping, self._kv_replicas, max_bytes, max_merge_rows, EXCHANGE_CHANNELS + self._mapping, + self._kv_replicas, + max_bytes, + max_merge_rows, + exchange_channels(self._enable_pdl), + attn.head_dim, ) self._exchange_created = True @@ -799,6 +965,13 @@ def _run_dedicated( class GqaKvReplicaFusedFmha(_GqaKvReplicaFmha): """KV-replica split with the fused partial attention kernel (gqa_kv_replica_fused.py).""" + # Per (token count, q_len): whether the RoPE kernel's q all-gather grid stays resident (decided once per shape). + _rope_gather_resident: Optional[Dict[Tuple[int, int], bool]] = None + + def __init__(self, attn: "TrtllmAttention") -> None: + super().__init__(attn) + self._rope_gather_resident = {} + @classmethod def _is_available(cls, attn: "TrtllmAttention") -> bool: return ( @@ -828,6 +1001,109 @@ def prepare_workspace( super().prepare_workspace(q, k, v, metadata, forward_args, workspace) kv_replica_fused_state(q.device, self._multi_processor_count, metadata.max_num_requests) + def kv_append_plan( + self, metadata: "TrtllmAttentionMetadata", num_tokens: int + ) -> Optional[KvAppendPlan]: + """GqaDecodeFmha.kv_append_plan; when this library takes the call, the plan also carries the q all-gather + arguments (plan.rope_gather) for run_prologue.""" + plan = super().kv_append_plan(metadata, num_tokens) + if plan is not None: + if self._multi_processor_count is None: + self._multi_processor_count = self._get_multi_processor_count(plan.seq_lens.device) + from .manager import generation_cell_bound + + # Only for calls this library takes: _is_supported's check, at the same selection-cache cell bound (the + # members' exchange calls stay identical, and no gather runs for a call another library serves). + if plan.num_requests >= 2 and self._takes( + *generation_cell_bound(plan.num_requests, plan.q_len), metadata + ): + plan.rope_gather = self._rope_gather(self.attn, num_tokens) + return plan + + def _rope_gather(self, attn: "TrtllmAttention", num_tokens: int) -> Optional[tuple]: + """Arguments of a q all-gather inside the prologue's RoPE kernel, or None. + + Every member decides from the same shapes, so the members' exchange calls stay identical. The conditions + are _run_dedicated's (exchange, payload) and PDL (the kernel releases the partial kernel right after its own + wait, which keeps the prefix-KV prefetch overlapping the exchange); run_prologue checks the grid residency.""" + exchange = self._exchange + if ( + not self._enable_pdl + or exchange is None + or num_tokens * attn.num_heads * (attn.head_dim * 2 + 4) > exchange.max_words * 4 + ): + return None + return ( + *exchange.rope_gather_args( + ROPE_GATHER_CHANNEL, num_tokens * attn.num_heads, attn.head_dim + ), + True, + ) + + def run_prologue( + self, + plan: KvAppendPlan, + qkv: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + cos_sin: torch.Tensor, + positions: torch.Tensor, + eps: float, + rotary_dim: int, + mrope_section: Optional[tuple], + ) -> Tuple[torch.Tensor, torch.Tensor]: + """GqaDecodeFmha.run_prologue; with plan.rope_gather and a grid that stays resident (it polls the peers), the + RoPE kernel also all-gathers the FP8 query over the KV group (plan.q_gathered), and kv_replica_fused_decode + launches no all-gather.""" + from ...kernels.fused_qk_norm_rope_gate import ( + fused_qkv_rope_gate_fp8_append_gather, + rope_gather_max_tokens, + ) + + attn = self.attn + gather = plan.rope_gather + num_tokens = qkv.shape[0] + shape = (num_tokens, plan.q_len) + if gather is not None and shape not in self._rope_gather_resident: + # Triton specializes the kernel on the token count and q_len, so the bound is taken per shape. + self._rope_gather_resident[shape] = num_tokens <= rope_gather_max_tokens( + qkv, + q_weight, + k_weight, + cos_sin, + positions, + eps, + attn.num_heads, + attn.num_kv_heads, + attn.head_dim, + rotary_dim, + mrope_section, + plan, + gather, + ) + if gather is None or not self._rope_gather_resident[shape]: + return super().run_prologue( + plan, qkv, q_weight, k_weight, cos_sin, positions, eps, rotary_dim, mrope_section + ) + qkv_out, gate_out, plan.q_fp8, plan.scales, plan.q_gathered = ( + fused_qkv_rope_gate_fp8_append_gather( + qkv, + q_weight, + k_weight, + cos_sin, + positions, + eps, + attn.num_heads, + attn.num_kv_heads, + attn.head_dim, + rotary_dim, + mrope_section, + plan, + gather, + ) + ) + return qkv_out, gate_out + def _run_kv_replica( self, params: FmhaParams, @@ -842,6 +1118,26 @@ def _run_kv_replica( gate: Optional[torch.Tensor], ) -> None: rows, hq, d = q.shape + plan = params.fwd.kv_append + q_gathered = None + if ( + plan is not None + and plan.q_gathered is not None + and plan.q_fp8 is not None + and q.data_ptr() == plan.q_fp8.data_ptr() + and plan.q_gathered.shape[0] == rows + ): + q_gathered = plan.q_gathered + # The caller offered o_proj's static FP8 input scale with the gate: the merge writes the gated output as + # o_proj's own quant would, for the whole call, and the caller hands that E4M3 tensor to o_proj. + fwd = params.fwd + out_fp8 = None + if ( + gate is not None + and fwd.gated_out_scale is not None + and (fwd.output is None or fwd.output.shape[0] == rows) + ): + out_fp8 = torch.empty((rows, hq, d), dtype=torch.float8_e4m3fn, device=q.device) kv_replica_fused_decode( exchange, q, @@ -857,7 +1153,12 @@ def _run_kv_replica( ), self._enable_pdl, gate=gate, + q_gathered=q_gathered, + out_fp8=out_fp8, + out_scale=fwd.gated_out_scale if out_fp8 is not None else None, ) + if out_fp8 is not None: + fwd.output_fp8 = out_fp8.view(rows, hq * d) class GqaKvReplicaFmha(_GqaKvReplicaFmha): @@ -885,6 +1186,9 @@ def _largest_segment_rows(max_requests: int, q_len: int, group_heads: int) -> in ) def _takes(self, batch: int, q_len: int, metadata: "TrtllmAttentionMetadata") -> bool: + # The segment attention calls FlashInfer's decode op directly (trtllm_gen_paged_decode). + if not trtllm_gen_paged_decode_supported(): + return False # One counter per (FMHA request, folded head) of the segment attention, at the largest call of this cell. group_heads = self._kv_replicas * self.attn.num_heads max_num_requests = metadata.max_num_requests @@ -1157,6 +1461,9 @@ def _is_supported( cell = self._decode_cell(q, metadata, forward_args, phase, generation_only=False) if cell is None or metadata.num_generations > _SEGMENTED_MAX_BATCH: return False + # The segment attention calls FlashInfer's decode op directly (trtllm_gen_paged_decode). + if not trtllm_gen_paged_decode_supported(): + return False batch, q_len = cell attn = self.attn return segmented_decode_supported( diff --git a/tensorrt_llm/_torch/attention/backends/fmha/gqa_kv_replica.py b/tensorrt_llm/_torch/attention/backends/fmha/gqa_kv_replica.py index 27d02b6e67b6..835b27b92b72 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/gqa_kv_replica.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/gqa_kv_replica.py @@ -32,8 +32,14 @@ from .gqa_kv_replica_fused import KvReplicaFusedState, kv_replica_fused_partial from .gqa_segmented_decode import draft_block, seg_geometry, segment_attention -# Channels of the KV group's exchange: 0 carries the q all-gather, 1 the all-to-all + merge. -EXCHANGE_CHANNELS = 2 +# Channels of the KV group's exchange: 0 carries the q all-gather, 1 the all-to-all + merge, 2 the q all-gather inside +# the RoPE / FP8 kernel (fused_qkv_rope_gate_fp8_append_gather), which runs only with PDL. +ROPE_GATHER_CHANNEL = 2 + + +def exchange_channels(enable_pdl: bool) -> int: + """Channels of the KV group's exchange (the RoPE kernel's channel only with PDL).""" + return ROPE_GATHER_CHANNEL + 1 if enable_pdl else ROPE_GATHER_CHANNEL @triton.jit @@ -478,6 +484,37 @@ def _allgather_q(exchange, q: torch.Tensor, enable_pdl: bool) -> torch.Tensor: ) +# Per device and O dtype: flat (O, LSE) storage the pushed-mode partial kernel takes as its unwritten out_o / out_lse. +_PUSHED_PARTIAL_PLACEHOLDERS: dict = {} + + +def _pushed_partial_placeholders( + cp: int, rows: int, hq: int, d: int, dtype: torch.dtype, device: torch.device +) -> Tuple[torch.Tensor, torch.Tensor]: + """``(o [cp, rows, hq, d], lse [cp, rows, hq] FP32)`` for a partial kernel that pushes its rows to the members + (``ll``) and never writes them, nor does ``alltoall_merge(pushed=True)`` read them: prefix views of storage kept + per device and dtype (grown on demand), with the shape, strides and base alignment of a fresh ``torch.empty``, + so the kernels compile and launch as with one. Under CUDA graph capture a fresh pair, as before (the captured + graph keeps its own addresses).""" + numel_o, numel_lse = cp * rows * hq * d, cp * rows * hq + if torch.cuda.is_current_stream_capturing(): + return ( + torch.empty(cp, rows, hq, d, dtype=dtype, device=device), + torch.empty(cp, rows, hq, dtype=torch.float32, device=device), + ) + key = (device, dtype) + bufs = _PUSHED_PARTIAL_PLACEHOLDERS.get(key) + if bufs is None or bufs[0].numel() < numel_o or bufs[1].numel() < numel_lse: + grown_o = max(numel_o, bufs[0].numel() if bufs is not None else 0) + grown_lse = max(numel_lse, bufs[1].numel() if bufs is not None else 0) + bufs = ( + torch.empty(grown_o, dtype=dtype, device=device), + torch.empty(grown_lse, dtype=torch.float32, device=device), + ) + _PUSHED_PARTIAL_PLACEHOLDERS[key] = bufs + return bufs[0][:numel_o].view(cp, rows, hq, d), bufs[1][:numel_lse].view(cp, rows, hq) + + def kv_replica_fused_decode( exchange, q: torch.Tensor, @@ -491,20 +528,33 @@ def kv_replica_fused_decode( fused_state: KvReplicaFusedState, enable_pdl: bool, gate: Optional[torch.Tensor] = None, + q_gathered: Optional[torch.Tensor] = None, + out_fp8: Optional[torch.Tensor] = None, + out_scale: Optional[torch.Tensor] = None, ) -> None: """KV-replica split generation attention of this rank's heads, partials from the fused kernel - (gqa_kv_replica_fused.py). + (gqa_kv_replica_fused.py). With out_fp8 [b * q_len, Hq_local, D] E4M3 and out_scale (the consumer's static + input scale), the merge writes the (gated) result there as the consumer's own static quant would and leaves + out unwritten (TPGroupExchange.alltoall_merge). exchange: TPGroupExchange (distributed/ll_exchange.py) whose groups are the KV groups (member = CP rank); channel 0 carries the q all-gather, channel 1 the all-to-all + LSE merge (+ gate) of the per-destination (O, LSE) partials. q [b * q_len, Hq_local, D] (FP8), out [b * q_len, Hq_local, D]; gate optional (out * sigmoid(gate)). fused_state: the fused kernel's counters and workspace on this device. + q_gathered: the group's q [b * q_len, cp * Hq_local * D] FP8 when the RoPE kernel already all-gathered it + (fused_qkv_rope_gate_fp8_append_gather); then no all-gather is launched here. """ cp, cp_rank = exchange.group_size, exchange.grank rows, hq, d = q.shape - q_all = _allgather_q(exchange, q, enable_pdl) - o = torch.empty(cp, rows, hq, d, dtype=out.dtype, device=q.device) - lse = torch.empty(cp, rows, hq, dtype=torch.float32, device=q.device) + if q_gathered is not None: + assert q_gathered.shape == (rows, cp * hq * d) and q_gathered.dtype == q.dtype + q_all = q_gathered.view(rows, cp, hq, d).permute(1, 0, 2, 3) + else: + q_all = _allgather_q(exchange, q, enable_pdl) + # The partial kernel's combine pushes its (O, LSE) rows into the members' merge slots, so neither it nor the merge + # touches o / lse: placeholders of their shapes. + o, lse = _pushed_partial_placeholders(cp, rows, hq, d, out.dtype, q.device) + ll = exchange.merge_push_args(1, rows * hq, d) kv_replica_fused_partial( q_all, kv_pool, @@ -519,8 +569,21 @@ def kv_replica_fused_decode( lse, fused_state, enable_pdl=enable_pdl, + ll=ll, ) - exchange.alltoall_merge(o, lse, out.view(rows, hq, d), gate=gate, channel=1) + if out_fp8 is not None: + exchange.alltoall_merge( + o, + lse, + None, + gate=gate, + channel=1, + out_fp8=out_fp8.view(rows, hq, d), + out_scale=out_scale, + pushed=True, + ) + else: + exchange.alltoall_merge(o, lse, out.view(rows, hq, d), gate=gate, channel=1, pushed=True) def kv_replica_decode( diff --git a/tensorrt_llm/_torch/attention/backends/fmha/gqa_kv_replica_fused.py b/tensorrt_llm/_torch/attention/backends/fmha/gqa_kv_replica_fused.py index 3c849bc751c1..da7092e2f044 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/gqa_kv_replica_fused.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/gqa_kv_replica_fused.py @@ -23,7 +23,7 @@ """ import functools -from typing import Dict, Union +from typing import Dict, Optional, Tuple, Union import torch @@ -35,9 +35,9 @@ HEAD_DIM = 256 MAX_ROWS = 128 MAX_Q_LEN = 16 -# Plan variants by batch: one request per lane of the plan warp up to 32, two per lane up to 64 (wide plan), and above -# 64 the two-slot kernel (kernel_two, four requests per lane): a CTA computes up to two requests, so no request is held -# to whole CTAs. +# Plan variants by batch (_plan): one request per lane of the plan warp up to 32, two per lane up to 64 (wide plan), and +# the two-slot kernel (kernel_two, four requests per lane) above 64 or where whole CTAs per request leave CTAs idle: a +# CTA computes up to two requests, so no request is held to whole CTAs. _LANE_PLAN_MAX_BATCH = 32 _WIDE_PLAN_MAX_BATCH = 64 _TWO_SLOT_MAX_BATCH = 128 @@ -78,6 +78,29 @@ def _num_ctas(sm_count: int) -> int: return max(sm_count, 1) +# _plan takes the two-slot plan (a balanced split, at the cost of a second epilogue) where a whole-CTA plan, b uniform +# requests x floor(n_ctas / b) CTAs each, keeps fewer than this share of the CTAs busy. +_TWO_SLOT_MAX_BUSY_SHARE = 0.765 + + +def ld_red_max_supported(device: torch.device) -> bool: + """Whether the partial kernel's softmax_v2 runs on device: it takes row maxima with tcgen05.ld.red.max (LDTM.STAT), + behind the shared tcgen05 gate.""" + from ..prims_ts.kernels.tcgen05_compat import ldtm_stat_supported + + return ldtm_stat_supported(torch.cuda.get_device_capability(device)) + + +def _plan(b: int, n_ctas: int) -> str: + """The kernel plan for a batch of b requests: "lane" up to 32, "wide" up to 64, "two" above 64 and where a + whole-CTA plan would keep under _TWO_SLOT_MAX_BUSY_SHARE of the CTAs busy with uniform requests.""" + if b > _WIDE_PLAN_MAX_BATCH: + return "two" + if b * (n_ctas // b) < _TWO_SLOT_MAX_BUSY_SHARE * n_ctas: + return "two" + return "wide" if b > _LANE_PLAN_MAX_BATCH else "lane" + + def kv_replica_fused_supported( q_len: int, cp_size: int, hq: int, batch: int, sm_count: int ) -> bool: @@ -89,18 +112,26 @@ def kv_replica_fused_supported( class KvReplicaFusedState: - """Grid-barrier counters and partial workspace of the kernel on one device, for batches up to ``max_batch``. + """Grid-barrier counters, partial workspace and kernel choices on one device, for batches up to ``max_batch``. Shared by every layer, like the attention workspace: the layers' calls are ordered on one stream. counters: int64 [max_batch + 1, max_batch], row b serves batch size b; zero-initialized once, never reset. """ + plans: Tuple[Optional[str], ...] = () + softmax_v2: bool = False + def __init__(self, device: torch.device, sm_count: int, max_batch: int): self.sm_count = sm_count self.max_batch = max_batch - need = cp_partial_balanced_ws_bytes( - MAX_ROWS, _num_ctas(sm_count), 2 if max_batch > _WIDE_PLAN_MAX_BATCH else 1 + n_ctas = _num_ctas(sm_count) + # plans[b]: the kernel plan of a batch of b requests (_plan; b < n_ctas). + self.plans = (None,) + tuple( + _plan(b, n_ctas) for b in range(1, min(max_batch, n_ctas - 1) + 1) ) + self.softmax_v2 = ld_red_max_supported(device) + two = "two" in self.plans + need = cp_partial_balanced_ws_bytes(MAX_ROWS, n_ctas, 2 if two else 1) self.workspace = torch.empty(need // 4 + 64, dtype=torch.float32, device=device) self.counters = torch.zeros(max_batch + 1, max_batch, dtype=torch.int64, device=device) @@ -141,6 +172,9 @@ def _compiled( o_vec16: bool, use_pdl: bool, plan: str, + ll_slot_words: int = 0, + ll_lse_base: int = 0, + softmax_v2: bool = False, ): import cuda.bindings.driver as cuda import cutlass @@ -162,6 +196,10 @@ def _compiled( p_shift=_P_SHIFT, wide_plan=plan == "wide", two_slot=plan == "two", + ll_push=ll_slot_words > 0, + ll_slot_words=ll_slot_words, + ll_lse_base=ll_lse_base, + softmax_v2=softmax_v2, ) assert kernel.ws_bytes == cp_partial_balanced_ws_bytes( q_len * gh, n_ctas, 2 if plan == "two" else 1 @@ -201,7 +239,11 @@ def _compiled( gmem_ptr(f32, cutlass.Float32, a["ws"]), gmem_ptr(i64, cutlass.Int64, a["cnt"]), I32(1), + gmem_ptr(i64, cutlass.Int64, 8), + gmem_ptr(i32, I32, 4), + I32(0), stream, + **({"options": kernel.compile_options} if kernel.compile_options else {}), ) @@ -219,6 +261,7 @@ def kv_replica_fused_partial( out_lse: torch.Tensor, state: KvReplicaFusedState, enable_pdl: bool = False, + ll: Optional[tuple] = None, ) -> None: """This CP rank's partial attention of every group head over the pages it owns (contract: the unit test's kv_replica_fused_partial_ref). @@ -267,10 +310,10 @@ def kv_replica_fused_partial( ) assert tuple(out_lse.shape) == (cp, rows, hq) and out_lse.dtype == torch.float32 assert 1 <= b <= state.max_batch - plan = "two" if b > _WIDE_PLAN_MAX_BATCH else ("wide" if b > _LANE_PLAN_MAX_BATCH else "lane") - slots = 2 if plan == "two" else 1 n_ctas = _num_ctas(state.sm_count) assert b < n_ctas, "more CTAs than requests, every CTA co-resident (one per SM)" + plan = state.plans[b] + slots = 2 if plan == "two" else 1 cnt = state.counters ws = state.workspace assert ws.numel() * 4 >= cp_partial_balanced_ws_bytes(R, n_ctas, slots), ( @@ -301,11 +344,32 @@ def kv_replica_fused_partial( ) if plan != "lane": logger.info_once( - f"KV-replica split fused partial attention: {plan} plan above {_LANE_PLAN_MAX_BATCH} requests " - f"(first call: batch {b}, q_len {q_len})", + f"KV-replica split fused partial attention: {plan} plan (first call: batch {b}, q_len {q_len})", key=f"kv_replica_fused_{plan}", ) - fn = _compiled(q_len, gh, hq, cp, n_ctas, b1_ptr, b2_ptr, o_vec16, bool(enable_pdl), plan) + # ll = (peer table [G] int64, row epochs int32, member index, slot words, LSE base) of the merge channel + # (TPGroupExchange.merge_push_args): the combine pushes its rows to the members instead of out_o / out_lse + if ll is not None: + ll_peers, ll_state, ll_grank, ll_slot_words, ll_lse_base = ll + assert ll_peers.dtype == torch.int64 and ll_peers.numel() == cp and ll_grank == cp_rank + assert ll_state.dtype == torch.int32 and ll_state.numel() >= rows * hq + else: + ll_peers, ll_state, ll_grank, ll_slot_words, ll_lse_base = cnt, cnt, 0, 0, 0 + fn = _compiled( + q_len, + gh, + hq, + cp, + n_ctas, + b1_ptr, + b2_ptr, + o_vec16, + bool(enable_pdl), + plan, + ll_slot_words, + ll_lse_base, + state.softmax_v2, + ) fp8 = cutlass.Float8E4M3FN f32 = cutlass.Float32 I32 = cutlass.Int32 @@ -336,5 +400,8 @@ def kv_replica_fused_partial( gmem_ptr(ws, f32, a["ws"]), gmem_ptr(cnt[b], cutlass.Int64, a["cnt"]), I32(b), + gmem_ptr(ll_peers, cutlass.Int64, 8), + gmem_ptr(ll_state, I32, 4), + I32(ll_grank), stream, ) diff --git a/tensorrt_llm/_torch/attention/backends/fmha/gqa_segmented_decode.py b/tensorrt_llm/_torch/attention/backends/fmha/gqa_segmented_decode.py index 55ad6b606517..6a26a3f9fa1f 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/gqa_segmented_decode.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/gqa_segmented_decode.py @@ -31,7 +31,7 @@ from tensorrt_llm._torch.flashinfer_utils import IS_FLASHINFER_AVAILABLE from ....modules.fla.op import gdc_wait_with_memory_clobber -from .flashinfer_trtllm_gen import _get_bmm1_scale_log2 +from .flashinfer_trtllm_gen import trtllm_gen_paged_decode if IS_FLASHINFER_AVAILABLE: import flashinfer @@ -310,6 +310,12 @@ def _seg_merge_kernel( tl.extra.cuda.gdc_launch_dependents() +def load_trtllm_gen_decode_module() -> None: + """Load FlashInfer's trtllm-gen decode module, which segment_attention and the trtllm-gen decode call; FlashInfer + JIT-builds it on first use.""" + flashinfer.decode.get_trtllm_gen_fmha_module() + + def segment_attention( seg_q: torch.Tensor, kv_pool: torch.Tensor, @@ -325,9 +331,9 @@ def segment_attention( ) -> None: """trtllm-gen decode of every segment as a one-token request of seg_q's folded heads, with its base-2 LSE. - Calls FlashInfer's trtllm-gen decode op directly (the op behind ``trtllm_batch_decode_with_kv_cache``), skipping - the public wrapper's per-call argument validation. Launched without PDL: the FMHA may read the segment tables / - lengths, which the kernel right before it writes, before its dependency wait. + Calls FlashInfer's trtllm-gen decode op directly (trtllm_gen_paged_decode), skipping the public wrapper's per-call + argument validation. Launched without PDL: the FMHA may read the segment tables / lengths, which the kernel right + before it writes, before its dependency wait. Args: workspace: the trtllm-gen decode's FMHA workspace plus segment_attention_softmax_bytes(*seg_q.shape[:2]) @@ -338,43 +344,23 @@ def segment_attention( assert counter.numel() * counter.element_size() >= 4 * max( num_requests * num_heads, sm_count ), "multi-CTA counter buffer too small for the segment attention call" - flashinfer.decode.get_trtllm_gen_fmha_module().trtllm_paged_attention_decode( + trtllm_gen_paged_decode( seg_out, - None, # out_scale_factor seg_q, kv_pool, - kv_pool, workspace, counter, seg_table, seg_lens, _SEGMENT_MAX_Q_LEN, # max_q_len max_seg_len, - _get_bmm1_scale_log2(bmm1_scale) if isinstance(bmm1_scale, torch.Tensor) else bmm1_scale, + bmm1_scale, bmm2_scale, - -1.0, # o_sf_scale - -1, # o_sf_vec_size - 0, # o_sf_start_index num_requests, -1, # window_left - 0, # sparse_mla_top_k sm_count, False, # enable_pdl - workspace.numel() * workspace.element_size(), - None, # sinks - None, # cum_seq_lens_q - None, # k_block_scales - None, # v_block_scales - None, # skip_softmax_threshold_scale_factor - False, # uses_shared_paged_kv_idx - seg_lse, - 1.0, # lse_scale - seg_lse.stride(0), - seg_lse.stride(1), - False, # enable_block_sparse_attention - None, # sparse_mla_top_k_lens - 0, # bf16q_fp8kv_transform_mode (FP8 query) - None, # use_fp16_softmax + lse=seg_lse, ) diff --git a/tensorrt_llm/_torch/attention/backends/fmha/manager.py b/tensorrt_llm/_torch/attention/backends/fmha/manager.py index 7dfa76a803be..eeac0a3caf55 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/manager.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/manager.py @@ -317,7 +317,12 @@ def generation_selection_cell( num_tokens = q.shape[0] if forward_args.attention_input_type == AttentionInputType.mixed: num_tokens -= metadata.num_ctx_tokens - q_len = num_tokens // num_generations + return generation_cell_bound(num_generations, num_tokens // num_generations) + + +def generation_cell_bound(num_generations: int, q_len: int) -> tuple[int, int]: + """(generation requests, q_len) at the upper bound of their selection-cache cell (``generation_selection_cell``): + a decision made for the call's own sizes must evaluate a library's support here to agree with its selection.""" return ( max( num_generations, diff --git a/tensorrt_llm/_torch/attention/backends/interface.py b/tensorrt_llm/_torch/attention/backends/interface.py index a89dd3e49ce0..b7898890af30 100644 --- a/tensorrt_llm/_torch/attention/backends/interface.py +++ b/tensorrt_llm/_torch/attention/backends/interface.py @@ -1136,6 +1136,11 @@ class AttentionForwardArgs: # the output sets output_gate_applied, and the caller applies the gate otherwise. output_gate: Optional[torch.Tensor] = None output_gate_applied: bool = False + # o_proj's static FP8 input scale offered together with output_gate: an FMHA library that applies the gate may + # also write the gated output as E4M3 at this scale, byte for byte as o_proj's own static quant would, into + # output_fp8 [num_tokens, num_heads * head_dim]; the caller then passes output_fp8 to o_proj (output unwritten). + gated_out_scale: Optional[torch.Tensor] = None + output_fp8: Optional[torch.Tensor] = None # Paged FP8 query / K / V the caller already wrote for this generation-only call (fmha/gqa_decode.py). kv_append: Optional["KvAppendPlan"] = None # Optional normalized diffusion timestep for timestep-varying sparse attention. diff --git a/tensorrt_llm/_torch/attention/backends/trtllm.py b/tensorrt_llm/_torch/attention/backends/trtllm.py index a9695c03f157..fd901414d475 100644 --- a/tensorrt_llm/_torch/attention/backends/trtllm.py +++ b/tensorrt_llm/_torch/attention/backends/trtllm.py @@ -2147,6 +2147,12 @@ class TrtllmAttention(AttentionBackend[TrtllmAttentionMetadata]): cache_context_plan: bool = False # FMHA library classes this instance tries before the registry's libraries. prepended_fmha_lib_classes: tuple = () + # Head dimension per K/V stage of FlashInferTrtllmGenFmha's FP8 paged causal context attention, run through + # trtllm::fmha_paged_context_fp8; 0 keeps FlashInfer's kernel. + context_fmha_head_dim_per_stage_kv: int = 0 + # In a context-only step, FlashInferTrtllmGenFmha computes only each request's last output row (the others are + # zero); every row's K / V is still written. + context_last_rows_only: bool = False # Layer state the native attention op reads through FmhaParams.attn. The # generator (scripts/generate_fmha_params.py) collects these annotations; @@ -2191,6 +2197,8 @@ def __init__( skip_correction_threshold: float = 0.0, gqa_decode: Optional["GqaDecodeSetup"] = None, cache_context_plan: bool = False, + context_fmha_head_dim_per_stage_kv: int = 0, + context_last_rows_only: bool = False, **kwargs, ) -> None: """ @@ -2220,6 +2228,8 @@ def __init__( cache_context_plan (bool): Plan a context-only forward once for the layers that share its metadata and run the trtllm-gen context kernel from that plan (dense, non-sparse layers only). + context_fmha_head_dim_per_stage_kv (int): See the class attribute. + context_last_rows_only (bool): See the class attribute. """ super().__init__(layer_idx, num_heads, head_dim, num_kv_heads, quant_config, **kwargs) @@ -2293,6 +2303,15 @@ def __init__( self.local_layer_idx: Optional[int] = None self._fmha_manager: Optional[FmhaManager] = None self.gqa_decode = gqa_decode + if context_fmha_head_dim_per_stage_kv < 0 or ( + context_fmha_head_dim_per_stage_kv > 0 + and head_dim % context_fmha_head_dim_per_stage_kv != 0): + raise ValueError( + f"context_fmha_head_dim_per_stage_kv=" + f"{context_fmha_head_dim_per_stage_kv} must be 0 or divide " + f"head_dim={head_dim}.") + self.context_fmha_head_dim_per_stage_kv = context_fmha_head_dim_per_stage_kv + self.context_last_rows_only = context_last_rows_only # A GQA decode library of this layer, which plans the module's KV append and deferred prologue (set with # the FMHA manager). self.gqa_decode_fmha: Optional["GqaDecodeFmha"] = None diff --git a/tensorrt_llm/_torch/attention/backends/utils.py b/tensorrt_llm/_torch/attention/backends/utils.py index 55aee8575f66..84ea0bb0254a 100644 --- a/tensorrt_llm/_torch/attention/backends/utils.py +++ b/tensorrt_llm/_torch/attention/backends/utils.py @@ -87,6 +87,8 @@ def create_attention( skip_correction_threshold: float = 0.0, gqa_decode: Optional["GqaDecodeSetup"] = None, cache_context_plan: bool = False, + context_fmha_head_dim_per_stage_kv: int = 0, + context_last_rows_only: bool = False, ) -> AttentionBackend: if attention_chunk_size is not None and backend_name.upper() != "TRTLLM": raise ValueError( @@ -125,6 +127,8 @@ def create_attention( skip_correction_threshold=skip_correction_threshold, gqa_decode=gqa_decode, cache_context_plan=cache_context_plan, + context_fmha_head_dim_per_stage_kv=context_fmha_head_dim_per_stage_kv, + context_last_rows_only=context_last_rows_only, ) return attn_cls( diff --git a/tensorrt_llm/_torch/attention/kernels/blackwell/gqa_kv_replica_partial_attn.py b/tensorrt_llm/_torch/attention/kernels/blackwell/gqa_kv_replica_partial_attn.py index 473374c14afa..bfca8e8eb5ce 100644 --- a/tensorrt_llm/_torch/attention/kernels/blackwell/gqa_kv_replica_partial_attn.py +++ b/tensorrt_llm/_torch/attention/kernels/blackwell/gqa_kv_replica_partial_attn.py @@ -63,8 +63,8 @@ * combine: CTA j of the request finalizes chunk j; the merge loop is dispatched to a compile-time lanes-per-granule variant. -Two-slot plan (``two_slot``, kernel_two, 65..128 requests): the plans above give every request at least one CTA, so -past ~n_ctas / 2 uniform requests a CTA runs a whole request while others idle. +Two-slot plan (``two_slot``, kernel_two, up to 128 requests; the host takes it from 33): the plans above give every +request at least one CTA, so past ~n_ctas / 2 uniform requests a CTA runs a whole request while others idle. Here T = the smallest tile count with sum_r max(t_r, T) <= n_ctas * T; request r takes the virtual tile range [V_r, V_r + max(t_r, T)) (requests in order) and CTA i the range [i * T, (i + 1) * T), so a CTA computes at most T tiles, of at most two requests (slot 0, then slot 1, through one K / V ring and one O accumulator). Each request keeps @@ -495,6 +495,114 @@ def _st_global_f32(addr, v, *, loc=None, ip=None) -> None: ) +@dsl_user_op +def _ffma2(a0, a1, b0, b1, c0, c1, *, loc=None, ip=None): + """(a0 * b0 + c0, a1 * b1 + c1) as one fma.rn.f32x2 (each lane IEEE fma.rn.f32: bitwise as two FFMA).""" + out = _asm( + llvm.StructType.get_literal([T.f32(), T.f32()]), + [Float32(v).ir_value(loc=loc, ip=ip) for v in (a0, a1, b0, b1, c0, c1)], + "{\n\t.reg .b64 a, b, c, d;\n\tmov.b64 a, {$2, $3};\n\tmov.b64 b, {$4, $5};\n\t" + "mov.b64 c, {$6, $7};\n\tfma.rn.f32x2 d, a, b, c;\n\tmov.b64 {$0, $1}, d;\n\t}\n", + "=f,=f,f,f,f,f,f,f", + False, + loc, + ip, + ) + return tuple(Float32(llvm.extractvalue(T.f32(), out, [i], loc=loc, ip=ip)) for i in range(2)) + + +@dsl_user_op +def _fadd2(a0, a1, b0, b1, *, loc=None, ip=None): + """(a0 + b0, a1 + b1) as one add.rn.f32x2 (bitwise as two add.rn.f32).""" + out = _asm( + llvm.StructType.get_literal([T.f32(), T.f32()]), + [Float32(v).ir_value(loc=loc, ip=ip) for v in (a0, a1, b0, b1)], + "{\n\t.reg .b64 a, b, d;\n\tmov.b64 a, {$2, $3};\n\tmov.b64 b, {$4, $5};\n\t" + "add.rn.f32x2 d, a, b;\n\tmov.b64 {$0, $1}, d;\n\t}\n", + "=f,=f,f,f,f,f", + False, + loc, + ip, + ) + return tuple(Float32(llvm.extractvalue(T.f32(), out, [i], loc=loc, ip=ip)) for i in range(2)) + + +def _ld_red_max_ptx() -> str: + """4 x tcgen05.ld.red.max (LDTM.STAT, SM103) of 32 FP32 columns each from $1, $1 + 32, $1 + 64, $1 + 96 (this + warp's 32 lanes), one wait, $0 = the max over the 128 columns. The loaded values stay in asm-local registers.""" + regs = lambda k: ", ".join(f"v{k * 32 + j}" for j in range(32)) # noqa: E731 + body = "{\n\t.reg .f32 v<128>;\n\t.reg .f32 m<4>;\n\t.reg .b32 a<4>;\n\tmov.b32 a0, $1;\n\t" + body += "add.u32 a1, $1, 32;\n\tadd.u32 a2, $1, 64;\n\tadd.u32 a3, $1, 96;\n\t" + for k in range(4): + body += f"tcgen05.ld.red.sync.aligned.32x32b.x32.f32.max {{{regs(k)}}}, m{k}, [a{k}];\n\t" + body += "tcgen05.wait::ld.sync.aligned;\n\tmax.f32 m0, m0, m1;\n\tmax.f32 m2, m2, m3;\n\tmax.f32 $0, m0, m2;\n\t}\n" + return body + + +@dsl_user_op +def _tmem_row_max128(taddr, *, loc=None, ip=None) -> Float32: + """Max of this thread's row over 128 consecutive FP32 TMEM columns at taddr (lane field = the warp's lane base), + by LDTM.STAT; waits for the loads itself.""" + return Float32( + _asm( + T.f32(), + [Int32(taddr).ir_value(loc=loc, ip=ip)], + _ld_red_max_ptx(), + "=f,r", + True, + loc, + ip, + ) + ) + + +@dsl_user_op +def _ld_shared_u32(addr, *, loc=None, ip=None) -> Int32: + return Int32( + _asm( + T.i32(), + [Int32(addr).ir_value(loc=loc, ip=ip)], + "ld.shared.b32 $0, [$1];", + "=r,r", + True, + loc, + ip, + ) + ) + + +@dsl_user_op +def _lamport_word(word, *, loc=None, ip=None) -> Uint32: + """A Lamport word (ll_exchange.py): the word, or 0x7FFFFFFF in place of the empty marker 0xFFFFFFFF (NaN data + only; still NaN).""" + return Uint32( + _asm( + T.i32(), + [Uint32(word).ir_value(loc=loc, ip=ip)], + "{ .reg .pred p; setp.eq.u32 p, $1, 0xFFFFFFFF; selp.b32 $0, 0x7FFFFFFF, $1, p; }", + "=r,r", + False, + loc, + ip, + ) + ) + + +@dsl_user_op +def _f32_bits(x, *, loc=None, ip=None) -> Uint32: + return Uint32( + _asm( + T.i32(), + [Float32(x).ir_value(loc=loc, ip=ip)], + "mov.b32 $0, $1;", + "=r,f", + False, + loc, + ip, + ) + ) + + @dsl_user_op def _griddep_wait(*, loc=None, ip=None) -> None: _asm(None, [], "griddepcontrol.wait;", "~{memory}", True, loc, ip) @@ -609,9 +717,25 @@ def __init__( p_shift: float = 5.0, wide_plan: bool = False, two_slot: bool = False, + ll_push: bool = False, + ll_slot_words: int = 0, + ll_lse_base: int = 0, + softmax_v2: bool = False, ): + """ll_push: the combine stores each finalized (O, LSE) row as Lamport words straight into the owning + member's alltoall_merge receive slot (ll_exchange.py: TPGroupExchange.merge_push_args; slot geometry + ll_slot_words / ll_lse_base, one epoch per row position), instead of out_o / out_lse; the merge then only polls. + softmax_v2 (SM103's tcgen05.ld.red.max): unmasked tiles take the row max from TMEM and exponentiate per + 32-column chunk reloaded from TMEM with FFMA2 / FADD2; same arithmetic and order, bitwise as the default.""" assert gh == cp_size * hql, "group heads = cp_size x q heads per rank" assert not (wide_plan and two_slot), "one plan variant" + self.softmax_v2 = bool(softmax_v2) + # cute.compile options: softmax_v2 builds with ptxas -O1, which keeps its MUFU.EX2 issues back to back. + self.compile_options = "--ptxas-options -O1" if self.softmax_v2 else None + self.ll_push = bool(ll_push) + self.ll_slot_words = int(ll_slot_words) + self.ll_lse_base = int(ll_lse_base) + assert not self.ll_push or 0 < self.ll_lse_base < self.ll_slot_words self.wide_plan = bool(wide_plan) self.two_slot = bool(two_slot) self.q_len = q_len @@ -672,6 +796,9 @@ def __call__( ws_ptr: cute.Pointer, cnt_ptr: cute.Pointer, batch: Int32, + ll_peers_ptr: cute.Pointer, + ll_state_ptr: cute.Pointer, + ll_grank: Int32, stream, ): R = self.rows @@ -701,6 +828,9 @@ def __call__( mLse = cute.make_tensor(lse_ptr, cute.make_layout((1,))) mWs = cute.make_tensor(ws_ptr, cute.make_layout((1,))) mCnt = cute.make_tensor(cnt_ptr, cute.make_layout((8,))) # grid-barrier epoch per request + # ll_push: every member's receive region of the merge channel (G <= 8) and this member's row epochs + mPeers = cute.make_tensor(ll_peers_ptr, cute.make_layout((8,))) + mLLState = cute.make_tensor(ll_state_ptr, cute.make_layout((1 << 20,))) mma_qk = sm100_utils.make_trivial_tiled_mma( FP8, @@ -785,6 +915,9 @@ def __call__( l_sh, mWs, mCnt, + mPeers, + mLLState, + ll_grank, sQ_l, sK_l, sV_l, @@ -827,6 +960,9 @@ def __call__( l_sh, mWs, mCnt, + mPeers, + mLLState, + ll_grank, sQ_l, sK_l, sV_l, @@ -970,40 +1106,52 @@ def _softmax_tile( scale, apply_mask: cutlass.Constexpr, i_loc=None, + s_taddr=None, ): """Softmax of tile i (CTA-local) for row st (TMEM lane st): S -> x, mask (apply_mask: keys of slot 0 / 1 visible iff key < cnt_a / cnt_b), lazy rescale of (m, l, O row), P -> SMEM as E4M3. stt = [m_ref, l_acc]. The O rescale of a lazy-rescale tile runs after P(i) is in SMEM (by then GEMM2(i - 1) has normally completed, and the S registers are free for 64-column TMEM round trips), before P(i) is released to GEMM2(i). - i_loc (kernel_two): the tile's index in its request (O holds nothing of the request before i_loc 1).""" + i_loc (kernel_two): the tile's index in its request (O holds nothing of the request before i_loc 1). + s_taddr (softmax_v2): this warp's TMEM address of S buffer 0 (lane base in bits 16+).""" s_full, s_empty, p_full, p_empty, o_done = bars_sm il = i if i_loc is None else i_loc sb = i % 2 + V2: cutlass.Constexpr = self.softmax_v2 and not apply_mask cute.arch.mbarrier_wait(s_full + sb, (i // 2) & 1) accS = tStS[(None, None), 0, 0, sb] - for c in cutlass.range_constexpr(4): - cute.copy(t2r, thr_ld.partition_S(cute.local_tile(accS, (M_ROWS, 32), (0, c))), xs[c]) - cute.arch.fence_view_async_tmem_load() - cute.arch.mbarrier_arrive(s_empty + sb) - # Mask (tiles with the new tokens, the request tail or a duplicate second slot; straight-line) - if const_expr(apply_mask): + mraw = Float32(0.0) + if const_expr(V2): + mraw = _tmem_row_max128( + s_taddr + sb * TILE_KEYS + ) # LDTM.STAT, waits itself; S stays in TMEM + else: for c in cutlass.range_constexpr(4): - for v in cutlass.range_constexpr(32): - if const_expr(32 * c + v < PAGE): - xs[c][v] = _keep_lt(xs[c][v], 32 * c + v, cnt_a) - else: - xs[c][v] = _keep_lt(xs[c][v], 32 * c + v - PAGE, cnt_b) - # Row max of the raw scores (scale > 0) - m0 = xs[0][0] - m1 = xs[1][0] - m2 = xs[2][0] - m3 = xs[3][0] - for v in cutlass.range_constexpr(1, 32): - m0 = cute.arch.fmax(m0, xs[0][v]) - m1 = cute.arch.fmax(m1, xs[1][v]) - m2 = cute.arch.fmax(m2, xs[2][v]) - m3 = cute.arch.fmax(m3, xs[3][v]) - mx = cute.arch.fmax(cute.arch.fmax(m0, m1), cute.arch.fmax(m2, m3)) * scale + cute.copy( + t2r, thr_ld.partition_S(cute.local_tile(accS, (M_ROWS, 32), (0, c))), xs[c] + ) + cute.arch.fence_view_async_tmem_load() + cute.arch.mbarrier_arrive(s_empty + sb) + # Mask (tiles with the new tokens, the request tail or a duplicate second slot; straight-line) + if const_expr(apply_mask): + for c in cutlass.range_constexpr(4): + for v in cutlass.range_constexpr(32): + if const_expr(32 * c + v < PAGE): + xs[c][v] = _keep_lt(xs[c][v], 32 * c + v, cnt_a) + else: + xs[c][v] = _keep_lt(xs[c][v], 32 * c + v - PAGE, cnt_b) + # Row max of the raw scores (scale > 0) + m0 = xs[0][0] + m1 = xs[1][0] + m2 = xs[2][0] + m3 = xs[3][0] + for v in cutlass.range_constexpr(1, 32): + m0 = cute.arch.fmax(m0, xs[0][v]) + m1 = cute.arch.fmax(m1, xs[1][v]) + m2 = cute.arch.fmax(m2, xs[2][v]) + m3 = cute.arch.fmax(m3, xs[3][v]) + mraw = cute.arch.fmax(cute.arch.fmax(m0, m1), cute.arch.fmax(m2, m3)) + mx = mraw * scale m_ref = stt[0] need = Int32(0) if mx > m_ref + self.rescale_threshold: @@ -1031,17 +1179,44 @@ def _softmax_tile( lc = Float32(0.0) ld = Float32(0.0) pw = cute.make_rmem_tensor((32,), Uint32) - for c in cutlass.range_constexpr(4): - for q4 in cutlass.range_constexpr(8): - p0 = _ex2(_fma(xs[c][4 * q4], scale, neg_m)) - p1 = _ex2(_fma(xs[c][4 * q4 + 1], scale, neg_m)) - p2 = _ex2(_fma(xs[c][4 * q4 + 2], scale, neg_m)) - p3 = _ex2(_fma(xs[c][4 * q4 + 3], scale, neg_m)) - la = la + p0 - lb = lb + p1 - lc = lc + p2 - ld = ld + p3 - pw[8 * c + q4] = _pack_e4m3x4(p0, p1, p2, p3) + if const_expr(V2): + # v2: S chunk c + 1 loads from TMEM while chunk c is exponentiated (xs[0] / xs[1] alternate); FFMA2 / + # FADD2 keep v1's per-element arithmetic and each accumulator's order, so P and l are bitwise as v1. + cute.copy(t2r, thr_ld.partition_S(cute.local_tile(accS, (M_ROWS, 32), (0, 0))), xs[0]) + cute.arch.fence_view_async_tmem_load() + for c in cutlass.range_constexpr(4): + xb = xs[c % 2] + if const_expr(c + 1 < 4): + cute.copy( + t2r, + thr_ld.partition_S(cute.local_tile(accS, (M_ROWS, 32), (0, c + 1))), + xs[(c + 1) % 2], + ) + for q4 in cutlass.range_constexpr(8): + a01 = _ffma2(xb[4 * q4], xb[4 * q4 + 1], scale, scale, neg_m, neg_m) + a23 = _ffma2(xb[4 * q4 + 2], xb[4 * q4 + 3], scale, scale, neg_m, neg_m) + p0 = _ex2(a01[0]) + p1 = _ex2(a01[1]) + p2 = _ex2(a23[0]) + p3 = _ex2(a23[1]) + la, lb = _fadd2(la, lb, p0, p1) + lc, ld = _fadd2(lc, ld, p2, p3) + pw[8 * c + q4] = _pack_e4m3x4(p0, p1, p2, p3) + if const_expr(c + 1 < 4): + cute.arch.fence_view_async_tmem_load() + cute.arch.mbarrier_arrive(s_empty + sb) # every read of this S buffer is done + else: + for c in cutlass.range_constexpr(4): + for q4 in cutlass.range_constexpr(8): + p0 = _ex2(_fma(xs[c][4 * q4], scale, neg_m)) + p1 = _ex2(_fma(xs[c][4 * q4 + 1], scale, neg_m)) + p2 = _ex2(_fma(xs[c][4 * q4 + 2], scale, neg_m)) + p3 = _ex2(_fma(xs[c][4 * q4 + 3], scale, neg_m)) + la = la + p0 + lb = lb + p1 + lc = lc + p2 + ld = ld + p3 + pw[8 * c + q4] = _pack_e4m3x4(p0, p1, p2, p3) stt[1] = stt[1] + ((la + lb) + (lc + ld)) pb = i % 2 cute.arch.mbarrier_wait(p_empty + pb, ((i // 2) & 1) ^ 1) @@ -1439,6 +1614,9 @@ def _combine( l_st: Int32, l_sh: Int32, sScal: cute.Tensor, + mPeers: cute.Tensor, + mLLState: cute.Tensor, + ll_grank: Int32, comb_phase=0, ): """CTA ``split`` of the request's ``c_req`` CTAs finalizes elements [o_lo, o_hi) of the request with the @@ -1499,6 +1677,9 @@ def _combine( l_st, l_sh, sScal, + mPeers, + mLLState, + ll_grank, ) if lg_gps == 0: self._merge(1, *args) @@ -1540,6 +1721,9 @@ def _merge( l_st: Int32, l_sh: Int32, sScal: cute.Tensor, + mPeers: cute.Tensor, + mLLState: cute.Tensor, + ll_grank: Int32, ): """Granule merge of the combine for ``lanes`` (compile time) lanes per granule.""" gps: cutlass.Constexpr = ( @@ -1614,35 +1798,88 @@ def _merge( w1 = _pack_bf16x2(a2 * scl, a3 * scl) w2 = _pack_bf16x2(a4 * scl, a5 * scl) w3 = _pack_bf16x2(a6 * scl, a7 * scl) - if const_expr(self.o_vec16): - _st_global_v4_u32(addr, w0, w1, w2, w3) - else: - _st_global_u32(addr, w0) - _st_global_u32(addr + 4, w1) - _st_global_u32(addr + 8, w2) - _st_global_u32(addr + 12, w3) - if e0 % HEAD_DIM == 0: - lse_out = -Float32.inf - if den > Float32(0.0): - lse_out = mrow + _lg2(den) - _st_global_f32( - l_base + (dd * l_sd + tok * l_st + hh * l_sh) * 4, lse_out + lse_out = -Float32.inf + if den > Float32(0.0): + lse_out = mrow + _lg2(den) + if const_expr(self.ll_push): + self._ll_store( + mPeers, mLLState, ll_grank, dd, tok, hh, e0, w0, w1, w2, w3, lse_out ) + else: + if const_expr(self.o_vec16): + _st_global_v4_u32(addr, w0, w1, w2, w3) + else: + _st_global_u32(addr, w0) + _st_global_u32(addr + 4, w1) + _st_global_u32(addr + 8, w2) + _st_global_u32(addr + 12, w3) + if e0 % HEAD_DIM == 0: + _st_global_f32( + l_base + (dd * l_sd + tok * l_st + hh * l_sh) * 4, lse_out + ) else: # this rank sees no key of the request: O = 0, LSE = -inf if jg == 0: if g < n_gran: - if const_expr(self.o_vec16): - _st_global_v4_u32(addr, Uint32(0), Uint32(0), Uint32(0), Uint32(0)) - else: - _st_global_u32(addr, Uint32(0)) - _st_global_u32(addr + 4, Uint32(0)) - _st_global_u32(addr + 8, Uint32(0)) - _st_global_u32(addr + 12, Uint32(0)) - if e0 % HEAD_DIM == 0: - _st_global_f32( - l_base + (dd * l_sd + tok * l_st + hh * l_sh) * 4, -Float32.inf + if const_expr(self.ll_push): + self._ll_store( + mPeers, + mLLState, + ll_grank, + dd, + tok, + hh, + e0, + Uint32(0), + Uint32(0), + Uint32(0), + Uint32(0), + -Float32.inf, ) + else: + if const_expr(self.o_vec16): + _st_global_v4_u32(addr, Uint32(0), Uint32(0), Uint32(0), Uint32(0)) + else: + _st_global_u32(addr, Uint32(0)) + _st_global_u32(addr + 4, Uint32(0)) + _st_global_u32(addr + 8, Uint32(0)) + _st_global_u32(addr + 12, Uint32(0)) + if e0 % HEAD_DIM == 0: + _st_global_f32( + l_base + (dd * l_sd + tok * l_st + hh * l_sh) * 4, -Float32.inf + ) + + @cute.jit + def _ll_store( + self, + mPeers: cute.Tensor, + mLLState: cute.Tensor, + ll_grank: Int32, + dd: Int32, + tok: Int32, + hh: Int32, + e0: Int32, + w0: Uint32, + w1: Uint32, + w2: Uint32, + w3: Uint32, + lse: Float32, + ): + """ll_push: one granule's 4 O words (and, at d = 0, the row's LSE) into member dd's merge slot, the layout + alltoall_merge's push writes: row position r = tok * hql + hh (one partial per member), epoch mLLState[r], + slot half epoch & 1, this member's source slot ll_grank; O words at r * D/2, LSE at ll_lse_base + r. The + Lamport words are 4-byte words of 16-byte stores (each lands whole), so the poller needs no fence.""" + r = tok * self.hql + hh + ep = mLLState[r] + half = Int64(ep & 1) * Int64(self.cp * self.ll_slot_words) + base = mPeers[dd] + (half + Int64(ll_grank) * Int64(self.ll_slot_words)) * 4 + o_addr = base + (Int64(r) * Int64(HEAD_DIM // 2) + Int64((e0 % HEAD_DIM) // 2)) * 4 + lse_addr = base + (Int64(self.ll_lse_base) + Int64(r)) * 4 + _st_global_v4_u32( + o_addr, _lamport_word(w0), _lamport_word(w1), _lamport_word(w2), _lamport_word(w3) + ) + if e0 % HEAD_DIM == 0: + _st_global_u32(lse_addr, _lamport_word(_f32_bits(lse))) @cute.kernel def kernel( @@ -1672,6 +1909,9 @@ def kernel( l_sh: Int32, mWs: cute.Tensor, mCnt: cute.Tensor, + mPeers: cute.Tensor, + mLLState: cute.Tensor, + ll_grank: Int32, sQ_l: cute.ComposedLayout, sK_l: cute.ComposedLayout, sV_l: cute.ComposedLayout, @@ -1885,7 +2125,16 @@ def kernel( tcgen05.commit(empty_k + s) if i >= 1: mma_pv = self._gemm2( - i - 1, mma_pv, tOtO, tCrP, tCrV, full_v, p_full, empty_v, p_empty, o_done + i - 1, + mma_pv, + tOtO, + tCrP, + tCrV, + full_v, + p_full, + empty_v, + p_empty, + o_done, ) with cute.arch.elect_one(): tcgen05.commit(o_full) @@ -1921,6 +2170,10 @@ def kernel( x2 = cute.make_rmem_tensor_like(frag, Float32) x3 = cute.make_rmem_tensor_like(frag, Float32) xs = (x0, x1, x2, x3) + s_taddr = Int32(0) + if const_expr(self.softmax_v2): + # this warp's TMEM address of S buffer 0: allocated base + lane base (32 lanes per warp) + s_taddr = _ld_shared_u32(tmem_holder.toint()) + sw * (32 << 16) stt = cute.make_rmem_tensor((2,), Float32) stt[0] = -Float32.inf stt[1] = Float32(0.0) @@ -1963,6 +2216,7 @@ def kernel( cnt_b, scale, True, + s_taddr=s_taddr, ) else: self._softmax_tile( @@ -1986,6 +2240,7 @@ def kernel( cnt_b, scale, False, + s_taddr=s_taddr, ) if n_t > 0: # Normalized FP16 partial row -> staging (the K / V rings are free once o_full fired) @@ -2108,6 +2363,9 @@ def kernel( l_st, l_sh, sScal, + mPeers, + mLLState, + ll_grank, ) # Release the dependents: after a CTA barrier that follows the last global store cute.arch.sync_threads() @@ -2147,6 +2405,9 @@ def kernel_two( l_sh: Int32, mWs: cute.Tensor, mCnt: cute.Tensor, + mPeers: cute.Tensor, + mLLState: cute.Tensor, + ll_grank: Int32, sQ_l: cute.ComposedLayout, sK_l: cute.ComposedLayout, sV_l: cute.ComposedLayout, @@ -2451,6 +2712,10 @@ def kernel_two( x2 = cute.make_rmem_tensor_like(frag, Float32) x3 = cute.make_rmem_tensor_like(frag, Float32) xs = (x0, x1, x2, x3) + s_taddr = Int32(0) + if const_expr(self.softmax_v2): + # this warp's TMEM address of S buffer 0: allocated base + lane base (32 lanes per warp) + s_taddr = _ld_shared_u32(tmem_holder.toint()) + sw * (32 << 16) stt = cute.make_rmem_tensor((2,), Float32) bars_sm = (s_full, s_empty, p_full, p_empty, o_done) for k in cutlass.range_constexpr(2): @@ -2508,6 +2773,7 @@ def kernel_two( scale, True, i_loc=i, + s_taddr=s_taddr, ) else: self._softmax_tile( @@ -2532,6 +2798,7 @@ def kernel_two( scale, False, i_loc=i, + s_taddr=s_taddr, ) # ---- normalized FP16 partial row -> the workspace (chunk-major, see _combine) ---- l_tot = stt[1] @@ -2671,6 +2938,9 @@ def kernel_two( l_st, l_sh, sScal, + mPeers, + mLLState, + ll_grank, comb_phase=(Int32(0), cph1)[k], ) # ======================= release the dependents: after a CTA barrier that follows the last global store ===== diff --git a/tensorrt_llm/_torch/attention/kernels/fused_qk_norm_rope_gate.py b/tensorrt_llm/_torch/attention/kernels/fused_qk_norm_rope_gate.py index 07091c568875..becc5d46783e 100644 --- a/tensorrt_llm/_torch/attention/kernels/fused_qk_norm_rope_gate.py +++ b/tensorrt_llm/_torch/attention/kernels/fused_qk_norm_rope_gate.py @@ -24,15 +24,22 @@ """ import functools -from typing import Optional, Tuple +from typing import TYPE_CHECKING, Optional, Tuple import torch import triton import triton.language as tl +import triton.language.extra.libdevice as tldevice +from ...distributed.ll_exchange import ll_pos_gather from ...flashinfer_utils import get_env_enable_pdl from ...modules.fla.op import gdc_wait_with_memory_clobber +if TYPE_CHECKING: + from triton.compiler import CompiledKernel + + from ..backends.fmha.gqa_decode import KvAppendPlan + _MIN_TILED_HEAD_ROWS = 3072 # 384 eight-token CTAs. @@ -65,7 +72,7 @@ def _fused_qkv_gemma_rmsnorm_rope_gate_kernel( mrope_section1: tl.constexpr, mrope_section2: tl.constexpr, block_tokens: tl.constexpr, -): +) -> None: """Normalize and rotate independent rows in a token/head tile. Normalized Q/K round through the output dtype before RoPE, as in the @@ -450,12 +457,14 @@ def fused_qkv_gemma_rmsnorm_rope_gate( @triton.jit -def _fp8_like_cxx(x_bf16_as_f32, scale_bf16_as_f32): +def _fp8_like_cxx(x_bf16_as_f32: tl.tensor, scale_bf16_as_f32: tl.tensor) -> tl.tensor: # mmha::store_8bits_vec for T=bf16: bf16 * bf16 (one rounding), then cvt.rn.satfinite to e4m3. return (x_bf16_as_f32 * scale_bf16_as_f32).to(tl.bfloat16).to(tl.float32).to(tl.float8e4nv) -@triton.jit +# ga_grank is not specialized: every member of the KV group compiles the same kernel, so the residency bound of +# rope_gather_max_tokens (and with it the decision to gather) is the same on every member. +@triton.jit(do_not_specialize=["ga_grank"]) def _qkv_rope_gate_fp8_append_kernel( qkv_ptr, qkv_out_ptr, @@ -483,6 +492,10 @@ def _qkv_rope_gate_fp8_append_kernel( bt_stride_kv, max_pages, host_bmm1_scale, + ga_peers_ptr, + ga_state_ptr, + ga_out_ptr, + ga_grank, q_len: tl.constexpr, page_size: tl.constexpr, num_q_heads: tl.constexpr, @@ -498,9 +511,14 @@ def _qkv_rope_gate_fp8_append_kernel( use_mrope: tl.constexpr, mrope_section1: tl.constexpr, mrope_section2: tl.constexpr, -): - # Same arithmetic as _fused_qkv_gemma_rmsnorm_rope_gate_kernel (kept verbatim); the FP8 outputs are derived - # from the bf16-rounded values it stores. + GATHER: tl.constexpr = False, + GA_G: tl.constexpr = 1, + GA_SLOT_WORDS: tl.constexpr = 1, + PDL: tl.constexpr = False, +) -> None: + # Same arithmetic as _fused_qkv_gemma_rmsnorm_rope_gate_kernel; the FP8 outputs come from its bf16-rounded values. + # GATHER: every q program also all-gathers its FP8 head over the KV group into ga_out (ll_pos_gather). + # PDL: operands no predecessor writes load before griddepcontrol.wait; dependents are released right after it. token = tl.program_id(0).to(tl.int64) head = tl.program_id(1) q_size = num_q_heads * head_dim @@ -508,8 +526,6 @@ def _qkv_rope_gate_fp8_append_kernel( output_dtype = tl.float16 if output_fp16 else tl.bfloat16 scale = tl.load(kv_scale_orig_quant_ptr).to(tl.bfloat16).to(tl.float32) - # Paged destination of this token (used by the K / V programs): position cache_seq_len - q_len + t, as in - # applyBiasRopeUpdateKVCacheV2 for a uniform q_len. req = token // q_len t_in_req = token - req * q_len pos = tl.load(seq_lens_ptr + req).to(tl.int64) - q_len + t_in_req @@ -544,35 +560,23 @@ def _qkv_rope_gate_fp8_append_kernel( head_offsets = tl.arange(0, head_block) head_mask = head_offsets < head_dim - x = tl.load(input_base + head_offsets, mask=head_mask, other=0.0).to(tl.float32) weight = tl.load(weight_ptr + head_offsets, mask=head_mask, other=0.0).to(tl.float32) - inverse_rms = tl.rsqrt(tl.sum(x * x, axis=0) / head_dim + eps) - normalized = (x * inverse_rms * (weight + 1.0)).to(output_dtype).to(tl.float32) - - if has_pass_through: - pass_mask = head_mask & (head_offsets >= rotary_dim) - tl.store(output_base + head_offsets, normalized, mask=pass_mask) - tl.store( - fp8_base + head_offsets, - _fp8_like_cxx(normalized, scale), - mask=pass_mask & fp8_ok, - ) - rotary_offsets = tl.arange(0, rotary_block) rotary_mask = rotary_offsets < half_rotary - x_first = tl.load(input_base + rotary_offsets, mask=rotary_mask, other=0.0).to(tl.float32) - x_second = tl.load( - input_base + half_rotary + rotary_offsets, mask=rotary_mask, other=0.0 - ).to(tl.float32) weight_first = tl.load(weight_ptr + rotary_offsets, mask=rotary_mask, other=0.0).to( tl.float32 ) weight_second = tl.load( weight_ptr + half_rotary + rotary_offsets, mask=rotary_mask, other=0.0 ).to(tl.float32) - x_first = (x_first * inverse_rms * (weight_first + 1.0)).to(output_dtype).to(tl.float32) - x_second = (x_second * inverse_rms * (weight_second + 1.0)).to(output_dtype).to(tl.float32) + if GATHER: + ar_g = tl.arange(0, GA_G) + pv = tl.load(ga_peers_ptr + ar_g) + if PDL: + gdc_wait_with_memory_clobber() + tl.extra.cuda.gdc_launch_dependents() + # After the wait: the positions are a copy the immediate predecessor may still be writing. if use_mrope: section = tl.where( (rotary_offsets % 3 == 1) & (rotary_offsets < mrope_section1 * 3), @@ -600,6 +604,27 @@ def _qkv_rope_gate_fp8_append_kernel( ) cos = tl.where(position_is_valid, cos, float("nan")) sin = tl.where(position_is_valid, sin, float("nan")) + + x = tl.load(input_base + head_offsets, mask=head_mask, other=0.0).to(tl.float32) + inverse_rms = tl.rsqrt(tl.sum(x * x, axis=0) / head_dim + eps) + normalized = (x * inverse_rms * (weight + 1.0)).to(output_dtype).to(tl.float32) + + if has_pass_through: + pass_mask = head_mask & (head_offsets >= rotary_dim) + tl.store(output_base + head_offsets, normalized, mask=pass_mask) + tl.store( + fp8_base + head_offsets, + _fp8_like_cxx(normalized, scale), + mask=pass_mask & fp8_ok, + ) + + x_first = tl.load(input_base + rotary_offsets, mask=rotary_mask, other=0.0).to(tl.float32) + x_second = tl.load( + input_base + half_rotary + rotary_offsets, mask=rotary_mask, other=0.0 + ).to(tl.float32) + x_first = (x_first * inverse_rms * (weight_first + 1.0)).to(output_dtype).to(tl.float32) + x_second = (x_second * inverse_rms * (weight_second + 1.0)).to(output_dtype).to(tl.float32) + rot_first = (x_first * cos - x_second * sin).to(output_dtype) rot_second = (x_second * cos + x_first * sin).to(output_dtype) tl.store(output_base + rotary_offsets, rot_first, mask=rotary_mask) @@ -620,6 +645,30 @@ def _qkv_rope_gate_fp8_append_kernel( gate_output = gate_out_ptr + token * gate_out_stride_token + local_head * head_dim gate = tl.load(gate_input + head_offsets, mask=head_mask, other=0.0) tl.store(gate_output + head_offsets, gate, mask=head_mask) + if GATHER: + # The program's FP8 head (stored above in three pieces) as head_dim / 4 little-endian words. + tl.debug_barrier() + wq = tl.arange(0, head_dim // 4) + qb = q8_ptr + token * q_size + local_head * head_dim + 4 * wq + b0 = tl.load(qb).to(tl.uint8, bitcast=True).to(tl.int32) + b1 = tl.load(qb + 1).to(tl.uint8, bitcast=True).to(tl.int32) + b2 = tl.load(qb + 2).to(tl.uint8, bitcast=True).to(tl.int32) + b3 = tl.load(qb + 3).to(tl.uint8, bitcast=True).to(tl.int32) + words = b0 | (b1 << 8) | (b2 << 16) | (b3 << 24) + ll_pos_gather( + words, + pv, + ga_state_ptr, + ga_out_ptr, + token * num_q_heads + local_head, + token, + local_head, + ga_grank, + G=GA_G, + SLOT_WORDS=GA_SLOT_WORDS, + W=head_dim // 4, + HQ=num_q_heads, + ) else: local_head = head - num_q_heads - num_kv_heads head_offsets = tl.arange(0, head_block) @@ -630,9 +679,12 @@ def _qkv_rope_gate_fp8_append_kernel( output_base = ( qkv_out_ptr + token * qkv_out_stride_token + q_size + kv_size + local_head * head_dim ) + blk = tl.load(block_tables_ptr + req * bt_stride_req + bt_stride_kv + safe_page) + if PDL: + gdc_wait_with_memory_clobber() + tl.extra.cuda.gdc_launch_dependents() value = tl.load(input_base + head_offsets, mask=head_mask, other=0.0) tl.store(output_base + head_offsets, value, mask=head_mask) - blk = tl.load(block_tables_ptr + req * bt_stride_req + bt_stride_kv + safe_page) fp8_ok = pos_ok & (blk >= 0) v_base = ( kv_pool_ptr @@ -659,11 +711,26 @@ def _qkv_rope_gate_fp8_append_kernel( tl.store(scales_ptr + 4, s) -@torch.library.custom_op( - "trtllm::fused_qkv_rope_gate_fp8_append", - mutates_args=("kv_pool",), -) -def _fused_qkv_rope_gate_fp8_append( +# A GATHER grid polls its peers, so all of it must be resident: at most the compiled kernel's occupancy per SM, and +# at most this many, which leaves warp slots on each SM to the kernels PDL overlaps with it. +GATHER_MAX_PROGRAMS_PER_SM = 8 + + +@functools.lru_cache(maxsize=None) +def _resident_programs_per_sm(kernel: "CompiledKernel") -> int: + """Programs of a compiled Triton kernel the driver keeps resident per SM (its registers, shared memory, warps).""" + from cuda.bindings import driver + + kernel._init_handles() + err, programs = driver.cuOccupancyMaxActiveBlocksPerMultiprocessor( + driver.CUfunction(kernel.function), kernel.metadata.num_warps * 32, kernel.metadata.shared + ) + if err != driver.CUresult.CUDA_SUCCESS: + raise RuntimeError(f"cuOccupancyMaxActiveBlocksPerMultiprocessor failed: {err}") + return programs + + +def _rope_fp8_append_kernel_call( qkv: torch.Tensor, q_weight: torch.Tensor, k_weight: torch.Tensor, @@ -684,7 +751,12 @@ def _fused_qkv_rope_gate_fp8_append( use_mrope: bool, mrope_section1: int, mrope_section2: int, -) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + ga: Optional[tuple], + outputs: tuple, +) -> Tuple[tuple, tuple, dict]: + """Check the operands of both custom ops and return (grid, args, meta) of _qkv_rope_gate_fp8_append_kernel. + ``ga``: (peer table, epochs, member index, group size, slot words, PDL) of fused_qkv_rope_gate_fp8_append_gather. + ``outputs``: (qkv_out, gate_out, q8, scales, gathered q as int32 words or None), tensors or their dtypes.""" assert qkv.dim() == 2 and qkv.stride(-1) == 1 assert qkv.dtype == torch.bfloat16 assert q_weight.shape == (head_dim,) and k_weight.shape == (head_dim,) @@ -719,18 +791,18 @@ def _fused_qkv_rope_gate_fp8_append( q_size = num_q_heads * head_dim kv_size = num_kv_heads * head_dim assert qkv.shape[1] == 2 * q_size + 2 * kv_size - qkv_out = torch.empty((num_tokens, q_size + 2 * kv_size), dtype=qkv.dtype, device=qkv.device) - gate_out = torch.empty((num_tokens, num_q_heads, head_dim), dtype=qkv.dtype, device=qkv.device) - q8 = torch.empty( - (num_tokens, num_q_heads, head_dim), dtype=torch.float8_e4m3fn, device=qkv.device - ) - scales = torch.empty((8,), dtype=torch.float32, device=qkv.device) - if num_tokens == 0: - return qkv_out, gate_out, q8, scales - + qkv_out, gate_out, q8, scales, q_all_words = outputs + ga_peers, ga_state, ga_grank, ga_g, ga_slot_words, pdl = scales, scales, 0, 1, 1, False + if ga is not None: + ga_peers, ga_state, ga_grank, ga_g, ga_slot_words, pdl = ga + assert head_dim % 4 == 0 and (head_dim // 4) & (head_dim // 4 - 1) == 0 + assert ga_peers.dtype == torch.int64 and ga_peers.numel() == ga_g + assert ga_state.dtype == torch.int32 and ga_state.numel() >= num_tokens * num_q_heads + else: + q_all_words = scales half_rotary = rotary_dim // 2 grid = (num_tokens, num_q_heads + 2 * num_kv_heads) - _qkv_rope_gate_fp8_append_kernel[grid]( + args = ( qkv, qkv_out, gate_out, @@ -748,8 +820,8 @@ def _fused_qkv_rope_gate_fp8_append( num_tokens, cos_sin.shape[0], qkv.stride(0), - qkv_out.stride(0), - gate_out.stride(0), + q_size + 2 * kv_size, # qkv_out.stride(0) + q_size, # gate_out.stride(0) cos_sin.stride(0), kv_pool.stride(0), kv_pool.stride(1), @@ -757,6 +829,12 @@ def _fused_qkv_rope_gate_fp8_append( block_tables.stride(1), block_tables.shape[2], host_bmm1_scale, + ga_peers, + ga_state, + q_all_words, + ga_grank, + ) + meta = dict( q_len=q_len, page_size=page_size, num_q_heads=num_q_heads, @@ -772,11 +850,233 @@ def _fused_qkv_rope_gate_fp8_append( use_mrope=use_mrope, mrope_section1=mrope_section1, mrope_section2=mrope_section2, + GATHER=ga is not None, + GA_G=ga_g, + GA_SLOT_WORDS=ga_slot_words, + PDL=bool(pdl), num_warps=4, + launch_pdl=bool(pdl), + ) + return grid, args, meta + + +def _rope_fp8_append_launch( + qkv: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + cos_sin: torch.Tensor, + positions: torch.Tensor, + kv_pool: torch.Tensor, + block_tables: torch.Tensor, + seq_lens: torch.Tensor, + kv_scale_orig_quant: torch.Tensor, + kv_scale_quant_orig: torch.Tensor, + host_bmm1_scale: float, + q_len: int, + eps: float, + num_q_heads: int, + num_kv_heads: int, + head_dim: int, + rotary_dim: int, + use_mrope: bool, + mrope_section1: int, + mrope_section2: int, + ga: Optional[tuple] = None, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: + """Body of both custom ops. ``ga``: as in _rope_fp8_append_kernel_call; the fifth output is then the gathered q, + else None.""" + num_tokens = qkv.shape[0] + q_size = num_q_heads * head_dim + kv_size = num_kv_heads * head_dim + qkv_out = torch.empty((num_tokens, q_size + 2 * kv_size), dtype=qkv.dtype, device=qkv.device) + gate_out = torch.empty((num_tokens, num_q_heads, head_dim), dtype=qkv.dtype, device=qkv.device) + q8 = torch.empty( + (num_tokens, num_q_heads, head_dim), dtype=torch.float8_e4m3fn, device=qkv.device + ) + scales = torch.empty((8,), dtype=torch.float32, device=qkv.device) + q_all = None + if ga is not None: + q_all = torch.empty( + (num_tokens, ga[3] * q_size), dtype=torch.float8_e4m3fn, device=qkv.device + ) + grid, args, meta = _rope_fp8_append_kernel_call( + qkv, + q_weight, + k_weight, + cos_sin, + positions, + kv_pool, + block_tables, + seq_lens, + kv_scale_orig_quant, + kv_scale_quant_orig, + host_bmm1_scale, + q_len, + eps, + num_q_heads, + num_kv_heads, + head_dim, + rotary_dim, + use_mrope, + mrope_section1, + mrope_section2, + ga, + (qkv_out, gate_out, q8, scales, q_all.view(torch.int32) if q_all is not None else None), + ) + if num_tokens: + _qkv_rope_gate_fp8_append_kernel[grid](*args, **meta) + return qkv_out, gate_out, q8, scales, q_all + + +@torch.library.custom_op( + "trtllm::fused_qkv_rope_gate_fp8_append", + mutates_args=("kv_pool",), +) +def _fused_qkv_rope_gate_fp8_append( + qkv: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + cos_sin: torch.Tensor, + positions: torch.Tensor, + kv_pool: torch.Tensor, + block_tables: torch.Tensor, + seq_lens: torch.Tensor, + kv_scale_orig_quant: torch.Tensor, + kv_scale_quant_orig: torch.Tensor, + host_bmm1_scale: float, + q_len: int, + eps: float, + num_q_heads: int, + num_kv_heads: int, + head_dim: int, + rotary_dim: int, + use_mrope: bool, + mrope_section1: int, + mrope_section2: int, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + qkv_out, gate_out, q8, scales, _ = _rope_fp8_append_launch( + qkv, + q_weight, + k_weight, + cos_sin, + positions, + kv_pool, + block_tables, + seq_lens, + kv_scale_orig_quant, + kv_scale_quant_orig, + host_bmm1_scale, + q_len, + eps, + num_q_heads, + num_kv_heads, + head_dim, + rotary_dim, + use_mrope, + mrope_section1, + mrope_section2, ) return qkv_out, gate_out, q8, scales +@torch.library.custom_op( + "trtllm::fused_qkv_rope_gate_fp8_append_gather", + mutates_args=("kv_pool", "ga_state"), +) +def _fused_qkv_rope_gate_fp8_append_gather( + qkv: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + cos_sin: torch.Tensor, + positions: torch.Tensor, + kv_pool: torch.Tensor, + block_tables: torch.Tensor, + seq_lens: torch.Tensor, + kv_scale_orig_quant: torch.Tensor, + kv_scale_quant_orig: torch.Tensor, + host_bmm1_scale: float, + q_len: int, + eps: float, + num_q_heads: int, + num_kv_heads: int, + head_dim: int, + rotary_dim: int, + use_mrope: bool, + mrope_section1: int, + mrope_section2: int, + ga_peers: torch.Tensor, + ga_state: torch.Tensor, + ga_grank: int, + ga_group: int, + ga_slot_words: int, + pdl: bool, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + qkv_out, gate_out, q8, scales, q_all = _rope_fp8_append_launch( + qkv, + q_weight, + k_weight, + cos_sin, + positions, + kv_pool, + block_tables, + seq_lens, + kv_scale_orig_quant, + kv_scale_quant_orig, + host_bmm1_scale, + q_len, + eps, + num_q_heads, + num_kv_heads, + head_dim, + rotary_dim, + use_mrope, + mrope_section1, + mrope_section2, + ga=(ga_peers, ga_state, ga_grank, ga_group, ga_slot_words, pdl), + ) + return qkv_out, gate_out, q8, scales, q_all + + +@_fused_qkv_rope_gate_fp8_append_gather.register_fake +def _( + qkv: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + cos_sin: torch.Tensor, + positions: torch.Tensor, + kv_pool: torch.Tensor, + block_tables: torch.Tensor, + seq_lens: torch.Tensor, + kv_scale_orig_quant: torch.Tensor, + kv_scale_quant_orig: torch.Tensor, + host_bmm1_scale: float, + q_len: int, + eps: float, + num_q_heads: int, + num_kv_heads: int, + head_dim: int, + rotary_dim: int, + use_mrope: bool, + mrope_section1: int, + mrope_section2: int, + ga_peers: torch.Tensor, + ga_state: torch.Tensor, + ga_grank: int, + ga_group: int, + ga_slot_words: int, + pdl: bool, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + num_tokens = qkv.shape[0] + qkv_width = (num_q_heads + 2 * num_kv_heads) * head_dim + return ( + qkv.new_empty((num_tokens, qkv_width)), + qkv.new_empty((num_tokens, num_q_heads, head_dim)), + qkv.new_empty((num_tokens, num_q_heads, head_dim), dtype=torch.float8_e4m3fn), + qkv.new_empty((8,), dtype=torch.float32), + qkv.new_empty((num_tokens, ga_group * num_q_heads * head_dim), dtype=torch.float8_e4m3fn), + ) + + @_fused_qkv_rope_gate_fp8_append.register_fake def _( qkv: torch.Tensor, @@ -822,7 +1122,7 @@ def fused_qkv_rope_gate_fp8_append( head_dim: int, rotary_dim: int, mrope_section: Optional[Tuple[int, int, int]], - plan, + plan: "KvAppendPlan", ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: """``fused_qkv_gemma_rmsnorm_rope_gate`` plus the FP8 query, the paged FP8 K / V append and the FMHA scales. @@ -855,6 +1155,112 @@ def fused_qkv_rope_gate_fp8_append( ) +def rope_gather_max_tokens( + qkv: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + cos_sin: torch.Tensor, + positions: torch.Tensor, + eps: float, + num_q_heads: int, + num_kv_heads: int, + head_dim: int, + rotary_dim: int, + mrope_section: Optional[Tuple[int, int, int]], + plan: "KvAppendPlan", + gather: tuple, +) -> int: + """The most tokens fused_qkv_rope_gate_fp8_append_gather takes with these arguments: its grid polls the peers, + so all of it must be resident. Compiles the kernel the call would launch, without launching it.""" + use_mrope = mrope_section is not None + assert qkv.shape[0] > 0 + # Fresh outputs are aligned like these stand-ins, so Triton compiles the kernel the launch takes. + outputs = (qkv.dtype, qkv.dtype, torch.float8_e4m3fn, torch.float32, torch.int32) + grid, args, meta = _rope_fp8_append_kernel_call( + qkv, + q_weight, + k_weight, + cos_sin, + positions, + plan.kv_pool, + plan.block_tables, + plan.seq_lens, + plan.kv_scale_orig_quant, + plan.kv_scale_quant_orig, + plan.host_bmm1_scale, + plan.q_len, + eps, + num_q_heads, + num_kv_heads, + head_dim, + rotary_dim, + use_mrope, + mrope_section[1] if use_mrope else 0, + mrope_section[2] if use_mrope else 0, + gather, + outputs, + ) + compiled = _qkv_rope_gate_fp8_append_kernel.warmup(*args, grid=grid, **meta) + per_sm = min(GATHER_MAX_PROGRAMS_PER_SM, _resident_programs_per_sm(compiled)) + sms = torch.cuda.get_device_properties(qkv.device).multi_processor_count + return per_sm * sms // grid[1] + + +def fused_qkv_rope_gate_fp8_append_gather( + qkv: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + cos_sin: torch.Tensor, + positions: torch.Tensor, + eps: float, + num_q_heads: int, + num_kv_heads: int, + head_dim: int, + rotary_dim: int, + mrope_section: Optional[Tuple[int, int, int]], + plan: "KvAppendPlan", + gather: tuple, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """``fused_qkv_rope_gate_fp8_append`` that also all-gathers the FP8 query over the KV-replica group in the same + launch (bit-identical to the plain kernel followed by TPGroupExchange.allgather of its FP8 query). + + ``gather``: (peer table, epochs, member index, group size, slot words) from + TPGroupExchange.rope_gather_args, plus the PDL flag. Every member issues the same call, with at most + rope_gather_max_tokens tokens. The fifth output is the gathered query + ``[num_tokens, group * num_q_heads * head_dim]`` FP8, member-major per token (allgather's layout). + """ + use_mrope = mrope_section is not None + ga_peers, ga_state, ga_grank, ga_group, ga_slot_words, pdl = gather + return _fused_qkv_rope_gate_fp8_append_gather( + qkv, + q_weight, + k_weight, + cos_sin, + positions, + plan.kv_pool, + plan.block_tables, + plan.seq_lens, + plan.kv_scale_orig_quant, + plan.kv_scale_quant_orig, + plan.host_bmm1_scale, + plan.q_len, + eps, + num_q_heads, + num_kv_heads, + head_dim, + rotary_dim, + use_mrope, + mrope_section[1] if use_mrope else 0, + mrope_section[2] if use_mrope else 0, + ga_peers, + ga_state, + ga_grank, + ga_group, + ga_slot_words, + bool(pdl), + ) + + @functools.lru_cache(maxsize=None) def _sigmoid_mul_pdl(device_index: int) -> bool: """Whether the output-gate kernel launches with PDL. It reads its inputs only after griddepcontrol.wait and @@ -867,6 +1273,7 @@ def _fused_sigmoid_mul_kernel( output_ptr, attention_ptr, gate_ptr, + scale_ptr, output_stride_token, attention_stride_token, gate_stride_token, @@ -874,8 +1281,12 @@ def _fused_sigmoid_mul_kernel( hidden_size: tl.constexpr, head_dim: tl.constexpr, block_size: tl.constexpr, + OUT_FP8: tl.constexpr = False, LAUNCH_WITH_PDL: tl.constexpr = False, -): +) -> None: + """output = attention * sigmoid(gate). With OUT_FP8 the output is the E4M3 that static_quantize_e4m3_per_tensor + makes of that product: rounded to the attention dtype, times the correctly rounded reciprocal of the scale + (scale_ptr; unread otherwise), RN-satfinite.""" if LAUNCH_WITH_PDL: tl.extra.cuda.gdc_launch_dependents() token = tl.program_id(0).to(tl.int64) @@ -897,41 +1308,48 @@ def _fused_sigmoid_mul_kernel( mask=mask, other=0.0, ).to(tl.float32) - tl.store( - output_ptr + token * output_stride_token + offsets, - attention * tl.sigmoid(gate), - mask=mask, - ) + if OUT_FP8: + y = (attention * tl.sigmoid(gate)).to(attention_ptr.dtype.element_ty).to(tl.float32) + y *= tldevice.rcp_rn(tl.load(scale_ptr).to(tl.float32)) + tl.store( + output_ptr + token * output_stride_token + offsets, + y.to(output_ptr.dtype.element_ty), + mask=mask, + ) + else: + tl.store( + output_ptr + token * output_stride_token + offsets, + attention * tl.sigmoid(gate), + mask=mask, + ) -@torch.library.custom_op( - "trtllm::fused_sigmoid_mul_inplace", - mutates_args=("attention_output",), -) -def fused_sigmoid_mul_inplace( +def _sigmoid_mul_launch( + output: torch.Tensor, attention_output: torch.Tensor, gate: torch.Tensor, + input_scale: Optional[torch.Tensor] = None, ) -> None: - """Apply ``attention_output *= sigmoid(gate)`` with a Triton kernel.""" + """Launch _fused_sigmoid_mul_kernel for an output-gate call: output = attention_output * sigmoid(gate), as the + E4M3 static quant at input_scale when given. One program per (token, block of hidden_size), 4 warps, PDL where + _sigmoid_mul_pdl allows it.""" assert attention_output.dim() == 2 and attention_output.stride(-1) == 1 num_tokens, hidden_size = attention_output.shape if gate.dim() == 3: assert gate.shape[0] == num_tokens assert gate.shape[1] * gate.shape[2] == hidden_size assert gate.stride(-1) == 1 - head_dim = gate.shape[2] - gate_stride_token = gate.stride(0) - gate_stride_head = gate.stride(1) + head_dim, gate_stride_token, gate_stride_head = ( + gate.shape[2], + gate.stride(0), + gate.stride(1), + ) else: assert gate.dim() == 2 and gate.shape == attention_output.shape assert gate.stride(-1) == 1 - head_dim = hidden_size - gate_stride_token = gate.stride(0) - gate_stride_head = hidden_size - + head_dim, gate_stride_token, gate_stride_head = hidden_size, gate.stride(0), hidden_size if num_tokens == 0: return - max_block_size = 1024 if num_tokens < 1024 else 2048 block_size = min(triton.next_power_of_2(hidden_size), max_block_size) grid = (num_tokens, triton.cdiv(hidden_size, block_size)) @@ -940,17 +1358,52 @@ def fused_sigmoid_mul_inplace( if _sigmoid_mul_pdl(attention_output.device.index) else {} ) + out_fp8 = input_scale is not None _fused_sigmoid_mul_kernel[grid]( - attention_output, + output, attention_output, gate, - attention_output.stride(0), + input_scale if out_fp8 else attention_output, + output.stride(0), attention_output.stride(0), gate_stride_token, gate_stride_head, hidden_size=hidden_size, head_dim=head_dim, block_size=block_size, + OUT_FP8=out_fp8, num_warps=4, **pdl_kwargs, ) + + +@torch.library.custom_op("trtllm::fused_sigmoid_mul_fp8", mutates_args=()) +def fused_sigmoid_mul_fp8( + attention_output: torch.Tensor, + gate: torch.Tensor, + input_scale: torch.Tensor, +) -> torch.Tensor: + """``static_quantize_e4m3_per_tensor(attention_output * sigmoid(gate), input_scale)`` in one kernel: the E4M3 + input of an FP8 per-tensor o_proj, bit for bit the in-place gate kernel followed by that quantization.""" + out = torch.empty_like(attention_output, dtype=torch.float8_e4m3fn) + _sigmoid_mul_launch(out, attention_output, gate, input_scale) + return out + + +@fused_sigmoid_mul_fp8.register_fake +def _( + attention_output: torch.Tensor, gate: torch.Tensor, input_scale: torch.Tensor +) -> torch.Tensor: + return torch.empty_like(attention_output, dtype=torch.float8_e4m3fn) + + +@torch.library.custom_op( + "trtllm::fused_sigmoid_mul_inplace", + mutates_args=("attention_output",), +) +def fused_sigmoid_mul_inplace( + attention_output: torch.Tensor, + gate: torch.Tensor, +) -> None: + """Apply ``attention_output *= sigmoid(gate)`` with a Triton kernel.""" + _sigmoid_mul_launch(attention_output, attention_output, gate) diff --git a/tensorrt_llm/_torch/attention/qk_norm_attention.py b/tensorrt_llm/_torch/attention/qk_norm_attention.py index 3c049d027f50..7541705a221d 100644 --- a/tensorrt_llm/_torch/attention/qk_norm_attention.py +++ b/tensorrt_llm/_torch/attention/qk_norm_attention.py @@ -29,7 +29,7 @@ from .attention import Attention from .backends.interface import PositionalEmbeddingParams from .kernels.fused_qk_norm_rope_gate import (fused_qkv_gemma_rmsnorm_rope_gate, - fused_qkv_rope_gate_fp8_append, + fused_sigmoid_mul_fp8, fused_sigmoid_mul_inplace) _QKV_ROPE_TILING_ENABLED = os.environ.get("TRTLLM_ENABLE_QKV_ROPE_TILING", @@ -148,6 +148,9 @@ class QKNormRoPEAttention(Attention): It is a subclass of Attention, and overrides the apply_rope method to apply QK norm and RoPE. """ + # Prefill output gates write o_proj's E4M3 input (_output_gate_fp8_scale). + fp8_output_gate: bool = False + def __init__( self, *, @@ -174,6 +177,9 @@ def __init__( head_dim: Optional[int] = None, use_gqa_decode_fmha: bool = False, cache_context_plan: bool = False, + fp8_output_gate: bool = False, + context_fmha_head_dim_per_stage_kv: int = 0, + context_last_rows_only: bool = False, ): self.pretrained_config = config.pretrained_config @@ -183,6 +189,7 @@ def __init__( # qk_norm_rope kernel via the use_gemma flag threaded through below. self.use_gemma_rms_norm = use_gemma_rms_norm self._fuse_qk_norm_rope_gate = False + self.fp8_output_gate = fp8_output_gate # If fuse_qk_norm_rope is true, do not apply fused RoPE in attention OP, and self.rotary_emb # will be skipped in the overridden apply_rope. rope_fusion=None lets @@ -214,6 +221,9 @@ def __init__( head_dim=head_dim, use_gqa_decode_fmha=use_gqa_decode_fmha, cache_context_plan=cache_context_plan, + context_fmha_head_dim_per_stage_kv= + context_fmha_head_dim_per_stage_kv, + context_last_rows_only=context_last_rows_only, ) self.q_norm = RMSNorm(hidden_size=self.head_dim, @@ -317,20 +327,11 @@ def preprocess_qkv(self, qkv, position_ids, attn_metadata=None): 2 * self.head_dim)[:, :, self.head_dim:] return qkv[:, :packed], None, None, gate, plan if plan is not None: - qkv, gate, plan.q_fp8, plan.scales = fused_qkv_rope_gate_fp8_append( - qkv, - self.q_norm.weight, - self.k_norm.weight, + qkv, gate = gqa_decode.run_prologue( + plan, qkv, self.q_norm.weight, self.k_norm.weight, self.rotary_emb.rotary_cos_sin, - positions, - self.q_norm.variance_epsilon, - self.num_heads, - self.num_key_value_heads, - self.head_dim, - self._get_qk_norm_rotary_dim(), - mrope_section, - plan, - ) + positions, self.q_norm.variance_epsilon, + self._get_qk_norm_rotary_dim(), mrope_section) return qkv, None, None, gate, plan qkv, gate = fused_qkv_gemma_rmsnorm_rope_gate( qkv, @@ -348,17 +349,33 @@ def preprocess_qkv(self, qkv, position_ids, attn_metadata=None): ) return qkv, None, None, gate, None - def apply_output_gate(self, attention_output, gate): + def apply_output_gate(self, attention_output: torch.Tensor, + gate: torch.Tensor) -> torch.Tensor: if (self._fuse_qk_norm_rope_gate and torch.version.hip is None and attention_output.device.type == "cuda" and attention_output.dim() == 2 and attention_output.stride(-1) == 1 and gate.dim() in (2, 3) and gate.stride(-1) == 1 and gate.numel() == attention_output.numel()): + fp8_scale = self._output_gate_fp8_scale(attention_output) + if fp8_scale is not None: + return fused_sigmoid_mul_fp8(attention_output, gate, fp8_scale) fused_sigmoid_mul_inplace(attention_output, gate) return attention_output return super().apply_output_gate(attention_output, gate) + # With fp8_output_gate, calls of at least this many rows (prefill-sized) have the gate kernel write o_proj's + # E4M3 input where o_proj takes one (Linear.static_fp8_input_scale); smaller calls keep the BF16 gate. + _OUTPUT_GATE_FP8_MIN_TOKENS = 1024 + + def _output_gate_fp8_scale( + self, attention_output: torch.Tensor) -> Optional[torch.Tensor]: + rows = attention_output.shape[0] + if (not self.fp8_output_gate or rows < self._OUTPUT_GATE_FP8_MIN_TOKENS + or attention_output.dtype != torch.bfloat16): + return None + return self.o_proj.static_fp8_input_scale(rows) + def apply_qk_norm(self, q, k): def q_l2norm(): diff --git a/tensorrt_llm/_torch/compilation/multi_stream/auto_multi_stream.py b/tensorrt_llm/_torch/compilation/multi_stream/auto_multi_stream.py index a2e5513f6498..aa37e681d582 100644 --- a/tensorrt_llm/_torch/compilation/multi_stream/auto_multi_stream.py +++ b/tensorrt_llm/_torch/compilation/multi_stream/auto_multi_stream.py @@ -52,6 +52,7 @@ def estimate_time(node: Node) -> int: moe_ops = { torch.ops.trtllm.fp4_block_scale_moe_runner.default, + torch.ops.trtllm.fp4_block_scale_moe_decode_runner.default, torch.ops.trtllm.fused_moe.default, torch.ops.trtllm.moe_custom_op.default, } diff --git a/tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py b/tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py index 68f912b900c5..3c26a095c778 100644 --- a/tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py +++ b/tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py @@ -1931,6 +1931,26 @@ def _( ): return q.new_empty(q.shape, dtype=out_dtype) + @torch.library.register_fake("trtllm::fmha_paged_context_fp8") + def _( + q: torch.Tensor, + kv_pool: torch.Tensor, + block_tables: torch.Tensor, + seq_lens_kv: torch.Tensor, + cu_seqlens_q: torch.Tensor, + cu_seqlens_kv: torch.Tensor, + out: torch.Tensor, + scale_bmm1: torch.Tensor, + scale_out: torch.Tensor, + max_q_len: int, + max_kv_len: int, + head_dim_per_stage_kv: int, + allow_nvrtc: bool = False, + ) -> bool: + # The fail-safe answer: whether a cubin exists is known only at run + # time, and on False the caller runs FlashInfer, which is always valid. + return False + @torch.library.register_fake("trtllm::dit_v_amax") def _(qkv: torch.Tensor, num_heads: int, head_dim: int): return qkv.new_empty((1, ), dtype=torch.float32) diff --git a/tensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.py b/tensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.py index 0a36ea331288..d566587c208a 100644 --- a/tensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.py +++ b/tensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.py @@ -3281,7 +3281,12 @@ def __init__(self, tile_size: int, output_dtype: torch.dtype, scaling_vector_size: int = 16, - use_expert_counts: bool = False): + use_expert_counts: bool = False, + weights_evict_first: bool = False, + weights_evict_first_max_tokens: int = 0): + """``weights_evict_first``: load the expert weights (B / SFB) evict-first. Such a runner serves calls + of up to ``weights_evict_first_max_tokens`` tokens (the caller's bound; 0: unknown), and its tuning + covers row buckets up to that bound whatever the tuning call's rows.""" super().__init__() self.num_experts = num_experts self.top_k = top_k @@ -3298,6 +3303,9 @@ def __init__(self, raise ValueError("Expert-count scheduling requires top_k=1") self.fc2_n_tile_size_override = ( _get_cutedsl_fc2_n_tile_size_override()) + self.weights_evict_first = weights_evict_first + self.weights_evict_first_max_tokens = ( + weights_evict_first_max_tokens if weights_evict_first else 0) if (sm_version := get_sm_version()) not in (100, 103): raise ValueError( @@ -3325,6 +3333,8 @@ def unique_id(self): "fc2_n_tile_size_override", self.fc2_n_tile_size_override, ) + if self.weights_evict_first: + runner_id += ("weights_evict_first", ) return runner_id def _get_default_tactic( @@ -3389,7 +3399,9 @@ def get_valid_tactics( return valid_tactics def get_tuning_config(self) -> TuningConfig: - key = self.unique_id() + """The runner's TuningConfig; an evict-first runner with a token bound tunes up to the permuted rows of + that bound (``tune_max_num_tokens``), so its tactics cover every call it serves.""" + key = (self.unique_id(), self.weights_evict_first_max_tokens) if key not in self.__class__.tuning_config_cache: helper = GroupedGemmInputsHelper(self.num_experts, self.top_k, self.num_local_experts, @@ -3425,6 +3437,10 @@ def get_tuning_config(self) -> TuningConfig: inputs_pre_hook=helper.inputs_pre_hook_finalize_fusion, use_cold_l2_cache=True, share_jit_builds=True, + # The dynamic dimension is input 0's (permuted) rows. + tune_max_num_tokens=helper.get_max_num_permuted_tokens( + self.weights_evict_first_max_tokens) + if self.weights_evict_first_max_tokens > 0 else None, ) return self.__class__.tuning_config_cache[key] @@ -3540,8 +3556,14 @@ def forward(self, inputs: List[torch.Tensor], cache_key = (self.scaling_vector_size, self.tile_size, mma_tiler_mn, cluster_shape_mn, raster_along_m, - self.use_expert_counts, self.num_local_experts) + self.use_expert_counts, self.num_local_experts, + self.weights_evict_first) if cache_key not in self.__class__.kernel_cache: + # Passed only when set: subclass runners may bind a + # kernel_class without this parameter. + evict_kwargs = ({ + "weights_evict_first": True + } if self.weights_evict_first else {}) gemm = self.__class__.kernel_class( sf_vec_size=self.scaling_vector_size, mma_tiler_mn=mma_tiler_mn, @@ -3549,6 +3571,7 @@ def forward(self, inputs: List[torch.Tensor], raster_along_m=raster_along_m, use_expert_counts=self.use_expert_counts, num_local_experts=self.num_local_experts, + **evict_kwargs, ) # Compute max active clusters on current device hardware_info = cutlass.utils.HardwareInfo() @@ -3636,7 +3659,13 @@ def cute_dsl_nvfp4_grouped_gemm_finalize_inplace_blackwell( scaling_vector_size: int = 16, expert_counts: Optional[torch.Tensor] = None, expert_capacity: int = 0, + weights_evict_first: bool = False, + weights_evict_first_max_tokens: int = 0, ) -> None: + """``weights_evict_first``: load the expert weights (B / SFB) with an L2 evict_first policy (same math). + ``weights_evict_first_max_tokens``: the most tokens of a call that takes ``weights_evict_first`` (the + caller's bound): that runner is tuned up to it, whatever the tuning call's tokens (0: up to the tuning + call's).""" tuner = AutoTuner.get() if expert_counts is None and expert_capacity != 0: raise ValueError( @@ -3658,7 +3687,9 @@ def cute_dsl_nvfp4_grouped_gemm_finalize_inplace_blackwell( tile_size, output_dtype, scaling_vector_size, - use_expert_counts=expert_counts is not None) + use_expert_counts=expert_counts is not None, + weights_evict_first=weights_evict_first, + weights_evict_first_max_tokens=weights_evict_first_max_tokens) inputs = [ input, weight, input_scale, weight_scale, alpha, output, @@ -3698,6 +3729,8 @@ def _( scaling_vector_size: int = 16, expert_counts: Optional[torch.Tensor] = None, expert_capacity: int = 0, + weights_evict_first: bool = False, + weights_evict_first_max_tokens: int = 0, ) -> None: num_tokens = token_final_scales.size(0) n = weight.size(1) diff --git a/tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py b/tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py index 0c2ecd60c175..ff6be0391a2d 100644 --- a/tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py +++ b/tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py @@ -16,7 +16,7 @@ import os from dataclasses import dataclass, replace from functools import lru_cache -from typing import List, Optional, Tuple, Union +from typing import Callable, List, Optional, Tuple, Union import torch @@ -447,6 +447,9 @@ class FP4BlockScaleMoERunner(TunableRunner): runner_dict = dict() tuning_config = None + decode_tuning = False + decode_early_release_rows = 0 + decode_spare_sms = 0 def __init__(self, num_experts: int, @@ -462,7 +465,9 @@ def __init__(self, act_type: int, tune_max_num_tokens: int = 8192, use_dp: bool = False, - decode_tuning: bool = False): + decode_tuning: bool = False, + decode_early_release_rows: int = 0, + decode_spare_sms: int = 0): self.num_experts = num_experts self.top_k = top_k @@ -475,6 +480,12 @@ def __init__(self, self.routing_method_type = routing_method_type self.do_finalize = do_finalize self.act_type = act_type + # Declared by the model (decode_moe.select): decode-step tuning and kernels; the engine releases its + # dependents after its own wait from decode_early_release_rows rows (0: never) and leaves decode_spare_sms + # SMs of its persistent grid free (the backend's reserve_sms_for_concurrent_kernels for this call). + self.decode_tuning = decode_tuning + self.decode_early_release_rows = decode_early_release_rows + self.decode_spare_sms = decode_spare_sms self.tuning_config = FP4BlockScaleMoERunner.get_tuning_config( self.num_experts // self.local_num_experts, @@ -485,8 +496,11 @@ def __init__(self, # The unique_id is used by the autotuner to get the cache key, so we hash on members # that influence tactic validity here. e.g. we are tuning FC1 and FC2 so the routing type does not matter def unique_id(self): - return (self.top_k, self.intermediate_size, self.local_num_experts, - self.act_type) + key = (self.top_k, self.intermediate_size, self.local_num_experts, + self.act_type) + # Without decode tuning the key is the base tuple. With it, finalized and un-finalized calls run + # different kernels (decode_moe.select), so they are tuned apart. + return key + (True, self.do_finalize) if self.decode_tuning else key def get_runner(self): instance_key = (self.act_type, ) @@ -503,19 +517,31 @@ def forward( output: Optional[torch.Tensor] = None, prerouted: Optional[Tuple[List[torch.Tensor], torch.Tensor, torch.Tensor]] = None, + engine_state: Optional[torch.Tensor] = None, + lamport_out: Optional[torch.Tensor] = None, + candidates: Optional[torch.Tensor] = None, ) -> torch.Tensor: """``prerouted``: (routing tables for ``tactic``'s tile, top-k ids, BF16 top-k weights); the tables number this rank's experts from 0 (-1: another rank), so the kernels run an all-local problem and skip the - routing kernel.""" + routing kernel. ``engine_state`` / ``lamport_out``: see + ``decode_moe.select`` and ``decode_moe.LamportFc2Buffer``; an + un-finalized call that takes ``ENGINE`` or ``CUTE_FC2`` leaves its FC2 + rows in ``lamport_out`` (and returns that view), a ``CUBIN`` call + returns its own rows and leaves ``lamport_out`` untouched. + ``candidates``: ``PreroutedRouting.candidates``; the call must take + ``ENGINE``, which fills ``prerouted`` from them.""" assert isinstance(tactic, list) args = FP4BlockScaleMoEInputs(*inputs) kernel_runner = self.get_runner() - + # The positional arguments of the runner's run_moe / run_moe_prerouted + # (fp4BlockScaleMoe.cpp; decode_moe.GEMM2_BIAS_ARG and its siblings + # name the ones its FC1-only entries drop). + run_args: Tuple[object, ...] if prerouted is not None: tables, topk_ids, topk_weights = prerouted - return kernel_runner.run_moe_prerouted( + run_args = ( None, None, args.hidden_states, args.hidden_states_scale, args.gemm1_weights, args.gemm1_weights_scale, args.gemm1_bias, args.gemm1_alpha, args.gemm1_beta, args.gemm1_clamp_limit, @@ -526,19 +552,88 @@ def forward( self.local_num_experts, self.routed_scaling_factor, self.routing_method_type, self.do_finalize, tactic, topk_weights, topk_ids, output, *tables, tactic[0]) - - return kernel_runner.run_moe( - args.routing_logits, args.routing_bias, args.hidden_states, - args.hidden_states_scale, args.gemm1_weights, - args.gemm1_weights_scale, args.gemm1_bias, args.gemm1_alpha, - args.gemm1_beta, args.gemm1_clamp_limit, args.gemm2_weights, - args.gemm2_weights_scale, args.gemm2_bias, - args.output1_scale_scalar, args.output1_scale_gate_scalar, - args.output2_scale_scalar, self.num_experts, self.top_k, - self.n_group, self.topk_group, self.intermediate_size, - self.local_expert_offset, self.local_num_experts, - self.routed_scaling_factor, self.routing_method_type, - self.do_finalize, tactic, args.topk_weights, args.topk_ids, output) + run = kernel_runner.run_moe_prerouted + else: + run_args = (args.routing_logits, args.routing_bias, + args.hidden_states, args.hidden_states_scale, + args.gemm1_weights, args.gemm1_weights_scale, + args.gemm1_bias, args.gemm1_alpha, args.gemm1_beta, + args.gemm1_clamp_limit, args.gemm2_weights, + args.gemm2_weights_scale, args.gemm2_bias, + args.output1_scale_scalar, + args.output1_scale_gate_scalar, + args.output2_scale_scalar, self.num_experts, self.top_k, + self.n_group, self.topk_group, self.intermediate_size, + self.local_expert_offset, self.local_num_experts, + self.routed_scaling_factor, self.routing_method_type, + self.do_finalize, tactic, args.topk_weights, + args.topk_ids, output) + run = kernel_runner.run_moe + if not self.decode_tuning and candidates is None: + # Every model's call (no decode kernels declared): the runner's + # own kernels; a Lamport buffer only goes to ENGINE / CUTE_FC2. + return run(*run_args) + return self._forward_decode(args, kernel_runner, run, run_args, tactic, + output, prerouted, engine_state, + lamport_out, candidates) + + def _forward_decode( + self, + args: FP4BlockScaleMoEInputs, + kernel_runner: torch.ScriptObject, + run: Callable[..., List[torch.Tensor]], + run_args: Tuple[object, ...], + tactic: List[int], + output: Optional[torch.Tensor], + prerouted: Optional[Tuple[List[torch.Tensor], torch.Tensor, + torch.Tensor]], + engine_state: Optional[torch.Tensor], + lamport_out: Optional[torch.Tensor], + candidates: Optional[torch.Tensor], + ) -> List[torch.Tensor]: + """``forward`` of a call that may take the decode kernels + (``decode_moe.select``); ``run`` / ``run_args``: the runner entry point + and its arguments for the CUBIN call.""" + from ..moe.fused_moe.trtllm_gen import decode_moe + kernel = decode_moe.DecodeKernel.CUBIN + if self.decode_tuning: + kernel = decode_moe.select(kernel_runner, + self.act_type, + tactic, + args, + top_k=self.top_k, + do_finalize=self.do_finalize, + output=output, + intermediate_size=self.intermediate_size, + prerouted=prerouted is not None, + engine_state=engine_state) + if candidates is not None and kernel != decode_moe.DecodeKernel.ENGINE: + raise ValueError( + "pre-routed candidates need the decode MoE engine, which this " + f"call does not take ({kernel})") + if kernel == decode_moe.DecodeKernel.ENGINE: + tables, topk_ids, topk_weights = prerouted + m = args.hidden_states.shape[0] + return decode_moe.run_engine( + args, + tables, + tactic[0], + self.top_k, + self.local_num_experts, + engine_state, + lamport_out, + release_after_wait=0 < self.decode_early_release_rows <= m, + spare_sms=self.decode_spare_sms, + candidates=candidates, + topk_ids=topk_ids, + topk_weights=topk_weights, + local_start=self.local_expert_offset) + if kernel == decode_moe.DecodeKernel.CUTE_FC2: + fc1 = (kernel_runner.run_moe_prerouted_fc1 + if prerouted is not None else kernel_runner.run_moe_fc1) + return decode_moe.run_cute_fc2( + fc1(*decode_moe.fc1_only_args(run_args)), args, lamport_out) + return run(*run_args) def get_valid_tactics(self, inputs: List[torch.Tensor], profile: OptimizationProfile, @@ -704,53 +799,67 @@ def lookup_tactic( return [int(tactic[0]), int(tactic[1])] -@torch.library.custom_op("trtllm::fp4_block_scale_moe_runner", mutates_args=()) -def fp4_block_scale_moe_runner( - routing_logits: Optional[torch.Tensor], - routing_bias: Optional[torch.Tensor], - hidden_states: torch.Tensor, - hidden_states_scale: torch.Tensor, - gemm1_weights: torch.Tensor, - gemm1_weights_scale: torch.Tensor, - gemm1_bias: torch.Tensor, - gemm1_alpha: torch.Tensor, - gemm1_beta: torch.Tensor, - gemm1_clamp_limit: torch.Tensor, - gemm2_weights: torch.Tensor, - gemm2_weights_scale: torch.Tensor, - gemm2_bias: torch.Tensor, - output1_scale_scalar: torch.Tensor, - output1_scale_gate_scalar: torch.Tensor, - output2_scale_scalar: torch.Tensor, - num_experts: int, - top_k: int, - n_group: Optional[int], - topk_group: Optional[int], - intermediate_size: int, - local_expert_offset: int, - local_num_experts: int, - routed_scaling_factor: Optional[float], - routing_method_type: int, - do_finalize: bool, - act_type: int = ActType_TrtllmGen.SwiGlu.value, - topk_weights: Optional[torch.Tensor] = None, - topk_ids: Optional[torch.Tensor] = None, - output: Optional[torch.Tensor] = None, - tune_max_num_tokens: int = 8192, - use_dp: bool = False, - prerouted_tables: Optional[torch.Tensor] = None, - prerouted_ids: Optional[torch.Tensor] = None, - prerouted_weights: Optional[torch.Tensor] = None, - prerouted_tactic: Optional[List[int]] = None, - decode_tuning: bool = False) -> List[torch.Tensor]: +def _run_fp4_block_scale_moe(routing_logits: Optional[torch.Tensor], + routing_bias: Optional[torch.Tensor], + hidden_states: torch.Tensor, + hidden_states_scale: torch.Tensor, + gemm1_weights: torch.Tensor, + gemm1_weights_scale: torch.Tensor, + gemm1_bias: torch.Tensor, + gemm1_alpha: torch.Tensor, + gemm1_beta: torch.Tensor, + gemm1_clamp_limit: torch.Tensor, + gemm2_weights: torch.Tensor, + gemm2_weights_scale: torch.Tensor, + gemm2_bias: torch.Tensor, + output1_scale_scalar: torch.Tensor, + output1_scale_gate_scalar: torch.Tensor, + output2_scale_scalar: torch.Tensor, + num_experts: int, + top_k: int, + n_group: Optional[int], + topk_group: Optional[int], + intermediate_size: int, + local_expert_offset: int, + local_num_experts: int, + routed_scaling_factor: Optional[float], + routing_method_type: int, + do_finalize: bool, + act_type: int = ActType_TrtllmGen.SwiGlu.value, + topk_weights: Optional[torch.Tensor] = None, + topk_ids: Optional[torch.Tensor] = None, + output: Optional[torch.Tensor] = None, + tune_max_num_tokens: int = 8192, + use_dp: bool = False, + prerouted_tables: Optional[torch.Tensor] = None, + prerouted_ids: Optional[torch.Tensor] = None, + prerouted_weights: Optional[torch.Tensor] = None, + prerouted_tactic: Optional[List[int]] = None, + prerouted_candidates: Optional[ + torch.Tensor] = None, + decode_tuning: bool = False, + decode_engine_state: Optional[torch.Tensor] = None, + lamport_fc2_out: Optional[torch.Tensor] = None, + decode_early_release_rows: int = 0, + decode_spare_sms: int = 0) -> List[torch.Tensor]: """``decode_tuning``: see ``FP4BlockScaleMoERunner.get_tuning_config``. + ``decode_engine_state``: the calling backend's decode MoE engine state + (``moe_persistent_engine.new_state``), which pre-routed calls need to take + the engine; ``decode_early_release_rows`` / + ``decode_spare_sms``: see ``FP4BlockScaleMoERunner``. ``lamport_fc2_out``: a ``decode_moe.LamportFc2Buffer`` tensor; with + ``do_finalize=False`` a call that takes ``ENGINE`` or ``CUTE_FC2`` writes + its FC2 rows there and returns an empty tensor in their place (an output + may not alias an input); a ``CUBIN`` call returns its own rows. + ``prerouted_tables`` (flat int32 routing tables), ``prerouted_ids`` / ``prerouted_weights`` (top-k ids, BF16 top-k weights), built for ``prerouted_tactic``'s tile (``lookup_tactic``): the op runs that tactic and skips its routing kernel; with ``do_finalize=False`` it then returns the FC2 rows only (the top-k weights and the expanded -> - permuted index are the caller's tensors).""" + permuted index are the caller's tensors). ``prerouted_candidates`` + (``PreroutedRouting.candidates``): the decode MoE engine writes those + tables, ids and weights itself.""" tuner = AutoTuner.get() kernel_runner = FP4BlockScaleMoERunner( @@ -768,6 +877,8 @@ def fp4_block_scale_moe_runner( tune_max_num_tokens=tune_max_num_tokens, use_dp=use_dp, decode_tuning=decode_tuning, + decode_early_release_rows=decode_early_release_rows, + decode_spare_sms=decode_spare_sms, ) # Prepare dummy topk tensors and hook for AutoTuner profiling @@ -828,9 +939,12 @@ def fp4_block_scale_moe_runner( prerouted_tables, hidden_states.shape[0], top_k, local_num_experts, prerouted_tactic[0]), prerouted_ids, - prerouted_weights)) + prerouted_weights), + engine_state=decode_engine_state, + lamport_out=lamport_fc2_out, + candidates=prerouted_candidates) if not do_finalize: - return [result[0]] + result = result[:1] else: kernel_runner, best_tactic = tuner.choose_one( "trtllm::fp4_block_scale_moe_runner", @@ -841,7 +955,14 @@ def fp4_block_scale_moe_runner( result = kernel_runner( input_tensors, tactic=[-1, -1] if best_tactic == -1 else best_tactic, - output=output) + output=output, + lamport_out=lamport_fc2_out) + # Rows written into the Lamport buffer come back as the empty placeholder + # (an output may not alias an input; moe_op_backend hands the buffer on). + if lamport_fc2_out is not None and not do_finalize: + from ..moe.fused_moe.trtllm_gen.decode_moe import rows_in_lamport + if rows_in_lamport(result[0], lamport_fc2_out): + return [result[0].new_empty(0), *result[1:]] # When output is provided and do_finalize=True, the result is written in-place to output. # Return empty tensor to avoid aliasing constraint violation in PyTorch 2.9.1+ # (custom op output cannot be the same tensor as input). @@ -851,6 +972,182 @@ def fp4_block_scale_moe_runner( return result +@torch.library.custom_op("trtllm::fp4_block_scale_moe_runner", mutates_args=()) +def fp4_block_scale_moe_runner( + routing_logits: Optional[torch.Tensor], + routing_bias: Optional[torch.Tensor], + hidden_states: torch.Tensor, + hidden_states_scale: torch.Tensor, + gemm1_weights: torch.Tensor, + gemm1_weights_scale: torch.Tensor, + gemm1_bias: torch.Tensor, + gemm1_alpha: torch.Tensor, + gemm1_beta: torch.Tensor, + gemm1_clamp_limit: torch.Tensor, + gemm2_weights: torch.Tensor, + gemm2_weights_scale: torch.Tensor, + gemm2_bias: torch.Tensor, + output1_scale_scalar: torch.Tensor, + output1_scale_gate_scalar: torch.Tensor, + output2_scale_scalar: torch.Tensor, + num_experts: int, + top_k: int, + n_group: Optional[int], + topk_group: Optional[int], + intermediate_size: int, + local_expert_offset: int, + local_num_experts: int, + routed_scaling_factor: Optional[float], + routing_method_type: int, + do_finalize: bool, + act_type: int = ActType_TrtllmGen.SwiGlu.value, + topk_weights: Optional[torch.Tensor] = None, + topk_ids: Optional[torch.Tensor] = None, + output: Optional[torch.Tensor] = None, + tune_max_num_tokens: int = 8192, + use_dp: bool = False, + prerouted_tables: Optional[torch.Tensor] = None, + prerouted_ids: Optional[torch.Tensor] = None, + prerouted_weights: Optional[torch.Tensor] = None, + prerouted_tactic: Optional[List[int]] = None, + decode_tuning: bool = False) -> List[torch.Tensor]: + """The TRTLLM-Gen NVFP4 MoE runner (see ``_run_fp4_block_scale_moe``); functional: it writes no argument + except ``output``, as on every model's path. The decode kernels that write state run in + ``fp4_block_scale_moe_decode_runner``.""" + return _run_fp4_block_scale_moe(routing_logits, + routing_bias, + hidden_states, + hidden_states_scale, + gemm1_weights, + gemm1_weights_scale, + gemm1_bias, + gemm1_alpha, + gemm1_beta, + gemm1_clamp_limit, + gemm2_weights, + gemm2_weights_scale, + gemm2_bias, + output1_scale_scalar, + output1_scale_gate_scalar, + output2_scale_scalar, + num_experts, + top_k, + n_group, + topk_group, + intermediate_size, + local_expert_offset, + local_num_experts, + routed_scaling_factor, + routing_method_type, + do_finalize, + act_type=act_type, + topk_weights=topk_weights, + topk_ids=topk_ids, + output=output, + tune_max_num_tokens=tune_max_num_tokens, + use_dp=use_dp, + prerouted_tables=prerouted_tables, + prerouted_ids=prerouted_ids, + prerouted_weights=prerouted_weights, + prerouted_tactic=prerouted_tactic, + decode_tuning=decode_tuning) + + +@torch.library.custom_op("trtllm::fp4_block_scale_moe_decode_runner", + mutates_args=("decode_engine_state", "lamport_fc2_out", + "prerouted_tables", "prerouted_ids", + "prerouted_weights")) +def fp4_block_scale_moe_decode_runner( + routing_logits: Optional[torch.Tensor], + routing_bias: Optional[torch.Tensor], + hidden_states: torch.Tensor, + hidden_states_scale: torch.Tensor, + gemm1_weights: torch.Tensor, + gemm1_weights_scale: torch.Tensor, + gemm1_bias: torch.Tensor, + gemm1_alpha: torch.Tensor, + gemm1_beta: torch.Tensor, + gemm1_clamp_limit: torch.Tensor, + gemm2_weights: torch.Tensor, + gemm2_weights_scale: torch.Tensor, + gemm2_bias: torch.Tensor, + output1_scale_scalar: torch.Tensor, + output1_scale_gate_scalar: torch.Tensor, + output2_scale_scalar: torch.Tensor, + num_experts: int, + top_k: int, + n_group: Optional[int], + topk_group: Optional[int], + intermediate_size: int, + local_expert_offset: int, + local_num_experts: int, + routed_scaling_factor: Optional[float], + routing_method_type: int, + do_finalize: bool, + act_type: int = ActType_TrtllmGen.SwiGlu.value, + topk_weights: Optional[torch.Tensor] = None, + topk_ids: Optional[torch.Tensor] = None, + output: Optional[torch.Tensor] = None, + tune_max_num_tokens: int = 8192, + use_dp: bool = False, + prerouted_tables: Optional[torch.Tensor] = None, + prerouted_ids: Optional[torch.Tensor] = None, + prerouted_weights: Optional[torch.Tensor] = None, + prerouted_tactic: Optional[List[int]] = None, + prerouted_candidates: Optional[torch.Tensor] = None, + decode_tuning: bool = False, + decode_engine_state: Optional[torch.Tensor] = None, + lamport_fc2_out: Optional[torch.Tensor] = None, + decode_early_release_rows: int = 0, + decode_spare_sms: int = 0) -> List[torch.Tensor]: + """``fp4_block_scale_moe_runner`` with the decode kernels a model declares (``decode_tuning``): the decode MoE + engine writes its call state, the Lamport FC2 rows and, when it routes the call, the pre-routed tables, ids and + weights. Under torch.compile it runs inside the opaque ``trtllm::moe_custom_op``.""" + return _run_fp4_block_scale_moe( + routing_logits, + routing_bias, + hidden_states, + hidden_states_scale, + gemm1_weights, + gemm1_weights_scale, + gemm1_bias, + gemm1_alpha, + gemm1_beta, + gemm1_clamp_limit, + gemm2_weights, + gemm2_weights_scale, + gemm2_bias, + output1_scale_scalar, + output1_scale_gate_scalar, + output2_scale_scalar, + num_experts, + top_k, + n_group, + topk_group, + intermediate_size, + local_expert_offset, + local_num_experts, + routed_scaling_factor, + routing_method_type, + do_finalize, + act_type=act_type, + topk_weights=topk_weights, + topk_ids=topk_ids, + output=output, + tune_max_num_tokens=tune_max_num_tokens, + use_dp=use_dp, + prerouted_tables=prerouted_tables, + prerouted_ids=prerouted_ids, + prerouted_weights=prerouted_weights, + prerouted_tactic=prerouted_tactic, + prerouted_candidates=prerouted_candidates, + decode_tuning=decode_tuning, + decode_engine_state=decode_engine_state, + lamport_fc2_out=lamport_fc2_out, + decode_early_release_rows=decode_early_release_rows, + decode_spare_sms=decode_spare_sms) + + def fp4_block_scale_fake_output_without_finalize( hidden_states: Union[torch.Tensor, Fp4QuantizedTensor], num_experts: int, @@ -877,44 +1174,55 @@ def fp4_block_scale_fake_output_without_finalize( ] -@fp4_block_scale_moe_runner.register_fake -def _(routing_logits, - routing_bias, - hidden_states, - hidden_states_scale, - gemm1_weights, - gemm1_weights_scale, - gemm1_bias, - gemm1_alpha, - gemm1_beta, - gemm1_clamp_limit, - gemm2_weights, - gemm2_weights_scale, - gemm2_bias, - output1_scale_scalar, - output1_scale_gate_scalar, - output2_scale_scalar, - num_experts, - top_k, - n_group, - topk_group, - intermediate_size, - local_expert_offset, - local_num_experts, - routed_scaling_factor, - routing_method_type, - do_finalize, - act_type, - topk_weights: Optional[torch.Tensor] = None, - topk_ids: Optional[torch.Tensor] = None, - output: Optional[torch.Tensor] = None, - tune_max_num_tokens: int = 8192, - use_dp: bool = False, - prerouted_tables: Optional[torch.Tensor] = None, - prerouted_ids: Optional[torch.Tensor] = None, - prerouted_weights: Optional[torch.Tensor] = None, - prerouted_tactic: Optional[List[int]] = None, - decode_tuning: bool = False) -> List[torch.Tensor]: +def _fp4_block_scale_moe_fake( + routing_logits, + routing_bias, + hidden_states, + hidden_states_scale, + gemm1_weights, + gemm1_weights_scale, + gemm1_bias, + gemm1_alpha, + gemm1_beta, + gemm1_clamp_limit, + gemm2_weights, + gemm2_weights_scale, + gemm2_bias, + output1_scale_scalar, + output1_scale_gate_scalar, + output2_scale_scalar, + num_experts, + top_k, + n_group, + topk_group, + intermediate_size, + local_expert_offset, + local_num_experts, + routed_scaling_factor, + routing_method_type, + do_finalize, + act_type, + topk_weights: Optional[torch.Tensor] = None, + topk_ids: Optional[torch.Tensor] = None, + output: Optional[torch.Tensor] = None, + tune_max_num_tokens: int = 8192, + use_dp: bool = False, + prerouted_tables: Optional[torch.Tensor] = None, + prerouted_ids: Optional[torch.Tensor] = None, + prerouted_weights: Optional[torch.Tensor] = None, + prerouted_tactic: Optional[List[int]] = None, + prerouted_candidates: Optional[torch.Tensor] = None, + decode_tuning: bool = False, + decode_engine_state: Optional[torch.Tensor] = None, + lamport_fc2_out: Optional[torch.Tensor] = None, + decode_early_release_rows: int = 0, + decode_spare_sms: int = 0) -> List[torch.Tensor]: + """The fake of both ops, registered for each with the decode op's parameters (their defaults are the plain op's); + the decode op's state arguments do not shape the outputs.""" + if lamport_fc2_out is not None: + # Whether the rows come back in the buffer depends on the kernel the + # host picks per call; the model hands the buffer in eager calls only. + raise NotImplementedError("the Lamport FC2 output is eager-only") if do_finalize: num_tokens = hidden_states.shape[0] hidden_size = hidden_states.shape[1] * 2 @@ -932,6 +1240,10 @@ def _(routing_logits, return outputs[:1] if prerouted_tables is not None else outputs +fp4_block_scale_moe_runner.register_fake(_fp4_block_scale_moe_fake) +fp4_block_scale_moe_decode_runner.register_fake(_fp4_block_scale_moe_fake) + + @dataclass(frozen=True) class FP8BlockScaleMoEInputs: diff --git a/tensorrt_llm/_torch/cute_dsl_utils.py b/tensorrt_llm/_torch/cute_dsl_utils.py index 29d345734c85..49fa7874a701 100644 --- a/tensorrt_llm/_torch/cute_dsl_utils.py +++ b/tensorrt_llm/_torch/cute_dsl_utils.py @@ -13,14 +13,18 @@ # See the License for the specific language governing permissions and # limitations under the License. +import functools import math import platform import sys import types -from typing import Optional +from typing import TYPE_CHECKING, Optional, Union from ..logger import logger +if TYPE_CHECKING: + import torch + def _skip_legacy_cutlass_mlir_helpers() -> None: """Keep Cutlass version discovery from importing its legacy helper tree.""" @@ -47,7 +51,7 @@ def _skip_legacy_cutlass_mlir_helpers() -> None: try: from cutlass import cute # noqa _skip_legacy_cutlass_mlir_helpers() - logger.info(f"cutlass dsl is available") + logger.info("cutlass dsl is available") IS_CUTLASS_DSL_AVAILABLE = True try: @@ -100,6 +104,26 @@ def gmem_ptr(tensor, dtype, assumed_align: int): assumed_align=assumed_align) +@functools.lru_cache(maxsize=None) +def _smem_optin_bytes(device_index: int) -> int: + import torch + + return torch.cuda.get_device_properties( + device_index).shared_memory_per_block_optin + + +def smem_optin_bytes( + device: Optional[Union[int, "torch.device"]] = None) -> int: + """A CTA's opt-in shared memory limit on ``device`` (default: the current CUDA device).""" + import torch + + if isinstance(device, torch.device): + device = device.index + if device is None: + device = torch.cuda.current_device() + return _smem_optin_bytes(device) + + def install_cutlass_dsl_compatibility() -> None: """Restore CuTe aliases required by pinned third-party FA4 and QuACK.""" if not IS_CUTLASS_DSL_AVAILABLE: diff --git a/tensorrt_llm/_torch/distributed/communicator.py b/tensorrt_llm/_torch/distributed/communicator.py index 5b938a98a812..bcb3ca5dec62 100644 --- a/tensorrt_llm/_torch/distributed/communicator.py +++ b/tensorrt_llm/_torch/distributed/communicator.py @@ -235,6 +235,18 @@ def broadcast_or_none(self, obj, root=0): return None return self.broadcast(obj, root=root) + def broadcast_or_none_with_header(self, obj, header: list[int], root=0): + """``broadcast_or_none`` plus a fixed-size int64 ``header`` that rides + with the "anything?" word, so it costs no extra round. + + ``header`` holds the root's values; other ranks pass a placeholder of + the same length. Returns ``(root's header, root's object or None)``. + """ + values = self.broadcast_int64([int(obj is not None), *header], + root=root) + received = self.broadcast(obj, root=root) if values[0] else None + return [int(v) for v in values[1:]], received + @abstractmethod def allgather(self, obj, root=0): pass @@ -1383,7 +1395,8 @@ def _cuda_broadcast_object(self, obj, pg, root: int, - allow_none: bool = False): + allow_none: bool = False, + header: Optional[list[int]] = None): """Broadcast a pickled object through CUDA staging. The root does not wait for the current call: size and payload are @@ -1404,11 +1417,16 @@ def _cuda_broadcast_object(self, every rank then skips the payload round and returns ``None``. Unambiguous because pickle never yields 0 bytes; without the flag ``None`` pickles like any other object. + + ``header``: int64 values (the root's; a same-length placeholder + elsewhere) sent in the size word's tensor; the call then returns + ``(root's header, object)``. """ is_root = torch.distributed.get_rank() == root with self._cuda_obj_guard(), self._cuda_obj_stream_ctx(): staging = self._cuda_obj_staging_for(pg) - size = staging["bcast_size"] + size, pinned_size = self._cuda_bcast_size_buffers( + staging, 1 + (len(header) if header is not None else 0)) if is_root: if allow_none and obj is None: data = b"" @@ -1421,8 +1439,10 @@ def _cuda_broadcast_object(self, # by stream order, the call before that's broadcast # kernels -- see the docstring). fence.synchronize() - pinned_size = staging["bcast_pinned_size"] pinned_size[0] = nbytes + if header is not None: + pinned_size[1:].copy_( + torch.as_tensor(header, dtype=torch.int64)) size.copy_(pinned_size, non_blocking=True) buf = None if nbytes: @@ -1442,15 +1462,33 @@ def _cuda_broadcast_object(self, dist.broadcast(size, src=root, group=pg) if buf is not None: dist.broadcast(buf, src=root, group=pg) - return obj + return obj if header is None else (list(header), obj) dist.broadcast(size, src=root, group=pg) - nbytes = int(size.cpu()) + received_size = size.cpu().tolist() + nbytes = received_size[0] if nbytes == 0: - return None + return None if header is None else (received_size[1:], None) buf = torch.empty(nbytes, dtype=torch.uint8, device="cuda") dist.broadcast(buf, src=root, group=pg) data = buf.cpu() - return pickle.loads(data.numpy().tobytes()) # nosec B301 + received = pickle.loads(data.numpy().tobytes()) # nosec B301 + return received if header is None else (received_size[1:], received) + + @staticmethod + def _cuda_bcast_size_buffers(staging: dict, width: int): + """The CUDA size word of a broadcast and its pinned host mirror: the + single word, or ``width`` words when a header rides along.""" + if width == 1: + return staging["bcast_size"], staging["bcast_pinned_size"] + key = ("bcast_header", width) + buffers = staging.get(key) + if buffers is None: + buffers = (torch.empty(width, dtype=torch.int64, device="cuda"), + torch.empty(width, + dtype=torch.int64, + pin_memory=prefer_pinned())) + staging[key] = buffers + return buffers @log_op def broadcast(self, obj, root=0, prefer_cpu=False): @@ -1496,6 +1534,17 @@ def broadcast_or_none(self, obj, root=0): allow_none=True) return super().broadcast_or_none(obj, root=root) + @log_op + def broadcast_or_none_with_header(self, obj, header: list[int], root=0): + vote_pg = self._cuda_obj_pg("world") if mpi_disabled() else None + if vote_pg is not None: + return self._cuda_broadcast_object(obj, + vote_pg, + root, + allow_none=True, + header=header) + return super().broadcast_or_none_with_header(obj, header, root=root) + @log_op def allgather(self, obj): vote_pg = self._cuda_obj_pg("world") diff --git a/tensorrt_llm/_torch/distributed/ll_exchange.py b/tensorrt_llm/_torch/distributed/ll_exchange.py index 21285322ac7a..2a320f41ec99 100644 --- a/tensorrt_llm/_torch/distributed/ll_exchange.py +++ b/tensorrt_llm/_torch/distributed/ll_exchange.py @@ -10,7 +10,9 @@ (``orderable_int32(v) = bits(v) if bits(v) >= 0 else bits(v) ^ 0x7FFFFFFF``, with -0.0 taken as +0.0), so the signed int64 maximum over the ranks is the global argmax and, among equal values, the lowest global index wins -- ``torch.argmax`` over the concatenated vocabulary. -``TPGroupExchange``: all-gather and all-to-all + LSE merge within TP subgroups (KV-replica split attention). +``TPGroupExchange``: all-gather and all-to-all + LSE merge within TP subgroups (KV-replica split attention). Its +words move as Lamport data: plain 32-bit words in receive slots that hold the sentinel 0xFFFFFFFF until written; a +reader polls until no word of its tile is the sentinel, then writes it back. Slot halves and epochs as below. TPKeyExchange protocol (NCCL LL-protocol style): each 32-bit half of a key travels as one 8-byte packet ``(epoch << 32) | word`` that the rank stores into every rank's receive slot; a reader polls @@ -38,13 +40,14 @@ from __future__ import annotations -from typing import Dict, Optional, Sequence, Tuple +from typing import Any, Dict, List, Optional, Sequence, Tuple import torch import triton import triton.language as tl from tensorrt_llm.logger import logger +from tensorrt_llm.mapping import Mapping from ..modules.fla.op import gdc_wait_with_memory_clobber @@ -59,10 +62,20 @@ _MERGE_GRID = 8 # Warps of alltoall_merge; 0: up to 4, one per 32 words of a row's poll tile. _MERGE_WARPS = 0 +# With argmax_row_split, argmax_logits launches up to 32 programs of 2 warps per row up to this many rows (Gumbel +# rows: from _ARGMAX_ROW_SPLIT_GUMBEL_MIN_ROWS), else ~2 (greedy) / ~8 (Gumbel) programs per SM in total. +_ARGMAX_ROW_SPLIT_MAX_ROWS = 512 +_ARGMAX_ROW_SPLIT_GUMBEL_MIN_ROWS = 15 # Constants read inside the Triton kernels must be constexpr globals. _LO_MASK = tl.constexpr(0xFFFFFFFF) _NEG_ZERO_BITS = tl.constexpr(-2147483648) # 0x80000000 as int32 (-0.0f) _INT64_MIN = tl.constexpr(-(2**63)) +_INT32_MAX = tl.constexpr(2147483647) +# Lamport words: an empty receive word, and what a data word equal to it (only NaN data) is sent as instead (NaN in +# every FP8 byte, both BF16 halves and as FP32). +LAMPORT_EMPTY = -1 +_LAMPORT_EMPTY = tl.constexpr(LAMPORT_EMPTY) +_LAMPORT_NAN = tl.constexpr(0x7FFFFFFF) def _block_m(m: int, max_rows: int) -> int: @@ -217,6 +230,117 @@ def _tp_key_exchange_kernel( ) +@triton.jit +def fast_gumbel_key( + logits_ptr, + stride_m, + v_shard, + temp_ptr, + seed_ptr, + row, + part, + vocab_offset, + vocab_full, + greedy_threshold, + split, + BLOCK_V: tl.constexpr, + SEED_OFFSET: tl.constexpr, +): + """The exchange key of chunk ``part`` of ``row`` under the four-draws Gumbel noise of seed + ``seed_ptr[0] + SEED_OFFSET`` (``_argmax_exchange_kernel``'s FAST_GUMBEL). ``split`` (programs per row) may be a + runtime value: a caller that launches at many row counts keeps one compiled kernel.""" + chunk = tl.cdiv(tl.cdiv(v_shard, split), BLOCK_V) * BLOCK_V # whole tiles + start = part * chunk + end = tl.minimum(start + chunk, v_shard) + row_ptr = logits_ptr + row.to(tl.int64) * stride_m + lanes = tl.arange(0, BLOCK_V) + lane_v = tl.full([BLOCK_V], float("-inf"), tl.float32) + lane_i = start + lanes + temperature = tl.load(temp_ptr + row).to(tl.float32) + if temperature >= greedy_threshold: + seed = tl.load(seed_ptr) + SEED_OFFSET + inv_t = 1.0 / temperature + base = (row * vocab_full + vocab_offset) // 4 + q = tl.arange(0, BLOCK_V // 4) + for off in range(start, end, BLOCK_V): + cols = off + lanes + x = tl.load(row_ptr + cols, mask=cols < end, other=float("-inf")) + xs = x.to(tl.float32) * inv_t + u0, u1, u2, u3 = tl.rand4x(seed, base + off // 4 + q) + u = tl.reshape(tl.join(tl.join(u0, u1), tl.join(u2, u3)), [BLOCK_V]) + u = tl.minimum(tl.maximum(u, 1e-12), 0.99999994) # strictly inside (0, 1) + xs = xs - tl.log(-tl.log(u)) + take = xs > lane_v + lane_v = tl.where(take, xs, lane_v) + lane_i = tl.where(take, cols, lane_i) + else: + for off in range(start, end, BLOCK_V): + cols = off + lanes + x = tl.load(row_ptr + cols, mask=cols < end, other=float("-inf")).to(tl.float32) + take = x > lane_v + lane_v = tl.where(take, x, lane_v) + lane_i = tl.where(take, cols, lane_i) + best_v = tl.max(lane_v, axis=0) + best_i = tl.min(tl.where(lane_v == best_v, lane_i, _INT32_MAX), axis=0) + return (_orderable_key_hi(best_v).to(tl.int64) << 32) | ( + _LO_MASK - (best_i.to(tl.int64) + vocab_offset) + ) + + +@triton.jit +def argmax_exchange_finish( + key, + row, + m, + max_out_ptr, + tok_out_ptr, + scratch_ptr, + ticket_ptr, + state_ptr, + pv, + rank, + split, + NRANKS: tl.constexpr, + WORDS: tl.constexpr, + BLOCK_M: tl.constexpr, + DO_MAX: tl.constexpr, + DO_TOKENS: tl.constexpr, +): + """Fold ``key`` into ``row``'s scratch key; the program that takes the last ticket swaps the keys + out (resetting the scratch and the ticket) and runs the exchange. Returns whether this program + took the last ticket. ``split`` (programs per row) may be a runtime value.""" + tl.atomic_max(scratch_ptr + row, key, sem="relaxed", scope="gpu") + ticket = tl.atomic_add(ticket_ptr, 1, sem="acq_rel", scope="gpu") + last = ticket == m * split - 1 + if last: + rows = tl.arange(0, BLOCK_M) + ok = rows < m + lo_mask = tl.full([BLOCK_M], _LO_MASK, tl.int64) + floor = tl.full([BLOCK_M], _INT64_MIN, tl.int64) + keys = tl.atomic_xchg(scratch_ptr + rows, floor, mask=ok, sem="acquire", scope="gpu") + tl.store(ticket_ptr, 0) + _ll_exchange_words( + (keys >> 32) & lo_mask, + keys & lo_mask, + rows, + ok, + m, + max_out_ptr, + tok_out_ptr, + tok_out_ptr, + state_ptr, + pv, + rank, + NRANKS, + WORDS, + BLOCK_M, + DO_MAX, + False, + DO_TOKENS, + ) + return last + + @triton.jit( do_not_specialize=[ "m", @@ -254,6 +378,7 @@ def _argmax_exchange_kernel( DO_TOKENS: tl.constexpr, WAIT: tl.constexpr, GUMBEL: tl.constexpr, + FAST_GUMBEL: tl.constexpr = False, ): """Global greedy argmax (or Gumbel-max sample) of vocabulary-sharded logits in one launch. @@ -267,67 +392,92 @@ def _argmax_exchange_kernel( ``GUMBEL``: rows with ``temp[row] >= greedy_threshold`` maximize ``logit / T + G`` instead, with ``G = -log(-log(u))``, ``u = tl.rand(seed, row * vocab_full + global index)`` clamped into (0, 1) -- the noise of a vocabulary entry does not depend on the sharding, so the global argmax - is a sample of softmax(logits / T); ``seed`` (int64 [1]) is read after the dependency wait.""" + is a sample of softmax(logits / T); ``seed`` (int64 [1]) is read after the dependency wait. + + ``FAST_GUMBEL`` (TPKeyExchange fast_gumbel; DO_MAX off): the Gumbel rows draw one Philox call per four entries + instead -- the noise of global entry ``4 * n + j`` of ``row`` is word ``(0, 2, 1, 3)[j]`` of ``philox(seed, + row * vocab_full / 4 + n)``, so the winner does not depend on the sharding, SPLIT or BLOCK_V. Lanes keep running + maxima; one reduction per program; SPLIT chunks are whole BLOCK_V tiles.""" pv = tl.load(peers_ptr + tl.arange(0, NRANKS)) # host-written table: ahead of the wait if WAIT: gdc_wait_with_memory_clobber() pid = tl.program_id(0) row = pid // SPLIT part = pid % SPLIT - chunk = tl.cdiv(v_shard, SPLIT) - start = part * chunk - end = tl.minimum(start + chunk, v_shard) - best_v = -float("inf") - best_i = start - if GUMBEL: - temperature = tl.load(temp_ptr + row).to(tl.float32) - sample = temperature >= greedy_threshold - seed = tl.load(seed_ptr) - for off in range(start, end, BLOCK_V): - cols = off + tl.arange(0, BLOCK_V) - x = tl.load( - logits_ptr + row.to(tl.int64) * stride_m + cols, mask=cols < end, other=-float("inf") - ).to(tl.float32) + if FAST_GUMBEL: + key = fast_gumbel_key( + logits_ptr, + stride_m, + v_shard, + temp_ptr, + seed_ptr, + row, + part, + vocab_offset, + vocab_full, + greedy_threshold, + SPLIT, + BLOCK_V, + 0, + ) + else: + chunk = tl.cdiv(v_shard, SPLIT) + start = part * chunk + end = tl.minimum(start + chunk, v_shard) + best_v = -float("inf") + best_i = start if GUMBEL: - if sample: - u = tl.rand(seed, row * vocab_full + vocab_offset + cols) - u = tl.minimum(tl.maximum(u, 1e-12), 0.99999994) # strictly inside (0, 1) - x = x / temperature - tl.log(-tl.log(u)) - v, i = tl.max(x, axis=0, return_indices=True, return_indices_tie_break_left=True) - take = v > best_v # strict: an earlier tile keeps a tie - best_i = tl.where(take, off + i, best_i) - best_v = tl.where(take, v, best_v) - key = (_orderable_key_hi(best_v).to(tl.int64) << 32) | ( - _LO_MASK - (best_i.to(tl.int64) + vocab_offset) - ) - tl.atomic_max(scratch_ptr + row, key, sem="relaxed", scope="gpu") - ticket = tl.atomic_add(ticket_ptr, 1, sem="acq_rel", scope="gpu") - if ticket == m * SPLIT - 1: - rows = tl.arange(0, BLOCK_M) - ok = rows < m - lo_mask = tl.full([BLOCK_M], _LO_MASK, tl.int64) - floor = tl.full([BLOCK_M], _INT64_MIN, tl.int64) - keys = tl.atomic_xchg(scratch_ptr + rows, floor, mask=ok, sem="acquire", scope="gpu") - tl.store(ticket_ptr, 0) - _ll_exchange_words( - (keys >> 32) & lo_mask, - keys & lo_mask, - rows, - ok, - m, - max_out_ptr, - tok_out_ptr, - tok_out_ptr, - state_ptr, - pv, - rank, - NRANKS, - WORDS, - BLOCK_M, - DO_MAX, - False, - DO_TOKENS, + temperature = tl.load(temp_ptr + row).to(tl.float32) + sample = temperature >= greedy_threshold + seed = tl.load(seed_ptr) + for off in range(start, end, BLOCK_V): + cols = off + tl.arange(0, BLOCK_V) + x = tl.load( + logits_ptr + row.to(tl.int64) * stride_m + cols, + mask=cols < end, + other=-float("inf"), + ).to(tl.float32) + if GUMBEL: + if sample: + u = tl.rand(seed, row * vocab_full + vocab_offset + cols) + u = tl.minimum(tl.maximum(u, 1e-12), 0.99999994) # strictly inside (0, 1) + x = x / temperature - tl.log(-tl.log(u)) + v, i = tl.max(x, axis=0, return_indices=True, return_indices_tie_break_left=True) + take = v > best_v # strict: an earlier tile keeps a tie + best_i = tl.where(take, off + i, best_i) + best_v = tl.where(take, v, best_v) + key = (_orderable_key_hi(best_v).to(tl.int64) << 32) | ( + _LO_MASK - (best_i.to(tl.int64) + vocab_offset) ) + argmax_exchange_finish( + key, + row, + m, + max_out_ptr, + tok_out_ptr, + scratch_ptr, + ticket_ptr, + state_ptr, + pv, + rank, + SPLIT, + NRANKS, + WORDS, + BLOCK_M, + DO_MAX, + DO_TOKENS, + ) + + +# Tile width of the four-draws Gumbel kernel. +_FAST_GUMBEL_BLOCK_V = 1024 + + +def _fast_gumbel_split(m: int, v_shard: int, num_sms: int) -> int: + """Programs per row of the four-draws Gumbel kernel: ~8 programs per SM in total, at most 64 per row.""" + return 2 * max( + 1, min(32, (4 * num_sms) // max(m, 1), triton.cdiv(v_shard, _FAST_GUMBEL_BLOCK_V)) + ) @triton.jit @@ -365,7 +515,8 @@ def unpack_argmax_tokens(keys: torch.Tensor) -> torch.Tensor: class _PeerBuffers: - """``nbytes`` per rank of a TP group, writable by every rank; zero-filled before ``create`` returns. + """``nbytes`` per rank of a TP group, writable by every rank; filled with byte ``fill`` (default 0) before + ``create`` returns. IPC memory inside a node; across the nodes of an NVLink domain unicast MNNVL memory (``TpMnnvlMemory``, no multicast object: NVLS multicast groups are a rack-wide NVSwitch resource and these exchanges only use the @@ -391,7 +542,7 @@ def close(self) -> None: del keep @classmethod - def create(cls, mapping, nbytes: int) -> Optional["_PeerBuffers"]: + def create(cls, mapping: Mapping, nbytes: int, fill: int = 0) -> Optional["_PeerBuffers"]: """Collective over the TP group (every rank must call it in step); None without peer memory.""" from tensorrt_llm._ipc_utils import IpcMemory, can_access_peer from tensorrt_llm._utils import mpi_disabled @@ -416,8 +567,21 @@ def create(cls, mapping, nbytes: int) -> Optional["_PeerBuffers"]: if not all(comm.allgather(ok)): del ipc return None - torch.cuda.synchronize() - comm.barrier() + error = None + try: + if fill: + from cuda.bindings import runtime as cudart + + (err,) = cudart.cudaMemset(ipc.local_ptr, fill, nbytes) + if err != cudart.cudaError_t.cudaSuccess: + raise RuntimeError(f"cudaMemset: {err}") + torch.cuda.synchronize() + except RuntimeError as e: + error = e + # Agreed before the barrier: every rank's buffer is filled before any rank writes into it. + if not cls._all_filled(comm, "IPC", error): + del ipc + return None return cls(ipc.local_ptr, ipc.peer_ptrs, nbytes, "IPC", ipc) try: mem = TpMnnvlMemory(mapping, nbytes) @@ -425,20 +589,59 @@ def create(cls, mapping, nbytes: int) -> Optional["_PeerBuffers"]: logger.warning(f"[ll_exchange] MNNVL peer buffers failed: {e}") return None peers = [mem.ptr + r * mem.rank_stride for r in range(mapping.tp_size)] - mem.as_torch_strided_tensor(torch.uint8)[mapping.tp_rank].zero_() - torch.cuda.synchronize() - comm.barrier() # every rank's buffer is zeroed before any rank writes into it + error = None + try: + mem.as_torch_strided_tensor(torch.uint8)[mapping.tp_rank].fill_(fill) + torch.cuda.synchronize() + except RuntimeError as e: + error = e + if not cls._all_filled(comm, "MNNVL", error): + del mem + return None return cls(peers[mapping.tp_rank], peers, nbytes, "MNNVL", mem) + @staticmethod + def failures(comm: Any, error: Optional[BaseException]) -> List[str]: + """Collective over ``comm`` (``TpMnnvlMemory.get_comm``): "rank r: " for every rank that passed an + error, the same list on every rank (empty when all succeeded).""" + errors = comm.allgather(None if error is None else str(error)) + return [f"rank {r}: {e}" for r, e in enumerate(errors) if e is not None] + + @staticmethod + def _all_filled(comm: Any, transport: str, error: Optional[BaseException]) -> bool: + """Every rank's fill outcome, agreed over the TP group (the barrier the writes wait for); on any failure + every rank logs each failed rank's cause and declines the buffers.""" + failed = _PeerBuffers.failures(comm, error) + if failed: + logger.warning( + f"[ll_exchange] {transport} peer buffer fill failed ({'; '.join(failed)})" + ) + return not failed + class TPKeyExchange: """Elementwise max / gather of ``M <= MAX_ROWS`` int64 keys per rank over a TP group, one launch.""" + fast_gumbel: bool = False + argmax_row_split: bool = False + def __init__( - self, rank: int, nranks: int, buffers: _PeerBuffers, num_channels: int, max_rows: int + self, + rank: int, + nranks: int, + buffers: _PeerBuffers, + num_channels: int, + max_rows: int, + fast_gumbel: bool = False, + argmax_row_split: bool = False, ): + """``fast_gumbel``: argmax_logits' temperature rows draw their Gumbel noise four entries per Philox call + (another noise stream than the default kernel's, so other tokens for a given seed). + ``argmax_row_split``: argmax_logits splits rows by _ARGMAX_ROW_SPLIT_* (same tokens, other launch shape).""" if nranks not in (2, 4, 8, 16) or len(buffers.peer_ptrs) != nranks: raise ValueError(f"unsupported exchange group: rank {rank} of {nranks}") + self.fast_gumbel = fast_gumbel + self.argmax_row_split = argmax_row_split self.rank = rank self.nranks = nranks self.num_channels = num_channels @@ -477,7 +680,12 @@ def close(self) -> None: @classmethod def create( - cls, mapping, max_rows: int, num_channels: int = _NUM_CHANNELS + cls, + mapping, + max_rows: int, + num_channels: int = _NUM_CHANNELS, + fast_gumbel: bool = False, + argmax_row_split: bool = False, ) -> Optional["TPKeyExchange"]: """Collective over the TP group; None where peer memory is unavailable (caller keeps NCCL). @@ -495,7 +703,15 @@ def create( ) if buffers is None: return None - return cls(mapping.tp_rank, mapping.tp_size, buffers, num_channels, max_rows) + return cls( + mapping.tp_rank, + mapping.tp_size, + buffers, + num_channels, + max_rows, + fast_gumbel, + argmax_row_split, + ) def _check(self, m: int, channel: int): if not 1 <= m <= self.MAX_ROWS: @@ -503,6 +719,27 @@ def _check(self, m: int, channel: int): if not 0 <= channel < self.num_channels: raise ValueError(f"channel {channel} out of range [0, {self.num_channels})") + def fast_gumbel_launch(self, m: int, v_shard: int, channel: int) -> tuple: + """For a kernel that runs ``fast_gumbel_key`` and ``argmax_exchange_finish`` itself (an + ``argmax_logits`` sample with its own epilogue): ``(grid, split, block_v, scratch, ticket, + state, peers, rank, nranks, words, block_m, pdl)`` of an ``m``-row call on ``channel``.""" + self._check(m, channel) + split = _fast_gumbel_split(m, v_shard, self._num_sms) + return ( + m * split, + split, + _FAST_GUMBEL_BLOCK_V, + self._scratch[channel], + self._ticket[channel:], + self._state[channel:], + self._peers[channel], + self.rank, + self.nranks, + self._words, + _block_m(m, self.MAX_ROWS), + self._pdl, + ) + def _launch( self, m, @@ -635,10 +872,68 @@ def argmax_logits( gumbel = temperature is not None if gumbel: assert seed is not None and seed.dtype == torch.int64 and temperature.numel() == m + if ( + gumbel + and self.fast_gumbel + and split is None + and max_out is None + and v_shard % 4 == 0 + and vocab_offset % 4 == 0 + ): + fsplit = _fast_gumbel_split(m, v_shard, self._num_sms) + if tokens_out is None: + tokens_out = torch.empty(m, dtype=torch.int32, device=logits.device) + _argmax_exchange_kernel[(m * fsplit,)]( + logits, + logits.stride(0), + v_shard, + self._state, + tokens_out, + self._scratch[channel], + self._ticket[channel:], + self._state[channel:], + self._peers[channel], + temperature.reshape(-1), + seed, + m, + self.rank, + vocab_offset, + v_shard * self.nranks, + float(greedy_threshold), + SPLIT=fsplit, + BLOCK_V=_FAST_GUMBEL_BLOCK_V, + NRANKS=self.nranks, + WORDS=self._words, + BLOCK_M=_block_m(m, self.MAX_ROWS), + DO_MAX=False, + DO_TOKENS=True, + WAIT=self._pdl, + GUMBEL=True, + FAST_GUMBEL=True, + num_warps=4, + launch_pdl=self._pdl, + ) + return tokens_out + num_warps = 4 if m <= 64 else 8 + block_v = None + # Every split draws the same tokens: an entry's noise depends only on (seed, row, global index) and ties go + # to the lowest index. + if split is None and self.argmax_row_split: + if m <= _ARGMAX_ROW_SPLIT_MAX_ROWS and not ( + gumbel and m < _ARGMAX_ROW_SPLIT_GUMBEL_MIN_ROWS + ): + split = max(1, min(32, triton.cdiv(v_shard, 256))) + block_v = 512 if gumbel else None + num_warps = 2 + elif gumbel: + # Gumbel-max rows cost Philox + two logs per entry rather than bytes: ~8 programs per SM in total, + # at most 32 per row, at least 1024 columns each. + split = max(1, min(32, (8 * self._num_sms) // m, triton.cdiv(v_shard, 1024))) if split is None: # ~2 programs per SM in total, at least 1 and at most 32 per row. split = max(1, min(32, (2 * self._num_sms) // m, triton.cdiv(v_shard, 256))) - block_v = max(16, min(4096, triton.next_power_of_2(triton.cdiv(v_shard, split)))) + if block_v is None: + block_v = max(16, min(4096, triton.next_power_of_2(triton.cdiv(v_shard, split)))) if tokens_out is None: tokens_out = torch.empty(m, dtype=torch.int32, device=logits.device) _argmax_exchange_kernel[(m * split,)]( @@ -667,12 +962,78 @@ def argmax_logits( DO_TOKENS=True, WAIT=self._pdl, GUMBEL=gumbel, - num_warps=4 if m <= 64 else 8, + num_warps=num_warps, launch_pdl=self._pdl, ) return tokens_out +# The Lamport protocol of the group exchanges (allgather, ll_pos_gather, alltoall_merge; the CuTe producers that push +# into a merge slot follow it too): a sender stores its words into every member's receive slot, a word equal to the +# empty sentinel sent as _LAMPORT_NAN; a receiver polls its slot until no word is empty, then empties it again. Each +# position (block / row) has its own epoch, a plain counter whose parity picks one of the two slot halves, so the +# next write to a half is two launches of the channel away. + + +@triton.jit +def _ll_word(words): + """``words`` as sent: the empty sentinel (only NaN data) goes out as another NaN.""" + return tl.where(words == _LAMPORT_EMPTY, _LAMPORT_NAN, words) + + +@triton.jit +def _ll_peer(pv, ar_g, d): + """Member ``d``'s receive region (int32 words) from the group's peer table ``pv`` [G].""" + return tl.sum(tl.where(ar_g == d, pv, 0)).to(tl.uint64).to(tl.pointer_type(tl.int32)) + + +@triton.jit +def _ll_half(epoch, G: tl.constexpr, SLOT_WORDS: tl.constexpr): + """Word offset of the slot half that ``epoch`` (its parity) selects.""" + return (epoch & 1).to(tl.int64) * (G * SLOT_WORDS) + + +@triton.jit +def _ll_empty_words(got, mask, MASKED: tl.constexpr): + """How many of the polled words ``got`` (where ``mask``, if ``MASKED``) have not arrived.""" + empty = got == _LAMPORT_EMPTY + if MASKED: + empty = empty & mask + return tl.sum(empty.to(tl.int32)) + + +@triton.jit +def _ll_reset(ptr, offs, got, mask, MASKED: tl.constexpr): + """Empty the received words again (``got``'s shape, where ``mask``, if ``MASKED``).""" + empty = tl.full(got.shape, _LAMPORT_EMPTY, tl.int32) + if MASKED: + tl.store(ptr + offs, empty, mask=mask) + else: + tl.store(ptr + offs, empty) + + +@triton.jit +def _ll_load(ptr, offs, mask, MASKED: tl.constexpr): + if MASKED: + got = tl.load(ptr + offs, mask=mask, other=0, volatile=True) + else: + got = tl.load(ptr + offs, volatile=True) + return got + + +@triton.jit +def _ll_poll(ptr, offs, mask, MASKED: tl.constexpr): + """The words at ``ptr + offs`` (where ``mask``, if ``MASKED``) once every one arrived; their slot is emptied + again.""" + got = _ll_load(ptr, offs, mask, MASKED) + waiting = _ll_empty_words(got, mask, MASKED) + while waiting > 0: + got = _ll_load(ptr, offs, mask, MASKED) + waiting = _ll_empty_words(got, mask, MASKED) + _ll_reset(ptr, offs, got, mask, MASKED) + return got + + @triton.jit def _ll_group_push( src_ptr, @@ -687,15 +1048,12 @@ def _ll_group_push( SLOT_WORDS: tl.constexpr, BLOCK: tl.constexpr, ): - slot = (epoch & 1).to(tl.int64) * (G * SLOT_WORDS) + slot_base - tag = epoch.to(tl.uint32, bitcast=True).to(tl.uint64) << 32 + slot = _ll_half(epoch, G, SLOT_WORDS) + slot_base w = block * BLOCK + tl.arange(0, BLOCK) ok = w < n_words - words = tl.load(src_ptr + w, mask=ok, other=0) - packet = (tag | words.to(tl.uint32, bitcast=True).to(tl.uint64)).to(tl.int64, bitcast=True) + lw = _ll_word(tl.load(src_ptr + w, mask=ok, other=0)) for d in tl.static_range(G): - dst = tl.sum(tl.where(ar_g == d, pv, 0)).to(tl.uint64).to(tl.pointer_type(tl.int64)) - tl.store(dst + slot + grank * SLOT_WORDS + w, packet, mask=ok) + tl.store(_ll_peer(pv, ar_g, d) + slot + grank * SLOT_WORDS + w, lw, mask=ok) @triton.jit @@ -711,23 +1069,19 @@ def _ll_group_poll( SLOT_WORDS: tl.constexpr, BLOCK: tl.constexpr, ): - slot = (epoch & 1).to(tl.int64) * (G * SLOT_WORDS) + slot = _ll_half(epoch, G, SLOT_WORDS) src_rank = tl.arange(0, G) w = block * BLOCK + tl.arange(0, BLOCK) ok = w < n_words offs = slot + src_rank[:, None].to(tl.int64) * SLOT_WORDS + w[None, :] mask = (src_rank[:, None] < G) & ok[None, :] - got = tl.load(mine + offs, mask=mask, other=0, volatile=True) - waiting = tl.sum((((got >> 32).to(tl.int32) != epoch) & mask).to(tl.int32)) - while waiting > 0: - got = tl.load(mine + offs, mask=mask, other=0, volatile=True) - waiting = tl.sum((((got >> 32).to(tl.int32) != epoch) & mask).to(tl.int32)) + got = _ll_poll(mine, offs, mask, True) row = w // row_words col = w % row_words out_offs = ( row[None, :].to(tl.int64) * out_row_stride + src_rank[:, None] * row_words + col[None, :] ) - tl.store(out_ptr + out_offs, got.to(tl.int32), mask=mask) + tl.store(out_ptr + out_offs, got, mask=mask) @triton.jit @@ -747,7 +1101,7 @@ def _ll_group_kernel( WAIT: tl.constexpr, TRIGGER: tl.constexpr, ): - """One launch of an LL all-gather of ``n_words`` 32-bit words per member. + """One launch of a Lamport all-gather of ``n_words`` 32-bit words per member. Words from member ``s`` land at ``out[(w // row_words) * out_row_stride + s * row_words + w % row_words]``. Every block of ``BLOCK`` words has its own epoch (``state_ptr[block]``) and slot @@ -763,7 +1117,7 @@ def _ll_group_kernel( tl.extra.cuda.gdc_launch_dependents() ar_g = tl.arange(0, G) pv = tl.load(peers_ptr + ar_g) - mine = tl.sum(tl.where(ar_g == grank, pv, 0)).to(tl.uint64).to(tl.pointer_type(tl.int64)) + mine = _ll_peer(pv, ar_g, grank) if WAIT: gdc_wait_with_memory_clobber() if TRIGGER == 2: @@ -787,10 +1141,18 @@ def _ll_group_kernel( BLOCK, ) _ll_group_poll( - out_ptr, mine, program, epoch, n_words, row_words, out_row_stride, G, SLOT_WORDS, BLOCK + out_ptr, + mine, + program, + epoch, + n_words, + row_words, + out_row_stride, + G, + SLOT_WORDS, + BLOCK, ) - nxt = epoch + 1 - tl.store(state_ptr + program, tl.where(nxt == 0, 2, nxt)) + tl.store(state_ptr + program, epoch + 1) else: for block in range(program, num_blocks, stride): epoch = tl.load(state_ptr + block, volatile=True) @@ -821,8 +1183,46 @@ def _ll_group_kernel( SLOT_WORDS, BLOCK, ) - nxt = epoch + 1 - tl.store(state_ptr + block, tl.where(nxt == 0, 2, nxt)) + tl.store(state_ptr + block, epoch + 1) + + +@triton.jit +def ll_pos_gather( + words, + pv, + state_ptr, + out_ptr, + pos, + row, + head, + grank, + G: tl.constexpr, + SLOT_WORDS: tl.constexpr, + W: tl.constexpr, + HQ: tl.constexpr, +): + """Lamport all-gather of this member's W words of position ``pos`` (= row * HQ + head) + inside a producer kernel (TPGroupExchange.rope_gather_args) into ``out`` [rows, G * HQ * W] words, member-major as + allgather. One epoch per position; the caller's grid must stay within one wave (every program polls).""" + epoch = tl.load(state_ptr + pos, volatile=True) + half = _ll_half(epoch, G, SLOT_WORDS) + w = tl.arange(0, W) + ar_g = tl.arange(0, G) + base = half + grank * SLOT_WORDS + pos.to(tl.int64) * W + offs = half + ar_g[:, None].to(tl.int64) * SLOT_WORDS + pos.to(tl.int64) * W + w[None, :] + mine = _ll_peer(pv, ar_g, grank) + lw = _ll_word(words) + for d in tl.static_range(G): + tl.store(_ll_peer(pv, ar_g, d) + base + w, lw) + got = _ll_poll(mine, offs, 0, False) + out_offs = ( + row.to(tl.int64) * (G * HQ * W) + + ar_g[:, None].to(tl.int64) * (HQ * W) + + head * W + + w[None, :] + ) + tl.store(out_ptr + out_offs, got) + tl.store(state_ptr + pos, epoch + 1) # alltoall_merge receive layout inside each (parity, source) slot of a channel: the O words of row position pos at @@ -873,6 +1273,10 @@ def _ll_merge_kernel( v_sp, state_ptr, # int32 [max_merge_rows]: one epoch per slot position (row * P + p) of the channel peers_ptr, # int64 [G]: the channel's region in every member's receive buffer + o8_ptr, # int16 view of the E4M3 out [T, Hh, D] (two elements per word, the lower one in the low byte) + o8_st, + o8_sh, + qs_ptr, # FP32 [1]: the consumer's static input scale s (OUT_FP8) rows, grank, HH: tl.constexpr, @@ -886,73 +1290,68 @@ def _ll_merge_kernel( HAS_VALID: tl.constexpr, WAIT: tl.constexpr, EARLY_TRIGGER: tl.constexpr, + OUT_FP8: tl.constexpr, + PUSH: tl.constexpr, ): """All-to-all of per-destination (O, LSE) partials + LSE-weighted merge (see alltoall_merge). Row r = t * HH + h; partial (source s, segment p) of row r sits at slot position r * P + p (O words at pos * DW, LSE word at LSE_BASE + pos), every position with its own epoch. Program q moves rows - q, q + grid, ... (push all, then poll + merge each).""" + q, q + grid, ... (push all, then poll + merge each). OUT_FP8: the BF16 result goes out as E4M3 the + way the consumer's static per-tensor quant writes it (scaleMatrixPerTensorVec: FP32(BF16) x (1 / s), + cvt.rn.satfinite; 1 / s as div.rn).""" if EARLY_TRIGGER: tl.extra.cuda.gdc_launch_dependents() ar_g = tl.arange(0, G) pv = tl.load(peers_ptr + ar_g) # host-written table: ahead of the wait - mine = tl.sum(tl.where(ar_g == grank, pv, 0)).to(tl.uint64).to(tl.pointer_type(tl.int64)) + mine = _ll_peer(pv, ar_g, grank) if WAIT: gdc_wait_with_memory_clobber() program = tl.program_id(0) stride = tl.num_programs(0) w = tl.arange(0, DW) - for r in range(program, rows, stride): + # PUSH False: the producer kernel already stored this member's words (merge_push_args) + for r in range(program, rows if PUSH else 0, stride): t = r // HH h = r % HH for p in tl.static_range(P): pos = r * P + p epoch = tl.load(state_ptr + pos, volatile=True) - tag = epoch.to(tl.uint32, bitcast=True).to(tl.uint64) << 32 - slot = (epoch & 1).to(tl.int64) * (G * SLOT_WORDS) + grank * SLOT_WORDS + slot = _ll_half(epoch, G, SLOT_WORDS) + grank * SLOT_WORDS for d in tl.static_range(G): - dst = tl.sum(tl.where(ar_g == d, pv, 0)).to(tl.uint64).to(tl.pointer_type(tl.int64)) + dst = _ll_peer(pv, ar_g, d) ow = tl.load(o_ptr + d * o_sd + p * o_sp + t * o_st + h * DW + w) - ow_p = (tag | ow.to(tl.uint32, bitcast=True).to(tl.uint64)).to( - tl.int64, bitcast=True - ) - tl.store(dst + slot + pos * DW + w, ow_p) lw = tl.load(lse_ptr + d * l_sd + p * l_sp + t * l_st + h) - lw_p = (tag | lw.to(tl.uint32, bitcast=True).to(tl.uint64)).to( - tl.int64, bitcast=True - ) - tl.store(dst + slot + LSE_BASE + pos, lw_p) + tl.store(dst + slot + pos * DW + w, _ll_word(ow)) + tl.store(dst + slot + LSE_BASE + pos, _ll_word(lw)) c = tl.arange(0, P * DW) # columns of a row's poll tile: partial c // DW, word c % DW cp = c // DW first = (c % DW) == 0 for r in range(program, rows, stride): t = r // HH h = r % HH - # [G, P * DW] tiles of the row's O packets and (column p * DW only) LSE packets, one owner thread per - # packet: racing volatile loads of thread-replicated data could disagree and make the loop exit - # non-uniform (barrier deadlock in the reductions). Masked-off LSE lanes read as "arrived". + # [G, P * DW] tiles of the row's O words and (column p * DW only) LSE words, one owner thread per word: + # racing volatile loads of thread-replicated data could disagree and make the loop exit non-uniform + # (barrier deadlock in the reductions). Masked-off LSE lanes read as "arrived". ecol = tl.load(state_ptr + r * P + cp, volatile=True) # epoch of each column's position - tagc = (ecol.to(tl.uint32, bitcast=True).to(tl.uint64) << 32).to(tl.int64, bitcast=True) - slotc = (ecol & 1).to(tl.int64) * (G * SLOT_WORDS) + slotc = _ll_half(ecol, G, SLOT_WORDS) src = ar_g.to(tl.int64) * SLOT_WORDS o_offs = slotc[None, :] + src[:, None] + r * (P * DW) + c[None, :] l_offs = slotc[None, :] + src[:, None] + LSE_BASE + r * P + cp[None, :] lm = first[None, :] & (ar_g[:, None] < G) - arrived = tagc[None, :] + tl.zeros([G, P * DW], dtype=tl.int64) + # arrived = not empty (masked-off LSE lanes read 0); read, then empty again. The next write to these words + # is two launches of the channel away, after this rank's next launch has pushed. got_o = tl.load(mine + o_offs, volatile=True) - got_l = tl.load(mine + l_offs, mask=lm, other=arrived, volatile=True) - waiting = tl.sum(((got_o >> 32).to(tl.int32) != ecol[None, :]).to(tl.int32)) + tl.sum( - ((got_l >> 32).to(tl.int32) != ecol[None, :]).to(tl.int32) - ) + got_l = tl.load(mine + l_offs, mask=lm, other=0, volatile=True) + waiting = _ll_empty_words(got_o, 0, False) + _ll_empty_words(got_l, 0, False) while waiting > 0: got_o = tl.load(mine + o_offs, volatile=True) - got_l = tl.load(mine + l_offs, mask=lm, other=arrived, volatile=True) - waiting = tl.sum(((got_o >> 32).to(tl.int32) != ecol[None, :]).to(tl.int32)) + tl.sum( - ((got_l >> 32).to(tl.int32) != ecol[None, :]).to(tl.int32) - ) - nxt = ecol + 1 - tl.store(state_ptr + r * P + cp, tl.where(nxt == 0, 2, nxt), mask=first) - # every column of partial p carries that partial's LSE (column p * DW holds the packet) + got_l = tl.load(mine + l_offs, mask=lm, other=0, volatile=True) + waiting = _ll_empty_words(got_o, 0, False) + _ll_empty_words(got_l, 0, False) + _ll_reset(mine, o_offs, got_o, 0, False) + _ll_reset(mine, l_offs, got_l, lm, True) + tl.store(state_ptr + r * P + cp, ecol + 1, mask=first) + # every column of partial p carries that partial's LSE (column p * DW holds the word) lbits = tl.where(lm, got_l.to(tl.int32), 0) lse_full = tl.zeros([G, P * DW], dtype=tl.float32) for p in tl.static_range(P): @@ -991,7 +1390,30 @@ def _ll_merge_kernel( gw = tl.load(gate_ptr + t * g_st + h * g_sh + w) res_lo = res_lo * tl.sigmoid(_bf16_lo(gw)) res_hi = res_hi * tl.sigmoid(_bf16_hi(gw)) - tl.store(out_ptr + t * out_st + h * out_sh + w, _bf16_pack(res_lo, res_hi)) + if OUT_FP8: + s = tl.load(qs_ptr + w * 0) + f = tl.inline_asm_elementwise( + "div.rn.f32 $0, 0f3F800000, $1;", + "=r,r", + [s], + dtype=tl.float32, + is_pure=True, + pack=1, + ) + q_lo = res_lo.to(tl.bfloat16).to(tl.float32) * f + q_hi = res_hi.to(tl.bfloat16).to(tl.float32) * f + # cvt ... d, a, b puts a in the upper byte: (hi, lo) keeps the lower element in the low byte + w8 = tl.inline_asm_elementwise( + "cvt.rn.satfinite.e4m3x2.f32 $0, $2, $1;", + "=h,r,r", + [q_lo, q_hi], + dtype=tl.int16, + is_pure=True, + pack=1, + ) + tl.store(o8_ptr + t * o8_st + h * o8_sh + w, w8) + else: + tl.store(out_ptr + t * out_st + h * out_sh + w, _bf16_pack(res_lo, res_hi)) if not EARLY_TRIGGER: # PDL invariant: released only after a CTA barrier that follows this program's last # global access (EARLY_TRIGGER is an opt-in for consumers that only read static data before their wait) @@ -1000,15 +1422,18 @@ def _ll_merge_kernel( class TPGroupExchange: - """One-launch LL all-gather and all-to-all + merge within groups of ``group_size`` consecutive TP + """One-launch all-gather and all-to-all + merge within groups of ``group_size`` consecutive TP ranks (members ``[g * G, (g + 1) * G)``), e.g. the 4 ranks of a tray sharing a KV head under TP8. - Data is moved as 32-bit words (per-row bytes must be a multiple of 4). Every member must issue - the same calls (same shapes, same channel order); channels are independent epoch counters for + Data is moved as 32-bit Lamport words (per-row bytes must be a multiple of 4, see the module docstring). Every + member must issue the same calls (same shapes, same channel order); channels are independent epoch counters for call sites that may overlap in time. Graph-safe; inputs are read after griddepcontrol.wait. Dependents are released at completion unless ``trigger`` says otherwise (see ``_ll_group_kernel``); a consumer always reads the exchange output only after its own griddepcontrol.wait.""" + # Head dim (bytes) of the in-kernel all-gathers (rope_gather_args); 0: none. + gather_head_dim: int = 0 + def __init__( self, mapping, @@ -1017,6 +1442,7 @@ def __init__( max_words: int, max_merge_rows: int, num_channels: int, + gather_head_dim: int = 0, ): self.group_size = group_size self.group = mapping.tp_rank // group_size @@ -1027,14 +1453,14 @@ def __init__( self.transport = buffers.transport self._buffers = buffers device = torch.device("cuda", torch.cuda.current_device()) - self.channel_bytes = 2 * group_size * max_words * 8 + self.channel_bytes = self.buffer_bytes(group_size, max_words, 1) members = [self.group * group_size + i for i in range(group_size)] table = [ [buffers.peer_ptrs[r] + c * self.channel_bytes for r in members] for c in range(num_channels) ] self._peers = torch.tensor(table, dtype=torch.int64, device=device) - # One epoch per (channel, block of 256 words); 0 = never sent, the first launch uses 1. + # One epoch per (channel, block of 256 words): a counter whose parity picks the slot half (starts at 1). self._state = torch.ones( (num_channels, triton.cdiv(max_words, 256)), dtype=torch.int32, device=device ) @@ -1043,6 +1469,13 @@ def __init__( self._merge_state = torch.ones( (num_channels, max_merge_rows), dtype=torch.int32, device=device ) + # pos_gather (rope_gather_args): one epoch per (channel, position of gather_head_dim bytes) of an all-gather + # done inside the producing kernel. + self.gather_head_dim = gather_head_dim + positions = max_words // (gather_head_dim // 4) if gather_head_dim >= 4 else 0 + self._pos_state = torch.ones( + (num_channels, max(1, positions)), dtype=torch.int32, device=device + ) self._channel_kind: Dict[int, str] = {} self._num_sms = torch.cuda.get_device_properties(device).multi_processor_count from ..flashinfer_utils import get_env_enable_pdl @@ -1064,19 +1497,44 @@ def is_supported(mapping, group_size: int) -> bool: and not mpi_disabled() ) + @staticmethod + def buffer_bytes(group_size: int, max_words: int, num_channels: int) -> int: + """Receive bytes per rank: per channel two slot halves of ``group_size`` source slots of ``max_words`` + words.""" + return num_channels * 2 * group_size * max_words * 4 + @classmethod def create( - cls, mapping, group_size: int, max_bytes: int, max_merge_rows: int, num_channels: int = 4 + cls, + mapping, + group_size: int, + max_bytes: int, + max_merge_rows: int, + num_channels: int = 4, + gather_head_dim: int = 0, ) -> Optional["TPGroupExchange"]: """Collective over the whole TP group. ``max_bytes``: largest per-(source, destination) payload; - ``max_merge_rows``: largest ``rows x P`` of one alltoall_merge (its LSE words share that payload).""" + ``max_merge_rows``: largest ``rows x P`` of one alltoall_merge (its LSE words share that payload); + ``gather_head_dim``: head dim (bytes) of the in-kernel all-gathers (rope_gather_args), 0 without them.""" if not cls.is_supported(mapping, group_size): return None max_words = max_bytes // 4 - buffers = _PeerBuffers.create(mapping, num_channels * 2 * group_size * max_words * 8) + buffers = _PeerBuffers.create( + mapping, + cls.buffer_bytes(group_size, max_words, num_channels), + fill=LAMPORT_EMPTY & 0xFF, + ) if buffers is None: return None - return cls(mapping, buffers, group_size, max_words, max_merge_rows, num_channels) + return cls( + mapping, + buffers, + group_size, + max_words, + max_merge_rows, + num_channels, + gather_head_dim, + ) def close(self) -> None: """Release the peer memory (every rank calls it after its last launch).""" @@ -1143,7 +1601,14 @@ def allgather( self, x: torch.Tensor, out: Optional[torch.Tensor] = None, channel: int = 0, trigger=False ) -> torch.Tensor: """``[rows, *rest]`` per member -> ``[rows, G * prod(rest)]`` (member-major along the last dim); - e.g. q ``[T, 4, 256]`` -> ``[T, 16 * 256]`` (view it as ``[T, 16, 256]``).""" + e.g. q ``[T, 4, 256]`` -> ``[T, 16 * 256]`` (view it as ``[T, 16, 256]``). FP32 / FP16 / BF16 / E4M3 / + E5M2 payloads only: a word equal to the empty-slot sentinel (all bits set: NaNs in each of these formats) + arrives as another NaN; in other dtypes (integers, float64, the fnuz / E8M0 / FP4 formats) the rewrite + would change a value.""" + if x.dtype not in _ALLGATHER_DTYPES: + raise ValueError( + f"allgather moves floating-point payloads whose all-ones words are NaN, got {x.dtype}" + ) assert x.is_contiguous() rows = x.shape[0] row_bytes = x[0].numel() * x.element_size() if rows else 0 @@ -1164,6 +1629,57 @@ def allgather( ) return out + def rope_gather_args( + self, channel: int, positions: int, head_dim: int + ) -> Tuple[torch.Tensor, torch.Tensor, int, int, int]: + """(peer table, epochs, member index, group size, slot words) for a kernel that all-gathers + ``positions`` FP8 heads of ``head_dim`` bytes of its own output through ll_pos_gather (the RoPE / FP8 kernel + pushing its q heads, fused_qkv_rope_gate_fp8_append_gather). The channel is reserved for this kind; the call + rules of allgather apply (same calls and shapes on every member).""" + self._use_channel(channel, "pos_gather") + if head_dim != self.gather_head_dim: + raise ValueError( + f"head dim {head_dim}: the exchange was created for {self.gather_head_dim}" + ) + if ( + not 0 < positions <= self._pos_state.shape[1] + or positions * (head_dim // 4) > self.max_words + ): + raise ValueError( + f"{positions} positions of head dim {head_dim} exceed the channel's " + f"{self._pos_state.shape[1]} positions or {self.max_words} words" + ) + return ( + self._peers[channel], + self._pos_state[channel], + self.grank, + self.group_size, + self.max_words, + ) + + def merge_push_args( + self, channel: int, positions: int, head_dim: int + ) -> Tuple[torch.Tensor, torch.Tensor, int, int, int]: + """(peer table, row epochs, member index, slot words, LSE base) for a producer kernel that + stores its alltoall_merge partials itself (the KV-replica partial attention's combine, ll_push), so the + following ``alltoall_merge(..., pushed=True)`` only polls and merges. ``positions``: rows x P of the call. + Layout as the merge's own push: slot half epoch & 1, source slot = member index, O words of position pos at + pos * D/2, its LSE at the LSE base + pos, as Lamport words.""" + self._use_channel(channel, "merge") + lse_base = self.max_words - self.max_merge_rows + # Checked before the producer pushes: alltoall_merge's own check comes after the remote writes. + if not 0 < positions <= self.max_merge_rows or positions * (head_dim // 2) > lse_base: + raise ValueError( + f"{positions} positions of head dim {head_dim} exceed the channel's merge slot" + ) + return ( + self._peers[channel], + self._merge_state[channel], + self.grank, + self.max_words, + lse_base, + ) + def alltoall_merge( self, o: torch.Tensor, @@ -1175,9 +1691,17 @@ def alltoall_merge( extra_o: Optional[torch.Tensor] = None, extra_lse: Optional[torch.Tensor] = None, valid: Optional[torch.Tensor] = None, + out_fp8: Optional[torch.Tensor] = None, + out_scale: Optional[torch.Tensor] = None, + pushed: bool = False, ) -> torch.Tensor: """All-to-all of LSE-weighted partials + their merge, one launch. + With ``out_fp8`` [T, Hh, D] E4M3 and ``out_scale`` (the consumer's static input scale s, FP32, one + element), the merged (gated) BF16 result is written there instead of ``out`` (which may then be None), + byte for byte as the consumer's own static per-tensor quant of it would (``FP32(BF16) x (1 / s)``, + cvt.rn.satfinite; 1 / s as div.rn), and ``out_fp8`` is returned. + ``o`` [G, P, T, Hh, D] BF16 (or [G, T, Hh, D] for P = 1) and ``lse`` [G, P, T, Hh] FP32 (base 2): this rank's ``P`` (1 or 2) partials for every member ``d``; any G / P / T strides, Hh / D dense (strides D, 1), LSE Hh stride 1. Member ``d`` merges, for its rows (t, h), the ``G * P`` partials it receives -- @@ -1199,6 +1723,11 @@ def alltoall_merge( ) _, P, T, HH, D = o.shape assert P in (1, 2), "1 or 2 partials per (member, row)" + if pushed and P != 1: + # merge_push_args' producer pushes one partial per (member, row): other slots would never be written. + raise ValueError( + f"alltoall_merge(pushed=True) takes one partial per (member, row), got {P}" + ) assert o.stride(4) == 1 and o.stride(3) == D, "o: Hh / D dims dense" assert D % 2 == 0 and (D // 2) & (D // 2 - 1) == 0 and D >= 32, ( "D / 2 must be a power of two >= 16" @@ -1207,9 +1736,30 @@ def alltoall_merge( tuple(lse.shape) == (G, P, T, HH) and lse.dtype == torch.float32 and lse.stride(3) == 1 ) assert all(st % 2 == 0 for st in o.stride()[:3]), "o: even BF16 strides" - assert ( - tuple(out.shape) == (T, HH, D) and out.dtype == torch.bfloat16 and out.stride(-1) == 1 - ) + fp8 = out_fp8 is not None + if fp8: + assert ( + tuple(out_fp8.shape) == (T, HH, D) + and out_fp8.dtype == torch.float8_e4m3fn + and out_fp8.stride(-1) == 1 + and all(st % 2 == 0 for st in out_fp8.stride()[:2]) + ), "out_fp8: [T, Hh, D] E4M3, D dense, even strides" + assert ( + out_scale is not None + and out_scale.dtype == torch.float32 + and out_scale.numel() == 1 + ), "out_scale: FP32, one element" + o8_w = out_fp8.view(torch.int16) + else: + o8_w = None + if out is not None: + assert ( + tuple(out.shape) == (T, HH, D) + and out.dtype == torch.bfloat16 + and out.stride(-1) == 1 + ) + else: + assert fp8, "out: [T, Hh, D] BF16 (None only with out_fp8)" rows = T * HH dw = D // 2 lse_base = self.max_words - self.max_merge_rows @@ -1218,11 +1768,14 @@ def alltoall_merge( f"alltoall_merge payload of {rows} rows x {P} partials x {D} exceeds the channel slot" ) if rows == 0: - return out + return out_fp8 if fp8 else out o_w = o.view(torch.int32) lse_w = lse.view(torch.int32) - out_w = out.view(torch.int32) + # with OUT_FP8 the BF16 store is compiled out: any int32 view serves as its pointer + out_w = out.view(torch.int32) if out is not None else o_w dummy_i = out_w + if o8_w is None: + o8_w = o_w.view(torch.int16) # unused (OUT_FP8 off) if gate is not None: gate = gate.view(T, HH, D) assert gate.dtype == torch.bfloat16 and gate.stride(-1) == 1 @@ -1279,6 +1832,10 @@ def alltoall_merge( valid.stride(1) if valid is not None else 0, self._merge_state[channel], self._peers[channel], + o8_w, + o8_w.stride(0) if fp8 else 0, + o8_w.stride(1) if fp8 else 0, + out_scale if fp8 else lse_w, rows, self.grank, HH=HH, @@ -1292,28 +1849,52 @@ def alltoall_merge( HAS_VALID=valid is not None, WAIT=self._pdl, EARLY_TRIGGER=bool(early) and self._pdl, + OUT_FP8=fp8, + PUSH=not pushed, # no thread replication of the [G, P * D/2] poll tiles (see the kernel) num_warps=merge_warps, launch_pdl=self._pdl, ) - return out + return out_fp8 if fp8 else out _GROUP_EXCHANGES: Dict[tuple, Optional[TPGroupExchange]] = {} +# Payload dtypes of TPGroupExchange.allgather: those whose all-ones words are NaN. +_ALLGATHER_DTYPES = ( + torch.float32, + torch.float16, + torch.bfloat16, + torch.float8_e4m3fn, + torch.float8_e5m2, +) + def get_tp_group_exchange( - mapping, group_size: int, max_bytes: int, max_merge_rows: int, num_channels: int + mapping, + group_size: int, + max_bytes: int, + max_merge_rows: int, + num_channels: int, + gather_head_dim: int = 0, ) -> Optional[TPGroupExchange]: """The TP subgroup exchange, created by the first call (collective over the TP group, not during graph capture) - with these sizes and channels; later calls return it as created.""" - key = (tuple(mapping.tp_group), mapping.tp_rank, group_size, torch.cuda.current_device()) + with these sizes and channels; later calls with the same group, channel count and in-kernel gather head dim + return it as created (each call checks its payload against the sizes it was created with).""" + key = ( + tuple(mapping.tp_group), + mapping.tp_rank, + group_size, + num_channels, + gather_head_dim, + torch.cuda.current_device(), + ) if key not in _GROUP_EXCHANGES: if torch.cuda.is_current_stream_capturing(): return None try: ex = TPGroupExchange.create( - mapping, group_size, max_bytes, max_merge_rows, num_channels + mapping, group_size, max_bytes, max_merge_rows, num_channels, gather_head_dim ) except (RuntimeError, ValueError) as e: # callers keep their path without the exchange logger.warning(f"[TPGroupExchange] setup failed: {e}") @@ -1329,13 +1910,24 @@ def get_tp_group_exchange( _EXCHANGES: Dict[tuple, Optional[TPKeyExchange]] = {} -def create_tp_key_exchange(mapping, max_rows: int) -> Optional[TPKeyExchange]: +def create_tp_key_exchange( + mapping, max_rows: int, fast_gumbel: bool = False, argmax_row_split: bool = False +) -> Optional[TPKeyExchange]: """Build the TP group's exchange for launches of up to ``max_rows`` keys (collective: every rank of the group - calls it in step, outside CUDA-graph capture); None where unsupported. A second call returns the first one's.""" - key = (tuple(mapping.tp_group), mapping.tp_rank, torch.cuda.current_device()) + calls it in step, outside CUDA-graph capture); None where unsupported. A second call returns the first one's. + ``fast_gumbel``, ``argmax_row_split``: see TPKeyExchange.""" + key = ( + tuple(mapping.tp_group), + mapping.tp_rank, + torch.cuda.current_device(), + fast_gumbel, + argmax_row_split, + ) if key not in _EXCHANGES: try: - ex = TPKeyExchange.create(mapping, max_rows) + ex = TPKeyExchange.create( + mapping, max_rows, fast_gumbel=fast_gumbel, argmax_row_split=argmax_row_split + ) except (RuntimeError, ValueError) as e: # callers keep the NCCL all-gather logger.warning(f"[TPKeyExchange] setup failed, keeping NCCL all-gather: {e}") ex = None diff --git a/tensorrt_llm/_torch/distributed/mnnvl_fused_allreduce.py b/tensorrt_llm/_torch/distributed/mnnvl_fused_allreduce.py index 8b3f7dd3afaa..7e24f9d0c1e8 100644 --- a/tensorrt_llm/_torch/distributed/mnnvl_fused_allreduce.py +++ b/tensorrt_llm/_torch/distributed/mnnvl_fused_allreduce.py @@ -16,11 +16,18 @@ * ``MnnvlAllReduceNorm``: all-reduce + residual + RMSNorm (+ FP8 output), optionally with the MoE fold ``routed + sigmoid(gate) * shared`` computed in-kernel (``routed`` finalized, or finalized in-kernel from - the fc2 rows). Calls below ``TWO_SHOT_ROWS`` rows run the - one-shot slot kernel on its own multicast workspace, larger ones the two-shot kernel on the library's Lamport - workspace and flags. Both produce the library op's outputs. + the fc2 rows). Calls of up to ``SLOT_MAX_ROWS`` rows run the + slot kernel on its own multicast workspace, larger ones the two-shot kernel on the library's Lamport + workspace and flags. Both produce the library op's outputs: bit for bit where the norm's reduction tree is the + library's (the two-shot arithmetic replays the library's launch shape; the slot kernel's one-shot sums over + ``SLOT_CTAS`` CTAs per token, the library one-shot's for few rows, e.g. up to 18 at H 4096 on 148 SMs), otherwise + the residual bit for bit and the norm within one BF16 ulp (the FP32 sum of squares added in another order). + Calls of ``TWO_SHOT_ROWS`` to ``SLOT_MAX_ROWS`` rows run the slot transport with the two-shot kernel's + arithmetic, so their outputs are the two-shot's. * ``GemmAllReduceNorm``: FP8 per-tensor row-parallel GEMM (low-M warp MMA) + one-shot all-reduce + residual + RMSNorm in one launch, on the library's Lamport workspace. +* ``GemmTwoShotAllReduceNorm``: the same for 17-128 rows with an E4M3 input: tcgen05 GEMM + two-shot all-reduce + (``kernels/blackwell/gemm_twoshot_allreduce_norm.py``), on the same workspace. The all-reduce kernels take the row count at run time and compile per static geometry; the GEMM kernel compiles per row count (at most ``GemmAllReduceNorm.MAX_ROWS``). @@ -34,22 +41,75 @@ import torch from tensorrt_llm._utils import is_blackwell_datacenter +from tensorrt_llm.mapping import Mapping from ..cute_dsl_utils import IS_CUTLASS_DSL_AVAILABLE, graph_safe_cute_tensor from ..flashinfer_utils import get_env_enable_pdl -# Rows from which a call takes the two-shot kernel. +# Rows from which a call takes the two-shot kernel's arithmetic (on the slot transport up to SLOT_MAX_ROWS rows, on +# the two-shot kernel above). TWO_SHOT_ROWS = 64 +# Largest call on the slot (one-shot) transport; from TWO_SHOT_ROWS on it runs the two-shot kernel's arithmetic. +SLOT_MAX_ROWS = 128 + + +@functools.lru_cache(maxsize=None) +def lib_norm_tree( + m: int, hidden: int, sms: int, elts: int = 8, group: int = 1 +) -> Tuple[int, int, int]: + """(block, cluster, loads per thread) of the library's rmsNormLamport launch for ``m`` tokens on ``sms`` SMs: + ``adjustGridConfig``, or the non-CGA ``adjustGridConfig`` that ``twoshotAllreduceFusionOp`` takes + unless that gives a cluster > 1 with one load per thread (mnnvlAllreduceKernels.cu). The one port of it: the + CuTe kernels' norm reduction trees (and outputs) match the library's bit for bit only for its launch shape.""" + + def div_up(a: int, b: int) -> int: + return -(-a // b) + + def adjust(use_cluster: bool) -> Tuple[int, int, int]: + cluster = 8 if use_cluster else 1 + need = div_up(hidden, elts) + loads = 1 + block = div_up(need, cluster) + if use_cluster: + while (need % cluster != 0 or div_up(need, cluster) % group != 0) and cluster > 1: + cluster //= 2 + max_div = cluster + block = div_up(need, cluster) + while block < 128 and cluster >= 2: + block, cluster = block * 2, cluster // 2 + while m * cluster > sms and cluster > 1 and block <= 512: + block, cluster = block * 2, cluster // 2 + while cluster < max_div: + cc = cluster * 2 + cb = div_up(need, cc) + if cb < 64 or cb % group != 0 or m * cc > sms: + break + cluster, block = cc, cb + while block > 1024: + if use_cluster and cluster < 8: + cluster <<= 1 + elif loads < 8: + loads += 1 + else: + break + block = div_up(need, cluster * loads) + while block % group != 0 and loads < 8: + loads += 1 + block = div_up(need, cluster * loads) + return block, cluster, loads + + block, cluster, loads = adjust(True) + if not (cluster > 1 and loads == 1): + block, cluster, loads = adjust(False) + return block, cluster, loads + + def _ctas_per_token(rows: int, hidden: int, sms: int) -> int: - """CTAs per token, as the library one-shot's ``adjustGridConfig`` picks them, so the norm's reduction - tree (and output) match the library bit for bit.""" - threads = hidden // 8 - ctas = 8 - while ctas > 1 and (threads // ctas < 64 or (threads // ctas) % 32 or rows * ctas > sms): - ctas //= 2 - return ctas + """CTAs per token of the library's norm launch for ``rows`` tokens (:func:`lib_norm_tree`'s cluster), so the + norm's reduction tree (and output) match the library bit for bit.""" + return lib_norm_tree(rows, hidden, sms)[1] def _tokens_per_cta(rows: int, ctas: int, sms: int) -> int: @@ -81,6 +141,7 @@ def _compiled_two_shot( quant: bool, moe_topk: int, fc2_row: int, + l2pf: bool = False, ): import cuda.bindings.driver as cuda import cutlass @@ -100,6 +161,7 @@ def _compiled_two_shot( moe_topk=moe_topk, fc2_row=fc2_row, tpc=tpc, + l2pf=l2pf, ) x, gate, w, scale, q, table = _example_operands(hidden, nranks) stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream) @@ -120,6 +182,9 @@ def _compiled_two_shot( cutlass.Int64(0), cutlass.Int64(0), cutlass.Int32(0), + cutlass.Int64(0), + cutlass.Int64(0), + cutlass.Int64(0), stream, ) @@ -137,6 +202,9 @@ def _compiled_slot( moe_topk: int, fc2_row: int, region_bytes: int, + l2pf: bool = False, + fc2_lamport: bool = False, + ts_ctas: int = 0, ): import cuda.bindings.driver as cuda import cutlass @@ -156,6 +224,9 @@ def _compiled_slot( region_bytes=region_bytes, moe_topk=moe_topk, fc2_row=fc2_row, + l2pf=l2pf, + fc2_lamport=fc2_lamport, + ts_ctas=ts_ctas, ) x, gate, w, scale, q, _ = _example_operands(hidden, nranks) stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream) @@ -179,10 +250,28 @@ def _compiled_slot( z, z, cutlass.Int32(0), + z, + z, + z, stream, ) +def _l2pf_args(weight: Optional[torch.Tensor], nblk: int) -> Tuple[bool, int, int, int]: + """(l2pf, ptr, bytes, bytes per CTA) for a launch of ``nblk`` CTAs that prefetches ``weight`` into L2, a + 16-byte aligned slice per CTA; no prefetch without a weight or for one whose address or size is not a 16-byte + multiple (the bulk prefetch requires both).""" + if weight is None or nblk <= 0: + return False, 0, 0, 0 + ptr = weight.data_ptr() + nbytes = weight.numel() * weight.element_size() + if ptr % 16 or nbytes % 16: + return False, 0, 0, 0 + per = -(-nbytes // nblk) + per = -(-per // 16) * 16 + return True, ptr, nbytes, per + + def _example_operands(hidden: int, nranks: int): """Operands with the compiled layouts (rows are runtime): x [M, H], gate [M], weight [H], scale [1], FP8 out [M, H] as uint8, workspace table [3 + W].""" @@ -279,7 +368,8 @@ class MnnvlAllReduceNorm: @staticmethod def is_supported(mapping, dtype: torch.dtype, hidden_size: int) -> bool: """BF16, TP 2 / 4 / 8 / 16 without attention DP, hidden sizes the slot kernel's 8 CTAs per token split - into whole warps; SM 10.0 / 10.3.""" + into a power-of-two count of whole warps (its norm sum is a butterfly over them); SM 10.0 / 10.3.""" + warps_per_cta = hidden_size // 2048 return ( IS_CUTLASS_DSL_AVAILABLE and is_blackwell_datacenter() @@ -287,6 +377,7 @@ def is_supported(mapping, dtype: torch.dtype, hidden_size: int) -> bool: and mapping.tp_size in (2, 4, 8, 16) and not mapping.enable_attention_dp and hidden_size % 2048 == 0 + and warps_per_cta & (warps_per_cta - 1) == 0 and hidden_size // 64 <= 1024 ) @@ -300,7 +391,7 @@ def __init__(self, mapping, comm, hidden_size: int, table: _LamportTable): self._sms = props.multi_processor_count self._smem_bytes = props.shared_memory_per_block_optin self._sm_smem_bytes = props.shared_memory_per_multiprocessor - self.slot = _SlotWorkspace(mapping, comm, hidden_size, self.SLOT_CTAS, TWO_SHOT_ROWS) + self.slot = _SlotWorkspace(mapping, comm, hidden_size, self.SLOT_CTAS, SLOT_MAX_ROWS) dev = table.table.device # Never-read operands of the compiled signature (gate, FP8 out, scale); rows are runtime values. # zeros, not empty: models are built under MetaInitMode, which turns torch.empty into meta tensors @@ -310,11 +401,11 @@ def __init__(self, mapping, comm, hidden_size: int, table: _LamportTable): self._unused_scale = torch.zeros((1,), dtype=torch.float32, device=dev) def supports_rows(self, rows: int) -> bool: - """Whether one launch takes ``rows`` tokens: below TWO_SHOT_ROWS the slot workspace holds them, above it + """Whether one launch takes ``rows`` tokens: up to SLOT_MAX_ROWS the slot workspace holds them, above it the shared memory of a CTA holds its tokens' residuals and an SM holds both of its 512-thread CTAs.""" if rows <= 0: return False - if rows < TWO_SHOT_ROWS: + if rows <= SLOT_MAX_ROWS: return True ctas = _ctas_per_token(rows, self.hidden, self._sms) if self.hidden // 8 // ctas > 1024: @@ -359,12 +450,20 @@ def __call__( moe_fold: Optional[Tuple] = None, scale: Optional[torch.Tensor] = None, norm_out: bool = True, + l2_prefetch: Optional[torch.Tensor] = None, + fc2_lamport: bool = False, ) -> Tuple[torch.Tensor, ...]: """Input ``x`` [M, H] BF16, or ``moe_fold`` = (routed, shared [M, H], gate logits [M] / [M, 1]) giving ``routed + sigmoid(gate) * shared``. ``routed`` is the finalized routed output [M, H] BF16, or the un-finalized (fc2 [P, >= H] BF16, topk_weights [M, K] BF16, expanded_idx_to_permuted_idx [M, K] int32), finalized in-kernel. + ``l2_prefetch``: a contiguous CUDA tensor the launch pulls into L2 after its pushes (the next GEMM's weight). + + ``fc2_lamport``: the un-finalized fc2 is a Lamport FC2 buffer (``decode_moe.LamportFc2Buffer``): the fold polls + the rows it reads instead of waiting for FC2 and writes them back to 0xFFFFFFFF. The caller fences the shared + expert's stream before this launch, so the shared output and gate are read without a dependency wait. + Returns ``(norm, residual_out)``, ``(norm, fp8, residual_out)`` with ``scale``, or ``(fp8, residual_out)`` with ``scale`` and ``norm_out=False``, as the library op.""" import cuda.bindings.driver as cuda @@ -374,7 +473,12 @@ def __call__( nranks = self.mapping.tp_size m = residual.shape[0] topk = fc2_row = 0 + lamport = False fc2_ptr = topw_ptr = perm_ptr = 0 + if fc2_lamport and (moe_fold is None or isinstance(moe_fold[0], torch.Tensor)): + raise ValueError( + "fc2_lamport needs the un-finalized MoE fold (fc2 rows, top-k weights, permutation)" + ) if moe_fold is not None: routed, shared, gate = moe_fold if isinstance(routed, torch.Tensor): @@ -383,6 +487,7 @@ def __call__( fc2, topw, perm = routed assert perm.shape[0] == m and self.moe_fold_supported(fc2, topw, perm, hidden) topk, fc2_row = perm.shape[1], fc2.stride(0) + lamport = fc2_lamport fc2_ptr, topw_ptr, perm_ptr = ( fc2.data_ptr(), topw.contiguous().data_ptr(), @@ -413,11 +518,19 @@ def __call__( ) folds = moe_fold is not None stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream) - if m < TWO_SHOT_ROWS: + if m <= SLOT_MAX_ROWS: slot = self.slot + # from TWO_SHOT_ROWS on: the two-shot kernel's arithmetic for its CTA split at m (one token per CTA there) + ts = 0 + if m >= TWO_SHOT_ROWS: + ts = _ctas_per_token(m, hidden, self._sms) + assert _tokens_per_cta(m, ts, self._sms) == 1, ( + f"two-shot arithmetic at {m} rows: one token per CTA" + ) + l2pf, pf_ptr, pf_bytes, pf_per = _l2pf_args(l2_prefetch, m * self.SLOT_CTAS) fn = _compiled_slot( hidden, float(eps), nranks, self.SLOT_CTAS, self._pdl, folds, norm_out, - scale is not None, topk, fc2_row, slot.region_bytes, + scale is not None, topk, fc2_row, slot.region_bytes, l2pf, lamport, ts, ) # fmt: skip fn( *operands, @@ -428,15 +541,26 @@ def __call__( cutlass.Int64(topw_ptr), cutlass.Int64(perm_ptr), cutlass.Int32(self.mapping.tp_rank), + cutlass.Int64(pf_ptr), + cutlass.Int64(pf_bytes), + cutlass.Int64(pf_per), stream, ) else: # Two stages of max(scatter, broadcast) each. table = self.table(2 * ((m + nranks - 1) // nranks) * nranks * hidden * 2) ctas = _ctas_per_token(m, hidden, self._sms) + tpc = _tokens_per_cta(m, ctas, self._sms) + l2pf, pf_ptr, pf_bytes, pf_per = _l2pf_args( + l2_prefetch, -(-m // tpc) if tpc > 1 else m * ctas + ) + if lamport: + raise RuntimeError( + f"Lamport FC2 rows are folded by the slot kernel, up to {SLOT_MAX_ROWS} rows ({m} given)" + ) fn = _compiled_two_shot( - hidden, float(eps), nranks, ctas, _tokens_per_cta(m, ctas, self._sms), self._pdl, - folds, norm_out, scale is not None, topk, fc2_row, + hidden, float(eps), nranks, ctas, tpc, self._pdl, + folds, norm_out, scale is not None, topk, fc2_row, l2pf, ) # fmt: skip fn( *operands, @@ -445,6 +569,9 @@ def __call__( cutlass.Int64(topw_ptr), cutlass.Int64(perm_ptr), cutlass.Int32(self.mapping.tp_rank), + cutlass.Int64(pf_ptr), + cutlass.Int64(pf_bytes), + cutlass.Int64(pf_per), stream, ) if scale is None: @@ -642,3 +769,77 @@ def __call__( if norm_out: return norm, quant, res_out return quant, res_out + + +class GemmTwoShotAllReduceNorm: + """Row-parallel FP8 ``x @ W.T`` (tcgen05, E4M3 x) + two-shot all-reduce + residual + RMSNorm in one launch, for + the rows where the library all-reduce runs two-shot (above ``one_shot_threshold_bytes`` of BF16 message) up to + the kernel's MAX_ROWS.""" + + @staticmethod + def is_supported(mapping: Mapping, dtype: torch.dtype, hidden_size: int) -> bool: + """As ``MnnvlAllReduceNorm``, and the kernel takes the hidden size and TP group (``supports_hidden``).""" + from ..kernels.blackwell import gemm_twoshot_allreduce_norm as kern + + sms = torch.cuda.get_device_properties(torch.cuda.current_device()).multi_processor_count + return MnnvlAllReduceNorm.is_supported( + mapping, dtype, hidden_size + ) and kern.supports_hidden(hidden_size, mapping.tp_size, sms) + + def __init__( + self, + mapping: Mapping, + hidden_size: int, + table: _LamportTable, + one_shot_threshold_bytes: int, + ) -> None: + from ..kernels.blackwell import gemm_twoshot_allreduce_norm as kern + + self.mapping = mapping + self.hidden = hidden_size + self.table = table + self.min_rows = one_shot_threshold_bytes // (hidden_size * mapping.tp_size * 2) + 1 + self.max_rows = kern.MAX_ROWS + self._sms = torch.cuda.get_device_properties(table.table.device).multi_processor_count + + def supports(self, x: torch.Tensor, weight: torch.Tensor) -> bool: + from ..kernels.blackwell import gemm_twoshot_allreduce_norm as kern + + return ( + x.dim() == 2 + and x.shape[0] <= self.max_rows + and kern.supports( + x, weight, self.hidden, self.mapping.tp_size, self._sms, self.min_rows + ) + ) + + def takes(self, m: int, weight: torch.Tensor) -> bool: + """Whether a call of ``m`` rows with this weight fits, whatever its activation (checked before a BF16 + input is quantized).""" + from ..kernels.blackwell import gemm_twoshot_allreduce_norm as kern + + return m <= self.max_rows and kern.supports_problem( + m, weight, self.hidden, self.mapping.tp_size, self._sms, self.min_rows + ) + + def __call__( + self, + x: torch.Tensor, + weight: torch.Tensor, + weight_scale: torch.Tensor, + input_scale: torch.Tensor, + residual: torch.Tensor, + norm_weight: torch.Tensor, + eps: float, + scale: Optional[torch.Tensor] = None, + norm_out: bool = True, + ) -> Tuple[torch.Tensor, ...]: + """Outputs of ``MnnvlAllReduceNorm.__call__``.""" + from ..kernels.blackwell import gemm_twoshot_allreduce_norm as kern + + m = x.shape[0] + table = self.table(kern.workspace_bytes(m, self.hidden)) + return kern.gemm_twoshot_allreduce_norm( + x, weight, weight_scale, input_scale, residual.contiguous(), norm_weight, eps, table, + self.mapping.tp_rank, self.mapping.tp_size, scale=scale, norm_out=norm_out, + ) # fmt: skip diff --git a/tensorrt_llm/_torch/distributed/ops.py b/tensorrt_llm/_torch/distributed/ops.py index d54c60468dc9..98ce4c7e9b1d 100644 --- a/tensorrt_llm/_torch/distributed/ops.py +++ b/tensorrt_llm/_torch/distributed/ops.py @@ -877,6 +877,9 @@ class MNNVLAllReduce(nn.Module): # (mapping, hidden size), built with the first module of that pair; they share its workspace. fused_norm_kernels: typing.ClassVar[dict[tuple[Mapping, int], tuple]] = {} + # The GEMM + two-shot all-reduce + norm kernel (GemmTwoShotAllReduceNorm) on fused_norm's table, or None. + gemm_twoshot = None + SUPPORTED_FUSION_OPS: frozenset[AllReduceFusionOp] = frozenset({ AllReduceFusionOp.RMS_NORM, AllReduceFusionOp.RESIDUAL_RMS_NORM, @@ -954,6 +957,7 @@ def __init__(self, # (see _fused_norm_call). self.fused_norm: Optional[MnnvlAllReduceNorm] = None self.gemm_norm: Optional[GemmAllReduceNorm] = None + self.gemm_twoshot = None if fused: key = (mapping, hidden_size) if key not in MNNVLAllReduce.fused_norm_kernels: @@ -973,6 +977,13 @@ def __init__(self, MNNVLAllReduce.fused_norm_kernels[key] = kernels self.fused_norm, self.gemm_norm = MNNVLAllReduce.fused_norm_kernels[ key] + if self.fused_norm is not None: + from .mnnvl_fused_allreduce import GemmTwoShotAllReduceNorm + if GemmTwoShotAllReduceNorm.is_supported( + mapping, dtype, hidden_size): + self.gemm_twoshot = GemmTwoShotAllReduceNorm( + mapping, hidden_size, self.fused_norm.table, + _MNNVL_ONE_SHOT_THRESHOLD_BYTES) @staticmethod def get_supported_dtypes(): @@ -1221,7 +1232,8 @@ def _fused_norm_call(self, input: torch.Tensor, params: AllReduceParams, params.eps, x=input, scale=params.scale if quant else None, - norm_out=norm_out) + norm_out=norm_out, + l2_prefetch=params.l2_prefetch) def supports_moe_fold(self, num_tokens: int, hidden_size: int) -> bool: """Whether ``forward`` takes MoEAllReduceParams (shared-expert gate combine, optionally with the @@ -1240,6 +1252,10 @@ def _moe_fold_call( shared = params.shared_expert_output if (outputs is None or shared is None or not self.supports_moe_fold(shared.shape[0], shared.shape[-1])): + if params.fc2_lamport: + # Only this fold resets the Lamport rows the experts wrote. + raise ValueError( + "Lamport FC2 rows need the MoE fold of this all-reduce") return None if params.expanded_idx_to_permuted_idx is not None: routed = (routed, params.expert_scale_factor, @@ -1251,7 +1267,9 @@ def _moe_fold_call( moe_fold=(routed, params.shared_expert_output, params.shared_expert_gate), scale=params.scale if quant else None, - norm_out=norm_out) + norm_out=norm_out, + l2_prefetch=params.l2_prefetch, + fc2_lamport=params.fc2_lamport) def gemm_allreduce_norm(self, input: torch.Tensor, weight: torch.Tensor, weight_scale: torch.Tensor, @@ -1279,9 +1297,47 @@ def gemm_allreduce_norm(self, input: torch.Tensor, weight: torch.Tensor, scale=params.scale if quant else None, norm_out=norm_out) + def gemm_twoshot_allreduce_norm( + self, input: torch.Tensor, weight: torch.Tensor, + weight_scale: torch.Tensor, input_scale: torch.Tensor, + params: AllReduceParams) -> Optional[Tuple[torch.Tensor, ...]]: + """Row-parallel FP8 GEMM ``input @ weight.T`` + this all-reduce + ``params``' residual RMSNorm fusion in one + launch for the rows GemmTwoShotAllReduceNorm takes, or None. A BF16 input (the gated-attention o_proj) is + quantized with ``input_scale`` first, by the call FP8QDQLinearMethod.apply makes before cuBLAS. The kernel + exchanges BF16, so an E4M3-payload call (``params.fp8_payload``) stays on the library two-shot.""" + kern = self.gemm_twoshot + outputs = self._FUSED_NORM_OUTPUTS.get(params.fusion_op) + if (kern is None or outputs is None or params.bias is not None + or params.fp8_payload or weight.shape[0] != kern.hidden): + return None + if input.dtype == torch.bfloat16: + if (input.dim() != 2 or input.shape[1] != weight.shape[-1] + or not kern.takes(input.shape[0], weight)): + return None + input, _ = torch.ops.tensorrt_llm.static_quantize_e4m3_per_tensor( + input, input_scale) + if not kern.supports(input, weight): + return None + quant, norm_out = outputs + return kern(input, + weight, + weight_scale, + input_scale, + params.residual, + params.norm_weight, + params.eps, + scale=params.scale if quant else None, + norm_out=norm_out) + class AllReduce(nn.Module): + # TP2 residual RMSNorm fusion kernel, when the model declares allreduce_tp2_fused_norm. + tp2_allreduce = None + # (mapping, hidden, max tokens) -> the mapping's Tp2AllReduceNorm (built collectively once), or None where its + # setup failed. + tp2_fused_norm_kernels: typing.ClassVar[dict] = {} + def __init__(self, mapping: Mapping, strategy: AllReduceStrategy = AllReduceStrategy.AUTO, @@ -1334,6 +1390,7 @@ def __init__(self, self.workspace = None self.strategy = strategy self.mnnvl_allreduce = None + self.tp2_allreduce = None self.symm_mem_allreduce = None self._disable_mpi = mpi_disabled() self._group_name = (mapping.tp_group_name @@ -1356,7 +1413,11 @@ def __init__(self, fused_norm = bool( extra_attrs and extra_attrs.get("allreduce_mnnvl_fused_norm", False)) + # Declared by the model: a TP2 group without MNNVL runs large residual RMSNorm fusions on Tp2AllReduceNorm. + tp2_fused_norm = bool( + extra_attrs and extra_attrs.get("allreduce_tp2_fused_norm", False)) fused_norm_max_num_tokens = fused_norm_hidden_size = None + max_num_tokens = hidden_size = None if extra_attrs: from tensorrt_llm._torch.custom_ops.torch_custom_ops import \ AllReduceRunner @@ -1437,6 +1498,28 @@ def __init__(self, ) self.mnnvl_allreduce = None + # AUTO, or TWOSHOT (the kernel is a reduce-scatter + all-gather); other strategies run as chosen. + if (tp2_fused_norm and self.strategy in (AllReduceStrategy.AUTO, + AllReduceStrategy.TWOSHOT) + and self.mapping.tp_size == 2 and not self._disable_mpi + and self.mnnvl_allreduce is None + and dtype in (None, torch.bfloat16) + and hidden_size is not None and max_num_tokens is not None): + from .tp2_allreduce import Tp2AllReduceNorm + if Tp2AllReduceNorm.is_supported(self.mapping, hidden_size, + max_num_tokens): + key = (self.mapping, hidden_size, max_num_tokens) + if key not in AllReduce.tp2_fused_norm_kernels: + kernel = None + try: + kernel = Tp2AllReduceNorm(self.mapping, hidden_size, + max_num_tokens) + except RuntimeError as error: # raised on every rank + logger.warning( + f"[TP2 all-reduce] unavailable: {error}") + AllReduce.tp2_fused_norm_kernels[key] = kernel + self.tp2_allreduce = AllReduce.tp2_fused_norm_kernels[key] + def supports_moe_fold(self, num_tokens: int, hidden_size: int) -> bool: """Whether ``forward`` takes MoEAllReduceParams for ``num_tokens`` tokens: the routed MoE output (finalized, or the un-finalized fc2 rows) with the shared expert and its gate, folded in-kernel.""" @@ -1458,6 +1541,17 @@ def gemm_allreduce_norm(self, input: torch.Tensor, weight: torch.Tensor, all_reduce_params, gemm_tactic) + def gemm_twoshot_allreduce_norm( + self, input: torch.Tensor, weight: torch.Tensor, + weight_scale: torch.Tensor, input_scale: torch.Tensor, + all_reduce_params: AllReduceParams + ) -> Optional[Tuple[torch.Tensor, ...]]: + """See ``MNNVLAllReduce.gemm_twoshot_allreduce_norm``; None without the MNNVL kernels.""" + if self.mnnvl_allreduce is None: + return None + return self.mnnvl_allreduce.gemm_twoshot_allreduce_norm( + input, weight, weight_scale, input_scale, all_reduce_params) + def uses_nccl_symmetric_memory_window(self) -> bool: """Return True if this allreduce can use an NCCL window output buffer. @@ -1570,6 +1664,17 @@ def forward( raise ValueError( "AllReduce takes MoEAllReduceParams only where supports_moe_fold() holds" ) + tp2 = self.tp2_allreduce + # A CuTe DSL host launch, which torch.compile cannot trace. + if (tp2 is not None and not torch.compiler.is_compiling() + and all_reduce_params.bias is None + and all_reduce_params.residual is not None + and all_reduce_params.norm_weight is not None and tp2.supports( + input, all_reduce_params.fusion_op, + all_reduce_params.residual, all_reduce_params.norm_weight)): + return tp2(input, all_reduce_params.residual, + all_reduce_params.norm_weight, all_reduce_params.eps, + all_reduce_params.fusion_op, all_reduce_params.scale) # Fall back to regular AllReduce if specialized methods are not available or not applicable # Make sure the strategy is AUTO since allreduceOp does not have the branch for MNNVL/SYMM_MEM diff --git a/tensorrt_llm/_torch/distributed/tp2_allreduce.py b/tensorrt_llm/_torch/distributed/tp2_allreduce.py new file mode 100644 index 000000000000..dfe396cc6a58 --- /dev/null +++ b/tensorrt_llm/_torch/distributed/tp2_allreduce.py @@ -0,0 +1,219 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Workspace and launcher of the TP2 large-message all-reduce + residual RMSNorm (+ FP8) kernel +(``kernels/blackwell/tp2_allreduce_norm.py``), one per TP2 mapping. + +``AllReduce`` builds it (one per mapping, ``AllReduce.tp2_fused_norm_kernels``) when the model declares +``allreduce_tp2_fused_norm``, the strategy is AUTO or TWOSHOT and the TP2 group has no MNNVL all-reduce; +``AllReduce.forward`` routes the residual RMSNorm fusions of BF16 calls of ``MIN_TOKENS`` to ``max_tokens`` tokens +here. The workspace (each rank's two landing buffers of max_tokens / 2 rows and its flags: max_tokens x hidden x 2 +bytes, e.g. 128 MiB for 16384 tokens at hidden 4096) is peer memory without a multicast object +(``ll_exchange._PeerBuffers``: IPC inside a node, unicast MNNVL memory across nodes; the kernel reads only the two +unicast mappings), allocated when the first AllReduce of the mapping is built, before the KV cache is sized and any +CUDA graph is captured. Built only under MPI (``AllReduce`` skips it with MPI disabled). +""" + +from __future__ import annotations + +from typing import Optional, Tuple + +import torch + +from tensorrt_llm.functional import AllReduceFusionOp +from tensorrt_llm.logger import logger +from tensorrt_llm.mapping import Mapping + +from .ll_exchange import _PeerBuffers +from .mnnvl_memory import TpMnnvlMemory +from .ops import MNNVLAllReduce + +# Fusion op -> (quantized output, normalized output): the fusions of the CuTe DSL norm kernels. +_OUTPUTS = MNNVLAllReduce._FUSED_NORM_OUTPUTS + + +class Tp2AllReduceNorm: + """The TP2 all-reduce + residual RMSNorm of one mapping, for calls of ``MIN_TOKENS`` to ``max_tokens`` tokens. + Construction is collective and raises RuntimeError on every rank where the workspace cannot be set up.""" + + # Smaller calls stay on the library all-reduce, whose one-shot kernel is faster there. + MIN_TOKENS = 2048 + + @classmethod + def is_supported(cls, mapping: Mapping, hidden: int, max_tokens: int) -> bool: + """CuTe DSL, a TP2 mapping, calls that reach MIN_TOKENS, and a row the kernel's reduction tree spans.""" + from ..cute_dsl_utils import IS_CUTLASS_DSL_AVAILABLE + + if not (IS_CUTLASS_DSL_AVAILABLE and mapping.tp_size == 2 and max_tokens >= cls.MIN_TOKENS): + return False + from ..kernels.blackwell.tp2_allreduce_norm import Tp2WarpAllReduceNormKernel + + return Tp2WarpAllReduceNormKernel.supports_hidden(hidden) + + def __init__(self, mapping: Mapping, hidden: int, max_tokens: int) -> None: + self.mapping = mapping + self.hidden = hidden + self.max_tokens = max_tokens + dev = torch.device("cuda", torch.cuda.current_device()) + self.sms = torch.cuda.get_device_properties(dev).multi_processor_count + self.warps = 8 + half = (max_tokens + 1) // 2 + lbytes = half * hidden * 2 + flag_bytes = 2 * self.sms * self.warps * 4 + size = 2 * lbytes + flag_bytes + 4096 + # The TP pair's communicator, ordered by TP rank (the one the buffers agree over). + comm = TpMnnvlMemory.get_comm(mapping) + bufs = None + error = None + try: + # Collective: every rank's buffer is zero (the flags too) before any rank returns; None on every rank + # when the pair has no peer memory or the fill failed on a rank. + bufs = _PeerBuffers.create(mapping, size) + if bufs is None: + raise RuntimeError("no peer memory") + # The rest is not collective, so it is agreed on below. + self.ctl = torch.zeros((4,), dtype=torch.int32, device=dev) # epoch, arrival counter + o, q = bufs.local_ptr, bufs.peer_ptrs[1 - mapping.tp_rank] + self.table = torch.tensor( + [ + o, + o + lbytes, + o + 2 * lbytes, + q, + q + lbytes, + q + 2 * lbytes, + self.ctl.data_ptr(), + self.ctl.data_ptr() + 4, + ], + dtype=torch.int64, + device=dev, + ) + self._bufs = bufs + self._fns = {} + self._dummy_scale = torch.ones((1,), dtype=torch.float32, device=dev) + # CuTe views of the operands fixed across calls, built at the first call: the pointer table, the + # dummy scale, and each layer's norm weight (keyed by its data pointer; the view keeps it alive). + self._table_view = None + self._dummy_scale_view = None + self._norm_weight_views = {} + torch.cuda.synchronize() + # Any failure on this rank only (a CUDA error, out of memory, a host allocation) enters the agreement + # below; an exception escaping before it would leave the peer waiting in the collective. + except Exception as e: # noqa: BLE001 - re-raised on every rank below as RuntimeError + error = e + # A failure on one rank fails all of them. + causes = _PeerBuffers.failures(comm, error) + if causes: + if bufs is not None: + bufs.close() + raise RuntimeError( + f"TP2 all-reduce workspace setup failed ({'; '.join(causes)}); the library all-reduce serves these " + "calls" + ) from error + logger.info( + f"[TP2 all-reduce] workspace {size >> 20} MiB for {max_tokens} tokens, H {hidden}" + ) + + def supports( + self, + input: torch.Tensor, + fusion_op: AllReduceFusionOp, + residual: torch.Tensor, + norm_weight: torch.Tensor, + ) -> bool: + """BF16 input, residual and norm weight of the kernel's shapes, for one of its fusions.""" + return ( + fusion_op in _OUTPUTS + and input.dim() == 2 + and input.dtype == torch.bfloat16 + and input.shape[1] == self.hidden + and self.MIN_TOKENS <= input.shape[0] <= self.max_tokens + and input.is_contiguous() + and residual.dtype == torch.bfloat16 + and residual.shape == input.shape + and norm_weight.dtype == torch.bfloat16 + and norm_weight.numel() == self.hidden + ) + + def __call__( + self, + input: torch.Tensor, + residual: torch.Tensor, + norm_weight: torch.Tensor, + eps: float, + fusion_op: AllReduceFusionOp, + scale: Optional[torch.Tensor], + ) -> Tuple[torch.Tensor, ...]: + """Outputs of the library op for ``fusion_op``: [norm, residual], [fp8, residual] or [norm, fp8, residual].""" + import cuda.bindings.driver as cuda + import cutlass + + from ..cute_dsl_utils import graph_safe_cute_tensor + from ..flashinfer_utils import get_env_enable_pdl + from ..kernels.blackwell.tp2_allreduce_norm import Tp2WarpAllReduceNormKernel + + quant, norm_out = _OUTPUTS[fusion_op] + key = (norm_out, quant, float(eps)) + t = lambda a: graph_safe_cute_tensor(a, dynamic_leading_dim=a.dim() - 1) # noqa: E731 + residual = residual.contiguous() + res_out = torch.empty_like(residual) + norm = torch.empty_like(residual) if norm_out else res_out + q = ( + torch.empty(residual.shape, dtype=torch.float8_e4m3fn, device=residual.device) + if quant + else None + ) + if self._table_view is None: + self._table_view = graph_safe_cute_tensor(self.table) + self._dummy_scale_view = graph_safe_cute_tensor(self._dummy_scale) + weight_view = self._norm_weight_views.get(norm_weight.data_ptr()) + if weight_view is None: + weight_view = graph_safe_cute_tensor(norm_weight.reshape(-1)) + self._norm_weight_views[norm_weight.data_ptr()] = weight_view + sc = scale.reshape(1).float() if quant else self._dummy_scale + sc_view = graph_safe_cute_tensor(sc) if quant else self._dummy_scale_view + fn = self._fns.get(key) + if fn is None: + if torch.cuda.is_current_stream_capturing(): + raise RuntimeError( + "compile the TP2 all-reduce + norm kernel before CUDA graph capture" + ) + k = Tp2WarpAllReduceNormKernel( + hidden=self.hidden, + norm_eps=float(eps), + ctas=self.sms, + warps=self.warps, + norm_out=norm_out, + quant=quant, + use_pdl=get_env_enable_pdl(), + ) + ex = torch.empty((2, self.hidden), dtype=torch.bfloat16, device=input.device) + exq = torch.empty((2, self.hidden), dtype=torch.uint8, device=input.device) + fn = self._fns[key] = cutlass.cute.compile( + k, + t(ex), + t(ex), + graph_safe_cute_tensor(norm_weight.reshape(-1)), + graph_safe_cute_tensor(sc), + t(ex), + t(ex), + t(exq), + graph_safe_cute_tensor(self.table), + cutlass.Int32(0), + cuda.CUstream(torch.cuda.current_stream().cuda_stream), + ) + qv = q.view(torch.uint8) if quant else res_out.view(torch.uint8)[:, : self.hidden] + fn( + t(input), + t(residual), + weight_view, + sc_view, + t(res_out), + t(norm), + t(qv), + self._table_view, + cutlass.Int32(self.mapping.tp_rank), + cuda.CUstream(torch.cuda.current_stream().cuda_stream), + ) + if quant: + return (norm, q, res_out) if norm_out else (q, res_out) + return norm, res_out diff --git a/tensorrt_llm/_torch/kernels/blackwell/gate_add_rmsnorm_fp8.py b/tensorrt_llm/_torch/kernels/blackwell/gate_add_rmsnorm_fp8.py new file mode 100644 index 000000000000..d7ec12009cee --- /dev/null +++ b/tensorrt_llm/_torch/kernels/blackwell/gate_add_rmsnorm_fp8.py @@ -0,0 +1,299 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Shared-expert gate + residual add + RMSNorm + static E4M3 quant in one launch (CuTe DSL). + +Bitwise equal to the three launches it replaces: ``fused_sigmoid_gate_mul_add`` (``x = bf16(f + sigmoid(g) * s)``), +FlashInfer's fused add + RMSNorm (``FusedAddRMSNormKernel``, subclassed here for its layout and row reduction) and +``static_quantize_e4m3_per_tensor`` of the BF16 norm output. One CTA covers whole rows (``supports_hidden``). +""" + +import functools +import math +from typing import Optional, Tuple + +import cutlass +import cutlass.cute as cute +import torch +from cutlass import Float32, Int32, Int64 +from flashinfer.norm.kernels.fused_add_rmsnorm import FusedAddRMSNormKernel +from flashinfer.norm.kernels.rmsnorm import RMSNormKernel +from flashinfer.norm.utils import ( + get_ptr_as_int64, + get_sm_version, + predicate_k, + row_reduce_sum_multirow, +) + +from .low_m_mma_gemm import _rcp_rn +from .mnnvl_allreduce_norm import ( + _e4m3x2, + _fma, + _hi, + _ld_u16, + _lo, + _pack_bf16, + _sigmoid_triton, + _st_v2, +) + + +class GateAddRMSNormFp8Kernel(FusedAddRMSNormKernel): + """``h = bf16(f + sigmoid(g) * s) + r`` (FP32), ``r <- bf16(h)``, ``y = bf16(h * rstd * (w + weight_bias))``, + ``q = e4m3(y / scale)``; ``f`` is overwritten by ``y`` when ``write_y``.""" + + def __init__( + self, + hidden: int, + weight_bias: float = 1.0, + write_y: bool = True, + sm_version: Optional[int] = None, + ): + super().__init__(cutlass.BFloat16, hidden, weight_bias, sm_version=sm_version) + if self.cluster_n != 1 or self.vec_size != 8 or self.cols_per_tile != hidden: + raise ValueError(f"hidden={hidden} does not fit one CTA per row group") + self.write_y = write_y + + def _smem_size_in_bytes(self) -> int: + # Rows load straight into registers; only the row reduction is shared. + return self.rows_per_block * self.warps_per_row * 4 + + @cute.jit + def __call__( + self, + mF: cute.Tensor, + mS: cute.Tensor, + mG: cute.Tensor, + mR: cute.Tensor, + mW: cute.Tensor, + mQ: cute.Tensor, + mScale: cute.Tensor, + M: Int64, + eps: Float32, + enable_pdl: cutlass.Constexpr[bool], + stream, + ): + tv_shape, tv_stride = RMSNormKernel._make_tv_layout( + self.threads_per_row, self.rows_per_block, self.vec_size, self.num_vec_blocks + ) + tv_layout = cute.make_layout(tv_shape, stride=tv_stride) + tiler_mn = (self.rows_per_block, self.cols_per_tile) + self.kernel(mF, mS, mG, mR, mW, mQ, mScale, M, eps, enable_pdl, tv_layout, tiler_mn).launch( + grid=[cute.ceil_div(M, self.rows_per_block), 1, 1], + block=[self.num_threads, 1, 1], + smem=self._smem_size_in_bytes(), + stream=stream, + use_pdl=enable_pdl, + ) + + @cute.kernel + def kernel( + self, + mF: cute.Tensor, + mS: cute.Tensor, + mG: cute.Tensor, + mR: cute.Tensor, + mW: cute.Tensor, + mQ: cute.Tensor, + mScale: cute.Tensor, + M: Int64, + eps: Float32, + enable_pdl: cutlass.Constexpr[bool], + tv_layout: cute.Layout, + tiler_mn: cute.Shape, + ): + tidx, _, _ = cute.arch.thread_idx() + bidx, _, _ = cute.arch.block_idx() + + H = self.H + threads_per_row = tv_layout.shape[0][0] + rows_per_block = tiler_mn[0] + warps_per_row = max(threads_per_row // 32, 1) + vec = self.vec_size + + smem = cutlass.utils.SmemAllocator() + reduction_buffer = smem.allocate_tensor( + Float32, cute.make_layout((rows_per_block, warps_per_row)), byte_alignment=4 + ) + + idX = cute.make_identity_tensor(mF.shape) + gF = cute.local_tile(mF, tiler_mn, (bidx, 0)) + gS = cute.local_tile(mS, tiler_mn, (bidx, 0)) + gR = cute.local_tile(mR, tiler_mn, (bidx, 0)) + cX = cute.local_tile(idX, tiler_mn, (bidx, 0)) + mW_2d = cute.make_tensor( + mW.iterator, cute.prepend(mW.layout, cute.make_layout((tiler_mn[0],), stride=(0,))) + ) + gW = cute.local_tile(mW_2d, tiler_mn, (0, 0)) + + copy_atom = cute.make_copy_atom( + cute.nvgpu.CopyUniversalOp(), mF.element_type, num_bits_per_copy=self.copy_bits + ) + tiled_copy = cute.make_tiled_copy(copy_atom, tv_layout, tiler_mn) + thr_copy = tiled_copy.get_slice(tidx) + + tFgF = thr_copy.partition_S(gF) + tXcX = thr_copy.partition_S(cX) + tXrX = cute.make_fragment_like(tFgF) + tSgS = thr_copy.partition_S(gS) + tSrS = cute.make_fragment_like(tSgS) + tRgR = thr_copy.partition_S(gR) + tRrR = cute.make_fragment_like(tRgR) + tWgW = thr_copy.partition_S(gW) + tWrW = cute.make_fragment_like(tWgW) + tXgO = thr_copy.partition_D(gF) + tRgO = thr_copy.partition_D(gR) + tXrO = cute.make_fragment_like(tXgO) + + tXpX = predicate_k(tXcX, limit=H) + row = tXcX[(0, 0), 0, 0][0] + row_in_bounds = row < M + t0 = tidx % threads_per_row + + # The norm weight and the quant scale are model weights: load them before the PDL wait. + cute.copy(copy_atom, tWgW, tWrW, pred=tXpX) + factor = _rcp_rn(mScale[0]) + + if enable_pdl: + cute.arch.griddepcontrol_wait() + + tXrX.store(cute.zeros_like(tXrX, dtype=mF.element_type)) + tSrS.store(cute.zeros_like(tSrS, dtype=mS.element_type)) + tRrR.store(cute.zeros_like(tRrR, dtype=mR.element_type)) + g = Float32(0.0) + if row_in_bounds: + cute.copy(copy_atom, tFgF, tXrX, pred=tXpX) + cute.copy(copy_atom, tSgS, tSrS, pred=tXpX) + cute.copy(copy_atom, tRgR, tRrR, pred=tXpX) + g = _lo(_ld_u16(get_ptr_as_int64(mG, Int64(row)))) + s = _sigmoid_triton(g) + + # fused_sigmoid_gate_mul_add: x = bf16(fma(sigmoid(g), s, f)), two BF16 per word. + wF = cute.recast_tensor(tXrX, Int32) + wS = cute.recast_tensor(tSrS, Int32) + for i in cutlass.range_constexpr(cute.size(wF)): + fw = wF[i] + sw = wS[i] + wF[i] = _pack_bf16(_fma(s, _lo(sw), _lo(fw)), _fma(s, _hi(sw), _hi(fw))) + + # FusedAddRMSNormKernel's arithmetic from here on. + h = tXrX.load().to(Float32) + tRrR.load().to(Float32) + tXrO.store(h.to(mR.element_type)) + if row_in_bounds: + cute.copy(copy_atom, tXrO, tRgO, pred=tXpX) + sum_sq = row_reduce_sum_multirow(h * h, threads_per_row, reduction_buffer, None, 1) + rstd = cute.math.rsqrt(sum_sq / Float32(H) + eps, fastmath=True) + cute.arch.barrier() + w = thr_copy.retile(tWrW).load().to(Float32) + y = h * rstd * (w + Float32(self.weight_bias)) + tXrO.store(y.to(mF.element_type)) + if cutlass.const_expr(self.write_y): + if row_in_bounds: + cute.copy(copy_atom, tXrO, tXgO, pred=tXpX) + + # E4M3 of the BF16 y: fragment words 4j .. 4j + 3 hold columns vec * (t0 + threads_per_row * j) .. + 7. + if row_in_bounds: + wY = cute.recast_tensor(tXrO, Int32) + q_base = get_ptr_as_int64(mQ, Int64(row) * Int64(H) + Int64(vec * t0)) + for j in cutlass.range_constexpr(self.num_vec_blocks): + y0 = wY[4 * j] + y1 = wY[4 * j + 1] + y2 = wY[4 * j + 2] + y3 = wY[4 * j + 3] + q0 = _e4m3x2(_lo(y0) * factor, _hi(y0) * factor) + q1 = _e4m3x2(_lo(y1) * factor, _hi(y1) * factor) + q2 = _e4m3x2(_lo(y2) * factor, _hi(y2) * factor) + q3 = _e4m3x2(_lo(y3) * factor, _hi(y3) * factor) + _st_v2(q_base + Int64(j * vec * threads_per_row), q0 | (q1 << 16), q2 | (q3 << 16)) + + if enable_pdl: + cute.arch.griddepcontrol_launch_dependents() + + +@functools.lru_cache(maxsize=None) +def supports_hidden(hidden: int) -> bool: + """Whether one CTA covers a row of ``hidden`` BF16 columns on the current device.""" + try: + GateAddRMSNormFp8Kernel(hidden, sm_version=get_sm_version(torch.device("cuda"))) + except ValueError: + return False + return True + + +@functools.lru_cache(maxsize=None) +def _compiled(hidden: int, weight_bias: float, write_y: bool, enable_pdl: bool, sm_version: int): + kernel = GateAddRMSNormFp8Kernel(hidden, weight_bias, write_y, sm_version=sm_version) + mk = cute.runtime.make_fake_compact_tensor + m = cute.sym_int(64) + align = math.gcd(128, hidden * 2) + + def rows(dtype, row_align): + return mk(dtype, (m, hidden), stride_order=(1, 0), assumed_align=row_align) + + return cute.compile( + kernel, + rows(cutlass.BFloat16, align), + rows(cutlass.BFloat16, align), + mk(cutlass.BFloat16, (m,), assumed_align=2), + rows(cutlass.BFloat16, align), + mk(cutlass.BFloat16, (hidden,), assumed_align=16), + rows(cutlass.Float8E4M3FN, math.gcd(128, hidden)), + mk(Float32, (1,), assumed_align=4), + Int64(1), + Float32(1e-6), + enable_pdl, + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + options="--enable-tvm-ffi", + ) + + +def gate_add_rmsnorm_fp8( + routed: torch.Tensor, + shared: torch.Tensor, + gate_logits: torch.Tensor, + residual: torch.Tensor, + weight: torch.Tensor, + eps: float, + scale: torch.Tensor, + write_y: bool = True, + weight_bias: float = 1.0, +) -> Tuple[torch.Tensor, torch.Tensor]: + """``routed`` [M, H] BF16 (overwritten by the norm output when ``write_y``), ``shared`` [M, H] BF16, + ``gate_logits`` [M, 1] BF16, ``residual`` [M, H] BF16 (updated in place), ``weight`` [H] BF16 (the norm adds + ``weight_bias`` in FP32), ``scale`` the static E4M3 scale. Returns (``routed``, E4M3 [M, H]).""" + from ...flashinfer_utils import get_env_enable_pdl + + m, hidden = routed.shape + q = torch.empty((m, hidden), dtype=torch.float8_e4m3fn, device=routed.device) + if m == 0: + return routed, q + fn = _compiled( + hidden, + float(weight_bias), + bool(write_y), + bool(get_env_enable_pdl()), + get_sm_version(routed.device), + ) + fn( + routed, + shared, + gate_logits.reshape(-1), + residual, + weight, + q, + scale.reshape(1), + m, + float(eps), + ) + return routed, q diff --git a/tensorrt_llm/_torch/kernels/blackwell/gdn_verify_tcgen05.py b/tensorrt_llm/_torch/kernels/blackwell/gdn_verify_tcgen05.py new file mode 100644 index 000000000000..16140841c46d --- /dev/null +++ b/tensorrt_llm/_torch/kernels/blackwell/gdn_verify_tcgen05.py @@ -0,0 +1,1689 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Gated DeltaNet MTP target-verify step on tcgen05: ``trtllm::gdn_verify`` (same arguments) with FP8 output. + +Per (request, value head) pair: the cached-replay delta rule over the request's T draft rows against its pn history +rows (keys, U rows, cumulative gates) and its checkpoint state h; this step's rows appended to the history, or, when +pn + T > 16, the checkpoint commit (h' = bf16(h e^gStart + sum_j Uc_j k_j^T), Uc_j = u_j e^(gStart - G_j) split +into bf16 hi + lo, TMA-stored over h) with this step's rows starting the other history buffer; then the gated RMSNorm +and the E4M3 quantization of the out_proj input. + +Work decomposition: persistent 128-thread CTAs (up to 4 per SM), each looping over pairs; thread v owns value column +v (TMEM lane v). For up to 128 requests the pairs are ordered so that the committing (folding) requests are spread +evenly over every CTA's pairs; above that, pair p = (request p / HV, head p % HV) and CTA b takes b, b + grid, ... +While a pair runs, the next pair's scalars are loaded and its checkpoint, history U and history-key rows are fetched +by TMA as soon as the current pair has released those buffers. + +Shared memory per CTA: two 20 KB regions, one per 64-wide key-dim half (128-byte swizzle, K-major 128-byte rows): + rows 0-15 [k_0..k_{T-1}, 0.., q_0..q_{T-1}, 0..] raw (thread-written; rows 8-15 later hold the Gram rows) + rows 16-31 history keys (TMA, rows >= pn zeroed) + rows 32-159 checkpoint state h (TMA; folded in place and TMA-stored on a commit) +plus the history U [v half][16 j][64 v] (TMA, MN-major), Uc hi / lo, the bf16 history coefficients, an FP32 scalar +block and the request-order table. +TMEM (128 columns): 0-15 state x [k|q], 16-31 Gram ([k|q|kh] x [k|q]), 32-47 history products, 64-127 fold chunk 0 +(kd 0-63); fold chunk 1 (kd 64-127) reuses 0-63 once the output path has read 0-47. + +PDL (``TRTLLM_ENABLE_PDL``, default on): barrier init, TMEM alloc, the order table and the first pair's scalar loads +and TMA run before griddepcontrol.wait; dependents are released when each CTA starts its last pair. With PDL off the +kernel is launched without the programmatic attribute, which makes both instructions no-ops. + +Precision: every stage has the arithmetic and roundings of ``trtllm::gdn_verify``; results differ from it only +through the MMA accumulation order (tcgen05 instead of mma.sync) and the gated norm's 128-column sum order. +""" + +from __future__ import annotations + +import functools + +import cutlass +import cutlass.cute as cute +import cutlass.experimental.cuda as cuda_exp +import torch +from cutlass import Float32, Int32, Int64 +from cutlass._mlir.dialects import llvm +from cutlass.cutlass_dsl import T as MT +from cutlass.cutlass_dsl import dsl_user_op +from cutlass.experimental import primitives as prims + +from ...flashinfer_utils import get_env_enable_pdl + +D = 128 +HIST = 16 +MIN_T, MAX_T = 2, 8 # draft rows per request: k and q rows each fit 8 of the 16 [k|q] rows +NTHR = 128 +ROWB = 128 # bytes per swizzled row (64 bf16) +REG_ROWS = 160 +REG_E = REG_ROWS * 64 # elements per region +REG_B = REG_ROWS * ROWB # 20480 bytes +KH_ROW, H_ROW = 16, 32 +UH_E = 2 * HIST * 64 # [v half][16 j][64] +TCOLS = 128 +CTAS_PER_SM = 4 # resident CTAs per SM (registers capped to 65536 / (4 x 128) = 128 by minctasm) +QSCALE = 0.08838834764831845 # 1 / sqrt(128) +NMAX = 128 # request-order table entries (n > NMAX keeps the identity order) +NCH = NMAX // 32 # table chunks, unrolled so the build costs two load latencies +# small FP32 smem block, float offsets: beta, e^G / |k|, e^G scale / |q|, history gates, A, c, norm partials, 1 / norms +FS_BETA, FS_EGK, FS_EGQ, FS_GH = 0, 8, 16, 32 +FS_A, FS_C, FS_NORM, FS_INV = 48, 112, 176, 208 +FS_N = 224 + + +# ----------------------------------------------------------------------------------------------- PTX helpers +def _asm(ret, args, ptx, cons, side, loc, ip): + return llvm.inline_asm( + ret, + [a.ir_value(loc=loc, ip=ip) for a in args], + ptx, + cons, + has_side_effects=side, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + + +def _f32op(ptx, nargs): + cons = "=f" + ",f" * nargs + + @dsl_user_op + def op(*args, loc=None, ip=None): + return Float32(_asm(MT.f32(), [Float32(a) for a in args], ptx, cons, False, loc, ip)) + + return op + + +_fma = _f32op("fma.rn.f32 $0, $1, $2, $3;", 3) +_fms = _f32op( + "{\n\t.reg .f32 t;\n\tneg.f32 t, $1;\n\tfma.rn.f32 $0, t, $2, $3;\n\t}", 3 +) # c - a * b +_mul = _f32op("mul.rn.f32 $0, $1, $2;", 2) +_add = _f32op("add.rn.f32 $0, $1, $2;", 2) +_sub = _f32op("sub.rn.f32 $0, $1, $2;", 2) +# __expf / __log2f / __fdividef as libdevice lowers them without FTZ +_expf = _f32op( + "{\n\t.reg .f32 t;\n\tmul.rn.f32 t, $1, 0f3FB8AA3B;\n\tex2.approx.f32 $0, t;\n\t}", 1 +) +_lg2 = _f32op("lg2.approx.f32 $0, $1;", 1) +_fdiv = _f32op("div.approx.f32 $0, $1, $2;", 2) +_div_rn = _f32op("div.rn.f32 $0, $1, $2;", 2) +_rcp_ftz = _f32op("rcp.approx.ftz.f32 $0, $1;", 1) +_sqrt_ftz = _f32op("sqrt.approx.ftz.f32 $0, $1;", 1) +_rsqrt_ftz = _f32op("rsqrt.approx.ftz.f32 $0, $1;", 1) +_bf16r = _f32op( + "{\n\t.reg .b16 b, z;\n\tmov.b16 z, 0;\n\tcvt.rn.bf16.f32 b, $1;\n\tmov.b32 $0, {z, b};\n\t}", 1 +) + + +@dsl_user_op +def _ld_u16(addr, *, loc=None, ip=None) -> Int32: + """The 16 raw bits at [addr], zero-extended (no conversion here, so the consumer can sit at its use).""" + return Int32( + _asm( + MT.i32(), + [Int64(addr)], + "{\n\t.reg .b16 h;\n\tld.global.b16 h, [$1];\n\tcvt.u32.u16 $0, h;\n\t}", + "=r,l,~{memory}", + True, + loc, + ip, + ) + ) + + +@dsl_user_op +def _bf16f(raw, *, loc=None, ip=None) -> Float32: + """bf16 bits (low half of raw) -> the exact FP32 value.""" + return Float32(_asm(MT.f32(), [Int32(raw)], "shl.b32 $0, $1, 16;", "=f,r", False, loc, ip)) + + +def _fold8x2(w, acc, eg): + """h' = bf16(h e^gStart + acc) for 8 values (h = four bf16x2 words), FMA rn as packed f32x2 pairs, one rounding.""" + out = [] + for i in range(4): + lo, hi = cute.arch.inline_ptx( + "{\n\tshl.b32 {$w0}, {$r0}, 16;\n\tand.b32 {$w1}, {$r0}, 0xffff0000;\n\t}", + write_only_types=[Float32, Float32], + read_only_args=[Int32(w[i])], + ) + r0, r1 = prims.fma_packed_f32x2( + (lo, hi), + (Float32(eg), Float32(eg)), + (Float32(acc[2 * i]), Float32(acc[2 * i + 1])), + rnd=prims.FPRoundingMode.RN, + ) + out.append( + cute.arch.inline_ptx( + "cvt.rn.bf16x2.f32 {$w0}, {$r1}, {$r0};", + write_only_types=[Int32], + read_only_args=[Float32(r0), Float32(r1)], + ) + ) + return out + + +@dsl_user_op +def _ld_s32(addr, *, loc=None, ip=None) -> Int32: + return Int32( + _asm(MT.i32(), [Int64(addr)], "ld.global.s32 $0, [$1];", "=r,l,~{memory}", True, loc, ip) + ) + + +@dsl_user_op +def _ld_f32(addr, *, loc=None, ip=None) -> Float32: + return Float32( + _asm(MT.f32(), [Int64(addr)], "ld.global.f32 $0, [$1];", "=f,l,~{memory}", True, loc, ip) + ) + + +@dsl_user_op +def _ld_bf16(addr, *, loc=None, ip=None) -> Float32: + return Float32( + _asm( + MT.f32(), + [Int64(addr)], + "{\n\t.reg .b16 h, z;\n\tmov.b16 z, 0;\n\tld.global.b16 h, [$1];\n\t" + "mov.b32 $0, {z, h};\n\t}", + "=f,l,~{memory}", + True, + loc, + ip, + ) + ) + + +@dsl_user_op +def _st_f32(addr, v, *, loc=None, ip=None) -> None: + _asm(None, [Int64(addr), Float32(v)], "st.global.f32 [$0], $1;", "l,f,~{memory}", True, loc, ip) + + +@dsl_user_op +def _st_bf16(addr, v, *, loc=None, ip=None) -> None: + _asm( + None, + [Int64(addr), Float32(v)], + "{\n\t.reg .b16 h;\n\tcvt.rn.bf16.f32 h, $1;\n\tst.global.b16 [$0], h;\n\t}", + "l,f,~{memory}", + True, + loc, + ip, + ) + + +@dsl_user_op +def _st_e4m3(addr, v, *, loc=None, ip=None) -> None: + """cvt.rn.satfinite.e4m3x2.f32 of (0, v); the low byte (v) to [addr].""" + _asm( + None, + [Int64(addr), Float32(v)], + "{\n\t.reg .b16 h;\n\tcvt.rn.satfinite.e4m3x2.f32 h, 0f00000000, $1;\n\t" + "st.global.b8 [$0], h;\n\t}", + "l,f,~{memory}", + True, + loc, + ip, + ) + + +@dsl_user_op +def _st_zero8(addr, *, loc=None, ip=None) -> None: + _asm( + None, + [Int64(addr)], + "{\n\t.reg .b16 z;\n\tmov.b16 z, 0;\n\tst.global.b8 [$0], z;\n\t}", + "l,~{memory}", + True, + loc, + ip, + ) + + +def _ldg128(addr): + return cute.arch.inline_ptx( + "ld.global.v4.b32 {{$w0}, {$w1}, {$w2}, {$w3}}, [{$r0}];", + write_only_types=[Int32] * 4, + read_only_args=[Int64(addr)], + ) + + +def _lds128(saddr): + return cute.arch.inline_ptx( + "ld.shared.v4.b32 {{$w0}, {$w1}, {$w2}, {$w3}}, [{$r0}];", + write_only_types=[Int32] * 4, + read_only_args=[Int32(saddr)], + ) + + +def _sts128(saddr, w): + cute.arch.inline_ptx( + "st.shared.v4.b32 [{$r0}], {{$r1}, {$r2}, {$r3}, {$r4}};", + read_only_args=[Int32(saddr), Int32(w[0]), Int32(w[1]), Int32(w[2]), Int32(w[3])], + ) + + +def _lds128f(saddr): + return cute.arch.inline_ptx( + "ld.shared.v4.f32 {{$w0}, {$w1}, {$w2}, {$w3}}, [{$r0}];", + write_only_types=[Float32] * 4, + read_only_args=[Int32(saddr)], + ) + + +def _sts128f(saddr, v): + cute.arch.inline_ptx( + "st.shared.v4.f32 [{$r0}], {{$r1}, {$r2}, {$r3}, {$r4}};", + read_only_args=[Int32(saddr), Float32(v[0]), Float32(v[1]), Float32(v[2]), Float32(v[3])], + ) + + +def _lds_f32(saddr): + return cute.arch.inline_ptx( + "ld.shared.f32 {$w0}, [{$r0}];", write_only_types=[Float32], read_only_args=[Int32(saddr)] + ) + + +def _sts_f32(saddr, v): + cute.arch.inline_ptx("st.shared.f32 [{$r0}], {$r1};", read_only_args=[Int32(saddr), Float32(v)]) + + +def _sts_bf16(saddr, v): + cute.arch.inline_ptx( + "{\n\t.reg .b16 h;\n\tcvt.rn.bf16.f32 h, {$r1};\n\tst.shared.b16 [{$r0}], h;\n\t}", + read_only_args=[Int32(saddr), Float32(v)], + ) + + +def _lds_bf16(saddr): + return cute.arch.inline_ptx( + "{\n\t.reg .b16 h, z;\n\tmov.b16 z, 0;\n\tld.shared.b16 h, [{$r0}];\n\t" + "mov.b32 {$w0}, {z, h};\n\t}", + write_only_types=[Float32], + read_only_args=[Int32(saddr)], + ) + + +def _uc_split(w, cd): + """Four bf16x2 words of history U (8 values) times cd (FP32), each split into bf16 hi + lo (RN): + hi = bf16(u cd), lo = bf16(u cd - hi). Returns 4 hi words, 4 lo words.""" + body = "{\n\t.reg .f32 u<8>, h<8>;\n\t.reg .b32 t;\n\t" + for i in range(4): + body += ( + f"shl.b32 t, {{$r{i}}}, 16;\n\tmov.b32 u{2 * i}, t;\n\t" + f"and.b32 t, {{$r{i}}}, 0xffff0000;\n\tmov.b32 u{2 * i + 1}, t;\n\t" + f"mul.rn.f32 u{2 * i}, u{2 * i}, {{$r4}};\n\tmul.rn.f32 u{2 * i + 1}, u{2 * i + 1}, {{$r4}};\n\t" + f"cvt.rn.bf16x2.f32 {{$w{i}}}, u{2 * i + 1}, u{2 * i};\n\t" + f"shl.b32 t, {{$w{i}}}, 16;\n\tmov.b32 h{2 * i}, t;\n\t" + f"and.b32 t, {{$w{i}}}, 0xffff0000;\n\tmov.b32 h{2 * i + 1}, t;\n\t" + f"sub.rn.f32 h{2 * i}, u{2 * i}, h{2 * i};\n\tsub.rn.f32 h{2 * i + 1}, u{2 * i + 1}, h{2 * i + 1};\n\t" + f"cvt.rn.bf16x2.f32 {{$w{4 + i}}}, h{2 * i + 1}, h{2 * i};\n\t" + ) + body += "}" + return cute.arch.inline_ptx( + body, + write_only_types=[Int32] * 8, + read_only_args=[Int32(w[0]), Int32(w[1]), Int32(w[2]), Int32(w[3]), Float32(cd)], + ) + + +def _sf(c, a, b): + """Float32 select (explicit, so no trace-time ternary on a dynamic condition).""" + return Float32(cutlass.select_(c, Float32(a), Float32(b))) + + +def _si(c, a, b): + return Int32(cutlass.select_(c, Int32(a), Int32(b))) + + +def _saddr(arr): + return Int32(llvm.ptrtoint(Int32.mlir_type, arr.ir_value())) + + +def _shfl(v, src): + return cute.arch.shuffle_sync(v, src) + + +def _bfly(v, m): + return cute.arch.shuffle_sync_bfly(v, m) + + +@dsl_user_op +def _ballot(v, *, loc=None, ip=None) -> Int32: + """vote.sync.ballot over the full warp of (v != 0).""" + return Int32( + _asm( + MT.i32(), + [Int32(v)], + "{\n\t.reg .pred p;\n\tsetp.ne.s32 p, $1, 0;\n\tvote.sync.ballot.b32 $0, p, 0xffffffff;\n\t}", + "=r,r", + True, + loc, + ip, + ) + ) + + +@dsl_user_op +def _popc(v, *, loc=None, ip=None) -> Int32: + return Int32(_asm(MT.i32(), [Int32(v)], "popc.b32 $0, $1;", "=r,r", False, loc, ip)) + + +@dsl_user_op +def _lanemask_lt(*, loc=None, ip=None) -> Int32: + return Int32(_asm(MT.i32(), [], "mov.u32 $0, %lanemask_lt;", "=r", False, loc, ip)) + + +def _sts_s32(saddr, v): + cute.arch.inline_ptx("st.shared.s32 [{$r0}], {$r1};", read_only_args=[Int32(saddr), Int32(v)]) + + +def _lds_s32(saddr): + return cute.arch.inline_ptx( + "ld.shared.s32 {$w0}, [{$r0}];", write_only_types=[Int32], read_only_args=[Int32(saddr)] + ) + + +# ----------------------------------------------------------------------------------------------- kernel +@cute.kernel +def _gdn_verify_tcgen05_kernel( + tm_h: cutlass.GridConstant[cuda_exp.TensorMap], + tm_u: cutlass.GridConstant[cuda_exp.TensorMap], + tm_k: cutlass.GridConstant[cuda_exp.TensorMap], + gX: cute.Tensor, + gZ: cute.Tensor, + gA: cute.Tensor, + gB: cute.Tensor, + gAlog: cute.Tensor, + gDtb: cute.Tensor, + gNw: cute.Tensor, + gScale: cute.Tensor, + gSlots: cute.Tensor, + gRepl: cute.Tensor, + gOldU: cute.Tensor, + gOldK: cute.Tensor, + gOldG: cute.Tensor, + gCbi: cute.Tensor, + gPacc: cute.Tensor, + gY: cute.Tensor, + n_pairs: Int32, + n_ctas: Int32, + xs: Int32, + zs: Int32, + abst: Int32, + uss: Int64, + kss: Int64, + gss: Int64, + cbs: Int64, + pas: Int64, + eps: Float32, + T_: cutlass.Constexpr[int], + HV: cutlass.Constexpr[int], + HK: cutlass.Constexpr[int], +): + GROUP: cutlass.Constexpr[int] = HV // HK + BF: cutlass.Constexpr = cutlass.BFloat16 + SW: cutlass.Constexpr = prims.Tcgen05SmemSwizzle.SWIZZLE_128B + + reg = cutlass.Array(BF, 2 * REG_E, space=cutlass.AddressSpace.smem, alignment=1024) + uhs = cutlass.Array(BF, UH_E, space=cutlass.AddressSpace.smem, alignment=1024) + ucs = cutlass.Array(BF, 2 * UH_E, space=cutlass.AddressSpace.smem, alignment=1024) + cfs = cutlass.Array(BF, 256, space=cutlass.AddressSpace.smem, alignment=128) + fs = cutlass.Array(Float32, FS_N, space=cutlass.AddressSpace.smem, alignment=16) + bars = cutlass.Array(Int64, 5, space=cutlass.AddressSpace.smem, alignment=8) + tmem_i32 = cutlass.Array(Int32, 1, space=cutlass.AddressSpace.smem, alignment=4) + ordt = cutlass.Array(Int32, NMAX, space=cutlass.AddressSpace.smem, alignment=16) + ordf = cutlass.Array(Int32, 4, space=cutlass.AddressSpace.smem, alignment=16) + + tid, _, _ = cute.arch.thread_idx() + bidx, _, _ = cute.arch.block_idx() + warp = cute.arch.warp_idx() + lane = tid % Int32(32) + pX = Int64(gX.iterator.toint()) + pZ = Int64(gZ.iterator.toint()) + pY = Int64(gY.iterator.toint()) + sR = _saddr(reg) + sU = _saddr(uhs) + sUc = _saddr(ucs) + sCf = _saddr(cfs) + sF = _saddr(fs) + s_order = _saddr(ordt) + sOrdF = _saddr(ordf) + pSl = Int64(gSlots.iterator.toint()) + # replay slots: the rows of the history (old_u / old_k / old_g, slot strides uss / kss / gss) and of its + # bookkeeping (cache_buf_idx / prev_acc, strides cbs / pas); a padded request (state slot < 0) reads replay slot 0 + pRs = Int64(gRepl.iterator.toint()) + pPa = Int64(gPacc.iterator.toint()) + pCb = Int64(gCbi.iterator.toint()) + pOg = Int64(gOldG.iterator.toint()) + pAl = Int64(gAlog.iterator.toint()) + pDt = Int64(gDtb.iterator.toint()) + nw = _bf16f(_ld_u16(Int64(gNw.iterator.toint()) + Int64(tid) * Int64(2))) + rscale = _div_rn(Float32(1.0), _ld_f32(Int64(gScale.iterator.toint()))) + + # ---- once per CTA: warp 0 sets up the barriers and TMEM while warp 1 builds the request order ---- + nreq = n_pairs // Int32(HV) + use_tab = nreq <= Int32(NMAX) + if warp == Int32(0): + if prims.elect_sync(): + for i in cutlass.range_constexpr(5): + prims.mbarrier_init(bars.subview(i), 1) + prims.fence_mbarrier_init() + prims.tcgen05_alloc(tmem_i32, TCOLS, group="cta_1") + prims.tcgen05_relinquish_alloc_permit(group="cta_1") + if warp == Int32(1): + if use_tab: + # folding requests (pn + T > HIST, slot >= 0) take positions 0, 1, ...; the others nreq - 1, ... + s_l = [] + for ci in cutlass.range_constexpr(NCH): + s_l.append( + _ld_s32( + pSl + Int64(cutlass.min(Int32(32 * ci) + lane, nreq - Int32(1))) * Int64(4) + ) + ) + pa_l = [] + for ci in cutlass.range_constexpr(NCH): + r_l = _ld_s32( + pRs + Int64(cutlass.min(Int32(32 * ci) + lane, nreq - Int32(1))) * Int64(4) + ) + r_l = _si(s_l[ci] >= Int32(0), r_l, 0) + pa_l.append(_ld_s32(pPa + Int64(r_l) * pas * Int64(4))) + lt_q = _lanemask_lt() + fpos = Int32(0) + opos = Int32(0) + for ci in cutlass.range_constexpr(NCH): + r_q = Int32(32 * ci) + lane + ok_q = r_q < nreq + fi_q = _si( + ok_q & (s_l[ci] >= Int32(0)) & ((pa_l[ci] + Int32(T_)) > Int32(HIST)), 1, 0 + ) + oi_q = _si(ok_q, 1, 0) - fi_q + bf_q = _ballot(fi_q) + bo_q = _ballot(oi_q) + pos_q = _si( + fi_q > Int32(0), + fpos + _popc(bf_q & lt_q), + nreq - Int32(1) - opos - _popc(bo_q & lt_q), + ) + if ok_q: + _sts_s32(s_order + pos_q * Int32(4), r_q) + fpos = fpos + _popc(bf_q) + opos = opos + _popc(bo_q) + if lane == Int32(0): + _sts_s32(sOrdF, fpos) + prims.barrier_cta_sync(0) + tmem_raw = tmem_i32.load() + base = prims.TmemAddr(tmem_raw) + npc = ( + n_pairs - bidx + n_ctas - Int32(1) + ) // n_ctas # pairs of this CTA: bidx, bidx + n_ctas, ... + + # ---- pair 0: its scalars and its checkpoint / history TMA, before the dependency wait ---- + # This CTA's pairs are b + G k' (the folding ones at k' < c_b); slot k takes a folding pair iff + # rem_k + c_b >= K, rem_k = ((k + phi) c_b) mod K, phi = b mod K; icnt = folding pairs in slots before k. + fcnt = _si(use_tab, _lds_s32(sOrdF), Int32(0)) + pf_b = fcnt * Int32(HV) + c_b = _si(pf_b > bidx, (pf_b - bidx + n_ctas - Int32(1)) // n_ctas, Int32(0)) + k_b = cutlass.max(npc, Int32(1)) + phi_b = bidx - (bidx // k_b) * k_b + rem = phi_b * c_b - ((phi_b * c_b) // k_b) * k_b + icnt = Int32(0) + isf0 = (rem + c_b) >= k_b + pnx = bidx + _si(isf0, icnt, c_b - icnt) * n_ctas + rem = rem + c_b - _si(isf0, k_b, Int32(0)) + icnt = icnt + _si(isf0, 1, 0) + pq = pnx + rq_n = _si( + use_tab, + _lds_s32(s_order + cutlass.min(pnx // Int32(HV), Int32(NMAX - 1)) * Int32(4)), + pnx // Int32(HV), + ) + slot_n = _ld_s32(pSl + Int64(rq_n) * Int64(4)) + rs_n = _ld_s32(pRs + Int64(rq_n) * Int64(4)) + # slot 1's position, request and slot (slot 0's when the CTA has one pair) + isf1 = (rem + c_b) >= k_b + pq_nn = _si(npc > Int32(1), bidx + _si(isf1, icnt, c_b + Int32(1) - icnt) * n_ctas, pnx) + rem = rem + c_b - _si(isf1, k_b, Int32(0)) + icnt = icnt + _si(isf1, 1, 0) + rq_nn = _si( + use_tab, + _lds_s32(s_order + cutlass.min(pq_nn // Int32(HV), Int32(NMAX - 1)) * Int32(4)), + pq_nn // Int32(HV), + ) + slot_nn = _ld_s32(pSl + Int64(rq_nn) * Int64(4)) + rs_nn = _ld_s32(pRs + Int64(rq_nn) * Int64(4)) + rs_n = _si(slot_n >= Int32(0), rs_n, 0) + hvn = pnx - (pnx // Int32(HV)) * Int32(HV) + pn_n = _ld_s32(pPa + Int64(rs_n) * pas * Int64(4)) + buf_n = _ld_s32(pCb + Int64(rs_n) * cbs * Int64(4)) + g0n = ( + pOg + + (Int64(rs_n) * gss + Int64(hvn * Int32(HIST))) * Int64(4) + + Int64(lane & Int32(15)) * Int64(4) + ) + gh0_n = _ld_f32(g0n) + gh1_n = _ld_f32(g0n + Int64(HV * HIST * 4)) + al_n = _ld_f32(pAl + Int64(hvn) * Int64(4)) + dt_n = _ld_f32(pDt + Int64(hvn) * Int64(4)) + has_nx = npc > Int32(0) + if has_nx & (slot_n >= Int32(0)): + hvx0 = pnx - (pnx // Int32(HV)) * Int32(HV) + hkx0 = hvx0 // Int32(GROUP) + nbx0 = (pn_n + Int32(7)) // Int32(8) + if warp == Int32(0): + if prims.elect_sync(): + prims.mbarrier_arrive_expect_tx( + bars.subview(0), Int32(2 * 16384) + nbx0 * Int32(4096) + ) + for x in cutlass.range_constexpr(2): + prims.cp_async_bulk_tensor_shared_cta_global( + reg.subview(x * REG_E + H_ROW * 64), + tm_h.get_ptr(), + (Int32(64 * x), Int32(0), hvx0, slot_n), + bars.subview(0), + ) + for jb in cutlass.range_constexpr(2): + if Int32(jb) < nbx0: + for x in cutlass.range_constexpr(2): + prims.cp_async_bulk_tensor_shared_cta_global( + uhs.subview(x * HIST * 64 + jb * 8 * 64), + tm_u.get_ptr(), + (Int32(64 * x), hvx0, Int32(8 * jb), buf_n, rs_n), + bars.subview(0), + ) + prims.cp_async_bulk_tensor_shared_cta_global( + reg.subview(x * REG_E + (KH_ROW + 8 * jb) * 64), + tm_k.get_ptr(), + (Int32(64 * x), hkx0, Int32(8 * jb), buf_n, rs_n), + bars.subview(0), + ) + cute.arch.griddepcontrol_wait() + + j = Int32(0) # pairs processed (phase of barriers 0-2) + jf = Int32(0) # folds done (phase of barrier 3) + for kk in cutlass.range(npc): + if kk == npc - Int32(1): + # out_proj may launch once every CTA has started its last pair + cute.arch.griddepcontrol_launch_dependents() + # this pair's scalars (prefetched); then issue the next pair's scalar loads + pid = pq # this pair's position in the order; its request was located with it + rq = rq_n + slot = slot_n + rslot = rs_n + pn = pn_n + buf = buf_n + gh0 = gh0_n + gh1 = gh1_n + a_log = al_n + dtb = dt_n + has_nx = (kk + Int32(1)) < npc + # the next pair was located one pair ago (this pair itself on the last one); locate slot kk + 2 + pnx = pq_nn + rq_n = rq_nn + slot_n = slot_nn + rs_n = rs_nn + isfn = (rem + c_b) >= k_b + pnxx = _si( + (kk + Int32(2)) < npc, bidx + _si(isfn, icnt, c_b + kk + Int32(2) - icnt) * n_ctas, pnx + ) + rem = rem + c_b - _si(isfn, k_b, Int32(0)) + icnt = icnt + _si(isfn, 1, 0) + pq_nn = pnxx + rq_nn = _si( + use_tab, + _lds_s32(s_order + cutlass.min(pnxx // Int32(HV), Int32(NMAX - 1)) * Int32(4)), + pnxx // Int32(HV), + ) + slot_nn = _ld_s32(pSl + Int64(rq_nn) * Int64(4)) + rs_nn = _ld_s32(pRs + Int64(rq_nn) * Int64(4)) + pq = pnx + rs_n = _si(slot_n >= Int32(0), rs_n, 0) + hvn = pnx - (pnx // Int32(HV)) * Int32(HV) + pn_n = _ld_s32(pPa + Int64(rs_n) * pas * Int64(4)) + # lane & (n_ctas >> 31) is 0 at run time but lane-dependent to the compiler, so buf_n stays a vector + # value and its uniform copies are made at the TMA issues, not here + buf_n = _ld_s32(pCb + (Int64(rs_n) * cbs + Int64(lane & (n_ctas >> Int32(31)))) * Int64(4)) + g0n = ( + pOg + + (Int64(rs_n) * gss + Int64(hvn * Int32(HIST))) * Int64(4) + + Int64(lane & Int32(15)) * Int64(4) + ) + gh0_n = _ld_f32(g0n) + gh1_n = _ld_f32(g0n + Int64(HV * HIST * 4)) + al_n = _ld_f32(pAl + Int64(hvn) * Int64(4)) + dt_n = _ld_f32(pDt + Int64(hvn) * Int64(4)) + n = rq + hv = pid - (pid // Int32(HV)) * Int32(HV) + hk = hv // Int32(GROUP) + row0 = n * Int32(T_) + ph = j & Int32(1) + phf = jf & Int32(1) + fpair = Int32(0) + if slot < Int32(0): + # padded request: defined zeros for out_proj; the next pair's TMA can go now (nothing is in flight) + for t in cutlass.range_constexpr(T_): + _st_zero8(pY + Int64(row0 + Int32(t)) * Int64(HV * D) + Int64(hv * Int32(D) + tid)) + if has_nx & (slot_n >= Int32(0)): + hvx1 = pnx - (pnx // Int32(HV)) * Int32(HV) + hkx1 = hvx1 // Int32(GROUP) + nbx1 = (pn_n + Int32(7)) // Int32(8) + if warp == Int32(0): + if prims.elect_sync(): + prims.mbarrier_arrive_expect_tx( + bars.subview(0), Int32(2 * 16384) + nbx1 * Int32(4096) + ) + for x in cutlass.range_constexpr(2): + prims.cp_async_bulk_tensor_shared_cta_global( + reg.subview(x * REG_E + H_ROW * 64), + tm_h.get_ptr(), + (Int32(64 * x), Int32(0), hvx1, slot_n), + bars.subview(0), + ) + for jb in cutlass.range_constexpr(2): + if Int32(jb) < nbx1: + for x in cutlass.range_constexpr(2): + prims.cp_async_bulk_tensor_shared_cta_global( + uhs.subview(x * HIST * 64 + jb * 8 * 64), + tm_u.get_ptr(), + (Int32(64 * x), hvx1, Int32(8 * jb), buf_n, rs_n), + bars.subview(0), + ) + prims.cp_async_bulk_tensor_shared_cta_global( + reg.subview(x * REG_E + (KH_ROW + 8 * jb) * 64), + tm_k.get_ptr(), + (Int32(64 * x), hkx1, Int32(8 * jb), buf_n, rs_n), + bars.subview(0), + ) + else: + is_write = (pn + Int32(T_)) > Int32(HIST) + wbuf = _si(is_write, Int32(1) - buf, buf) + woff = _si(is_write, 0, pn) + ghs = _sf(buf != Int32(0), gh1, gh0) + if tid < Int32(HIST): + _sts_f32(sF + (Int32(FS_GH) + tid) * Int32(4), ghs) + g_start = _sf(pn > Int32(0), _shfl(ghs, cutlass.max(pn - Int32(1), Int32(0))), 0.0) + neg_a = Float32(0.0) - _expf(a_log) + # ---- this step's rows: q / k into the swizzled [k|q] rows, v / z of this column, a / b of token lane ---- + r = tid >> Int32(3) + c8 = tid & Int32(7) + is_k = r < Int32(T_) + is_q = (r >= Int32(8)) & (r < Int32(8 + T_)) + tok = _si(is_k, r, _si(is_q, r - Int32(8), 0)) + col = _si(is_k, Int32(HK * D) + hk * Int32(D), hk * Int32(D)) + for x in cutlass.range_constexpr(2): + w = _ldg128( + pX + + (Int64(row0 + tok) * Int64(xs) + Int64(col + Int32(64 * x) + c8 * Int32(8))) + * Int64(2) + ) + keep = is_k | is_q + wz = [_si(keep, w[i], 0) for i in range(4)] + _sts128( + sR + Int32(x * REG_B) + r * Int32(ROWB) + ((c8 ^ (r & Int32(7))) * Int32(16)), + wz, + ) + vv = [] + zz = [] + for t in cutlass.range_constexpr(T_): + vv.append( + _ld_bf16( + pX + + ( + Int64(row0 + Int32(t)) * Int64(xs) + + Int64(Int32(2 * HK * D) + hv * Int32(D) + tid) + ) + * Int64(2) + ) + ) + zz.append( + _ld_bf16( + pZ + + (Int64(row0 + Int32(t)) * Int64(zs) + Int64(hv * Int32(D) + tid)) + * Int64(2) + ) + ) + lt = lane < Int32(T_) + lc = _si(lt, lane, 0) + a_t = _ld_bf16( + Int64(gA.iterator.toint()) + (Int64(row0 + lc) * Int64(abst) + Int64(hv)) * Int64(2) + ) + b_t = _ld_bf16( + Int64(gB.iterator.toint()) + (Int64(row0 + lc) * Int64(abst) + Int64(hv)) * Int64(2) + ) + # gating (every warp, lanes < T), cumulative log-decay by an 8-lane scan (the library's d = 1, 2, 4 order) + xg = _add(a_t, dtb) + spl = _mul(Float32(0.6931471805599453), _lg2(_add(Float32(1.0), _expf(xg)))) + spl = _sf(xg <= Float32(20.0), spl, xg) + gl = _sf(lt, _mul(neg_a, spl), 0.0) + beta = _sf(lt, _fdiv(Float32(1.0), _add(Float32(1.0), _expf(Float32(0.0) - b_t))), 0.0) + for d in cutlass.range_constexpr(3): + o = cute.arch.shuffle_sync_up(gl, 1 << d) + gl = _sf(lane >= Int32(1 << d), _add(gl, o), gl) + gv = _add(g_start, gl) + tcf = tid >> Int32(4) + jcf = tid & Int32(15) + ec = _expf(_sub(_shfl(gv, tcf), _shfl(ghs, jcf))) + ia = tid & Int32(63) + ta = ia >> Int32(3) + sa = ia & Int32(7) + is_a = tid >= Int32(64) + exa = _expf(_sub(_shfl(gv, ta), _shfl(gv, sa))) + bta = _shfl(beta, ta) + + # ---- history rows beyond pn: zeros (0 x NaN from stale or uninitialized rows would poison the MMAs) ---- + while not prims.mbarrier_try_wait_parity(bars.subview(0), ph, time_limit=10_000_000): + pass + jr = tid >> Int32(3) + if jr >= pn: + zero4 = [Int32(0)] * 4 + for x in cutlass.range_constexpr(2): + _sts128(sU + Int32(x * HIST * ROWB) + jr * Int32(ROWB) + c8 * Int32(16), zero4) + _sts128( + sR + Int32(x * REG_B + KH_ROW * ROWB) + jr * Int32(ROWB) + c8 * Int32(16), + zero4, + ) + prims.fence_proxy(prims.Proxy.ASYNC_SHARED, space=prims.SharedSpace.shared_cta) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + prims.barrier_cta_sync(0) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + + # ---- MMA 1: Gram ([k|q|kh|h...] x [k|q], TMEM 16-31) and state x [k|q] (TMEM 0-15) ---- + if warp == Int32(0): + idesc16 = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, a_dtype=BF, b_dtype=BF, n_dim=16, m_dim=128 + ) + if prims.elect_sync(): + for x in cutlass.range_constexpr(2): + dq = prims.Tcgen05SmemDesc.build( + start_address=reg.subview(x * REG_E), + leading_byte_offset=16, + stride_byte_offset=1024, + layout=SW, + ) + dh = prims.Tcgen05SmemDesc.build( + start_address=reg.subview(x * REG_E + H_ROW * 64), + leading_byte_offset=16, + stride_byte_offset=1024, + layout=SW, + ) + for kq in cutlass.range_constexpr(4): + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F16, + prims.CTAGroup.CTA_1, + prims.TmemAddr.from_row_col( + base.row_id, base.col_id + Int32(16) + ).as_ptr(Float32), + dq.advance_start_address(32 * kq), + dq.advance_start_address(32 * kq), + idesc16, + (x > 0) or (kq > 0), + ) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F16, + prims.CTAGroup.CTA_1, + prims.TmemAddr.from_row_col(base.row_id, base.col_id).as_ptr( + Float32 + ), + dh.advance_start_address(32 * kq), + dq.advance_start_address(32 * kq), + idesc16, + (x > 0) or (kq > 0), + ) + prims.tcgen05_commit(bars.subview(1), group=prims.CTAGroup.CTA_1) + + # ---- fold operands (all threads): Uc = uh e^(gStart - G_j), split into bf16 hi + lo ---- + if is_write: + fp_gh = _lds_f32(sF + (Int32(FS_GH) + jr) * Int32(4)) + fp_cd = _sf(jr < pn, _expf(_sub(g_start, fp_gh)), 0.0) + for x in cutlass.range_constexpr(2): + fp_off = ( + Int32(x * HIST * ROWB) + + jr * Int32(ROWB) + + ((c8 ^ (jr & Int32(7))) * Int32(16)) + ) + fp_hl = _uc_split(_lds128(sU + fp_off), fp_cd) + _sts128(sUc + fp_off, fp_hl[0:4]) + _sts128(sUc + Int32(UH_E * 2) + fp_off, fp_hl[4:8]) + + # ---- Gram rows and norms (warp 0 reads TMEM lanes 0-31) published to the q rows of both regions, free + # once MMA 1 is done: Gram rows 0-15 -> region 0 rows 8-15, rows 16-31 -> region 1 rows 8-15 (64 B each) + gram0 = sR + Int32(8 * ROWB) + gram1 = sR + Int32(REG_B + 8 * ROWB) + if warp == Int32(0): + while not prims.mbarrier_try_wait_parity( + bars.subview(1), ph, time_limit=10_000_000 + ): + pass + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + # MMA 1 was the last reader of the state rows and the key rows of a non-folding pair: load the next + # pair's state and keys now (its U rows follow after MMA 2, under the same expect_tx) + if ((pn + Int32(T_)) <= Int32(HIST)) & has_nx & (slot_n >= Int32(0)): + hvx5 = pnx - (pnx // Int32(HV)) * Int32(HV) + hkx5 = hvx5 // Int32(GROUP) + nbx5 = (pn_n + Int32(7)) // Int32(8) + if prims.elect_sync(): + prims.mbarrier_arrive_expect_tx( + bars.subview(0), Int32(2 * 16384) + nbx5 * Int32(4096) + ) + for x in cutlass.range_constexpr(2): + prims.cp_async_bulk_tensor_shared_cta_global( + reg.subview(x * REG_E + H_ROW * 64), + tm_h.get_ptr(), + (Int32(64 * x), Int32(0), hvx5, slot_n), + bars.subview(0), + ) + for jb in cutlass.range_constexpr(2): + if Int32(jb) < nbx5: + for x in cutlass.range_constexpr(2): + prims.cp_async_bulk_tensor_shared_cta_global( + reg.subview(x * REG_E + (KH_ROW + 8 * jb) * 64), + tm_k.get_ptr(), + (Int32(64 * x), hkx5, Int32(8 * jb), buf_n, rs_n), + bars.subview(0), + ) + gacc = cutlass.Array(Float32, 16, alignment=32) + gacc.store( + prims.tcgen05_ld( + "32x32b", + prims.TmemAddr.from_row_col(base.row_id, base.col_id + Int32(16)).as_ptr( + Float32 + ), + num=16, + ), + 0, + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + grow = _si( + lane < Int32(16), + gram0 + lane * Int32(64), + gram1 + (lane - Int32(16)) * Int32(64), + ) + for q4 in cutlass.range_constexpr(4): + _sts128f(grow + Int32(16 * q4), [gacc[4 * q4 + e] for e in range(4)]) + dg = gacc[0] + for i in cutlass.range_constexpr(1, 16): + dg = _sf(lane == Int32(i), gacc[i], dg) + inv = _rcp_ftz(_sqrt_ftz(_add(dg, Float32(1e-6)))) + inv = _sf( + lane >= Int32(8), _mul(Float32(QSCALE), inv), inv + ) # rows 8..: scale / |q_t| + if lane < Int32(16): + _sts_f32(sF + (Int32(FS_INV) + lane) * Int32(4), inv) + iql = _shfl( + inv, (lane + Int32(8)) & Int32(31) + ) # iq of token = lane (held by lane 8 + t) + if lane < Int32(8): + eg = _expf(gv) + _sts_f32(sF + (Int32(FS_BETA) + lane) * Int32(4), _sf(lt, beta, 0.0)) + _sts_f32(sF + (Int32(FS_EGK) + lane) * Int32(4), _sf(lt, _mul(eg, inv), 0.0)) + _sts_f32(sF + (Int32(FS_EGQ) + lane) * Int32(4), _sf(lt, _mul(eg, iql), 0.0)) + if lt: + gw = Int64(gOldG.iterator.toint()) + ( + Int64(rslot) * gss + + (Int64(wbuf) * Int64(HV) + Int64(hv)) * Int64(HIST) + + Int64(woff + lane) + ) * Int64(4) + _st_f32(gw, _sf(is_write, gl, gv)) + prims.barrier_cta_sync(0) + + # ---- coefficients, every thread: one (token, history row) bf16 coefficient pair and one A or c entry ---- + # history coefficients (raw e^(G_t - G_j)) / |row t| (bf16); B operand, K-major, no swizzle: element + # (n, j) at (n / 8) 256 + (j / 8) 128 + (n % 8) 16 + (j % 8) 2; rows n = T.. and 8 + T.. are zero + hjc = (jcf < pn) & (tcf < Int32(T_)) + ck = _sf( + hjc, + _mul( + _mul(_lds_f32(gram1 + jcf * Int32(64) + tcf * Int32(4)), ec), + _lds_f32(sF + (Int32(FS_INV) + tcf) * Int32(4)), + ), + 0.0, + ) + cq = _sf( + hjc, + _mul( + _mul(_lds_f32(gram1 + jcf * Int32(64) + (tcf + Int32(8)) * Int32(4)), ec), + _lds_f32(sF + (Int32(FS_INV + 8) + tcf) * Int32(4)), + ), + 0.0, + ) + cbc = ( + sCf + (jcf >> Int32(3)) * Int32(128) + (jcf & Int32(7)) * Int32(2) + tcf * Int32(16) + ) + _sts_bf16(cbc, ck) + _sts_bf16(cbc + Int32(256), cq) + # A[t][s] = beta_t ((kk ik_t) ik_s) e^(G_t - G_s), s < t (threads 64-127); + # c[t][s] = ((qk e^(G_t - G_s)) ik_s) iq_t, s <= t (threads 0-63) + iks = _lds_f32(sF + (Int32(FS_INV) + sa) * Int32(4)) + aval = _mul( + _mul( + bta, + _mul( + _mul( + _lds_f32(gram0 + ta * Int32(64) + sa * Int32(4)), + _lds_f32(sF + (Int32(FS_INV) + ta) * Int32(4)), + ), + iks, + ), + ), + exa, + ) + cval = _mul( + _mul(_mul(_lds_f32(gram0 + (ta + Int32(8)) * Int32(64) + sa * Int32(4)), exa), iks), + _lds_f32(sF + (Int32(FS_INV + 8) + ta) * Int32(4)), + ) + acv = _sf( + is_a, + _sf((sa < ta) & (ta < Int32(T_)), aval, 0.0), + _sf((sa <= ta) & (ta < Int32(T_)), cval, 0.0), + ) + _sts_f32(sF + (_si(is_a, FS_A, FS_C) + ta * Int32(8) + sa) * Int32(4), acv) + prims.fence_proxy(prims.Proxy.ASYNC_SHARED, space=prims.SharedSpace.shared_cta) + prims.barrier_cta_sync(0) + + # ---- MMA 2: history products (TMEM 32-47); fold chunk 0 (kd 0-63, TMEM 64-127) ---- + if warp == Int32(0): + idesc_h = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, a_dtype=BF, b_dtype=BF, n_dim=16, m_dim=128, a_major=1 + ) + idesc_f = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, + a_dtype=BF, + b_dtype=BF, + n_dim=64, + m_dim=128, + a_major=1, + b_major=1, + ) + if prims.elect_sync(): + du = prims.Tcgen05SmemDesc.build( + start_address=uhs, + leading_byte_offset=2048, + stride_byte_offset=1024, + layout=SW, + ) + dc = prims.Tcgen05SmemDesc.build( + start_address=cfs, + leading_byte_offset=128, + stride_byte_offset=256, + layout=prims.Tcgen05SmemSwizzle.NONE, + ) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F16, + prims.CTAGroup.CTA_1, + prims.TmemAddr.from_row_col(base.row_id, base.col_id + Int32(32)).as_ptr( + Float32 + ), + du, + dc, + idesc_h, + False, + ) + if is_write: + dhi = prims.Tcgen05SmemDesc.build( + start_address=ucs, + leading_byte_offset=2048, + stride_byte_offset=1024, + layout=SW, + ) + dlo = prims.Tcgen05SmemDesc.build( + start_address=ucs.subview(UH_E), + leading_byte_offset=2048, + stride_byte_offset=1024, + layout=SW, + ) + dk0 = prims.Tcgen05SmemDesc.build( + start_address=reg.subview(KH_ROW * 64), + leading_byte_offset=REG_B, + stride_byte_offset=1024, + layout=SW, + ) + f0 = prims.TmemAddr.from_row_col( + base.row_id, base.col_id + Int32(64) + ).as_ptr(Float32) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F16, + prims.CTAGroup.CTA_1, + f0, + dhi, + dk0, + idesc_f, + False, + ) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F16, + prims.CTAGroup.CTA_1, + f0, + dlo, + dk0, + idesc_f, + True, + ) + prims.tcgen05_commit(bars.subview(2), group=prims.CTAGroup.CTA_1) + + # ---- output path: thread v = tid ---- + bt = _lds128f(sF + Int32(FS_BETA * 4)) + _lds128f(sF + Int32((FS_BETA + 4) * 4)) + egk = _lds128f(sF + Int32(FS_EGK * 4)) + _lds128f(sF + Int32((FS_EGK + 4) * 4)) + egq = _lds128f(sF + Int32(FS_EGQ * 4)) + _lds128f(sF + Int32((FS_EGQ + 4) * 4)) + while not prims.mbarrier_try_wait_parity(bars.subview(1), ph, time_limit=10_000_000): + pass + while not prims.mbarrier_try_wait_parity(bars.subview(2), ph, time_limit=10_000_000): + pass + if (pn + Int32(T_)) <= Int32( + HIST + ): # not folding: history U free; the next pair's U rows now + if has_nx & (slot_n >= Int32(0)): + hvx2 = pnx - (pnx // Int32(HV)) * Int32(HV) + nbx2 = (pn_n + Int32(7)) // Int32(8) + if warp == Int32(0): + if prims.elect_sync(): + for jb in cutlass.range_constexpr(2): + if Int32(jb) < nbx2: + for x in cutlass.range_constexpr(2): + prims.cp_async_bulk_tensor_shared_cta_global( + uhs.subview(x * HIST * 64 + jb * 8 * 64), + tm_u.get_ptr(), + (Int32(64 * x), hvx2, Int32(8 * jb), buf_n, rs_n), + bars.subview(0), + ) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + trow = base.row_id + warp * Int32(32) + sacc = cutlass.Array(Float32, 16, alignment=32) + hacc = cutlass.Array(Float32, 16, alignment=32) + sacc.store( + prims.tcgen05_ld( + "32x32b", prims.TmemAddr.from_row_col(trow, base.col_id).as_ptr(Float32), num=16 + ), + 0, + ) + hacc.store( + prims.tcgen05_ld( + "32x32b", + prims.TmemAddr.from_row_col(trow, base.col_id + Int32(32)).as_ptr(Float32), + num=16, + ), + 0, + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + if is_write: + # TMEM 0-63 free: fold chunk 1 (kd 64-127) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + prims.barrier_cta_sync(1, thread_count=NTHR) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + if warp == Int32(0): + idesc_f1 = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, + a_dtype=BF, + b_dtype=BF, + n_dim=64, + m_dim=128, + a_major=1, + b_major=1, + ) + if prims.elect_sync(): + dhi1 = prims.Tcgen05SmemDesc.build( + start_address=ucs, + leading_byte_offset=2048, + stride_byte_offset=1024, + layout=SW, + ) + dlo1 = prims.Tcgen05SmemDesc.build( + start_address=ucs.subview(UH_E), + leading_byte_offset=2048, + stride_byte_offset=1024, + layout=SW, + ) + dk1 = prims.Tcgen05SmemDesc.build( + start_address=reg.subview(REG_E + KH_ROW * 64), + leading_byte_offset=REG_B, + stride_byte_offset=1024, + layout=SW, + ) + f1 = prims.TmemAddr.from_row_col(base.row_id, base.col_id).as_ptr(Float32) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F16, + prims.CTAGroup.CTA_1, + f1, + dhi1, + dk1, + idesc_f1, + False, + ) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F16, + prims.CTAGroup.CTA_1, + f1, + dlo1, + dk1, + idesc_f1, + True, + ) + prims.tcgen05_commit(bars.subview(3), group=prims.CTAGroup.CTA_1) + + # rhs = beta (v - e^G / |k| KS - KHI); forward solve (I + A) U = rhs; intra-chunk outputs; combine + uu = [] + for i in cutlass.range_constexpr(T_): + u = _mul(bt[i], _sub(_fms(egk[i], sacc[i], vv[i]), hacc[i])) + if cutlass.const_expr(i > 0): + arow = _lds128f(sF + Int32((FS_A + 8 * i) * 4)) + _lds128f( + sF + Int32((FS_A + 8 * i + 4) * 4) + ) + for s in cutlass.range_constexpr(i): + u = _fms(arow[s], uu[s], u) + uu.append(u) + xb = [] + for t in cutlass.range_constexpr(T_): + qn = Float32(0.0) + crow = _lds128f(sF + Int32((FS_C + 8 * t) * 4)) + _lds128f( + sF + Int32((FS_C + 8 * t + 4) * 4) + ) + for s in cutlass.range_constexpr(t + 1): + qn = _fma(crow[s], uu[s], qn) + ov = _add(_fma(egq[t], sacc[8 + t], hacc[8 + t]), qn) + xb.append(_bf16r(ov)) + # history U rows + ub = Int64(gOldU.iterator.toint()) + ( + Int64(rslot) * uss + + ((Int64(wbuf) * Int64(HIST) + Int64(woff)) * Int64(HV) + Int64(hv)) * Int64(D) + + Int64(tid) + ) * Int64(2) + for t in cutlass.range_constexpr(T_): + _st_bf16(ub + Int64(t * HV * D * 2), uu[t]) + # gated RMSNorm: per-token sums over the 128 columns (transpose-reduce over the warp), then the 4 warp + # partials + p = [_mul(xb[t], xb[t]) for t in range(T_)] + [Float32(0.0)] * (8 - T_) + up16 = (lane & Int32(16)) != Int32(0) + q4 = [ + _add(_sf(up16, p[i + 4], p[i]), _bfly(_sf(up16, p[i], p[i + 4]), 16)) + for i in range(4) + ] + up8 = (lane & Int32(8)) != Int32(0) + q2 = [ + _add(_sf(up8, q4[i + 2], q4[i]), _bfly(_sf(up8, q4[i], q4[i + 2]), 8)) + for i in range(2) + ] + up4 = (lane & Int32(4)) != Int32(0) + q1 = _add(_sf(up4, q2[1], q2[0]), _bfly(_sf(up4, q2[0], q2[1]), 4)) + q1 = _add(q1, _bfly(q1, 2)) + q1 = _add(q1, _bfly(q1, 1)) + ntok = ( + ((lane >> Int32(4)) & Int32(1)) * Int32(4) + + ((lane >> Int32(3)) & Int32(1)) * Int32(2) + + ((lane >> Int32(2)) & Int32(1)) + ) + if (lane & Int32(3)) == Int32(0): + _sts_f32(sF + (Int32(FS_NORM) + ntok * Int32(4) + warp) * Int32(4), q1) + prims.barrier_cta_sync(0) + for t in cutlass.range_constexpr(T_): + nv = _lds128f(sF + Int32((FS_NORM + 4 * t) * 4)) + ss = _add(_add(_add(nv[0], nv[1]), nv[2]), nv[3]) + rstd = _rsqrt_ftz(_fma(ss, Float32(1.0 / D), eps)) + yv = _mul(_mul(xb[t], rstd), nw) + sg = _fdiv(Float32(1.0), _add(Float32(1.0), _expf(Float32(0.0) - zz[t]))) + yv = _mul(yv, _mul(zz[t], sg)) + _st_e4m3( + pY + Int64(row0 + Int32(t)) * Int64(HV * D) + Int64(hv * Int32(D) + tid), + _mul(_bf16r(yv), rscale), + ) + # history keys of this step (one value head per key head): bf16(k_raw / |k_t|) + if (hv % Int32(GROUP)) == Int32(0): + kb = Int64(gOldK.iterator.toint()) + ( + Int64(rslot) * kss + + ((Int64(wbuf) * Int64(HIST) + Int64(woff)) * Int64(HK) + Int64(hk)) * Int64(D) + + Int64(tid) + ) * Int64(2) + kx = tid >> Int32(6) + ke = tid & Int32(63) + for t in cutlass.range_constexpr(T_): + kr = _lds_bf16( + sR + + kx * Int32(REG_B) + + Int32(t * ROWB) + + (((ke >> Int32(3)) ^ Int32(t & 7)) * Int32(16)) + + (ke & Int32(7)) * Int32(2) + ) + ikt = _lds_f32(sF + Int32((FS_INV + t) * 4)) + _st_bf16(kb + Int64(t * HK * D * 2), _mul(kr, ikt)) + + # ---- fold epilogue: h' = bf16(h e^gStart + acc), in place in shared memory, then TMA-stored ---- + if is_write: + eg0 = _expf(g_start) + for ch in cutlass.range_constexpr(2): + if cutlass.const_expr(ch == 1): + while not prims.mbarrier_try_wait_parity( + bars.subview(3), phf, time_limit=10_000_000 + ): + pass + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + ccol = 64 if ch == 0 else 0 + for half in cutlass.range_constexpr(2): + facc = cutlass.Array(Float32, 32, alignment=32) + facc.store( + prims.tcgen05_ld( + "32x32b", + prims.TmemAddr.from_row_col( + trow, base.col_id + Int32(ccol + 32 * half) + ).as_ptr(Float32), + num=32, + ), + 0, + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + for c4 in cutlass.range_constexpr(4): + cc = 4 * half + c4 + ha = ( + sR + + Int32(ch * REG_B + H_ROW * ROWB) + + tid * Int32(ROWB) + + ((Int32(cc) ^ (tid & Int32(7))) * Int32(16)) + ) + nwv = _fold8x2(_lds128(ha), [facc[8 * c4 + e] for e in range(8)], eg0) + _sts128(ha, nwv) + # this half is folded by every thread: store it now, one bulk group per half. Bulk groups are per + # thread, so lane 0 of warp 0 commits and later waits (not elect_sync) + prims.fence_proxy(prims.Proxy.ASYNC_SHARED, space=prims.SharedSpace.shared_cta) + prims.barrier_cta_sync(1, thread_count=NTHR) + if warp == Int32(0): + if lane == Int32(0): + prims.cp_async_bulk_tensor_global_shared_cta( + tm_h.get_ptr(), + reg.subview(ch * REG_E + H_ROW * 64), + (Int32(64 * ch), Int32(0), hv, slot), + ) + cute.arch.cp_async_bulk_commit_group() + # the next pair's U and key rows are free (MMA 2 and both fold MMAs are done): load them now; each + # state half once its store has been read out (lane 0: it owns the bulk groups) + if warp == Int32(0): + if lane == Int32(0): + nx8 = has_nx & (slot_n >= Int32(0)) + hvx8 = pnx - (pnx // Int32(HV)) * Int32(HV) + hkx8 = hvx8 // Int32(GROUP) + nbx8 = (pn_n + Int32(7)) // Int32(8) + if nx8: + prims.mbarrier_arrive_expect_tx( + bars.subview(0), Int32(2 * 16384) + nbx8 * Int32(4096) + ) + for jb in cutlass.range_constexpr(2): + if Int32(jb) < nbx8: + for x in cutlass.range_constexpr(2): + prims.cp_async_bulk_tensor_shared_cta_global( + uhs.subview(x * HIST * 64 + jb * 8 * 64), + tm_u.get_ptr(), + (Int32(64 * x), hvx8, Int32(8 * jb), buf_n, rs_n), + bars.subview(0), + ) + prims.cp_async_bulk_tensor_shared_cta_global( + reg.subview(x * REG_E + (KH_ROW + 8 * jb) * 64), + tm_k.get_ptr(), + (Int32(64 * x), hkx8, Int32(8 * jb), buf_n, rs_n), + bars.subview(0), + ) + cute.arch.cp_async_bulk_wait_group(1, read=True) + if nx8: + prims.cp_async_bulk_tensor_shared_cta_global( + reg.subview(H_ROW * 64), + tm_h.get_ptr(), + (Int32(0), Int32(0), hvx8, slot_n), + bars.subview(0), + ) + cute.arch.cp_async_bulk_wait_group(0, read=True) + if nx8: + prims.cp_async_bulk_tensor_shared_cta_global( + reg.subview(REG_E + H_ROW * 64), + tm_h.get_ptr(), + (Int32(64), Int32(0), hvx8, slot_n), + bars.subview(0), + ) + + j = j + Int32(1) + jf = jf + _si(is_write, 1, 0) + fpair = _si(is_write, 1, 0) + # end of pair: every TMEM read and shared-memory use of this pair is done before the next one starts; a + # folding pair already synced at its fold's barrier 1 (fpair is CTA-uniform) + cute.arch.sync_warp() + if fpair == Int32(0): + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + prims.barrier_cta_sync(0) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + + if npc == Int32(0): + cute.arch.griddepcontrol_launch_dependents() + if warp == Int32(0): + prims.tcgen05_dealloc(cutlass.inttoptr(tmem_raw, 6, Float32), TCOLS, group="cta_1") + + +@cute.jit +def _launch( + x: cute.Tensor, + z: cute.Tensor, + a: cute.Tensor, + b: cute.Tensor, + a_log: cute.Tensor, + dtb: cute.Tensor, + nw: cute.Tensor, + scale: cute.Tensor, + state: cute.Tensor, + slots: cute.Tensor, + repl: cute.Tensor, + oldu: cute.Tensor, + oldk: cute.Tensor, + oldg: cute.Tensor, + cbi: cute.Tensor, + pacc: cute.Tensor, + y: cute.Tensor, + stream, + n_pairs: Int32, + n_ctas: Int32, + xs: Int32, + zs: Int32, + abst: Int32, + s_slots: Int32, + sss16: Int64, + r_slots: Int32, + uss: Int64, + kss: Int64, + gss: Int64, + cbs: Int64, + pas: Int64, + eps: Float32, + T_: cutlass.Constexpr[int], + HV: cutlass.Constexpr[int], + HK: cutlass.Constexpr[int], + PDL: cutlass.Constexpr[bool], +): + BF = cutlass.BFloat16 + sw = cuda_exp.TensorMapSwizzle.s128b + tm_h = cuda_exp.create_tensor_map_tiled( + global_address=state.iterator.toint(), + dtype=BF, + global_dims=[D, D, HV, s_slots], + global_strides=[D * 2 // 16, D * D * 2 // 16, sss16], + box_dims=[64, D, 1, 1], + swizzle=sw, + ) + tm_u = cuda_exp.create_tensor_map_tiled( + global_address=oldu.iterator.toint(), + dtype=BF, + global_dims=[D, HV, HIST, 2, r_slots], + global_strides=[ + D * 2 // 16, + HV * D * 2 // 16, + HIST * HV * D * 2 // 16, + uss * 2 // 16, + ], + box_dims=[64, 1, 8, 1, 1], + swizzle=sw, + ) + tm_k = cuda_exp.create_tensor_map_tiled( + global_address=oldk.iterator.toint(), + dtype=BF, + global_dims=[D, HK, HIST, 2, r_slots], + global_strides=[ + D * 2 // 16, + HK * D * 2 // 16, + HIST * HK * D * 2 // 16, + kss * 2 // 16, + ], + box_dims=[64, 1, 8, 1, 1], + swizzle=sw, + ) + _gdn_verify_tcgen05_kernel( + tm_h, + tm_u, + tm_k, + x, + z, + a, + b, + a_log, + dtb, + nw, + scale, + slots, + repl, + oldu, + oldk, + oldg, + cbi, + pacc, + y, + n_pairs, + n_ctas, + xs, + zs, + abst, + uss, + kss, + gss, + cbs, + pas, + eps, + T_, + HV, + HK, + ).launch( + grid=(n_ctas, 1, 1), + block=(NTHR, 1, 1), + stream=stream, + use_pdl=PDL, + min_blocks_per_mp=CTAS_PER_SM, + max_number_threads=[NTHR, 1, 1], + ) + + +@functools.lru_cache(maxsize=None) +def _compiled(T_: int, HV: int, HK: int, use_pdl: bool): + mk = cute.runtime.make_fake_compact_tensor + bf, f32, i32 = cutlass.BFloat16, cutlass.Float32, cutlass.Int32 + return cute.compile( + _launch, + mk(bf, (1,), assumed_align=16), + mk(bf, (1,), assumed_align=2), + mk(bf, (1,), assumed_align=2), + mk(bf, (1,), assumed_align=2), + mk(f32, (1,), assumed_align=4), + mk(f32, (1,), assumed_align=4), + mk(bf, (1,), assumed_align=2), + mk(f32, (1,), assumed_align=4), + mk(bf, (1,), assumed_align=16), + mk(i32, (1,), assumed_align=4), + mk(i32, (1,), assumed_align=4), + mk(bf, (1,), assumed_align=16), + mk(bf, (1,), assumed_align=16), + mk(f32, (1,), assumed_align=4), + mk(i32, (1,), assumed_align=4), + mk(i32, (1,), assumed_align=4), + mk(cutlass.Uint8, (1,), assumed_align=1), + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + Int32(1), + Int32(1), + Int32(1), + Int32(1), + Int32(1), + Int32(1), + Int64(1), + Int32(1), + Int64(1), + Int64(1), + Int64(1), + Int64(1), + Int64(1), + Float32(1e-6), + T_=T_, + HV=HV, + HK=HK, + PDL=use_pdl, + options="--enable-tvm-ffi", + ) + + +@functools.lru_cache(maxsize=None) +def _num_sms(device_index: int) -> int: + return torch.cuda.get_device_properties(device_index).multi_processor_count + + +def _one(t): + return torch.as_strided(t, (1,), (1,)) + + +def _packed_slot_rows(t: torch.Tensor) -> bool: + """Whether the dimensions after t's leading (slot) dimension are packed.""" + expected = 1 + for d in range(t.dim() - 1, 0, -1): + if t.size(d) != 1 and t.stride(d) != expected: + return False + expected *= t.size(d) + return True + + +def gdn_verify_tcgen05_supported(T: int, HV: int, HK: int, fp8_out: bool) -> bool: + """Whether the kernel compiles for T draft rows per request and HV / HK value / key heads per rank. + + Head dim 128 and history 16 are fixed (checked per call); the output must be FP8. The caller checks for an + SM100-family GPU. + """ + return bool(fp8_out) and MIN_T <= T <= MAX_T and HK > 0 and HV > 0 and HV % HK == 0 + + +def compile_gdn_verify_tcgen05( + T: int, HV: int, HK: int, device: torch.device | None = None +) -> None: + """Compile (and cache) the kernel for (T, HV, HK) and the current ``TRTLLM_ENABLE_PDL`` ahead of any call, e.g. + after loading (the GDN mixer's cache_derived_state, for an FP8 out_proj only), so that no compilation runs inside a + warm-up or a CUDA-graph capture: a first call compiles lazily, also under capture.""" + assert gdn_verify_tcgen05_supported(T, HV, HK, True), (T, HV, HK) + dev = ( + torch.device("cuda", torch.cuda.current_device()) + if device is None + else torch.device(device) + ) + index = dev.index if dev.index is not None else torch.cuda.current_device() + with torch.cuda.device(index): + _compiled(T, HV, HK, get_env_enable_pdl()) + _num_sms(index) + + +def gdn_verify_tcgen05( + x: torch.Tensor, + z: torch.Tensor, + a: torch.Tensor, + b: torch.Tensor, + A_log: torch.Tensor, + dt_bias: torch.Tensor, + norm_w: torch.Tensor, + fp8_scale: torch.Tensor | None, + eps: float, + state: torch.Tensor, + slots: torch.Tensor, + old_u: torch.Tensor, + old_k: torch.Tensor, + old_g: torch.Tensor, + cache_buf_idx: torch.Tensor, + prev_acc: torch.Tensor, + replay_indices: torch.Tensor | None = None, +) -> torch.Tensor: + """``trtllm::gdn_verify`` with FP8 output (same arguments); returns y [n T, HV 128] float8_e4m3fn. + + state (the checkpoints), old_u, old_k and old_g are updated in place. The history (old_u, old_k, old_g) and its + bookkeeping (cache_buf_idx, prev_acc) are rows of replay_indices, which default to the state slots; their slot + strides may be those of a pool page (the other dimensions packed). + """ + n = slots.numel() + HV = old_u.shape[3] + HK = old_k.shape[3] + T_ = x.shape[0] // n + assert n > 0 and T_ * n == x.shape[0] + assert gdn_verify_tcgen05_supported(T_, HV, HK, fp8_scale is not None), (T_, HV, HK) + # gdnVerifyOp.cpp's dtype checks (the kernel reads these operands as BF16) and its FP32 scalar scale. + for name, t in (("qkv", x), ("z", z), ("a", a), ("b", b), ("old_u", old_u), ("old_k", old_k)): + assert t.dtype == torch.bfloat16, f"{name} must be bfloat16, got {t.dtype}" + assert state.dtype == torch.bfloat16, f"ssm_states must be bfloat16, got {state.dtype}" + assert fp8_scale.dtype == torch.float32 and fp8_scale.numel() == 1, ( + "fp8_scale must be a float32 scalar tensor" + ) + assert x.shape[1] >= (2 * HK + HV) * D and x.stride(1) == 1 and x.stride(0) % 8 == 0 + # The kernel is compiled for 16-byte aligned qkv / state bases (TMA and vector loads). + assert x.data_ptr() % 16 == 0, "qkv must have a 16-byte aligned base" + assert ( + old_u.dim() == 5 and old_u.shape[1] == 2 and old_u.shape[2] == HIST and old_u.shape[4] == D + ) + assert ( + old_k.dim() == 5 and old_k.shape[1] == 2 and old_k.shape[2] == HIST and old_k.shape[4] == D + ) + assert z.dim() == 3 and tuple(z.shape) == (x.shape[0], HV, D) + assert z.stride(-1) == 1 and z.stride(-2) == D and a.stride(1) == 1 and b.stride(1) == 1 + assert ( + a.dim() == 2 and tuple(a.shape) == (x.shape[0], HV) and tuple(b.shape) == (x.shape[0], HV) + ) + assert a.stride(0) == b.stride(0) + assert state.shape[1] == HV and state.shape[-1] == D and state.shape[-2] == D + assert ( + state.stride(3) == 1 + and state.stride(2) == D + and state.stride(1) == D * D + and state.stride(0) % 8 == 0 + and state.data_ptr() % 16 == 0 + ), "ssm_states must be [slots, HV, 128, 128] with packed, 16-byte aligned slots" + if replay_indices is None: + replay_indices = slots + assert replay_indices.numel() == n + # gdnVerifyOp.cpp's operand checks: int32 indices and bookkeeping, the history's replay slots, the gate / norm + # parameters. + assert slots.dtype == torch.int32 and slots.is_contiguous() + assert replay_indices.dtype == torch.int32 and replay_indices.is_contiguous() + assert cache_buf_idx.dtype == torch.int32 and cache_buf_idx.dim() == 1 + assert prev_acc.dtype == torch.int32 and prev_acc.dim() == 1 + assert old_g.dtype == torch.float32 and tuple(old_g.shape) == (old_u.shape[0], 2, HV, HIST) + assert old_k.shape[0] == old_u.shape[0] == cache_buf_idx.shape[0] == prev_acc.shape[0] + assert A_log.dtype == torch.float32 and A_log.is_contiguous() and A_log.numel() == HV + assert dt_bias.dtype == torch.float32 and dt_bias.is_contiguous() and dt_bias.numel() == HV + assert norm_w.dtype == torch.bfloat16 and norm_w.is_contiguous() and norm_w.numel() == D + u_stride, k_stride, g_stride = old_u.stride(), old_k.stride(), old_g.stride() + # packed slot rows (the per-slot strides a pool page gives are free); the TMA needs 16-byte slot strides and bases + assert u_stride[1:] == (HIST * HV * D, HV * D, D, 1) or _packed_slot_rows(old_u), u_stride + assert k_stride[1:] == (HIST * HK * D, HK * D, D, 1) or _packed_slot_rows(old_k), k_stride + assert g_stride[1:] == (HV * HIST, HIST, 1) or _packed_slot_rows(old_g), g_stride + assert u_stride[0] % 8 == 0 and k_stride[0] % 8 == 0 + assert old_u.data_ptr() % 16 == 0 and old_k.data_ptr() % 16 == 0 + assert ( + old_u.shape[2] == HIST + and old_u.shape[4] == D + and old_k.shape[2] == HIST + and old_k.shape[4] == D + ) + y = torch.empty((n * T_, HV * D), dtype=torch.float8_e4m3fn, device=x.device) + dev = x.device.index if x.device.index is not None else torch.cuda.current_device() + n_pairs = n * HV + n_ctas = min(n_pairs, CTAS_PER_SM * _num_sms(dev)) + fn = _compiled(T_, HV, HK, get_env_enable_pdl()) + fn( + _one(x), + _one(z), + _one(a), + _one(b), + _one(A_log), + _one(dt_bias), + _one(norm_w), + _one(fp8_scale), + _one(state), + _one(slots), + _one(replay_indices), + _one(old_u), + _one(old_k), + _one(old_g), + _one(cache_buf_idx), + _one(prev_acc), + _one(y.view(torch.uint8)), + n_pairs, + n_ctas, + x.stride(0), + z.stride(0), + a.stride(0), + state.shape[0], + state.stride(0) * 2 // 16, + old_u.shape[0], + u_stride[0], + k_stride[0], + g_stride[0], + cache_buf_idx.stride(0), + prev_acc.stride(0), + float(eps), + ) + return y diff --git a/tensorrt_llm/_torch/kernels/blackwell/gemm_twoshot_allreduce_norm.py b/tensorrt_llm/_torch/kernels/blackwell/gemm_twoshot_allreduce_norm.py new file mode 100644 index 000000000000..c7391f849c15 --- /dev/null +++ b/tensorrt_llm/_torch/kernels/blackwell/gemm_twoshot_allreduce_norm.py @@ -0,0 +1,887 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Row-parallel FP8 projection (tcgen05) + MNNVL two-shot all-reduce + residual + RMSNorm in one launch. + +``gemm_twoshot_allreduce_norm`` takes row-parallel decode projections (``o_proj`` / ``out_proj``) of up to +``MAX_ROWS`` rows where the library all-reduce runs two-shot + rmsNormLamport (above its one-shot message size; the +caller's ``min_rows``), in place of the projection on cuBLAS followed by those two launches: + +1. GEMM: x [M, K] E4M3 @ W [H, K].T E4M3 times ``s_in * s_w``, FP32 accumulation, BF16 partial. tcgen05 + cta_group::1 MMA, M 64 (<= 64 rows) or 128 (rows past M are TMA zero fill), N 32, K-step 32; one CTA per 32 + output columns (H / 32 CTAs, all co-resident); all K stages resident in shared memory. Weight tiles load by TMA + before ``griddepcontrol.wait``, activations after it. The partial is bitwise cuBLAS's (nvjet). +2. Scatter: column slice c (CTA c) is owned by rank ``c % W``. Every rank stores its BF16 slice tile into the + owner's SCATTER stage, laid out [src rank][c / W][vector][row] so that each warp store is contiguous. +3. Owner: CTA c of rank ``c % W`` sums its slice over the ranks (FP32, rank order -> BF16, the library's two-shot + arithmetic) and multicasts it into every rank's BROADCAST stage, [c][vector][row] (contiguous again). +4. Row: CTA r < M polls all H / 8 vectors of its row at once, adds the residual (BF16), and normalizes bit for bit + as rmsNormLamport: its sum of squares is replayed in the order of the library's launch shape for M rows + (``lib_norm_tree``: per vector 8 BF16 squares, the warp butterfly, the CTA's butterfly over its warp sums, the + cluster's CTA sums in order), ``rsqrt(sum / H + eps)``, ``bf16((w * x) * rstd)``; optional FP8 = + satfinite(norm * (1 / scale)). + +It shares the library's Lamport triple buffer and ``buffer_flags`` (two stages of M x H BF16, as the CuTe +two-shot), so its launches interleave with the library / CuTe all-reduces in one graph. No arrival counter: CTA 0 +rotates the flags only after its whole row arrived, which needs every rank's every CTA to have stored its tile, +i.e. to have read the flags. + +Schedule (none of it changes the arithmetic): +- The owner phase runs on warps 0-1 of every CTA, one item per thread (``supports_rows``); in a row CTA the + epilogue warps start polling their row only after the CTA's owner items are stored, so their spinning polls do + not slow the owner warps. +- The activation TMA box holds ceil8(rows) rows, not the MMA's M; the M-128 MMA reads the rows past the box from + the next stage, or for the last stage from a tail pad of smem_a, garbage that only reaches unstored rows. +- The Lamport row stride is padded to 8 rows, so every 512-byte warp store starts on a 128-byte line. +- The row poll is warp-uniform (vote.any), so the norm's shuffles run converged. +- Both TMA descriptors are prefetched, and the GEMM scales loaded, right after the dependency wait. +- M-128 launches (65+ rows) pad shared memory above half an SM: one CTA per SM, so a following call's early (PDL) + CTAs do not share SMs with this call's tail. +""" + +from __future__ import annotations + +import functools +from typing import Optional, Tuple + +import cutlass +import cutlass.cute as cute +import cutlass.experimental.cuda as cuda_exp +import torch +from cuda.bindings import driver as cuda +from cutlass import Float32, Int32, Int64 +from cutlass._mlir.dialects import llvm +from cutlass.cutlass_dsl import T, dsl_user_op +from cutlass.experimental import primitives as prims + +from ...distributed.mnnvl_fused_allreduce import lib_norm_tree +from .mnnvl_allreduce_norm import ( + _NEG_ZERO, + _add, + _bf16r, + _div_rn, + _e4m3x2, + _hi, + _ld_s64, + _ld_v4, + _ld_volatile_v4, + _lo, + _mul, + _pack_bf16, + _rsqrt, + _sanitize, + _shfl_bfly, + _st_s32, + _st_v2, + _st_v4, +) + +MMA_K = 128 # FP8 elements per 128-byte TMA row (s128b) +K_GRANULE = 32 # FP8 K of one MMA +MMA_N = 32 # output columns per CTA +SW_ALIGN = 1024 +TMA_WARP, MMA_WARP, EPI_WARP0 = 0, 1, 2 +THREADS = 6 * 32 +EPI_THREADS = 4 * 32 +# Row phase: each 8-lane group of the epilogue warps holds whole library norm warps (32 vectors each, 4 per lane), +# the order their sums of squares are replayed in; their warp sums then fit one warp. +LIB_WARP_VECS = 32 +MAX_LIB_WARPS = 32 +MAX_ROWS = 128 +NORM_BAR = 1 # named barrier of the four epilogue warps +OWN_WARPS = 2 # warps 0-1 (TMA, MMA) take the spread owner items +GATE_BAR = 3 # named barrier of the row gate over all THREADS (0 = CTA, 1 = NORM_BAR) + + +def _replayable(m: int, hidden: int, sms: int) -> bool: + """One library thread per 16-byte vector, CTAs of whole 128-thread groups: the orders this kernel replays.""" + block, cluster, loads = lib_norm_tree(m, hidden, sms) + return loads == 1 and block % 128 == 0 and block * cluster == hidden // 8 + + +@functools.lru_cache(maxsize=None) +def _sm_count(device_index: int) -> int: + return torch.cuda.get_device_properties(device_index).multi_processor_count + + +@functools.lru_cache(maxsize=None) +def _onesm_bytes(device_index: int) -> int: + """Shared memory of an M-128 CTA: half the SM's, so with the per-CTA reservation one CTA fits per SM.""" + return torch.cuda.get_device_properties(device_index).shared_memory_per_multiprocessor // 2 + + +@dsl_user_op +def _vote_any(p: Int32, *, loc=None, ip=None) -> Int32: + """1 if any lane of the (full) warp has p != 0, else 0.""" + return Int32( + llvm.inline_asm( + T.i32(), + [Int32(p).ir_value(loc=loc, ip=ip)], + "{\n\t.reg .pred pa, pb;\n\tsetp.ne.s32 pa, $1, 0;\n\tvote.sync.any.pred pb, pa, 0xffffffff;\n\t" + "selp.s32 $0, 1, 0, pb;\n\t}", + "=r,r", + has_side_effects=True, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def _shfl_idx(x: Float32, src: Int32, *, loc=None, ip=None) -> Float32: + return Float32( + llvm.inline_asm( + T.f32(), + [Float32(x).ir_value(loc=loc, ip=ip), Int32(src).ir_value(loc=loc, ip=ip)], + "shfl.sync.idx.b32 $0, $1, $2, 0x1f, 0xffffffff;", + "=f,f,r", + has_side_effects=True, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + +@cute.jit +def _flag_u32(word: Int32) -> Int64: + """A ``buffer_flags`` word (uint32 on the host, held as Int32 here) zero-extended: the buffer and clear sizes + reach 4 GiB.""" + return Int64(word) & Int64(0xFFFFFFFF) + + +@cute.jit +def _clear_dirty( + own: Int64, + fl, + buf_bytes: Int64, + dirty: Int32, + dirty_stages: Int32, + gtid: Int64, + gthreads: Int64, +): + """Clear this thread's share of the previous call's buffer (every dirty stage) to the Lamport sentinel.""" + neg0 = Int32(_NEG_ZERO) + for s_i in cutlass.range_constexpr(4): + if Int32(s_i) < dirty_stages: + stage_bytes = buf_bytes // Int64(dirty_stages) + stage = own + (Int64(dirty) * Int64(dirty_stages) + Int64(s_i)) * stage_bytes + sb = _flag_u32(fl.subview(4 + s_i).load()) + clear_vecs = (sb + Int64(15)) // Int64(16) + c = gtid + while c < clear_vecs: + _st_v4(stage + c * Int64(16), neg0, neg0, neg0, neg0) + c = c + gthreads + + +@cute.kernel +def _kernel( + tma_a_desc: cutlass.GridConstant[cuda_exp.TensorMap], + tma_w_desc: cutlass.GridConstant[cuda_exp.TensorMap], + gSin: cute.Tensor, + gSw: cute.Tensor, + gRes: cute.Tensor, + gNw: cute.Tensor, + gScale: cute.Tensor, + gResOut: cute.Tensor, + gOut: cute.Tensor, + gQuant: cute.Tensor, + gWs: cute.Tensor, + rank: Int32, + active_m: cutlass.Constexpr[int], + hidden: cutlass.Constexpr[int], + stages: cutlass.Constexpr[int], + nranks: cutlass.Constexpr[int], + norm_eps: cutlass.Constexpr[float], + norm_out: cutlass.Constexpr[bool], + quant: cutlass.Constexpr[bool], + mma_m: cutlass.Constexpr[int], + box_m: cutlass.Constexpr[int], + lib_wpc: cutlass.Constexpr[int], + lib_cluster: cutlass.Constexpr[int], + onesm_bytes: cutlass.Constexpr[int], +): + VPT: cutlass.Constexpr[int] = hidden // (8 * EPI_THREADS) # row vectors per epilogue thread + LIB_WARPS: cutlass.Constexpr[int] = hidden // (8 * LIB_WARP_VECS) # library norm warps of a row + LWG: cutlass.Constexpr[int] = VPT // 4 # library norm warps per 8-lane group + AB: cutlass.Constexpr = tma_a_desc.dtype + SWZ: cutlass.Constexpr = tma_a_desc.swizzle.to(prims.Tcgen05SmemSwizzle) + MP: cutlass.Constexpr[int] = (active_m + 7) // 8 * 8 # Lamport row stride + DESC_LEAD: cutlass.Constexpr[int] = MMA_K // 16 + DESC_STRIDE: cutlass.Constexpr[int] = 8 * MMA_K // 16 + A_STAGE: cutlass.Constexpr[int] = ( + box_m * MMA_K + ) # activation rows TMA writes per stage (= mma_m unless tight) + # The M-mma_m MMA reads mma_m rows from each stage's start: rows past box_m come from the next stage, and for the + # last stage from this tail, so the over-read never leaves smem_a whatever follows it (garbage that only reaches + # accumulator rows >= active_m, never stored). 0 unless the box is smaller than the MMA; a multiple of 1024 bytes. + A_TAIL: cutlass.Constexpr[int] = (mma_m - box_m) * MMA_K + W_STAGE: cutlass.Constexpr[int] = MMA_N * MMA_K + ONESM_PAD: cutlass.Constexpr[int] = ( + max(0, onesm_bytes - stages * (A_STAGE + W_STAGE) - A_TAIL) if mma_m == 128 else 0 + ) + NKB: cutlass.Constexpr[int] = MMA_K // K_GRANULE + ROWS_PER_SUB: cutlass.Constexpr[int] = mma_m // 4 # accumulator rows per TMEM subpartition + VECS: cutlass.Constexpr[int] = hidden // 8 # 16-byte vectors of a row + CVECS: cutlass.Constexpr[int] = MMA_N // 8 # vectors of a CTA's column slice + ROW_BYTES: cutlass.Constexpr[int] = hidden * 2 + NCTAS: cutlass.Constexpr[int] = hidden // MMA_N + CPR: cutlass.Constexpr[int] = NCTAS // nranks # slices each rank owns + SLICE_ITEMS: cutlass.Constexpr[int] = ( + CVECS * MP + ) # (vector, row) slots of one slice in the Lamport layout + OWN_TOTAL: cutlass.Constexpr[int] = ( + CPR * SLICE_ITEMS + ) # slots a rank owns (= items without padding) + PER_CTA: cutlass.Constexpr[int] = ( + OWN_TOTAL + NCTAS - 1 + ) // NCTAS # owner items per CTA (<= 64) + # the library norm's launch shape, as top-level constexprs (kernel parameters turn into Int32 inside dynamic + # control flow; these stay Python ints there) + LIB_WPC: cutlass.Constexpr[int] = lib_wpc # warps per CTA + LIB_CLUSTER: cutlass.Constexpr[int] = lib_cluster # CTAs per row + LOG_WPC: cutlass.Constexpr[int] = lib_wpc.bit_length() - 1 + + smem_a = cutlass.Array( + AB, stages * A_STAGE + A_TAIL, space=cutlass.AddressSpace.smem, alignment=SW_ALIGN + ) + smem_w = cutlass.Array( + AB, stages * W_STAGE, space=cutlass.AddressSpace.smem, alignment=SW_ALIGN + ) + full_bar = cutlass.Array(cutlass.Int64, stages, space=cutlass.AddressSpace.smem, alignment=8) + acc_bar = cutlass.Array(cutlass.Int64, 1, space=cutlass.AddressSpace.smem, alignment=8) + tmem_i32 = cutlass.Array(Int32, 1, space=cutlass.AddressSpace.smem, alignment=4) + fl = cutlass.Array(Int32, 8, space=cutlass.AddressSpace.smem, alignment=16) + nred = cutlass.Array( + Float32, LIB_WARPS, space=cutlass.AddressSpace.smem, alignment=16 + ) # library warp sums + sinkw = cutlass.Array(Int32, 4, space=cutlass.AddressSpace.smem, alignment=16) + if cutlass.const_expr(ONESM_PAD > 0): + onesm = cutlass.Array(Int32, ONESM_PAD // 4, space=cutlass.AddressSpace.smem, alignment=16) + if rank < Int32(0): # never true: keeps the allocation referenced + onesm.subview(ONESM_PAD // 4 - 1).store(rank) + + warp_idx = cute.arch.warp_idx() + tidx, _, _ = cute.arch.thread_idx() + bidx, _, _ = cute.arch.block_idx() + lane = tidx % Int32(32) + coord_n = bidx * Int32(MMA_N) + is_epi = warp_idx >= Int32(EPI_WARP0) + epi_tid = tidx - Int32(EPI_WARP0 * 32) + # row-phase vector of this epilogue thread's j-th slot: vbase + 8 j, vbase = 32 LWG G + a, G = 4 w + lane / 8 + # (its 8-lane group, which holds library warps LWG G .. LWG G + LWG - 1), a = lane % 8 + group = Int32(4) * (warp_idx - Int32(EPI_WARP0)) + (lane >> Int32(3)) + vbase = Int32(8 * VPT) * group + (lane & Int32(7)) + # TMEM rows: lanes 0..ROWS_PER_SUB-1 of subpartition (warp % 4) hold rows (warp % 4) * ROWS_PER_SUB + lane + my_row = (warp_idx % Int32(4)) * Int32(ROWS_PER_SUB) + lane + row_valid = is_epi & (lane < Int32(ROWS_PER_SUB)) & (my_row < Int32(active_m)) + row_cta = bidx < Int32(active_m) # this CTA normalizes row bidx + owner = bidx % Int32(nranks) # the rank that reduces column slice bidx + lslice = bidx // Int32(nranks) # its index among that rank's slices + idesc = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, a_dtype=AB, b_dtype=AB, n_dim=MMA_N, m_dim=mma_m + ) + + # ---- barriers, TMEM ---- + if warp_idx == TMA_WARP: + if prims.elect_sync(): + for s in cutlass.range_constexpr(stages): + prims.mbarrier_init(full_bar.subview(s), 1) + prims.mbarrier_init(acc_bar, 1) + prims.fence_mbarrier_init() + prims.barrier_cta_sync(0) + if warp_idx == TMA_WARP: + prims.tcgen05_alloc(tmem_i32, 32, group="cta_1") + prims.barrier_cta_sync(0) + tmem_raw = tmem_i32.load() + tmem_ptr = cutlass.inttoptr(tmem_raw, 6, Float32) + prims.tcgen05_relinquish_alloc_permit(group="cta_1") + + # ---- host-written state, before the dependency wait: workspace table, norm weight, the owner's buffer ---- + tbl = Int64(gWs.iterator.toint()) + own = _ld_s64(tbl) + mcast = _ld_s64(tbl + Int64(8)) + flags = _ld_s64(tbl + Int64(16)) + peer = _ld_s64(tbl + Int64(24) + Int64(owner) * Int64(8)) + nwr = cutlass.Array(Int32, 4 * VPT, alignment=16) + if is_epi: + for j in cutlass.range_constexpr(VPT): + a0, a1, a2, a3 = _ld_v4( + Int64(gNw.iterator.toint()) + (Int64(vbase) + Int64(8 * j)) * Int64(16) + ) + nwr[4 * j + 0] = a0 + nwr[4 * j + 1] = a1 + nwr[4 * j + 2] = a2 + nwr[4 * j + 3] = a3 + + a_ptr = tma_a_desc.get_ptr() + w_ptr = tma_w_desc.get_ptr() + tma_bytes = tma_a_desc.global_tx_bytes() + tma_w_desc.global_tx_bytes() + desc_a = prims.Tcgen05SmemDesc.build( + start_address=smem_a, + leading_byte_offset=DESC_LEAD * 16, + stride_byte_offset=DESC_STRIDE * 16, + layout=SWZ, + ) + desc_w = prims.Tcgen05SmemDesc.build( + start_address=smem_w, + leading_byte_offset=DESC_LEAD * 16, + stride_byte_offset=DESC_STRIDE * 16, + layout=SWZ, + ) + + # ---- TMA: weight tiles, dependency wait, activation tiles ---- + if warp_idx == TMA_WARP: + if prims.elect_sync(): + prims.prefetch_tensormap(a_ptr) + prims.prefetch_tensormap(w_ptr) + for s in cutlass.range_constexpr(stages): + prims.mbarrier_arrive_expect_tx(full_bar.subview(s), tma_bytes) + prims.cp_async_bulk_tensor_shared_cta_global( + smem_w.subview(s * W_STAGE), + w_ptr, + (Int32(s * MMA_K), coord_n), + full_bar.subview(s), + ) + cute.arch.griddepcontrol_wait() + for s in cutlass.range_constexpr(stages): + prims.cp_async_bulk_tensor_shared_cta_global( + smem_a.subview(s * A_STAGE), + a_ptr, + (Int32(s * MMA_K), Int32(0)), + full_bar.subview(s), + ) + + # ---- MMA ---- + if warp_idx == MMA_WARP: + for s in cutlass.range_constexpr(stages): + while not prims.mbarrier_try_wait_parity(full_bar.subview(s), 0, time_limit=10_000_000): + pass + for kb in cutlass.range_constexpr(NKB): + off_a = Int32(s * A_STAGE + kb * K_GRANULE) + off_w = Int32(s * W_STAGE + kb * K_GRANULE) + if prims.elect_sync(): + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F8F6F4, + prims.CTAGroup.CTA_1, + tmem_ptr, + desc_a.advance_start_address(off_a), + desc_w.advance_start_address(off_w), + idesc, + (s > 0) or (kb > 0), + ) + if prims.elect_sync(): + prims.tcgen05_commit(acc_bar, group=prims.CTAGroup.CTA_1) + + # ---- epilogue warps: dependency wait, residual of row bidx, the Lamport flags, the accumulator ---- + rres = cutlass.Array(Int32, 4 * VPT, alignment=16) + acc = cutlass.Array(Float32, MMA_N, alignment=32) + alr = cutlass.Array(Float32, 1) # alpha, loaded right after the dependency wait + row_off = Int64(bidx) * Int64(VECS) + Int64( + vbase + ) # vector index of this thread's j = 0 vector of row bidx + if is_epi: + cute.arch.griddepcontrol_wait() + alr[0] = gSin[0] * gSw[0] + if row_cta: + for j in cutlass.range_constexpr(VPT): + r0, r1, r2, r3 = _ld_v4( + Int64(gRes.iterator.toint()) + (row_off + Int64(8 * j)) * Int64(16) + ) + rres[4 * j + 0] = r0 + rres[4 * j + 1] = r1 + rres[4 * j + 2] = r2 + rres[4 * j + 3] = r3 + if epi_tid == Int32(0): + f0, f1, f2, f3 = _ld_volatile_v4(flags) + f4, f5, f6, f7 = _ld_volatile_v4(flags + Int64(16)) + fl.subview(0).store(f0) + fl.subview(1).store(f1) + fl.subview(2).store(f2) + fl.subview(3).store(f3) + fl.subview(4).store(f4) + fl.subview(5).store(f5) + fl.subview(6).store(f6) + fl.subview(7).store(f7) + while not prims.mbarrier_try_wait_parity(acc_bar, 0, time_limit=10_000_000): + pass + base = prims.TmemAddr(tmem_raw) + tsub = prims.TmemAddr.from_row_col(base.row_id, base.col_id).as_ptr(Float32) + acc.store(prims.tcgen05_ld("32x32b", tsub, num=MMA_N), 0) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + prims.barrier_cta_sync(0) + if warp_idx == TMA_WARP: + prims.tcgen05_dealloc(tmem_ptr, 32, group="cta_1") + + cur = fl.subview(0).load() + dirty = fl.subview(1).load() + buf_bytes = _flag_u32(fl.subview(2).load()) + dirty_stages = fl.subview(3).load() + data_off = Int64(cur) * buf_bytes + half = buf_bytes // Int64(2) + neg0 = Int32(_NEG_ZERO) + + # ---- scatter: this CTA's slice tile -> owner's SCATTER [src rank][slice / W][vector][row] (warp-contiguous) ---- + if row_valid: + alpha = alr[0] + dst = ( + peer + + data_off + + ( + (Int64(rank) * Int64(CPR) + Int64(lslice)) * Int64(CVECS) * Int64(MP) + + Int64(my_row) + ) + * Int64(16) + ) + for v in cutlass.range_constexpr(CVECS): + w0 = _sanitize(_pack_bf16(_mul(acc[8 * v + 0], alpha), _mul(acc[8 * v + 1], alpha))) + w1 = _sanitize(_pack_bf16(_mul(acc[8 * v + 2], alpha), _mul(acc[8 * v + 3], alpha))) + w2 = _sanitize(_pack_bf16(_mul(acc[8 * v + 4], alpha), _mul(acc[8 * v + 5], alpha))) + w3 = _sanitize(_pack_bf16(_mul(acc[8 * v + 6], alpha), _mul(acc[8 * v + 7], alpha))) + _st_v4(dst + Int64(16 * v * MP), w0, w1, w2, w3) + + # ---- PDL: the residual words are consumed (sunk to shared memory) by every thread, then release ---- + if is_epi: + if row_cta: + x = rres[0] + for i in cutlass.range_constexpr(1, 4 * VPT): + x = x ^ rres[i] + sinkw.subview(0).store(x) + prims.barrier_cta_sync(0) + if tidx == Int32(0): + cute.arch.griddepcontrol_launch_dependents() + + gtid = Int64(bidx) * Int64(THREADS) + Int64(tidx) + gthreads = Int64(NCTAS * THREADS) + _clear_dirty(own, fl, buf_bytes, dirty, dirty_stages, gtid, gthreads) + + # ---- owner: item g of this rank's CPR slices (g = local slice * 4 M + vector * M + row) on thread g % PER_CTA + # of warps 0-1 in CTA g / PER_CTA: the slice summed over the ranks in rank order, multicast ---- + if warp_idx < Int32(OWN_WARPS): + g = bidx * Int32(PER_CTA) + tidx + live = (tidx < Int32(PER_CTA)) & (g < Int32(OWN_TOTAL)) + lsl = g // Int32(SLICE_ITEMS) + it_ = g - lsl * Int32(SLICE_ITEMS) + live = live & ((it_ % Int32(MP)) < Int32(active_m)) # padding rows are never written + if live: + sgot = cutlass.Array(Int32, 4 * nranks, alignment=16) + spend = Int32(1) + while spend != Int32(0): + spend = Int32(0) + for rk in cutlass.range_constexpr(nranks): + # SCATTER [src rank][local slice][vector][row] = rk * OWN_TOTAL + g + h0, h1, h2, h3 = _ld_volatile_v4( + own + data_off + (Int64(rk * OWN_TOTAL) + Int64(g)) * Int64(16) + ) + sgot[4 * rk + 0] = h0 + sgot[4 * rk + 1] = h1 + sgot[4 * rk + 2] = h2 + sgot[4 * rk + 3] = h3 + if h0 == neg0: + spend = Int32(1) + if h1 == neg0: + spend = Int32(1) + if h2 == neg0: + spend = Int32(1) + if h3 == neg0: + spend = Int32(1) + ssum = cutlass.Array(Int32, 4, alignment=16) + for i in cutlass.range_constexpr(4): + lo_sum = Float32(0.0) + hi_sum = Float32(0.0) + for rk in cutlass.range_constexpr(nranks): + lo_sum = _add(lo_sum, _lo(sgot[4 * rk + i])) + hi_sum = _add(hi_sum, _hi(sgot[4 * rk + i])) + ssum[i] = _sanitize(_pack_bf16(lo_sum, hi_sum)) + # BROADCAST [slice][vector][row], slice = local slice * W + rank + _st_v4( + mcast + + data_off + + half + + ((Int64(lsl) * Int64(nranks) + Int64(rank)) * Int64(SLICE_ITEMS) + Int64(it_)) + * Int64(16), + ssum[0], + ssum[1], + ssum[2], + ssum[3], + ) + if row_cta: + # this CTA's owner items are stored: release the epilogue warps' row polls + cute.arch.barrier(barrier_id=GATE_BAR, number_of_threads=THREADS) + + # ---- row bidx: all its vectors at once, + residual, RMSNorm (rmsNormLamport arithmetic) ---- + if is_epi & row_cta: + cute.arch.barrier(barrier_id=GATE_BAR, number_of_threads=THREADS) + res = cutlass.Array(Float32, 8 * VPT, alignment=32) + bwa = cutlass.Array(Int32, 4 * VPT, alignment=16) + pend = Int32(1) + while pend != Int32(0): + pend = Int32(0) + for j in cutlass.range_constexpr(VPT): + # vector g = vbase + 8 j of the row = (slice g / 4, vector g % 4) -> [slice][vector][row] + c0, c1, c2, c3 = _ld_volatile_v4( + own + + data_off + + half + + ((Int64(vbase) + Int64(8 * j)) * Int64(MP) + Int64(bidx)) * Int64(16) + ) + bwa[4 * j + 0] = c0 + bwa[4 * j + 1] = c1 + bwa[4 * j + 2] = c2 + bwa[4 * j + 3] = c3 + if c0 == neg0: + pend = Int32(1) + if c1 == neg0: + pend = Int32(1) + if c2 == neg0: + pend = Int32(1) + if c3 == neg0: + pend = Int32(1) + pend = _vote_any(pend) + for j in cutlass.range_constexpr(VPT): + for i in cutlass.range_constexpr(4): + res[8 * j + 2 * i] = _bf16r(_add(_lo(bwa[4 * j + i]), _lo(rres[4 * j + i]))) + res[8 * j + 2 * i + 1] = _bf16r(_add(_hi(bwa[4 * j + i]), _hi(rres[4 * j + i]))) + for j in cutlass.range_constexpr(VPT): + _st_v4( + Int64(gResOut.iterator.toint()) + (row_off + Int64(8 * j)) * Int64(16), + _pack_bf16(res[8 * j + 0], res[8 * j + 1]), + _pack_bf16(res[8 * j + 2], res[8 * j + 3]), + _pack_bf16(res[8 * j + 4], res[8 * j + 5]), + _pack_bf16(res[8 * j + 6], res[8 * j + 7]), + ) + # rmsNormLamport's order (LIB_CLUSTER CTAs x LIB_WPC warps, a vector per library thread): this thread holds + # vectors a + 8 (j % 4) of library warp LWG G + j / 4, so its xor-16 and xor-8 steps are local and xor 4, 2, 1 + # run across the 8-lane group; the CTA and cluster sums follow the barrier. + qs = [] + for j in cutlass.range_constexpr(VPT): + q = Float32(0.0) + for e in cutlass.range_constexpr(8): + q = _add(q, _bf16r(_mul(res[8 * j + e], res[8 * j + e]))) + qs.append(q) + for lw in cutlass.range_constexpr(LWG): + y = _add(_add(qs[4 * lw + 0], qs[4 * lw + 2]), _add(qs[4 * lw + 1], qs[4 * lw + 3])) + y = _add(y, _shfl_bfly(y, Int32(4))) + y = _add(y, _shfl_bfly(y, Int32(2))) + y = _add(y, _shfl_bfly(y, Int32(1))) + if (lane & Int32(7)) == Int32(0): + if cutlass.const_expr(LWG == 1): + nred.subview(group).store(y) + else: + nred.subview(Int32(LWG) * group + Int32(lw)).store(y) + cute.arch.barrier(barrier_id=NORM_BAR, number_of_threads=EPI_THREADS) + # lane W holds warp sum S_W (lanes past LIB_WARPS repeat and are never read); xor m for m = LIB_WPC / 2 .. 1 is + # the CTA butterfly (the library's masks >= LIB_WPC add zeros); lane k LIB_WPC then holds CTA k's sum + u = nred.subview(lane & Int32(LIB_WARPS - 1)).load() + for st in cutlass.range_constexpr(LOG_WPC): + u = _add(u, _shfl_bfly(u, Int32(LIB_WPC >> (st + 1)))) + total = Float32(0.0) + for kc in cutlass.range_constexpr(LIB_CLUSTER): + total = _add(total, _shfl_idx(u, Int32(kc * LIB_WPC))) + rstd = _rsqrt(_add(_div_rn(total, Float32(float(hidden))), Float32(norm_eps))) + inv = Float32(1.0) + if cutlass.const_expr(quant): + inv = _div_rn(Float32(1.0), gScale[0]) + for j in cutlass.range_constexpr(VPT): + y = cutlass.Array(Float32, 8, alignment=32) + for i in cutlass.range_constexpr(4): + y[2 * i] = _bf16r(_mul(_mul(_lo(nwr[4 * j + i]), res[8 * j + 2 * i]), rstd)) + y[2 * i + 1] = _bf16r(_mul(_mul(_hi(nwr[4 * j + i]), res[8 * j + 2 * i + 1]), rstd)) + vrow = row_off + Int64(8 * j) + if cutlass.const_expr(norm_out): + _st_v4( + Int64(gOut.iterator.toint()) + vrow * Int64(16), + _pack_bf16(y[0], y[1]), + _pack_bf16(y[2], y[3]), + _pack_bf16(y[4], y[5]), + _pack_bf16(y[6], y[7]), + ) + if cutlass.const_expr(quant): + q01 = _e4m3x2(_mul(y[0], inv), _mul(y[1], inv)) + q23 = _e4m3x2(_mul(y[2], inv), _mul(y[3], inv)) + q45 = _e4m3x2(_mul(y[4], inv), _mul(y[5], inv)) + q67 = _e4m3x2(_mul(y[6], inv), _mul(y[7], inv)) + _st_v2( + Int64(gQuant.iterator.toint()) + vrow * Int64(8), + q01 | (q23 << 16), + q45 | (q67 << 16), + ) + # ---- hand the triple buffer to the next call (see the module docstring for why no arrival counter) ---- + if bidx == Int32(0): + if epi_tid == Int32(0): + _st_s32(flags, (cur + Int32(1)) % Int32(3)) + _st_s32(flags + Int64(4), cur) + _st_s32(flags + Int64(12), Int32(2)) + _st_s32(flags + Int64(16), Int32(MP * ROW_BYTES)) + _st_s32(flags + Int64(20), Int32(MP * ROW_BYTES)) + _st_s32(flags + Int64(24), Int32(0)) + _st_s32(flags + Int64(28), Int32(0)) + _st_s32(flags + Int64(32), Int32(0)) + + +@cute.jit +def _launch( + a: cute.Tensor, + w: cute.Tensor, + s_in: cute.Tensor, + s_w: cute.Tensor, + res: cute.Tensor, + nw: cute.Tensor, + scale: cute.Tensor, + res_out: cute.Tensor, + out: cute.Tensor, + qout: cute.Tensor, + table: cute.Tensor, + rank: Int32, + stream: cuda.CUstream, + active_m: cutlass.Constexpr[int], + hidden: cutlass.Constexpr[int], + k_total: cutlass.Constexpr[int], + nranks: cutlass.Constexpr[int], + norm_eps: cutlass.Constexpr[float], + norm_out: cutlass.Constexpr[bool], + quant: cutlass.Constexpr[bool], + lib_wpc: cutlass.Constexpr[int], + lib_cluster: cutlass.Constexpr[int], + onesm_bytes: cutlass.Constexpr[int], + use_pdl: cutlass.Constexpr[bool], +): + mma_m = 64 if active_m <= 64 else 128 + box_m = min(mma_m, (active_m + 7) // 8 * 8) + tma_a = cuda_exp.create_tensor_map_tiled( + global_address=a.iterator.toint(), + dtype=cutlass.Float8E4M3FN, + global_dims=[k_total, active_m], + global_strides=[k_total // 16], + box_dims=[MMA_K, box_m], + swizzle=cuda_exp.TensorMapSwizzle.s128b, + ) + tma_w = cuda_exp.create_tensor_map_tiled( + global_address=w.iterator.toint(), + dtype=cutlass.Float8E4M3FN, + global_dims=[k_total, hidden], + global_strides=[k_total // 16], + box_dims=[MMA_K, MMA_N], + swizzle=cuda_exp.TensorMapSwizzle.s128b, + ) + _kernel( + tma_a, + tma_w, + s_in, + s_w, + res, + nw, + scale, + res_out, + out, + qout, + table, + rank, + active_m, + hidden, + k_total // MMA_K, + nranks, + norm_eps, + norm_out, + quant, + mma_m, + box_m, + lib_wpc, + lib_cluster, + onesm_bytes, + ).launch(grid=(hidden // MMA_N, 1, 1), block=(THREADS, 1, 1), stream=stream, use_pdl=use_pdl) + + +def _compile( + m: int, + k: int, + hidden: int, + nranks: int, + eps: float, + norm_out: bool, + quant: bool, + sms: int, + onesm_bytes: int, + use_pdl: bool, +): + block, cluster, loads = lib_norm_tree(m, hidden, sms) + assert _replayable(m, hidden, sms), (m, hidden, sms, block, cluster, loads) + mk = cute.runtime.make_fake_compact_tensor + u8 = cutlass.Uint8 + # x and W only feed the host-built TMA descriptors, whose global address needs 16 bytes (``supports``). + return cute.compile( + _launch, + mk(u8, (m, k), stride_order=(1, 0), assumed_align=16), + mk(u8, (hidden, k), stride_order=(1, 0), assumed_align=16), + mk(cutlass.Float32, (1,), assumed_align=4), + mk(cutlass.Float32, (1,), assumed_align=4), + mk(cutlass.BFloat16, (m, hidden), stride_order=(1, 0), assumed_align=16), + mk(cutlass.BFloat16, (hidden,), assumed_align=16), + mk(cutlass.Float32, (1,), assumed_align=4), + mk(cutlass.BFloat16, (m, hidden), stride_order=(1, 0), assumed_align=16), + mk(cutlass.BFloat16, (m, hidden), stride_order=(1, 0), assumed_align=16), + mk(u8, (m, hidden), stride_order=(1, 0), assumed_align=16), + mk(cutlass.Int64, (3 + nranks,), assumed_align=8), + Int32(0), + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + active_m=m, + hidden=hidden, + k_total=k, + nranks=nranks, + norm_eps=eps, + norm_out=norm_out, + quant=quant, + lib_wpc=block // 32, + lib_cluster=cluster, + onesm_bytes=onesm_bytes, + use_pdl=use_pdl, + options="--enable-tvm-ffi", + ) + + +_COMPILED = {} + + +def _compiled(*key): + """``_compile(*key)``, once per key (M is a compile-time constant of the kernel); the first call of a key must + precede CUDA graph capture.""" + fn = _COMPILED.get(key) + if fn is None: + if torch.cuda.is_current_stream_capturing(): + raise RuntimeError( + f"compile the GEMM + two-shot all-reduce + norm kernel {key[:4]} before CUDA graph capture" + ) + fn = _COMPILED[key] = _compile(*key) + return fn + + +def supports_hidden(hidden: int, nranks: int, sms: int) -> bool: + """Whether the kernel takes this hidden size and TP group: whole library norm warps per 8-lane epilogue group + and their warp sums within one warp, one CTA per 32 output columns, all co-resident, owned round-robin by the + ranks.""" + return ( + hidden % (8 * EPI_THREADS * (LIB_WARP_VECS // 8)) == 0 + and hidden // (8 * LIB_WARP_VECS) <= MAX_LIB_WARPS + and hidden // MMA_N <= sms + and (hidden // MMA_N) % nranks == 0 + and nranks in (2, 4, 8, 16) + ) + + +def supports_rows(m: int, hidden: int, nranks: int, sms: int, min_rows: int) -> bool: + """Whether a call of ``m`` rows fits: from ``min_rows`` (the library's first two-shot rows), every owner item (a + rank's slices x vectors x padded rows) has a thread of the CTAs' ``OWN_WARPS`` warps, and the library norm's + launch for ``m`` rows is one this kernel replays.""" + nctas = hidden // MMA_N + own_total = (nctas // nranks) * (MMA_N // 8) * ((m + 7) // 8 * 8) + return ( + min_rows <= m <= min(MAX_ROWS, nctas) + and -(-own_total // nctas) <= OWN_WARPS * 32 + and _replayable(m, hidden, sms) + ) + + +def supports_problem( + m: int, weight: torch.Tensor, hidden: int, nranks: int, sms: int, min_rows: int +) -> bool: + """Whether a call of ``m`` rows with this E4M3 weight [H, K] fits (the activation not looked at); the weight's + address is 16-byte aligned, as its TMA descriptor needs.""" + k = weight.shape[-1] + return ( + weight.dtype == torch.float8_e4m3fn + and weight.shape == (hidden, k) + and weight.is_contiguous() + and weight.data_ptr() % 16 == 0 + and k % MMA_K == 0 + and k // MMA_K <= 8 + and supports_hidden(hidden, nranks, sms) + and supports_rows(m, hidden, nranks, sms, min_rows) + ) + + +def supports( + x: torch.Tensor, weight: torch.Tensor, hidden: int, nranks: int, sms: int, min_rows: int +) -> bool: + """Whether the launch takes this E4M3 activation and weight: ``supports_problem``, and x contiguous at a 16-byte + aligned address (the compiled kernel's assumption for both).""" + return ( + x.dim() == 2 + and x.dtype == torch.float8_e4m3fn + and x.shape[1] == weight.shape[-1] + and x.is_contiguous() + and x.data_ptr() % 16 == 0 + and supports_problem(x.shape[0], weight, hidden, nranks, sms, min_rows) + ) + + +def workspace_bytes(m: int, hidden: int) -> int: # rows padded to 8 (the Lamport row stride) + """Lamport buffer bytes one call needs: two stages of M x H BF16.""" + return 2 * ((m + 7) // 8 * 8) * hidden * 2 + + +def gemm_twoshot_allreduce_norm( + x: torch.Tensor, + weight: torch.Tensor, + weight_scale: torch.Tensor, + input_scale: torch.Tensor, + residual: torch.Tensor, + norm_weight: torch.Tensor, + eps: float, + table: torch.Tensor, + rank: int, + nranks: int, + scale: Optional[torch.Tensor] = None, + norm_out: bool = True, +) -> Tuple[torch.Tensor, ...]: + """x [M, K] E4M3 (static ``input_scale``), weight [H, K] E4M3 (``weight_scale``), residual [M, H] BF16, + norm_weight [H] BF16, table: the Lamport workspace table of ``_LamportTable`` (at least + ``workspace_bytes(M, H)`` per buffer). Outputs as ``MnnvlAllReduceNorm.__call__``.""" + from ...flashinfer_utils import get_env_enable_pdl + + m, k = x.shape + hidden = weight.shape[0] + dev = residual.device + fn = _compiled( + m, + k, + hidden, + nranks, + float(eps), + norm_out, + scale is not None, + _sm_count(dev.index), + _onesm_bytes(dev.index), + get_env_enable_pdl(), + ) + res_out = torch.empty_like(residual) + norm = torch.empty_like(residual) if norm_out else res_out + quant = ( + torch.empty(residual.shape, dtype=torch.uint8, device=dev) if scale is not None else None + ) + sc = scale if scale is not None else input_scale + fn( + x.view(torch.uint8), + weight.view(torch.uint8), + input_scale.reshape(1).float(), + weight_scale.reshape(1).float(), + residual, + norm_weight.reshape(-1), + sc.reshape(1).float(), + res_out, + norm, + # without quant the FP8 output is never written: any [M, H] bytes stand in for it + quant + if quant is not None + else res_out.view(torch.uint8).view(-1)[: m * hidden].view(m, hidden), + table, + rank, + ) + if scale is None: + return norm, res_out + q = quant.view(torch.float8_e4m3fn) + if norm_out: + return norm, q, res_out + return q, res_out diff --git a/tensorrt_llm/_torch/kernels/blackwell/inproj_ba_splitk.py b/tensorrt_llm/_torch/kernels/blackwell/inproj_ba_splitk.py new file mode 100644 index 000000000000..ea2c3a5243ed --- /dev/null +++ b/tensorrt_llm/_torch/kernels/blackwell/inproj_ba_splitk.py @@ -0,0 +1,327 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""BF16 projection to a few outputs, ``y[M, N] = x[M, K] @ W[N, K].T``, with the arithmetic of cuBLAS' split-K nvjet +kernel (four FP32 partials over K / 4 each, summed in order, then BF16; bitwise to F.linear where cuBLAS picks that +kernel), in one launch that loads W before the PDL wait: a 4-CTA cluster per 32-row token tile, CTA rank = K split, +in-order tcgen05 kind::f16 MMAs (M 64, the outputs in its first N rows), partials summed in the leader's DSMEM. +""" + +from __future__ import annotations + +import functools + +import cutlass +import cutlass.cute as cute +import cutlass.experimental.cuda as cuda_exp +import torch +from cuda.bindings import driver as cuda +from cutlass import Float32, Int32, Int64 +from cutlass._mlir.dialects import llvm +from cutlass.cutlass_dsl import dsl_user_op +from cutlass.experimental import primitives as prims + +from ...flashinfer_utils import get_env_enable_pdl + +SPLITS = 4 # K splits, one CTA each +KBOX = 64 # bf16 per 128-byte swizzle row +TOK = 32 # token rows per tile (MMA N) +MROWS = 64 # MMA M: the N outputs are its first rows; the others only feed accumulator rows that are never read +X_BOX = TOK * KBOX # elements per x box (4 KB) +XG = 4 # x boxes per barrier +THREADS = 128 +# Most rows of a call (three token tiles): cuBLAS keeps its split-K kernel up to here at in_proj_ba shapes. +MAX_ROWS = 96 + + +@dsl_user_op +def _st_bf16(addr: Int64, v: Float32, *, loc=None, ip=None) -> None: + llvm.inline_asm( + None, + [Int64(addr).ir_value(loc=loc, ip=ip), Float32(v).ir_value(loc=loc, ip=ip)], + "{\n\t.reg .b16 h;\n\tcvt.rn.bf16.f32 h, $1;\n\tst.global.b16 [$0], h;\n\t}", + "l,f,~{memory}", + has_side_effects=True, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + + +@functools.lru_cache(maxsize=None) +def _smem_limit() -> int: + """A CTA's opt-in shared memory on the current device.""" + return torch.cuda.get_device_properties( + torch.cuda.current_device() + ).shared_memory_per_block_optin + + +def _smem_bytes(k: int, n: int) -> int: + nbox = k // SPLITS // KBOX + return 2 * (nbox * n * KBOX + (MROWS - n) * KBOX + nbox * X_BOX) + 4 * SPLITS * TOK * n + 1024 + + +def plan(m: int, k: int, n: int) -> int | None: + """Token tiles, or None outside 1..MAX_ROWS rows or the kernel's shapes: K in whole barrier groups of x boxes per + split; N in whole 8-row swizzle atoms within the 16 accumulator rows of TMEM sub-partition 0 (MMA M 64), which + warp 0 reads; the CTA's shared memory within one SM.""" + if m < 1 or m > MAX_ROWS or k <= 0 or k % (SPLITS * KBOX * XG) or n not in (8, 16): + return None + if _smem_bytes(k, n) > _smem_limit(): + return None + return -(-m // TOK) + + +def supports(x: torch.Tensor, w: torch.Tensor) -> bool: + """Whether :func:`ba_splitk` takes x [M, K] and w [N, K]: BF16, contiguous, at the compiled kernel's 128-byte + alignment, and a shape :func:`plan` covers.""" + return ( + x.dtype == torch.bfloat16 + and w.dtype == torch.bfloat16 + and x.dim() == 2 + and w.dim() == 2 + and x.shape[1] == w.shape[1] + and x.is_contiguous() + and w.is_contiguous() + and x.data_ptr() % 128 == 0 + and w.data_ptr() % 128 == 0 + and plan(x.shape[0], x.shape[1], w.shape[0]) is not None + ) + + +@cute.kernel +def _kernel( + tma_x_desc: cutlass.GridConstant[cuda_exp.TensorMap], + tma_w_desc: cutlass.GridConstant[cuda_exp.TensorMap], + gOut: cute.Tensor, + m_rows: cutlass.Constexpr[int], + k_total: cutlass.Constexpr[int], + n_out: cutlass.Constexpr[int], +): + AB: cutlass.Constexpr = tma_w_desc.dtype + NB: cutlass.Constexpr[int] = n_out # output features + SWZ: cutlass.Constexpr = tma_w_desc.swizzle.to(prims.Tcgen05SmemSwizzle) + NKS: cutlass.Constexpr[int] = KBOX // 16 # MMAs per 64-K box + NBOX: cutlass.Constexpr[int] = k_total // SPLITS // KBOX # boxes per split + W_BOX: cutlass.Constexpr[int] = NB * KBOX # elements per W box (N rows), the boxes packed + # past the last box: the rows the MMA reads beyond the N outputs (contents irrelevant) + W_SLACK: cutlass.Constexpr[int] = (MROWS - NB) * KBOX + + smem_w = cutlass.Array( + AB, NBOX * W_BOX + W_SLACK, space=cutlass.AddressSpace.smem, alignment=1024 + ) + smem_x = cutlass.Array(AB, NBOX * X_BOX, space=cutlass.AddressSpace.smem, alignment=1024) + part = cutlass.Array( + Float32, SPLITS * TOK * NB, space=cutlass.AddressSpace.smem, alignment=16 + ) # leader's slots + w_bar = cutlass.Array(cutlass.Int64, 1, space=cutlass.AddressSpace.smem, alignment=8) + x_full = cutlass.Array(cutlass.Int64, NBOX // XG, space=cutlass.AddressSpace.smem, alignment=8) + acc_bar = cutlass.Array(cutlass.Int64, 1, space=cutlass.AddressSpace.smem, alignment=8) + tmem_i32 = cutlass.Array(Int32, 1, space=cutlass.AddressSpace.smem, alignment=4) + + warp_idx = cute.arch.warp_idx() + tidx, _, _ = cute.arch.thread_idx() + bidx, _, _ = cute.arch.block_idx() + lane = tidx % Int32(32) + split = cute.arch.block_idx_in_cluster() + tile = bidx // Int32(SPLITS) + tok0 = tile * Int32(TOK) + k0 = split * Int32(NBOX) # first 64-K box of this split + out_ptr = Int64(gOut.iterator.toint()) + + if warp_idx == 0: + if prims.elect_sync(): + prims.mbarrier_init(w_bar, 1) + for g in cutlass.range_constexpr(NBOX // XG): + prims.mbarrier_init(x_full.subview(g), 1) + prims.mbarrier_init(acc_bar, 1) + prims.fence_mbarrier_init() + if warp_idx == 1: + prims.tcgen05_alloc(tmem_i32, 32) + prims.barrier_cta_sync(0) + # Every CTA of the cluster has started before a peer stores into the leader's shared memory (waited below). + prims.barrier_cluster_arrive_relaxed() + tmem_raw = tmem_i32.load() + tmem_ptr = cutlass.inttoptr(tmem_raw, 6, Float32) + if warp_idx == 1: + prims.tcgen05_relinquish_alloc_permit() + x_ptr = tma_x_desc.get_ptr() + w_ptr = tma_w_desc.get_ptr() + w_bytes = tma_w_desc.global_tx_bytes() + x_bytes = tma_x_desc.global_tx_bytes() + + # ---- TMA warp: the W chunk before the wait, x after it (whole-warp polls, elect only around issues) ---- + if warp_idx == 0: + if prims.elect_sync(): + prims.mbarrier_arrive_expect_tx(w_bar, NBOX * w_bytes) + for b in cutlass.range_constexpr(NBOX): + prims.cp_async_bulk_tensor_shared_cta_global( + smem_w.subview(b * W_BOX), + w_ptr, + (k0 * Int32(KBOX) + Int32(b * KBOX), Int32(0)), + w_bar, + ) + cute.arch.griddepcontrol_wait() + if prims.elect_sync(): + for g in cutlass.range_constexpr(NBOX // XG): + prims.mbarrier_arrive_expect_tx(x_full.subview(g), XG * x_bytes) + for i in cutlass.range_constexpr(XG): + b = g * XG + i + prims.cp_async_bulk_tensor_shared_cta_global( + smem_x.subview(b * X_BOX), + x_ptr, + (k0 * Int32(KBOX) + Int32(b * KBOX), tok0), + x_full.subview(g), + ) + + # ---- MMA warp: 64 MMAs in K order ---- + if warp_idx == 1: + idesc = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, a_dtype=AB, b_dtype=AB, n_dim=TOK, m_dim=MROWS + ) + desc_w = prims.Tcgen05SmemDesc.build( + start_address=smem_w, leading_byte_offset=128, stride_byte_offset=1024, layout=SWZ + ) + desc_x = prims.Tcgen05SmemDesc.build( + start_address=smem_x, leading_byte_offset=128, stride_byte_offset=1024, layout=SWZ + ) + while not prims.mbarrier_try_wait_parity(w_bar, 0, time_limit=10_000_000): + pass + for b in cutlass.range_constexpr(NBOX): + if cutlass.const_expr(b % XG == 0): + while not prims.mbarrier_try_wait_parity( + x_full.subview(b // XG), 0, time_limit=10_000_000 + ): + pass + for ks in cutlass.range_constexpr(NKS): + if prims.elect_sync(): + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F16, + prims.CTAGroup.CTA_1, + tmem_ptr, + desc_w.advance_start_address(Int32(b * W_BOX * 2 + ks * 32)), + desc_x.advance_start_address(Int32(b * X_BOX * 2 + ks * 32)), + idesc, + (b > 0) or (ks > 0), + ) + if prims.elect_sync(): + prims.tcgen05_commit(acc_bar) + + prims.barrier_cluster_wait() + # ---- partial: lanes 0..N-1 of sub-partition 0 hold the N features x 32 tokens; push them into the leader ---- + if warp_idx == 0: + while not prims.mbarrier_try_wait_parity(acc_bar, 0, time_limit=10_000_000): + pass + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + acc = cutlass.Array(Float32, TOK, alignment=32) + base = prims.TmemAddr(tmem_raw) + acc.store( + prims.tcgen05_ld( + "32x32b", + prims.TmemAddr.from_row_col(base.row_id, base.col_id).as_ptr(Float32), + num=TOK, + ), + 0, + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + remote = prims.mapa(part, Int32(0)) + if lane < Int32(NB): + for c in cutlass.range_constexpr(TOK): + remote.store(acc[c], (split * Int32(TOK) + Int32(c)) * Int32(NB) + lane) + cute.arch.sync_warp() + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + prims.barrier_cluster_arrive() # release: the DSMEM stores before it + prims.barrier_cluster_wait() # acquire + cute.arch.griddepcontrol_launch_dependents() + if split == Int32(0): + for i in cutlass.range_constexpr(TOK * NB // THREADS): + idx = tidx + Int32(i * THREADS) + t = idx // Int32(NB) + f = idx % Int32(NB) + tok = tok0 + t + if tok < Int32(m_rows): + p = [] + for s in cutlass.range_constexpr(SPLITS): + p.append(part.load(Int32(s * TOK * NB) + idx)) + v = ((p[0] + p[1]) + p[2]) + p[3] + _st_bf16(out_ptr + (Int64(tok) * Int64(NB) + Int64(f)) * Int64(2), v) + if warp_idx == 1: + prims.tcgen05_dealloc(tmem_ptr, 32) + + +@cute.jit +def _launch( + x: cute.Tensor, + w: cute.Tensor, + out: cute.Tensor, + stream: cuda.CUstream, + m_rows: cutlass.Constexpr[int], + k_total: cutlass.Constexpr[int], + n_out: cutlass.Constexpr[int], + use_pdl: cutlass.Constexpr[bool], +): + tma_x = cuda_exp.create_tensor_map_tiled( + global_address=x.iterator.toint(), + dtype=cutlass.BFloat16, + global_dims=[k_total, m_rows], + global_strides=[k_total * 2 // 16], + box_dims=[KBOX, TOK], + swizzle=cuda_exp.TensorMapSwizzle.s128b, + ) + tma_w = cuda_exp.create_tensor_map_tiled( + global_address=w.iterator.toint(), + dtype=cutlass.BFloat16, + global_dims=[k_total, n_out], + global_strides=[k_total * 2 // 16], + box_dims=[KBOX, n_out], + swizzle=cuda_exp.TensorMapSwizzle.s128b, + ) + _kernel(tma_x, tma_w, out, m_rows, k_total, n_out).launch( + grid=(-(-m_rows // TOK) * SPLITS, 1, 1), + block=(THREADS, 1, 1), + cluster=(SPLITS, 1, 1), + stream=stream, + use_pdl=use_pdl, + ) + + +def _compile(m: int, k: int, n: int, use_pdl: bool): + mk = cute.runtime.make_fake_compact_tensor + return cute.compile( + _launch, + mk(cutlass.BFloat16, (m, k), stride_order=(1, 0), assumed_align=128), + mk(cutlass.BFloat16, (n, k), stride_order=(1, 0), assumed_align=128), + mk(cutlass.BFloat16, (m, n), stride_order=(1, 0), assumed_align=16), + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + m_rows=m, + k_total=k, + n_out=n, + use_pdl=use_pdl, + options="--enable-tvm-ffi", + ) + + +_COMPILED = {} + + +def _compiled(*key): + """``_compile(*key)``, once per key; the first call of a key must precede CUDA graph capture.""" + fn = _COMPILED.get(key) + if fn is None: + if torch.cuda.is_current_stream_capturing(): + raise RuntimeError( + f"compile the split-K in_proj_ba GEMM {key[:3]} before CUDA graph capture" + ) + fn = _COMPILED[key] = _compile(*key) + return fn + + +def ba_splitk(x: torch.Tensor, w: torch.Tensor, out: torch.Tensor | None = None) -> torch.Tensor: + """y[M, N] BF16 = x[M, K] BF16 @ w[N, K].T with cuBLAS' split-K 4 arithmetic (``supports`` operands).""" + m, k = x.shape + n = w.shape[0] + assert supports(x, w) + if out is None: + out = torch.empty((m, n), dtype=torch.bfloat16, device=x.device) + _compiled(m, k, n, get_env_enable_pdl())(x, w, out) + return out diff --git a/tensorrt_llm/_torch/kernels/blackwell/low_m_mma_gemm.py b/tensorrt_llm/_torch/kernels/blackwell/low_m_mma_gemm.py index dfed16035aba..07bad2c7fa52 100644 --- a/tensorrt_llm/_torch/kernels/blackwell/low_m_mma_gemm.py +++ b/tensorrt_llm/_torch/kernels/blackwell/low_m_mma_gemm.py @@ -1,6 +1,6 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Warp-MMA GEMM for decode-sized M (<= 64 rows) over per-tensor FP8 (W8A8) and BF16 weights. +"""Warp-MMA GEMM for decode-sized M (<= ``MAX_ROWS`` rows) over per-tensor FP8 (W8A8) and BF16 weights. ``C[M, :] = A[M, K] @ W.T`` with register-prefetched weights in two segments, each a whole number of CTAs: @@ -49,6 +49,8 @@ CHUNK = 64 # K elements per lane quad (16 per lane) N_TILE = 8 +# Most rows of one launch: loops, epilogue and shared memory scale with the row tiles. +MAX_ROWS = 128 FP8_ACTS = ("fp8", "quant", "bf16") @@ -291,7 +293,7 @@ def _g2r_atom(dtype, streaming: bool): class LowMMmaGemmKernel: - """``num_rows`` (<= 64) x K GEMM over an FP8 and a BF16 weight segment.""" + """``num_rows`` (<= ``MAX_ROWS``) x K GEMM over an FP8 and a BF16 weight segment.""" def __init__( self, @@ -334,8 +336,10 @@ def __init__( raise ValueError(f"ksplit={ksplit} must be 1, 2, 4 or 8") if k_extent % (CHUNK * k_warps * ksplit): raise ValueError(f"K={k_extent} must be a multiple of {CHUNK * k_warps * ksplit}") - if not 1 <= num_rows <= 64: - raise ValueError(f"num_rows={num_rows} must be in [1, 64]") + # Tactics are filtered on shared memory (a launch limit); 4 x n_tiles x row_tiles FP32 accumulators per thread + # can only spill, which the race times. + if not 1 <= num_rows <= MAX_ROWS: + raise ValueError(f"num_rows={num_rows} must be in [1, {MAX_ROWS}]") for tiles in (n_tiles, n_tiles_bf16): if tiles not in (1, 2, 4): raise ValueError(f"n_tiles={tiles} must be 1, 2 or 4") diff --git a/tensorrt_llm/_torch/kernels/blackwell/mnnvl_allreduce_norm.py b/tensorrt_llm/_torch/kernels/blackwell/mnnvl_allreduce_norm.py index d7203394dabb..11408954a802 100644 --- a/tensorrt_llm/_torch/kernels/blackwell/mnnvl_allreduce_norm.py +++ b/tensorrt_llm/_torch/kernels/blackwell/mnnvl_allreduce_norm.py @@ -555,6 +555,50 @@ def _cluster_sync(*, loc=None, ip=None) -> None: ) +# ---- L2 prefetch of the next GEMM's weight (``l2pf``) ---- +L2PF_CHUNK = 65536 +L2PF_MAX_CHUNKS = 8 # per CTA: 512 KB + + +@dsl_user_op +def _min_s64(a: Int64, b: Int64, *, loc=None, ip=None) -> Int64: + return Int64( + _asm( + T.i64(), + [_v(Int64(a), loc, ip), _v(Int64(b), loc, ip)], + "min.s64 $0, $1, $2;", + "=l,l,l", + False, + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def _prefetch_l2_bulk_if(addr: Int64, nbytes: Int64, *, loc=None, ip=None) -> None: + """``cp.async.bulk.prefetch.L2.global [addr], nbytes`` when nbytes > 0 (nothing to wait for).""" + _asm( + None, + [_v(Int64(addr), loc, ip), _v(Int64(nbytes), loc, ip)], + "{ .reg .pred p; .reg .b32 n; setp.gt.s64 p, $1, 0; cvt.u32.u64 n, $1; " + "@p cp.async.bulk.prefetch.L2.global [$0], n; }", + "l,l,~{memory}", + loc=loc, + ip=ip, + ) + + +def l2_prefetch_slice(pf_ptr: Int64, pf_bytes: Int64, pf_per: Int64, bid) -> None: + """CTA ``bid`` starts pulling bytes [bid * pf_per, min((bid + 1) * pf_per, pf_bytes)) of ``pf_ptr`` into L2 + (``pf_per``: 16-byte multiple from the host). Straight-line: up to L2PF_MAX_CHUNKS predicated bulk prefetches.""" + beg = Int64(bid) * pf_per + end = _min_s64(beg + pf_per, pf_bytes) + for c in range(L2PF_MAX_CHUNKS): + off = beg + Int64(c * L2PF_CHUNK) + _prefetch_l2_bulk_if(pf_ptr + off, _min_s64(end - off, Int64(L2PF_CHUNK))) + + class MnnvlAllReduceNormKernel: """MNNVL all-reduce + residual + RMSNorm for ``m`` tokens. @@ -588,6 +632,7 @@ def __init__( moe_topk: int = 0, fc2_row: int = 0, tpc: int = 1, + l2pf: bool = False, ): if hidden % (VEC * ctas) or (hidden // VEC // ctas) % 32 or hidden // VEC // ctas > 1024: raise ValueError(f"unsupported hidden size {hidden} for {ctas} CTAs per token") @@ -613,6 +658,7 @@ def __init__( self.norm_out = norm_out self.quant = quant self.row_bytes = hidden * 2 + self.l2pf = l2pf # prefetch pf_ptr's slice into L2 after this CTA's pushes @cute.jit def __call__( @@ -632,6 +678,9 @@ def __call__( topw_ptr: Int64, perm_ptr: Int64, rank: Int32, + pf_ptr: Int64, + pf_bytes: Int64, + pf_per: Int64, stream, ) -> None: m = cute.size(gRes, mode=[0]) @@ -653,6 +702,9 @@ def __call__( topw_ptr, perm_ptr, rank, + pf_ptr, + pf_bytes, + pf_per, ).launch( grid=[(m + self.tpc - 1) // self.tpc, 1, 1], block=[self.threads, 1, 1], @@ -678,6 +730,9 @@ def __call__( topw_ptr, perm_ptr, rank, + pf_ptr, + pf_bytes, + pf_per, ).launch( grid=[m * self.ctas, 1, 1], block=[self.threads, 1, 1], @@ -706,6 +761,9 @@ def kernel( topw_ptr: Int64, perm_ptr: Int64, rank: Int32, + pf_ptr: Int64, + pf_bytes: Int64, + pf_per: Int64, ) -> None: tidx, _, _ = cute.arch.thread_idx() bid, _, _ = cute.arch.block_idx() @@ -796,11 +854,10 @@ def kernel( if const_expr(self.moe_topk > 0): ev = cute.make_rmem_tensor((topk * 4,), Int32) for k in cutlass.range_constexpr(topk): - e0, e1, e2, e3 = _ld_v4( - fc2_ptr - + (Int64(_max0(pk[k])) * Int64(self.fc2_row) + Int64(vi) * Int64(VEC)) - * Int64(2) - ) + fa = fc2_ptr + ( + Int64(_max0(pk[k])) * Int64(self.fc2_row) + Int64(vi) * Int64(VEC) + ) * Int64(2) + e0, e1, e2, e3 = _ld_v4(fa) ev[4 * k + 0] = e0 ev[4 * k + 1] = e1 ev[4 * k + 2] = e2 @@ -843,6 +900,12 @@ def kernel( _sanitize(x3), ) + if const_expr(self.l2pf): + # The next GEMM's weight into L2 after this thread's push, so the burst overlaps the poll / reduce / + # norm phase rather than the fold's gathers (one thread, not thread 0). + if tidx == self.threads - 1: + l2_prefetch_slice(pf_ptr, pf_bytes, pf_per, bid) + # ---- PDL: release dependents only after every allocator-recyclable input is consumed by the whole CTA # (a dependent's pre-wait write into a recycled block must not race these reads). After this only the # persistent workspace / flags and this call's outputs are touched. ---- @@ -1089,6 +1152,9 @@ def kernel_mt( topw_ptr: Int64, perm_ptr: Int64, rank: Int32, + pf_ptr: Int64, + pf_bytes: Int64, + pf_per: Int64, ) -> None: """BF16 two-shot, ``tpc`` consecutive tokens per CTA (module docstring); per token the ``kernel`` path's arithmetic (two-shot, BF16, ctas == 1).""" @@ -1183,6 +1249,12 @@ def kernel_mt( _sanitize(x3), ) + if const_expr(self.l2pf): + # The next GEMM's weight into L2 after this thread's push, so the burst overlaps the poll / reduce / + # norm phase rather than the fold's gathers (one thread, not thread 0). + if tidx == self.threads - 1: + l2_prefetch_slice(pf_ptr, pf_bytes, pf_per, bid) + # ---- PDL: every input consumed (the residual words went to smem, x to the scatter) by every thread ---- if const_expr(self.use_pdl): cute.arch.sync_threads() diff --git a/tensorrt_llm/_torch/kernels/blackwell/mnnvl_slot_allreduce_norm.py b/tensorrt_llm/_torch/kernels/blackwell/mnnvl_slot_allreduce_norm.py index 9d0c2463d2b8..1a449ffebaad 100644 --- a/tensorrt_llm/_torch/kernels/blackwell/mnnvl_slot_allreduce_norm.py +++ b/tensorrt_llm/_torch/kernels/blackwell/mnnvl_slot_allreduce_norm.py @@ -19,13 +19,27 @@ workspace without ``buffer_flags``: * CTA ``b`` owns, per region, the slot block [b][rank][threads] (geometry must be fixed per workspace). Its - participation count ``n_b`` (int32 at ``ctl + 128 * b``, read by thread 0, written back + 1) selects region - ``n_b % 3``: multicast into it, clear own region ``(n_b + 2) % 3``, poll ``n_b % 3`` (-0.0 = not written). + participation index ``n_b`` in 0..2 (int32 at ``ctl + 128 * b``, read by thread 0, written back as + ``(n_b + 1) % 3``) selects region ``n_b``: multicast into it, clear own region ``(n_b + 2) % 3``, poll ``n_b`` + (-0.0 = not written). * Safety: a peer is at most one participation of CTA ``b`` ahead (it needs this rank's data in between), so - it writes regions ``n_b`` / ``n_b + 1`` only, never the one being cleared. + it writes regions ``n_b`` / ``(n_b + 1) % 3`` only, never the one being cleared. * Cross-CTA norm sums use st.async onto a per-CTA mbarrier (no barrier.cluster). -Before ``griddepcontrol.wait`` only the norm weight and shared memory / cluster state are touched. +``ts_ctas`` > 0 (rows from ``TWO_SHOT_ROWS``): the same one-shot transport with the two-shot kernel's +arithmetic for a two-shot launch of ``ts_ctas`` CTAs per token, so the outputs equal ``MnnvlAllReduceNormKernel``'s +two-shot outputs bit for bit: the rank-order FP32 sum is packed to BF16 and sanitized before the residual add (the +owner's broadcast word), the norm's sum of squares is the two-shot CTA butterfly over that CTA's warps, then summed in +CTA order (the cluster exchange carries every warp's sum, not one per CTA), and the norm output is ``(w * x) * rstd``. + +Before ``griddepcontrol.wait`` only the norm weight and shared memory / cluster state are touched, except in the +no-wait Lamport mode (``fc2_lamport``): there the fold reads the residual, the routing tables (relaxed loads), the +shared expert's output and gate, and polls FC2's rows, all before the wait, which comes only before the stores. That +is safe because none of these is written by a kernel still running when this launch starts: FC2 (the PDL primary) +releases it only after its own dependency wait and, for an engine that routes, after it wrote the routing tables, so +the residual's producer has completed; the shared expert runs on the aux stream, which the caller fences and joins +before this launch (a full stream dependency, not PDL); FC2's own rows are polled per 16-byte vector against +0xFFFFFFFF. The stores wait because the outputs may alias allocator blocks FC2 still reads. """ from __future__ import annotations @@ -67,10 +81,14 @@ _st_shared_f32, _st_v2, _st_v4, + l2_prefetch_slice, ) from .utils import griddepcontrol_launch_dependents, griddepcontrol_wait SLOT_STATE_STRIDE = 128 # bytes between per-CTA state words (one L2 line each) +#: The word FC2 never writes (0xFFFFFFFF: two BF16 0xFFFF; FC2's ``cvt.rn.satfinite.bf16x2.f32`` NaN is 0x7FFF): +#: with ``fc2_lamport`` the MoE fold reads FC2's rows while FC2 still runs and waits per 16-byte vector for it to go. +_FC2_SENT = -1 @dsl_user_op @@ -90,6 +108,40 @@ def _ld_cg_s32(addr: Int64, *, loc=None, ip=None) -> Int32: ) +@dsl_user_op +def _ld_relaxed_s32(addr: Int64, *, loc=None, ip=None) -> Int32: + return Int32( + llvm.inline_asm( + T.i32(), + [Int64(addr).ir_value(loc=loc, ip=ip)], + "ld.relaxed.gpu.global.b32 $0, [$1];", + "=r,l,~{memory}", + has_side_effects=True, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def _ld_relaxed_u16(addr: Int64, *, loc=None, ip=None) -> Int32: + return Int32( + llvm.inline_asm( + T.i32(), + [Int64(addr).ir_value(loc=loc, ip=ip)], + "{\n\t.reg .b16 h;\n\tld.relaxed.gpu.global.b16 h, [$1];\n\tcvt.u32.u16 $0, h;\n\t}", + "=r,l,~{memory}", + has_side_effects=True, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + @dsl_user_op def _mbar_init(addr: Int32, count: Int32, *, loc=None, ip=None) -> None: llvm.inline_asm( @@ -192,6 +244,9 @@ def __init__( region_bytes: int, moe_topk: int = 0, fc2_row: int = 0, + l2pf: bool = False, + fc2_lamport: bool = False, + ts_ctas: int = 0, ): if hidden % (VEC * ctas) or (hidden // VEC // ctas) % 32 or hidden // VEC // ctas > 1024: raise ValueError(f"unsupported hidden size {hidden} for {ctas} CTAs per token") @@ -199,6 +254,16 @@ def __init__( raise ValueError("unsupported group / cluster size") if region_bytes <= 0: raise ValueError("the slot protocol needs region_bytes") + token_warps = hidden // VEC // 32 + if ts_ctas and ( + ts_ctas not in (1, 2, 4, 8) + or token_warps % ts_ctas + or not 1 <= token_warps // ts_ctas <= 32 + or (token_warps // ts_ctas) & (token_warps // ts_ctas - 1) + ): + raise ValueError(f"unsupported two-shot CTA split {ts_ctas} for hidden size {hidden}") + # the two-shot kernel's arithmetic for its launch of ts_ctas CTAs per token (module docstring) + self.ts_ctas = ts_ctas self.hidden = hidden self.norm_eps = float(norm_eps) self.nranks = nranks @@ -212,6 +277,16 @@ def __init__( self.norm_out = norm_out self.quant = quant self.region_bytes = region_bytes + self.l2pf = l2pf # prefetch pf_ptr's slice into L2 after this CTA's pushes + # fc2_lamport (moe_topk > 0): fc2 is a Lamport buffer (0xFFFFFFFF where FC2 has not written yet), polled + # instead of a dependency wait before the fold; FC2 is the PDL primary, the aux-stream inputs are fenced by + # the caller (MnnvlAllReduceNorm fc2_lamport). The vectors read are written back to 0xFFFFFFFF. + self.fc2_lamport = fc2_lamport + # fc2_lamport: outputs come from the caching allocator and may alias blocks FC2 still reads, so every store + # waits for the dependency (which also orders this kernel's end after FC2's). + self.store_wait = bool(use_pdl and fc2_lamport) + if fc2_lamport and not (se_fold and moe_topk > 0): + raise ValueError("fc2_lamport needs the in-kernel MoE finalize") @cute.jit def __call__( @@ -233,6 +308,9 @@ def __call__( topw_ptr: Int64, perm_ptr: Int64, rank: Int32, + pf_ptr: Int64, + pf_bytes: Int64, + pf_per: Int64, stream, ) -> None: m = cute.size(gRes, mode=[0]) @@ -254,15 +332,31 @@ def __call__( topw_ptr, perm_ptr, rank, + pf_ptr, + pf_bytes, + pf_per, ).launch( grid=[m * self.ctas, 1, 1], block=[self.threads, 1, 1], cluster=[self.ctas, 1, 1], - smem=512, + smem=self.smem_bytes(), stream=stream, use_pdl=self.use_pdl, ) + def smem_bytes(self) -> int: + """Dynamic shared memory of a launch: ``kernel``'s allocations (warp sums, cluster sums, flags, mbarrier, + each 16-byte aligned), and at least 512 bytes. Nothing in the kernel reads beyond its allocations; the floor + keeps the launch of every hidden size up to 16384, whose allocations fit in it, at the shared-memory size + its decode-step timings were measured with (occupancy is bound by threads and registers, not by this).""" + + def up16(n: int) -> int: + return (n + 15) // 16 * 16 + + nsum = self.ctas * self.num_warps if self.ts_ctas else self.ctas + need = up16(4 * self.num_warps) + up16(4 * nsum) + 32 + (8 if self.ctas > 1 else 0) + return max(512, up16(need)) + @cute.kernel def kernel( self, @@ -283,6 +377,9 @@ def kernel( topw_ptr: Int64, perm_ptr: Int64, rank: Int32, + pf_ptr: Int64, + pf_bytes: Int64, + pf_per: Int64, ) -> None: tidx, _, _ = cute.arch.thread_idx() bid, _, _ = cute.arch.block_idx() @@ -298,9 +395,12 @@ def kernel( lane = tidx % 32 row_off = (Int64(tok) * Int64(vecs) + Int64(vi)) * Int64(16) + ts_ctas: cutlass.Constexpr = self.ts_ctas + # cluster exchange: one sum per CTA, or (ts_ctas) one per warp of the token, in global warp order + nsum: cutlass.Constexpr = ctas * num_warps if ts_ctas else ctas smem = cutlass.utils.SmemAllocator() red = smem.allocate_tensor(Float32, cute.make_layout((num_warps,)), byte_alignment=16) - csum = smem.allocate_tensor(Float32, cute.make_layout((ctas,)), byte_alignment=16) + csum = smem.allocate_tensor(Float32, cute.make_layout((nsum,)), byte_alignment=16) fl = smem.allocate_tensor(Int32, cute.make_layout((8,)), byte_alignment=16) red_addr = _smem_addr(red.iterator) csum_addr = _smem_addr(csum.iterator) @@ -315,25 +415,33 @@ def kernel( _mbar_init(mbar_addr, Int32(1)) _cluster_sync() if tidx == 0: - _mbar_expect_tx(mbar_addr, Int32(4 * ctas)) + _mbar_expect_tx(mbar_addr, Int32(4 * nsum)) - # ---- before the dependency wait: only the norm weight ---- + # ---- before the dependency wait: only the norm weight (with fc2_lamport also the fold's inputs below: there + # the wait comes before the stores; see the module docstring) ---- w0, w1, w2, w3 = _ld_v4(Int64(gW.iterator.toint()) + Int64(vi) * Int64(16)) topk: cutlass.Constexpr = self.moe_topk pk = cute.make_rmem_tensor((max(topk, 1),), Int32) wk = cute.make_rmem_tensor((max(topk, 1),), Int32) - if const_expr(self.use_pdl): + if const_expr(self.use_pdl and not self.fc2_lamport): griddepcontrol_wait() r0, r1, r2, r3 = _ld_v4(Int64(gRes.iterator.toint()) + row_off) if const_expr(self.se_fold): if const_expr(topk > 0): - # routing outputs of this step: only after the dependency wait (RAW) + # routing outputs of this step: after the dependency wait (RAW), or, with fc2_lamport, written before + # the dependency released this launch (an engine that routes releases it only after its tables) kbase = Int64(tok) * Int64(topk) for k in cutlass.range_constexpr(topk): - pk[k] = _ld_s32(perm_ptr + (kbase + Int64(k)) * Int64(4)) - wk[k] = _ld_u16(topw_ptr + (kbase + Int64(k)) * Int64(2)) + pa = perm_ptr + (kbase + Int64(k)) * Int64(4) + wa = topw_ptr + (kbase + Int64(k)) * Int64(2) + if const_expr(self.fc2_lamport): + pk[k] = _ld_relaxed_s32(pa) + wk[k] = _ld_relaxed_u16(wa) + else: + pk[k] = _ld_s32(pa) + wk[k] = _ld_u16(wa) else: f0, f1, f2, f3 = _ld_v4(Int64(gRouted.iterator.toint()) + row_off) h0, h1, h2, h3 = _ld_v4(Int64(gShared.iterator.toint()) + row_off) @@ -341,7 +449,7 @@ def kernel( else: x0, x1, x2, x3 = _ld_v4(Int64(gX.iterator.toint()) + row_off) - # ---- this CTA's participation count, read by one thread and shared through smem ---- + # ---- this CTA's participation index, read by one thread and shared through smem ---- if tidx == 0: fl[0] = _ld_cg_s32(ctl + Int64(bid) * Int64(SLOT_STATE_STRIDE)) cute.arch.sync_threads() @@ -350,15 +458,47 @@ def kernel( if const_expr(topk > 0): ev = cute.make_rmem_tensor((topk * 4,), Int32) for k in cutlass.range_constexpr(topk): - e0, e1, e2, e3 = _ld_v4( - fc2_ptr - + (Int64(_max0(pk[k])) * Int64(self.fc2_row) + Int64(vi) * Int64(VEC)) - * Int64(2) - ) + fa = fc2_ptr + ( + Int64(_max0(pk[k])) * Int64(self.fc2_row) + Int64(vi) * Int64(VEC) + ) * Int64(2) + if const_expr(self.fc2_lamport): + # real rows only: a word has exactly one reader, which resets it (non-local k stay 0 and + # are dropped by the select below) + e0 = Int32(0) + e1 = Int32(0) + e2 = Int32(0) + e3 = Int32(0) + if pk[k] >= 0: + e0, e1, e2, e3 = _ld_volatile_v4(fa) + else: + e0, e1, e2, e3 = _ld_v4(fa) ev[4 * k + 0] = e0 ev[4 * k + 1] = e1 ev[4 * k + 2] = e2 ev[4 * k + 3] = e3 + if const_expr(self.fc2_lamport): + # Lamport: FC2 writes every word of a real row once and never the word 0xFFFFFFFF (its BF16 NaN + # is 0x7FFF), so a local row's vector is complete once none of its words is that word. Non-local + # k (perm < 0) read row 0 above and are dropped by the select below, as without Lamport. + pending = Int32(1) + while pending != 0: + pending = Int32(0) + for k in cutlass.range_constexpr(topk): + if pk[k] >= 0: + bad = Int32(0) + for i in cutlass.range_constexpr(4): + if ev[4 * k + i] == Int32(_FC2_SENT): + bad = Int32(1) + if bad != 0: + fb = fc2_ptr + ( + Int64(pk[k]) * Int64(self.fc2_row) + Int64(vi) * Int64(VEC) + ) * Int64(2) + g0, g1, g2, g3 = _ld_volatile_v4(fb) + ev[4 * k + 0] = g0 + ev[4 * k + 1] = g1 + ev[4 * k + 2] = g2 + ev[4 * k + 3] = g3 + pending = Int32(1) acc = cute.make_rmem_tensor((VEC,), Float32) for e in cutlass.range_constexpr(VEC): acc[e] = Float32(0.0) @@ -375,6 +515,21 @@ def kernel( f1 = _pack_bf16(acc[2], acc[3]) f2 = _pack_bf16(acc[4], acc[5]) f3 = _pack_bf16(acc[6], acc[7]) + if const_expr(self.fc2_lamport): + # This thread is the only reader of these vectors: hand them back to the next FC2 (it writes + # after kernel boundaries that follow this kernel's end). + for k in cutlass.range_constexpr(topk): + if pk[k] >= 0: + fr = fc2_ptr + ( + Int64(pk[k]) * Int64(self.fc2_row) + Int64(vi) * Int64(VEC) + ) * Int64(2) + _st_v4( + fr, + Int32(_FC2_SENT), + Int32(_FC2_SENT), + Int32(_FC2_SENT), + Int32(_FC2_SENT), + ) g = _lo(gw) s = _sigmoid_triton(g) x0 = _pack_bf16(_fma(s, _lo(h0), _lo(f0)), _fma(s, _hi(h0), _hi(f0))) @@ -386,9 +541,7 @@ def kernel( neg0 = Int32(_NEG_ZERO) slot_cnt = fl[0] blk_bytes: cutlass.Constexpr = nranks * threads * 16 # [W slots] of this CTA - data_off = Int64(slot_cnt % Int32(3)) * Int64(self.region_bytes) + Int64(bid) * Int64( - blk_bytes - ) + data_off = Int64(slot_cnt) * Int64(self.region_bytes) + Int64(bid) * Int64(blk_bytes) _st_v4( mcast + data_off + (Int64(rank) * Int64(threads) + Int64(tidx)) * Int64(16), _sanitize(x0), @@ -398,6 +551,12 @@ def kernel( ) poll_base = own + data_off + Int64(tidx) * Int64(16) + if const_expr(self.l2pf): + # The next GEMM's weight into L2 after this thread's push, so the burst overlaps the poll / reduce / + # norm phase rather than the fold's gathers (one thread, not thread 0). + if tidx == self.threads - 1: + l2_prefetch_slice(pf_ptr, pf_bytes, pf_per, bid) + # ---- PDL: release dependents once every recyclable input is consumed (a dependent's pre-wait write # into a recycled block must not race these reads) ---- if const_expr(self.use_pdl): @@ -405,9 +564,9 @@ def kernel( cute.arch.sync_threads() griddepcontrol_launch_dependents() - # ---- count the participation; clear this thread's slots of the previous participation's region ---- + # ---- advance the participation index; clear this thread's slots of the previous participation's region ---- if tidx == 0: - _st_s32(ctl + Int64(bid) * Int64(SLOT_STATE_STRIDE), slot_cnt + Int32(1)) + _st_s32(ctl + Int64(bid) * Int64(SLOT_STATE_STRIDE), (slot_cnt + Int32(1)) % Int32(3)) pq = (slot_cnt + Int32(2)) % Int32(3) pbase = ( own @@ -449,16 +608,23 @@ def kernel( for r in cutlass.range_constexpr(nranks): lo = _add(lo, _lo(got[r * 4 + i])) hi = _add(hi, _hi(got[r * 4 + i])) - res[2 * i] = _bf16r(_add(_bf16r(lo), _lo(rw[i]))) - res[2 * i + 1] = _bf16r(_add(_bf16r(hi), _hi(rw[i]))) + if const_expr(ts_ctas > 0): + # the two-shot owner's broadcast word: BF16 pair, each -0.0 as +0.0 + sw = _sanitize(_pack_bf16(lo, hi)) + res[2 * i] = _bf16r(_add(_lo(sw), _lo(rw[i]))) + res[2 * i + 1] = _bf16r(_add(_hi(sw), _hi(rw[i]))) + else: + res[2 * i] = _bf16r(_add(_bf16r(lo), _lo(rw[i]))) + res[2 * i + 1] = _bf16r(_add(_bf16r(hi), _hi(rw[i]))) out_off = Int64(gResOut.iterator.toint()) + row_off - _st_v4( - out_off, - _pack_bf16(res[0], res[1]), - _pack_bf16(res[2], res[3]), - _pack_bf16(res[4], res[5]), - _pack_bf16(res[6], res[7]), - ) + if const_expr(not self.store_wait): + _st_v4( + out_off, + _pack_bf16(res[0], res[1]), + _pack_bf16(res[2], res[3]), + _pack_bf16(res[4], res[5]), + _pack_bf16(res[6], res[7]), + ) # ---- RMSNorm: BF16 squares, per-thread sum in element order, warp / CTA / cluster sums ---- tsum = Float32(0.0) @@ -469,21 +635,61 @@ def kernel( if lane == 0: _st_shared_f32(red_addr + Int32(4) * warp, tsum) cute.arch.sync_threads() - total = _tree_sum_smem(red_addr, num_warps) - if const_expr(ctas > 1): - if tidx < ctas: - _st_async_f32(csum_addr + Int32(4) * part, mbar_addr, Int32(tidx), total) - ready = _mbar_try_wait(mbar_addr, Int32(0)) - while ready == 0: + if const_expr(ts_ctas > 0): + # Two-shot arithmetic: warp sums at their global warp index (part * num_warps + w), a butterfly per + # two-shot CTA q over warps q * wpc .., the CTA sums in order (lane 0 of a full XOR butterfly stands for + # every lane: commutative adds, zero lanes add +0.0 to non-negative sums). + wpc: cutlass.Constexpr = (ctas * num_warps) // ts_ctas + src = red_addr + if const_expr(ctas > 1): + src = csum_addr + if tidx < ctas * num_warps: + _st_async_f32( + csum_addr + Int32(4) * (part * Int32(num_warps) + tidx % Int32(num_warps)), + mbar_addr, + tidx // Int32(num_warps), + _ld_shared_f32(red_addr + Int32(4) * (tidx % Int32(num_warps))), + ) ready = _mbar_try_wait(mbar_addr, Int32(0)) - total = Float32(0.0) - for p in cutlass.range_constexpr(ctas): - total = _add(total, _ld_shared_f32(csum_addr + Int32(4 * p))) + while ready == 0: + ready = _mbar_try_wait(mbar_addr, Int32(0)) + if const_expr(ts_ctas == 1): + total = _tree_sum_smem(src, wpc) + else: + total = Float32(0.0) + for q in cutlass.range_constexpr(ts_ctas): + total = _add(total, _tree_sum_smem(src + Int32(4 * q * wpc), wpc)) + else: + total = _tree_sum_smem(red_addr, num_warps) + if const_expr(ctas > 1): + if tidx < ctas: + _st_async_f32(csum_addr + Int32(4) * part, mbar_addr, Int32(tidx), total) + ready = _mbar_try_wait(mbar_addr, Int32(0)) + while ready == 0: + ready = _mbar_try_wait(mbar_addr, Int32(0)) + total = Float32(0.0) + for p in cutlass.range_constexpr(ctas): + total = _add(total, _ld_shared_f32(csum_addr + Int32(4 * p))) rstd = _rsqrt(_add(_div_rn(total, Float32(float(self.hidden))), Float32(self.norm_eps))) y = cute.make_rmem_tensor((VEC,), Float32) - for i in cutlass.range_constexpr(4): # (x * rstd) * w - y[2 * i] = _bf16r(_mul(_mul(res[2 * i], rstd), _lo(ww[i]))) - y[2 * i + 1] = _bf16r(_mul(_mul(res[2 * i + 1], rstd), _hi(ww[i]))) + if const_expr(ts_ctas > 0): + for i in cutlass.range_constexpr(4): # the two-shot's (w * x) * rstd + y[2 * i] = _bf16r(_mul(_mul(_lo(ww[i]), res[2 * i]), rstd)) + y[2 * i + 1] = _bf16r(_mul(_mul(_hi(ww[i]), res[2 * i + 1]), rstd)) + else: + for i in cutlass.range_constexpr(4): # (x * rstd) * w + y[2 * i] = _bf16r(_mul(_mul(res[2 * i], rstd), _lo(ww[i]))) + y[2 * i + 1] = _bf16r(_mul(_mul(res[2 * i + 1], rstd), _hi(ww[i]))) + if const_expr(self.store_wait): + # fc2_lamport: every store into allocator memory after the dependency wait (see __init__) + griddepcontrol_wait() + _st_v4( + out_off, + _pack_bf16(res[0], res[1]), + _pack_bf16(res[2], res[3]), + _pack_bf16(res[4], res[5]), + _pack_bf16(res[6], res[7]), + ) if const_expr(self.norm_out): _st_v4( Int64(gOut.iterator.toint()) + row_off, diff --git a/tensorrt_llm/_torch/kernels/blackwell/moe_bf16_engine.py b/tensorrt_llm/_torch/kernels/blackwell/moe_bf16_engine.py new file mode 100644 index 000000000000..ce7d1ce8f621 --- /dev/null +++ b/tensorrt_llm/_torch/kernels/blackwell/moe_bf16_engine.py @@ -0,0 +1,1024 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Decode MoE engine for BF16 experts routed from the router logits: Renormalize routing and one rank's routed experts +in one persistent launch, returning what ``trtllm::bf16_moe_runner`` returns un-finalized (per (token, k) a gemm2 row +and the BF16 top-k weight; the local picks' rows packed). + +Every CTA routes the step's rows in its prologue, then runs FC1 -> SwiGLU -> FC2 with ``kind::f16`` MMAs over the +whole K in order on the BlockMajorK weights in place. Scheduling: ``moe_persistent_engine``. + +Parity with ``bf16_moe_runner``: the same picks and gemm2 rows bit for bit; the BF16 top-k weights within 1 ulp. The +prologue's softmax is the fast-math sequence (``ex2.approx``, ``rcp.approx``) while the runner's routing +(RoutingKernel.cuh, built without fast math) uses ``expf`` and an IEEE divide, so a weight can round to the +neighbouring BF16 value. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Tuple + +import cuda.bindings.driver as cuda +import cutlass +import cutlass.cute as cute +import cutlass.utils.blackwell_helpers as sm100_utils +from cutlass import Int32, Int64 +from cutlass.cute.nvgpu import cpasync, tcgen05 +from cutlass.pipeline import ( + Agent, + CooperativeGroup, + PipelineAsync, + PipelineUmmaAsync, + PipelineUserType, + make_pipeline_state, + pipeline_init_arrive, + pipeline_init_wait, +) + +if TYPE_CHECKING: + import torch + +from ...cute_dsl_utils import gmem_ptr +from .moe_decode_front import ( + _below, + _bit, + _bitonic_pairs, + _key1, + _key_val, + _ld_v4, + _max_u32, + _min_u32, + _popc, + _red_or_shared, + _redux_max_u32, + _sel_eq, + _sel_eq_f, + _sel_lt, + _st_b16, + _st_b32, +) +from .moe_persistent_engine import ( + EPI_BAR, + EPI_GROUPS, + EPI_WARP0, + LOG2E, + NUM_ACC, + QD, + THREADS, + TILE_M, + PersistentMoeEngine, + launch, + new_state, + ring_smem_bytes, +) +from .ptx_helpers import ( + _add_rn, + _cp_async_16, + _cp_async_arrive_noinc, + _cp_async_commit, + _ex2, + _mul_rn, + _pack_bf16x2_rn, + _policy_evict_first, + _policy_evict_last, + _rcp, + _st_global_b32, + _st_global_b32_hint, + sum_tree, +) + +TILE_K = 128 # bf16 elements per ring stage (256 bytes per row) +KB = 64 # BlockMajorK block (128 bytes of bf16) +M_MAX = 32 # rows routed in the prologue (one token bit per row) +N_MAX = (16, 32) # MMA N (rows per segment; an expert holds at most m rows) + +__all__ = [ + "M_MAX", + "MoeBf16Engine", + "moe_bf16_engine", + "new_state", + "supports_local_experts", + "supports_routing", +] + + +# ---------------------------------------------------------------------------------------------------------------- +# PTX helpers +# ---------------------------------------------------------------------------------------------------------------- +def _sub_rn_ftz(a, b): + return cute.arch.inline_ptx( + "sub.rn.ftz.f32 {$w0}, {$r0}, {$r1};", + write_only_types=[cutlass.Float32], + read_only_args=[a, b], + ) + + +def _mul_rn_ftz(a, b): + return cute.arch.inline_ptx( + "mul.rn.ftz.f32 {$w0}, {$r0}, {$r1};", + write_only_types=[cutlass.Float32], + read_only_args=[a, b], + ) + + +def _pack_bf16x2_satfinite(lo, hi): + """{bf16(hi), bf16(lo)} by cvt.rn.satfinite.bf16x2.f32 (lo in the low half).""" + return cute.arch.inline_ptx( + "cvt.rn.satfinite.bf16x2.f32 {$w0}, {$r1}, {$r0};", + write_only_types=[Int32], + read_only_args=[lo, hi], + ) + + +def supports_routing(num_experts: int, top_k: int) -> bool: + """Router shapes the prologue takes: one warp per row, ``num_experts / 32`` logits per lane in whole 16-byte + loads (8 or 16, bitonic-sorted), and every pick within one lane's sorted keys.""" + per_lane = num_experts // 32 + return num_experts % 32 == 0 and per_lane in (8, 16) and 1 <= top_k <= per_lane + + +def supports_local_experts(num_experts: int, num_local: int) -> bool: + """Local expert counts the kernel takes: whole lanes of warp 0's per-expert scan (``segments``).""" + return num_local % 32 == 0 and 32 <= num_local <= num_experts + + +def _butterfly_sum(top_k: int): + """The routing kernels' softmax sum over the top-k values held by lanes 0 .. top_k - 1 (the others hold 0): the + warp butterfly (xor 16, 8, 4, 2, 1) as lane 0 sees it, as nested pairs of value indices (adding 0 is exact).""" + lanes = [i if i < top_k else None for i in range(32)] + for off in (16, 8, 4, 2, 1): + lanes = [ + lanes[i] + if lanes[i ^ off] is None + else (lanes[i ^ off] if lanes[i] is None else (lanes[i], lanes[i ^ off])) + for i in range(32) + ] + return lanes[0] + + +def smem_views(storage, num_local: int, top_k: int): + """Tensor views of the engine's shared-memory int32 arrays: nseg, seg_e, seg_r0, seg_n, mask (token bits per + local expert), eoff (first permuted row per local expert, then the total), pick (local expert of pick + row * top_k + k, or -1), p2t (permuted row -> token).""" + + def view(mr, n): + return mr.get_tensor(cute.make_layout(n)) + + return ( + view(storage.nseg, 4), + view(storage.seg_e, M_MAX * top_k), + view(storage.seg_r0, M_MAX * top_k), + view(storage.seg_n, M_MAX * top_k), + view(storage.mask, num_local), + view(storage.eoff, num_local + 1), + view(storage.pick, M_MAX * top_k), + view(storage.p2t, M_MAX * top_k), + ) + + +# ---------------------------------------------------------------------------------------------------------------- +class MoeBf16Engine(PersistentMoeEngine): + """Compile-time configuration: ``num_experts`` / ``top_k`` (routing, :func:`supports_routing`), ``num_local`` + (local experts), ``n_max`` (MMA N, rows per segment), ``num_stages`` (ring depth). Epilogues: FC1 + ``h = bf16_rn(u (g sigmoid(g)))`` with sigmoid ``rcp.approx(ex2.approx(-g log2e) + 1)``, FC2 + ``bf16_rn_satfinite(acc)``. Every segment holds >= 1 local pick, so a call has at most ``M_MAX * top_k``. + + The activation loader acquires an FC2 unit's segment counter, so the weight loader streams the unit's weights + while FC1 completes; the dependents are released as each CTA exits.""" + + fc2_wait_in_scheduler = False + + def __init__( + self, + hidden: int, + inter: int, + num_experts: int, + top_k: int, + num_local: int, + n_max: int, + num_stages: int, + ): + assert supports_routing(num_experts, top_k) + assert supports_local_experts(num_experts, num_local) + assert n_max in N_MAX + super().__init__(hidden, inter, n_max, num_stages, TILE_K) + self.num_experts, self.top_k, self.num_local = num_experts, top_k, num_local + self.b_stage_bytes = n_max * TILE_K * 2 + self.kchunks = TILE_K * 2 // 16 # 16-byte chunks of one activation row per stage + + def _setup(self): + self.tiled_mma = sm100_utils.make_trivial_tiled_mma( + self.a_dtype, + self.a_major_mode, + self.b_major_mode, + self.acc_dtype, + self.cta_group, + (TILE_M, self.n_max), + ) + total = NUM_ACC * self.n_max + cols = 32 + while cols < total: + cols *= 2 + self.num_tmem_cols = cols + self.cluster_layout_vmnk = cute.tiled_divide( + cute.make_layout((1, 1, 1)), (self.tiled_mma.thr_id.shape,) + ) + tiler = (TILE_M, self.n_max, self.tile_k) + self.a_smem_layout_staged = sm100_utils.make_smem_layout_a( + self.tiled_mma, tiler, self.a_dtype, self.num_stages + ) + self.b_smem_layout_staged = sm100_utils.make_smem_layout_b( + self.tiled_mma, tiler, self.b_dtype, self.num_stages + ) + + def _a_atoms(self, w_ptr, rows, k, e): + """TMA atom over the BlockMajorK weights: element (row r, k kk, expert x) at x rows k + (kk / 64) rows 64 + + r 64 + kk % 64 (the K mode is (64, K / 64)).""" + w = cute.make_tensor( + w_ptr, cute.make_layout((rows, (KB, k // KB), e), stride=(KB, (1, rows * KB), rows * k)) + ) + a_op = sm100_utils.cluster_shape_to_tma_atom_A((1, 1), self.tiled_mma.thr_id) + a_smem_layout = cute.slice_(self.a_smem_layout_staged, (None, None, None, 0)) + atom, tens = cute.nvgpu.make_tiled_tma_atom_A( + a_op, + w, + a_smem_layout, + (TILE_M, self.n_max, self.tile_k), + self.tiled_mma, + self.cluster_layout_vmnk.shape, + ) + self.tma_bytes_a = cute.size_in_bytes(self.a_dtype, a_smem_layout) + return atom, tens + + @cute.jit + def __call__( + self, + w1_ptr: cute.Pointer, + w2_ptr: cute.Pointer, + b_dummy_ptr: cute.Pointer, + x_addr: Int64, + x_row_bytes: Int64, + lg_addr: Int64, + m: Int32, + local_start: Int32, + wts_addr: Int64, + e2p_addr: Int64, + h_addr: Int64, + out_addr: Int64, + state_addr: Int64, + num_local: Int32, + grid_ctas: Int32, + stream: cuda.CUstream, + ): + e = num_local + self.a_dtype = w1_ptr.value_type + self.b_dtype = b_dummy_ptr.value_type + w_probe = cute.make_tensor( + w1_ptr, cute.make_ordered_layout((2 * self.inter, self.hidden, e), order=(1, 0, 2)) + ) + b_probe = cute.make_tensor( + b_dummy_ptr, cute.make_ordered_layout((self.n_max, self.tile_k, 1), order=(1, 0, 2)) + ) + self.a_major_mode = cutlass.utils.LayoutEnum.from_tensor(w_probe).mma_major_mode() + self.b_major_mode = cutlass.utils.LayoutEnum.from_tensor(b_probe).mma_major_mode() + self._setup() + a1, t1 = self._a_atoms(w1_ptr, 2 * self.inter, self.hidden, e) + a2, t2 = self._a_atoms(w2_ptr, self.hidden, self.inter, e) + self.kernel( + self.tiled_mma, + a1, + t1, + a2, + t2, + self.cluster_layout_vmnk, + self.a_smem_layout_staged, + self.b_smem_layout_staged, + x_addr, + x_row_bytes, + lg_addr, + m, + local_start, + wts_addr, + e2p_addr, + h_addr, + out_addr, + state_addr, + ).launch( + grid=[grid_ctas, 1, 1], + block=[THREADS, 1, 1], + cluster=(1, 1, 1), + stream=stream, + use_pdl=self.use_pdl, + min_blocks_per_mp=1, + ) + + # ------------------------------------------------------------------------------------------------------------ + @cute.kernel + def kernel( + self, + tiled_mma: cute.TiledMma, + tma_a1: cute.CopyAtom, + mA1: cute.Tensor, + tma_a2: cute.CopyAtom, + mA2: cute.Tensor, + cluster_layout_vmnk: cute.Layout, + a_smem_layout_staged: cute.ComposedLayout, + b_smem_layout_staged: cute.ComposedLayout, + x_addr: Int64, + x_row_bytes: Int64, + lg_addr: Int64, + m: Int32, + local_start: Int32, + wts_addr: Int64, + e2p_addr: Int64, + h_addr: Int64, + out_addr: Int64, + state_addr: Int64, + ): + warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + tidx, _, _ = cute.arch.thread_idx() + bidx, _, _ = cute.arch.block_idx() + gdx, _, _ = cute.arch.grid_dim() + lane = cute.arch.lane_idx() + Stages = self.num_stages + NT = THREADS + NLOC = self.num_local + SEGS = M_MAX * self.top_k + + @cute.struct + class SharedStorage: + ab_bars: cute.struct.MemRange[cutlass.Int64, Stages * 2] + acc_bars: cute.struct.MemRange[cutlass.Int64, NUM_ACC * 2] + tmem_bar: cutlass.Int64 + tmem_base: cutlass.Int32 + nseg: cute.struct.MemRange[cutlass.Int32, 4] + seg_e: cute.struct.MemRange[cutlass.Int32, SEGS] + seg_r0: cute.struct.MemRange[cutlass.Int32, SEGS] + seg_n: cute.struct.MemRange[cutlass.Int32, SEGS] + mask: cute.struct.MemRange[cutlass.Int32, NLOC] + eoff: cute.struct.MemRange[cutlass.Int32, NLOC + 1] + pick: cute.struct.MemRange[cutlass.Int32, SEGS] + p2t: cute.struct.MemRange[cutlass.Int32, SEGS] + uq: cute.struct.MemRange[cutlass.Int32, QD] + q_bars: cute.struct.MemRange[cutlass.Int64, 3 * QD] + + smem = cutlass.utils.SmemAllocator() + storage = smem.allocate(SharedStorage) + s_nseg, s_seg_e, s_seg_r0, s_seg_n, s_mask, s_eoff, s_pick, s_p2t = smem_views( + storage, NLOC, self.top_k + ) + if warp_idx == 0: + cpasync.prefetch_descriptor(tma_a1) + cpasync.prefetch_descriptor(tma_a2) + ab_pipeline = PipelineAsync.create( + barrier_storage=storage.ab_bars.data_ptr(), + num_stages=Stages, + producer_group=CooperativeGroup(Agent.Thread, 1 + 32), + consumer_group=CooperativeGroup(Agent.Thread), + defer_sync=True, + ) + ab_full = ab_pipeline.sync_object_full.barrier_storage + ab_empty = ab_pipeline.sync_object_empty.barrier_storage + acc_pipeline = PipelineUmmaAsync.create( + barrier_storage=storage.acc_bars.data_ptr(), + num_stages=NUM_ACC, + producer_group=CooperativeGroup(Agent.Thread), + consumer_group=CooperativeGroup(Agent.Thread, 128), + defer_sync=True, + ) + acc_full = acc_pipeline.sync_object_full.barrier_storage + acc_empty = acc_pipeline.sync_object_empty.barrier_storage + tmem_bar = storage.tmem_bar.ptr + tmem_base_smem_ptr = storage.tmem_base.ptr + s_q = storage.uq.get_tensor(cute.make_layout(QD)) + q_full = storage.q_bars.data_ptr() # full [QD], empty [QD], taken [QD] + self.init_barriers(warp_idx, tmem_bar, q_full) + sA = smem.allocate_tensor( + element_type=self.a_dtype, + layout=a_smem_layout_staged.outer, + byte_alignment=1024, + swizzle=a_smem_layout_staged.inner, + ) + sB = smem.allocate_tensor( + element_type=self.b_dtype, + layout=b_smem_layout_staged.outer, + byte_alignment=1024, + swizzle=b_smem_layout_staged.inner, + ) + sb_base = sB.iterator.toint() + pipeline_init_arrive(cluster_shape_mn=None, is_relaxed=True) + pipeline_init_wait(cluster_shape_mn=None) + + # pre-wait: the token masks start empty (shared memory only) + for i in cutlass.range(tidx, NLOC, NT, unroll=1): + s_mask[i] = Int32(0) + gen = self.wait_dependency(state_addr) + cute.arch.barrier() # the masks are zero before any warp sets bits in them + # ---- routing: every CTA routes all m rows (warp w: rows w, w + 12, ...), trtllm-gen Renormalize (same picks, + # weights within 1 BF16 ulp) + self.route(lg_addr, m, local_start, wts_addr, s_mask, s_pick, warp_idx, lane, bidx) + cute.arch.barrier() + # ---- segments (warp 0): per local expert its rows (token bits), first permuted row, segments of <= n_max + if warp_idx == 0: + self.segments(s_mask, s_eoff, s_seg_e, s_seg_r0, s_seg_n, s_nseg, lane) + cute.arch.barrier() + # ---- permuted row -> token (every CTA); expanded -> permuted for the fold (CTA 0) + self.rows(m, s_mask, s_eoff, s_pick, s_p2t, e2p_addr, tidx, bidx) + cute.arch.barrier() + nseg = s_nseg[0] + cnt_base, pool_addr, u1, u2, n1 = self.begin_call(state_addr, gen, nseg, bidx, tidx, gdx) + + if warp_idx == 0: + self.load_a( + ab_full, + ab_empty, + tma_a1, + mA1, + tma_a2, + mA2, + sA, + tiled_mma, + cluster_layout_vmnk, + s_seg_e, + s_q, + q_full, + u1, + bidx, + ) + elif warp_idx == 1: + self.load_b( + ab_full, + ab_empty, + s_seg_r0, + s_seg_n, + s_p2t, + sb_base, + x_addr, + x_row_bytes, + h_addr, + s_q, + q_full, + u1, + lane, + bidx, + cnt_base, + ) + elif warp_idx == 2: + self.mma( + ab_full, + ab_empty, + acc_full, + acc_empty, + tmem_bar, + tmem_base_smem_ptr, + tiled_mma, + sA, + sB, + s_q, + q_full, + u1, + ) + elif warp_idx == 3: + self.scheduler(s_q, q_full, n1, u1, u2, bidx, gdx, pool_addr, cnt_base, lane) + elif warp_idx >= EPI_WARP0: + self.epilogue( + acc_full, + acc_empty, + tmem_bar, + tmem_base_smem_ptr, + tiled_mma, + s_seg_r0, + s_seg_n, + h_addr, + out_addr, + cnt_base, + (tidx - EPI_WARP0 * 32) % 128, + (tidx - EPI_WARP0 * 32) // 128, + s_q, + q_full, + u1, + ) + self.end_call(warp_idx, tidx, gdx, tmem_base_smem_ptr, state_addr, gen) + return + + # ------------------------------------------------------------------------------------------------------------ + @cute.jit + def route(self, lg_addr, m, local_start, wts_addr, s_mask, s_pick, warp_idx, lane, bidx): + """Top-k Renormalize of the BF16 router logits [m, E], MoeDecodeFront's selection: lane l holds experts + E/32 l .. E/32 (l + 1) - 1, bitonic-sorted per lane, the warp max popped top_k times (keys unique); the + softmax in fast math (ex2.approx, rcp.approx: within 1 BF16 ulp of the runner's expf / IEEE divide), its sum + tree the routing kernels' warp butterfly. + Lane k < top_k records pick k: the token bit in its local expert's mask, its local expert (or -1), and in CTA + 0 its BF16 weight.""" + NLOC = self.num_local + TOPK = self.top_k + EPL = self.num_experts // 32 # logits (keys) per lane + SORT = _bitonic_pairs(EPL) + mask_addr = s_mask.iterator.toint() + for row in cutlass.range(warp_idx, m, THREADS // 32, unroll=1): + src = lg_addr + Int64(row) * Int64(self.num_experts * 2) + Int64(lane) * Int64(EPL * 2) + ws = [] + for v in cutlass.range_constexpr(EPL // 8): + ws.extend(_ld_v4(src + Int64(16 * v))) + e0 = lane * EPL + keys = cute.make_rmem_tensor(cute.make_layout((EPL,)), Int32) + for j in cutlass.range_constexpr(EPL // 2): + keys[2 * j] = _key1(ws[j], e0 + 2 * j) + keys[2 * j + 1] = _key1(ws[j] >> 16, e0 + 2 * j + 1) + for pi in cutlass.range_constexpr(len(SORT)): + i, jj, imax = SORT[pi] + x = keys[i] + y = keys[jj] + hi = _max_u32(x, y) + lo = _min_u32(x, y) + if cutlass.const_expr(imax): + keys[i] = hi + keys[jj] = lo + else: + keys[i] = lo + keys[jj] = hi + sel = cute.make_rmem_tensor(cute.make_layout((TOPK,)), Int32) + val = cute.make_rmem_tensor(cute.make_layout((TOPK,)), cutlass.Float32) + for k in cutlass.range_constexpr(TOPK): + head = keys[0] + g = _redux_max_u32(head) + sel[k] = Int32(65535) - (g & Int32(65535)) + val[k] = _key_val(g) + if cutlass.const_expr(k < TOPK - 1): + # pop: the owner lane's sorted keys move up by one + for j in cutlass.range_constexpr(TOPK - 1): + keys[j] = _sel_eq(head, g, keys[j + 1], keys[j]) + vmax = val[0] + ex = cute.make_rmem_tensor(cute.make_layout((TOPK,)), cutlass.Float32) + for k in cutlass.range_constexpr(TOPK): + # fast-math exp: FADD.FTZ, FMUL.FTZ by log2e, MUFU.EX2 (the runner: expf) + ex[k] = _ex2(_mul_rn_ftz(_sub_rn_ftz(val[k], vmax), cutlass.Float32(LOG2E))) + ssum = sum_tree(ex, _butterfly_sum(TOPK)) + my_sel = sel[0] + my_e = ex[0] + for k in cutlass.range_constexpr(TOPK - 1): + my_sel = _sel_eq(lane, Int32(k + 1), sel[k + 1], my_sel) + my_e = _sel_eq_f(lane, Int32(k + 1), ex[k + 1], my_e) + if lane < TOPK: + o = Int64(row) * Int64(TOPK) + Int64(lane) + if bidx == 0: + # MUFU.RCP of the sum, FMUL.FTZ, F2FP.BF16 (round to nearest even); the runner: IEEE divide + q = _mul_rn_ftz(my_e, _rcp(ssum)) + _st_b16(wts_addr + o * Int64(2), _pack_bf16x2_rn(q, q) & Int32(65535)) + lid = my_sel - local_start + pick = _sel_lt(lid, Int32(NLOC), lid, Int32(-1)) + if pick >= Int32(0): + _red_or_shared(mask_addr + pick * 4, _bit(row)) + s_pick[row * TOPK + lane] = pick + + @cute.jit + def segments(self, s_mask, s_eoff, s_seg_e, s_seg_r0, s_seg_n, s_nseg, lane): + """Warp 0, num_local / 32 local experts per lane: rows (token bits), first permuted row (warp scan), + segments of <= n_max rows in expert order.""" + NLOC = self.num_local + cnt = cute.make_rmem_tensor(cute.make_layout((NLOC // 32,)), Int32) + nsg = cute.make_rmem_tensor(cute.make_layout((NLOC // 32,)), Int32) + rows_l = Int32(0) + segs_l = Int32(0) + for q in cutlass.range_constexpr(NLOC // 32): + c = _popc(s_mask[lane * (NLOC // 32) + q]) + ns = (c + (self.n_max - 1)) // self.n_max + cnt[q] = c + nsg[q] = ns + rows_l = rows_l + c + segs_l = segs_l + ns + ri = rows_l + si = segs_l + for off in (1, 2, 4, 8, 16): + t1 = cute.arch.shuffle_sync_up(ri, off) + t2 = cute.arch.shuffle_sync_up(si, off) + if lane >= off: + ri = ri + t1 + si = si + t2 + roff = ri - rows_l + soff = si - segs_l + for q in cutlass.range_constexpr(NLOC // 32): + e = lane * (NLOC // 32) + q + s_eoff[e] = roff + for j in cutlass.range(nsg[q], unroll=1): + s_seg_e[soff] = e + s_seg_r0[soff] = roff + j * self.n_max + s_seg_n[soff] = cutlass.min(cnt[q] - j * self.n_max, self.n_max) + soff = soff + 1 + roff = roff + cnt[q] + if lane == 31: + s_nseg[0] = si + s_eoff[NLOC] = ri + + @cute.jit + def rows(self, m, s_mask, s_eoff, s_pick, s_p2t, e2p_addr, tidx, bidx): + """Permuted row -> token (an expert's rows in token order) in every CTA; CTA 0 writes the expanded -> permuted + index of every pick (-1 off this rank).""" + NLOC = self.num_local + for e in cutlass.range(tidx, NLOC, THREADS, unroll=1): + mk = s_mask[e] + r = s_eoff[e] + while mk != Int32(0): + low = mk & (Int32(0) - mk) + s_p2t[r] = _popc(low - Int32(1)) + r = r + 1 + mk = mk ^ low + if bidx == 0: + for i in cutlass.range(tidx, m * self.top_k, THREADS, unroll=1): + lid = s_pick[i] + v = Int32(-1) + if lid >= Int32(0): + v = s_eoff[lid] + _popc(s_mask[lid] & _below(i // self.top_k)) + _st_b32(e2p_addr + Int64(i) * Int64(4), v) + + @cute.jit + def load_a( + self, + ab_full, + ab_empty, + tma_a1: cute.CopyAtom, + mA1: cute.Tensor, + tma_a2: cute.CopyAtom, + mA2: cute.Tensor, + sA: cute.Tensor, + tiled_mma: cute.TiledMma, + cluster_layout_vmnk: cute.Layout, + s_seg_e: cute.Tensor, + s_q: cute.Tensor, + q_full, + u1, + bidx, + ): + """Weights of every unit, back to back through the ring (constant data).""" + thr_mma = tiled_mma.get_slice(0) + a_cta_layout = cute.make_layout(cute.slice_(cluster_layout_vmnk, (0, 0, None, 0)).shape) + g1 = cute.local_tile(mA1, (TILE_M, self.tile_k), (None, None, None)) + t1s, t1g = cpasync.tma_partition( + tma_a1, + 0, + a_cta_layout, + cute.group_modes(sA, 0, 3), + cute.group_modes(thr_mma.partition_A(g1), 0, 3), + ) + g2 = cute.local_tile(mA2, (TILE_M, self.tile_k), (None, None, None)) + t2s, t2g = cpasync.tma_partition( + tma_a2, + 0, + a_cta_layout, + cute.group_modes(sA, 0, 3), + cute.group_modes(thr_mma.partition_A(g2), 0, 3), + ) + st = make_pipeline_state(PipelineUserType.Producer, self.num_stages) + wp = _policy_evict_first() + k = Int32(0) + g = self.first_unit(s_q, q_full, u1, bidx) + self.take(q_full, 0) + while g >= 0: + is1, seg, mt = self.decode(g, u1) + ex = s_seg_e[seg] + if is1 != 0: + for kt in cutlass.range(self.k1_tiles, unroll=1): + cute.arch.mbarrier_wait(ab_empty + st.index, st.phase) + with cute.arch.elect_one(): + cute.arch.mbarrier_arrive_and_expect_tx( + ab_full + st.index, self.tma_bytes_a + ) + cute.copy( + tma_a1, + t1g[(None, mt, kt, ex)], + t1s[(None, st.index)], + tma_bar_ptr=ab_full + st.index, + cache_policy=wp, + ) + st.advance() + else: + for kt in cutlass.range(self.k2_tiles, unroll=1): + cute.arch.mbarrier_wait(ab_empty + st.index, st.phase) + with cute.arch.elect_one(): + cute.arch.mbarrier_arrive_and_expect_tx( + ab_full + st.index, self.tma_bytes_a + ) + cute.copy( + tma_a2, + t2g[(None, mt, kt, ex)], + t2s[(None, st.index)], + tma_bar_ptr=ab_full + st.index, + cache_policy=wp, + ) + st.advance() + k = k + 1 + g, slot = self.unit(s_q, q_full, k) + self.take(q_full, slot) + + @cute.jit + def _b_stage(self, is1, kt, rows, r0, sb_stage, x_addr, x_row_bytes, h_addr, s_p2t, lane): + """Issue one stage's activation rows (cp.async; 128-byte swizzle: K column j of 64 elements at j n_max 128, + row n at 1024 (n / 8) + 128 (n % 8), 16-byte chunk c at c ^ (n % 8)).""" + kc = self.kchunks + rb = (self.n_max // 8) * 1024 # bytes of one 128-byte-wide K column of swizzle atoms + if is1 != 0: + for n in cutlass.range(lane, rows, 32, unroll=1): + t = s_p2t[r0 + n] + src = x_addr + Int64(t) * x_row_bytes + Int64(kt * (kc * 16)) + dbase = sb_stage + (n >> 3) * 1024 + (n & 7) * 128 + n7 = n & 7 + for c in cutlass.range_constexpr(kc): + _cp_async_16( + dbase + ((c >> 3) * rb) + (((c & 7) ^ n7) << 4), src + Int64(c * 16) + ) + else: + for n in cutlass.range(lane, rows, 32, unroll=1): + r = r0 + n + src = h_addr + Int64(r) * Int64(self.inter * 2) + Int64(kt * (kc * 16)) + dbase = sb_stage + (n >> 3) * 1024 + (n & 7) * 128 + n7 = n & 7 + for c in cutlass.range_constexpr(kc): + _cp_async_16( + dbase + ((c >> 3) * rb) + (((c & 7) ^ n7) << 4), src + Int64(c * 16) + ) + _cp_async_commit() + + @cute.jit + def load_b( + self, + ab_full, + ab_empty, + s_seg_r0, + s_seg_n, + s_p2t, + sb_base, + x_addr, + x_row_bytes, + h_addr, + s_q, + q_full, + u1, + lane, + bidx, + cnt_base, + ): + """Activation rows of every unit: FC1 gathers x rows by permuted index -> token, FC2 reads the segment's + intermediate rows after this warp's own acquire of the segment's FC1 counter. Every lane arms an + asynchronous arrival on the stage's full barrier after issuing its copies (cp.async.mbarrier.arrive.noinc).""" + st = make_pipeline_state(PipelineUserType.Producer, self.num_stages) + k = Int32(0) + g = self.first_unit(s_q, q_full, u1, bidx) + while g >= 0: + is1, seg, mt = self.decode(g, u1) + rows = s_seg_n[seg] + r0 = s_seg_r0[seg] + kts = self.k2_tiles + if is1 != 0: + kts = self.k1_tiles + else: + # every lane acquires the counter, so its own copies below are ordered after the FC1 rows + self.wait_fc1_done(cnt_base, seg) + for kt in cutlass.range(kts, unroll=1): + cute.arch.mbarrier_wait(ab_empty + st.index, st.phase) + self._b_stage( + is1, + kt, + rows, + r0, + sb_base + st.index * self.b_stage_bytes, + x_addr, + x_row_bytes, + h_addr, + s_p2t, + lane, + ) + _cp_async_arrive_noinc((ab_full + st.index).toint()) + st.advance() + k = k + 1 + g, slot = self.unit(s_q, q_full, k) + + @cute.jit + def mma( + self, + ab_full, + ab_empty, + acc_full, + acc_empty, + tmem_bar, + tmem_base_smem_ptr, + tiled_mma: cute.TiledMma, + sA: cute.Tensor, + sB: cute.Tensor, + s_q: cute.Tensor, + q_full, + u1, + ): + tCrA = tiled_mma.make_fragment_A(sA) + tCrB = tiled_mma.make_fragment_B(sB) + acc_shape = tiled_mma.partition_shape_C((TILE_M, self.n_max)) + tCtAcc_fake = tiled_mma.make_fragment_C(acc_shape) + cute.arch.alloc_tmem(self.num_tmem_cols, tmem_base_smem_ptr) + cute.arch.mbarrier_arrive(tmem_bar) + cute.arch.relinquish_tmem_alloc_permit() + tmem_ptr = cute.arch.retrieve_tmem_ptr(self.acc_dtype, 16, tmem_base_smem_ptr) + num_kphases = cute.size(tCrA, mode=[2]) + ab_st = make_pipeline_state(PipelineUserType.Consumer, self.num_stages) + acc_st = make_pipeline_state(PipelineUserType.Producer, NUM_ACC) + k = Int32(0) + g, slot = self.unit(s_q, q_full, k) + while g >= 0: + kts = self.k2_tiles + if g < u1: + kts = self.k1_tiles + cute.arch.mbarrier_wait(acc_empty + acc_st.index, acc_st.phase) + tCtAcc = cute.make_tensor(tmem_ptr + acc_st.index * self.n_max, tCtAcc_fake.layout) + tiled_mma.set(tcgen05.Field.ACCUMULATE, False) + for _kt in cutlass.range(kts, unroll=1): + cute.arch.mbarrier_wait(ab_full + ab_st.index, ab_st.phase) + for kp in cutlass.range(num_kphases, unroll_full=True): + cute.gemm( + tiled_mma, + tCtAcc, + tCrA[(None, None, kp, ab_st.index)], + tCrB[(None, None, kp, ab_st.index)], + tCtAcc, + ) + tiled_mma.set(tcgen05.Field.ACCUMULATE, True) + with cute.arch.elect_one(): + tcgen05.commit(ab_empty + ab_st.index, None, self.cta_group) + ab_st.advance() + with cute.arch.elect_one(): + tcgen05.commit(acc_full + acc_st.index, None, self.cta_group) + acc_st.advance() + k = k + 1 + g, slot = self.unit(s_q, q_full, k) + + @cute.jit + def epilogue( + self, + acc_full, + acc_empty, + tmem_bar, + tmem_base_smem_ptr, + tiled_mma: cute.TiledMma, + s_seg_r0, + s_seg_n, + h_addr, + out_addr, + cnt_base, + epi_tid, + grp, + s_q: cute.Tensor, + q_full, + u1, + ): + tmem_ptr, tCtAcc_fake, tiled_copy_t2r, thr_copy_t2r, rAcc, row0 = self.epilogue_tmem( + tiled_mma, tmem_bar, tmem_base_smem_ptr, epi_tid + ) + lane = cute.arch.lane_idx() + wq = row0 // 32 # epilogue warp = 32-row block of the weight tile + q = row0 % 32 + hcol = ( + wq * 32 + (q % 8) * 4 + q // 8 + ) # FC2: hidden column of this TMEM lane (32-row block shuffle) + lead = ( + q // 8 + ) % 2 == 0 # FC2: owns the even column of a pair (partner lane q + 8 has hcol + 1) + bar_id = Int32(EPI_BAR) + grp + k = grp + g, slot = self.unit(s_q, q_full, k) + while g >= 0: + is1, seg, mt = self.decode(g, u1) + rows = s_seg_n[seg] + r0 = s_seg_r0[seg] + buf = k % NUM_ACC + cute.arch.mbarrier_wait(acc_full + buf, (k // NUM_ACC) & 1) + nch = (rows + 7) // 8 + if is1 != 0: + # up lanes q in [0, 8) and [16, 24) (gate partner q ^ 8); lane j < 8 stores the pair of intermediate + # columns 64 mt + 16 wq + 2 j (its own) and + 1 (lane j + 16's) + hc = Int64(mt * 64 + wq * 16 + lane * 2) + for ch in cutlass.range(nch, unroll=1): + self.load_acc( + tmem_ptr, tCtAcc_fake, tiled_copy_t2r, thr_copy_t2r, rAcc, buf, ch + ) + for t in cutlass.range_constexpr(8): + nrow = ch * 8 + t + xv = rAcc[t] + gate = cute.arch.shuffle_sync_bfly(xv, 8) + # u * (g * sigmoid(g)), sigmoid = rcp.approx(ex2.approx(-g log2e) + 1) + sgm = _rcp( + _add_rn( + _ex2(-_mul_rn(gate, cutlass.Float32(LOG2E))), + cutlass.Float32(1.0), + ) + ) + hv = _mul_rn(xv, _mul_rn(gate, sgm)) + hi = cute.arch.shuffle_sync_down(hv, 16) + if lane < 8: + if nrow < rows: + r = r0 + nrow + _st_global_b32( + h_addr + (Int64(r) * Int64(self.inter) + hc) * 2, + _pack_bf16x2_rn(hv, hi), + ) + cute.arch.fence_view_async_tmem_load() + cute.arch.mbarrier_arrive(acc_empty + buf) + self.free_unit(bar_id, epi_tid, q_full, slot, cnt_base, seg, True) + else: + col = Int64(mt * TILE_M + hcol) + op = _policy_evict_last() + for ch in cutlass.range(nch, unroll=1): + self.load_acc( + tmem_ptr, tCtAcc_fake, tiled_copy_t2r, thr_copy_t2r, rAcc, buf, ch + ) + for t in cutlass.range_constexpr(8): + partner = cute.arch.shuffle_sync_down(rAcc[t], 8) + nrow = ch * 8 + t + if lead: + if nrow < rows: + r = r0 + nrow + _st_global_b32_hint( + out_addr + (Int64(r) * Int64(self.hidden) + col) * 2, + _pack_bf16x2_satfinite(rAcc[t], partner), + op, + ) + cute.arch.fence_view_async_tmem_load() + cute.arch.mbarrier_arrive(acc_empty + buf) + self.free_unit(bar_id, epi_tid, q_full, slot, cnt_base, seg, False) + k = k + EPI_GROUPS + g, slot = self.unit(s_q, q_full, k) + + +# ---------------------------------------------------------------------------------------------------------------- +def stages_for(n_max: int, budget: int) -> int: + """Ring depth: (128 weight rows + n_max activation rows) x TILE_K bf16 per stage within the budget.""" + return min(10, budget // ((128 + n_max) * TILE_K * 2)) + + +def moe_bf16_engine( + x: torch.Tensor, + logits: torch.Tensor, + w31: torch.Tensor, + w2: torch.Tensor, + h: torch.Tensor, + out: torch.Tensor, + wts: torch.Tensor, + e2p: torch.Tensor, + state: torch.Tensor, + *, + top_k: int, + local_start: int, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Route and run the experts. ``x`` [m, H] bf16 (unit column stride), ``logits`` [m, E] bf16 (contiguous), + m <= M_MAX; ``w31`` [L, H/64, 2I, 64] / ``w2`` [L, I/64, H, 64] bf16 (BlockMajorK, trtllm-gen row shuffle), + local experts [local_start, local_start + L); ``h`` [>= m top_k, I] bf16 (scratch), ``out`` [>= m top_k, H] + bf16, ``wts`` [m, top_k] bf16 and ``e2p`` [m, top_k] int32 (outputs), ``state`` from :func:`new_state`. + Returns (out, wts, e2p): what bf16_moe_runner returns with do_finalize=False.""" + import torch + + e, hb, two_i, kb = w31.shape + hidden, inter = hb * kb, two_i // 2 + m, num_experts = logits.shape + assert kb == KB and tuple(w2.shape) == (e, inter // KB, hidden, KB), "BlockMajorK weights" + assert w31.dtype == torch.bfloat16 and w2.dtype == torch.bfloat16 and x.dtype == torch.bfloat16 + assert 1 <= m <= M_MAX, "m <= M_MAX rows routed in the prologue" + assert supports_routing(num_experts, top_k) and supports_local_experts(num_experts, e) + assert ( + x.dim() == 2 + and x.shape == (m, hidden) + and x.stride(1) == 1 + and (x.stride(0) * 2) % 16 == 0 + and x.data_ptr() % 16 == 0 + ) + assert logits.dtype == torch.bfloat16 and logits.is_contiguous() and logits.data_ptr() % 16 == 0 + assert ( + h.dtype == torch.bfloat16 + and h.shape[0] >= m * top_k + and h.shape[1] == inter + and h.is_contiguous() + ) + assert ( + out.dtype == torch.bfloat16 + and out.shape[0] >= m * top_k + and out.shape[1] == hidden + and out.is_contiguous() + ) + assert wts.dtype == torch.bfloat16 and wts.numel() == m * top_k and wts.is_contiguous() + assert e2p.dtype == torch.int32 and e2p.numel() == m * top_k and e2p.is_contiguous() + # one segment per expert: an expert holds at most m rows + n_max = N_MAX[0] if m <= N_MAX[0] else N_MAX[1] + num_stages = stages_for(n_max, ring_smem_bytes(x.device)) + args = ( + gmem_ptr(w31, cutlass.BFloat16, 128), + gmem_ptr(w2, cutlass.BFloat16, 128), + gmem_ptr(w2, cutlass.BFloat16, 128), + Int64(x.data_ptr()), + Int64(x.stride(0) * 2), + Int64(logits.data_ptr()), + Int32(m), + Int32(local_start), + Int64(wts.data_ptr()), + Int64(e2p.data_ptr()), + Int64(h.data_ptr()), + Int64(out.data_ptr()), + Int64(state.data_ptr()), + Int32(e), + ) + config = (hidden, inter, num_experts, top_k, e, n_max, num_stages) + launch(lambda: MoeBf16Engine(*config), (MoeBf16Engine, *config), args, x.device) + return out, wts, e2p diff --git a/tensorrt_llm/_torch/kernels/blackwell/moe_lowm_fc2.py b/tensorrt_llm/_torch/kernels/blackwell/moe_lowm_fc2.py new file mode 100644 index 000000000000..9a7df8373fb9 --- /dev/null +++ b/tensorrt_llm/_torch/kernels/blackwell/moe_lowm_fc2.py @@ -0,0 +1,869 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Routed NVFP4 MoE FC2 for decode-sized batches, bit-identical to the trtllm-gen FC2 cubin +``bmm_Bfloat16_E2m1E2m1_Fp32_Ab16_Bb16_t128x8x256_*_dynB`` (Gemm2 of ``moe/trtllmGen/runner.cu``), with a shared-memory +and register footprint that fits ``CTAS_PER_SM`` CTAs per SM. + +``out[p, h] = bf16_satfinite(scale[e] * sum_k act[p, k] * w2[e, h, k])`` for every permuted row ``p`` of a token tile +(8 rows) of local expert ``e``. Operands and routing tables are the trtllm-gen MoE runner's buffers (``moe_lowm_fc2``): +``w2`` rows shuffled in 32-row blocks with 128x4 E4M3 scales, the FC1 output with 8x4 scales. + +Bit-exactness: the cubin's MMA (``tcgen05.mma.kind::mxf4nvf4.block_scale.scale_vec::4X``, M 128, N 8, K 64) in its K +order with K tiles of 256 (the zero-filled K tail issues the same MMAs), one FP32 ``mul.rn`` by ``scale[e]`` and +``cvt.rn.satfinite.bf16x2.f32``. + +Work: a persistent grid walks the (m tile, token tile) pairs. Warp 0 streams weights by TMA before the PDL wait, warp 1 +activations after it, warp 2 issues the MMAs into two TMEM accumulators, warp 3 L2-prefetches later tiles' weights and +warps 4-7 scale, convert and store. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Optional + +import cuda.bindings.driver as cuda +import cutlass +import cutlass.cute as cute +import cutlass.utils.blackwell_helpers as sm100_utils +import cutlass.utils.blockscaled_layout as blockscaled_utils +from cutlass import Int32, Int64 +from cutlass.cute.nvgpu import cpasync, tcgen05 +from cutlass.pipeline import ( + Agent, + CooperativeGroup, + PipelineAsync, + PipelineUmmaAsync, + PipelineUserType, + make_pipeline_state, + pipeline_init_arrive, + pipeline_init_wait, +) + +from ...cute_dsl_utils import gmem_ptr +from ...flashinfer_utils import get_env_enable_pdl + +if TYPE_CHECKING: + import torch +from .moe_decode_front import _st_shared +from .ptx_helpers import _ld_nc_f32, _ld_s32, _scale_pack_bf16x2, _st_global_b32, s2t_copy + +TILE_M = 128 +TILE_N = 8 +TILE_K = 256 # the cubin's K tile (K order and zero-filled tail MMAs are defined by it) +SF_VEC = 16 +EPI_WARP0 = 4 +NUM_ACC = 2 +NUM_STAGES = 4 # K stages per CTA +CTAS_PER_SM = 2 + + +def _ld_b32(addr: Int64): + return cute.arch.inline_ptx( + "ld.global.b32 {$w0}, [{$r0}];", write_only_types=[Int32], read_only_args=[addr] + ) + + +def _fence_proxy_async_smem() -> None: + cute.arch.inline_ptx("fence.proxy.async.shared::cta;") + + +def _shfl_down8_f32(v): + return cute.arch.inline_ptx( + "shfl.sync.down.b32 {$w0}, {$r0}, 8, 0x1f, 0xffffffff;", + write_only_types=[cutlass.Float32], + read_only_args=[v], + ) + + +def _mbar_expect_tx(addr: Int32, nbytes: Int32) -> None: + cute.arch.inline_ptx( + "mbarrier.expect_tx.relaxed.cta.shared::cta.b64 [{$r0}], {$r1};", + read_only_args=[addr, nbytes], + ) + + +def _prefetch_bulk_l2(addr: Int64, nbytes: Int32) -> None: + cute.arch.inline_ptx( + "cp.async.bulk.prefetch.L2.global [{$r0}], {$r1};", read_only_args=[addr, nbytes] + ) + + +class MoeLowMFc2Nvfp4: + """Routed NVFP4 FC2, tile 128 (hidden) x 8 (rows) x 256 (K), ``NUM_STAGES`` K stages per CTA.""" + + def __init__(self, k_tiles: int, k_groups: int, use_pdl: bool = True): + self.use_pdl = use_pdl + self.k_tiles = k_tiles + self.k_groups = k_groups # 4-scale groups per activation row (I / 64) + self.tile_k = TILE_K + self.gps = TILE_K // (4 * SF_VEC) # 4-scale groups per K tile + self.num_stages = NUM_STAGES + self.cta_group = tcgen05.CtaGroup.ONE + self.acc_dtype = cutlass.Float32 + self.threads_per_cta = 256 + self.sfb_n = 128 # SFB rows per stage: one whole 128-row scale atom, rows 8.. stay zero + + @cute.jit + def _unit(self, t, m_tiles): + """(token tile, m tile) of unit t, token-tile major.""" + y = t // m_tiles + mt = t % m_tiles + return y, mt + + def _setup_attributes(self): + self.tiled_mma = sm100_utils.make_blockscaled_trivial_tiled_mma( + self.a_dtype, + self.b_dtype, + self.a_major_mode, + self.b_major_mode, + self.sf_dtype, + SF_VEC, + self.cta_group, + (TILE_M, TILE_N), + ) + mma_inst_k = cute.size(self.tiled_mma.shape_mnk, mode=[2]) + self.mma_inst_tile_k = self.tile_k // mma_inst_k + self.num_sfa_tmem_cols = (TILE_M // 32) * self.mma_inst_tile_k + self.num_sfb_tmem_cols = self.mma_inst_tile_k * (self.sfb_n // 32) + total = NUM_ACC * TILE_N + self.num_sfa_tmem_cols + self.num_sfb_tmem_cols + cols = 32 + while cols < total: + cols *= 2 + self.num_tmem_cols = cols + self.cluster_layout_vmnk = cute.tiled_divide( + cute.make_layout((1, 1, 1)), (self.tiled_mma.thr_id.shape,) + ) + tiler = (TILE_M, TILE_N, self.tile_k) + self.a_smem_layout_staged = sm100_utils.make_smem_layout_a( + self.tiled_mma, tiler, self.a_dtype, self.num_stages + ) + self.b_smem_layout_staged = sm100_utils.make_smem_layout_b( + self.tiled_mma, tiler, self.b_dtype, self.num_stages + ) + self.sfa_smem_layout_staged = blockscaled_utils.make_smem_layout_sfa( + self.tiled_mma, tiler, SF_VEC, self.num_stages + ) + self.mma_tiler_sfb = (TILE_M, self.sfb_n, self.tile_k) + self.tiled_mma_sfb = sm100_utils.make_blockscaled_trivial_tiled_mma( + self.a_dtype, + self.b_dtype, + self.a_major_mode, + self.b_major_mode, + self.sf_dtype, + SF_VEC, + tcgen05.CtaGroup.ONE, + (TILE_M, self.sfb_n), + ) + self.sfb_smem_layout_staged = blockscaled_utils.make_smem_layout_sfb( + self.tiled_mma_sfb, self.mma_tiler_sfb, SF_VEC, self.num_stages + ) + + @cute.jit + def __call__( + self, + a_ptr: cute.Pointer, + sfa_ptr: cute.Pointer, + b_ptr: cute.Pointer, + sfb_addr: Int64, + c_addr: Int64, + scale_addr: Int64, + cta_batch_addr: Int64, + cta_limit_addr: Int64, + num_ctas_addr: Int64, + max_ctas: Int32, + problem: tuple, + grid_ctas: Int32, + stream: cuda.CUstream, + ): + """problem = (H, I, E, padded rows); the grid is ``grid_ctas`` persistent CTAs; the tables hold ``max_ctas`` + entries.""" + h, k, e, rows = problem + a = cute.make_tensor(a_ptr, cute.make_ordered_layout((h, k, e), order=(1, 0, 2))) + b = cute.make_tensor(b_ptr, cute.make_ordered_layout((rows, k, 1), order=(1, 0, 2))) + self.a_dtype = a_ptr.value_type + self.b_dtype = b_ptr.value_type + self.sf_dtype = sfa_ptr.value_type + self.a_major_mode = cutlass.utils.LayoutEnum.from_tensor(a).mma_major_mode() + self.b_major_mode = cutlass.utils.LayoutEnum.from_tensor(b).mma_major_mode() + sfa = cute.make_tensor(sfa_ptr, blockscaled_utils.tile_atom_to_shape_SF(a.shape, SF_VEC)) + self._setup_attributes() + tiled_mma = self.tiled_mma + a_op = sm100_utils.cluster_shape_to_tma_atom_A((1, 1), 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, + (TILE_M, TILE_N, self.tile_k), + tiled_mma, + self.cluster_layout_vmnk.shape, + ) + b_op = sm100_utils.cluster_shape_to_tma_atom_B((1, 1), 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, + (TILE_M, TILE_N, self.tile_k), + tiled_mma, + self.cluster_layout_vmnk.shape, + ) + sfa_smem_layout = cute.slice_(self.sfa_smem_layout_staged, (None, None, None, 0)) + tma_atom_sfa, tma_tensor_sfa = cute.nvgpu.make_tiled_tma_atom_A( + a_op, + sfa, + sfa_smem_layout, + (TILE_M, TILE_N, self.tile_k), + tiled_mma, + self.cluster_layout_vmnk.shape, + internal_type=cutlass.Int16, + ) + self.tma_bytes_a = cute.size_in_bytes(self.a_dtype, a_smem_layout) + cute.size_in_bytes( + self.sf_dtype, sfa_smem_layout + ) + self.tma_bytes_b = cute.size_in_bytes(self.b_dtype, b_smem_layout) + self.kernel( + tiled_mma, + self.tiled_mma_sfb, + tma_atom_a, + tma_tensor_a, + tma_atom_sfa, + tma_tensor_sfa, + tma_atom_b, + tma_tensor_b, + self.cluster_layout_vmnk, + self.a_smem_layout_staged, + self.b_smem_layout_staged, + self.sfa_smem_layout_staged, + self.sfb_smem_layout_staged, + sfb_addr, + c_addr, + scale_addr, + cta_batch_addr, + cta_limit_addr, + num_ctas_addr, + max_ctas, + h, + k, + a_ptr.toint(), + sfa_ptr.toint(), + ).launch( + grid=[grid_ctas, 1, 1], + block=[self.threads_per_cta, 1, 1], + cluster=(1, 1, 1), + stream=stream, + use_pdl=self.use_pdl, + min_blocks_per_mp=CTAS_PER_SM, + ) + + @cute.kernel + def kernel( + self, + tiled_mma: cute.TiledMma, + tiled_mma_sfb: cute.TiledMma, + tma_atom_a: cute.CopyAtom, + mA_mkl: cute.Tensor, + tma_atom_sfa: cute.CopyAtom, + mSFA_mkl: cute.Tensor, + tma_atom_b: cute.CopyAtom, + mB_nkl: cute.Tensor, + cluster_layout_vmnk: cute.Layout, + a_smem_layout_staged: cute.ComposedLayout, + b_smem_layout_staged: cute.ComposedLayout, + sfa_smem_layout_staged: cute.Layout, + sfb_smem_layout_staged: cute.Layout, + sfb_addr: Int64, + c_addr: Int64, + scale_addr: Int64, + cta_batch_addr: Int64, + cta_limit_addr: Int64, + num_ctas_addr: Int64, + max_ctas: Int32, + h_total: Int32, + k_total: Int32, + a_base: Int64, + sfa_base: Int64, + ): + warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + tidx, _, _ = cute.arch.thread_idx() + bidx, _, _ = cute.arch.block_idx() + gdx, _, _ = cute.arch.grid_dim() + m_tiles = h_total // TILE_M + # Routing tables before the dependency wait (tile count; first tile's expert): the trtllm-gen FC1 cubin + # triggers this launch only after its own wait for the routing kernel (GemmOptions.h: a load task that + # triggers the secondary also waits for the primary). + n_ctas = _ld_s32(num_ctas_addr) + y0f, _mt0 = self._unit(bidx, m_tiles) + y0 = cutlass.min(y0f, max_ctas - 1) + e0 = _ld_s32(cta_batch_addr + Int64(y0) * 4) + if warp_idx == 0: + cpasync.prefetch_descriptor(tma_atom_a) + cpasync.prefetch_descriptor(tma_atom_sfa) + cpasync.prefetch_descriptor(tma_atom_b) + + Stages = self.num_stages + + @cute.struct + class SharedStorage: + ab_bars: cute.struct.MemRange[cutlass.Int64, Stages * 2] + acc_bars: cute.struct.MemRange[cutlass.Int64, NUM_ACC * 2] + tmem_bar: cutlass.Int64 + tmem_base: cutlass.Int32 + + smem = cutlass.utils.SmemAllocator() + storage = smem.allocate(SharedStorage) + ab_pipeline = PipelineAsync.create( + barrier_storage=storage.ab_bars.data_ptr(), + num_stages=Stages, + producer_group=CooperativeGroup(Agent.Thread, 2), + consumer_group=CooperativeGroup(Agent.Thread), + defer_sync=True, + ) + ab_full = ab_pipeline.sync_object_full.barrier_storage + ab_empty = ab_pipeline.sync_object_empty.barrier_storage + acc_pipeline = PipelineUmmaAsync.create( + barrier_storage=storage.acc_bars.data_ptr(), + num_stages=NUM_ACC, + producer_group=CooperativeGroup(Agent.Thread), + consumer_group=CooperativeGroup(Agent.Thread, 128), + defer_sync=True, + ) + acc_full = acc_pipeline.sync_object_full.barrier_storage + acc_empty = acc_pipeline.sync_object_empty.barrier_storage + tmem_bar = storage.tmem_bar.ptr + tmem_base_smem_ptr = storage.tmem_base.ptr + if warp_idx == 0: + with cute.arch.elect_one(): + cute.arch.mbarrier_init(tmem_bar, 32 + 128) + + sA = smem.allocate_tensor( + element_type=self.a_dtype, + layout=a_smem_layout_staged.outer, + byte_alignment=1024, + swizzle=a_smem_layout_staged.inner, + ) + sB = smem.allocate_tensor( + element_type=self.b_dtype, + layout=b_smem_layout_staged.outer, + byte_alignment=1024, + swizzle=b_smem_layout_staged.inner, + ) + sSFA = smem.allocate_tensor( + element_type=self.sf_dtype, layout=sfa_smem_layout_staged, byte_alignment=128 + ) + sSFB = smem.allocate_tensor( + element_type=self.sf_dtype, layout=sfb_smem_layout_staged, byte_alignment=128 + ) + # SFB: only rows 0..7 of each 128-row atom are ever written; zero the rest once. + sfb_base = sSFB.iterator.toint() + sfb_words = Stages * (self.sfb_n * (self.tile_k // SF_VEC)) // 4 + for i in cutlass.range(tidx, sfb_words, self.threads_per_cta, unroll=1): + _st_shared(sfb_base + i * 4, Int32(0)) + _fence_proxy_async_smem() + pipeline_init_arrive(cluster_shape_mn=None, is_relaxed=True) + pipeline_init_wait(cluster_shape_mn=None) + cute.arch.barrier() + + num_tiles = n_ctas * m_tiles + + if warp_idx == 0: + self.load_a( + ab_full, + ab_empty, + tma_atom_a, + mA_mkl, + sA, + tma_atom_sfa, + mSFA_mkl, + sSFA, + tiled_mma, + cluster_layout_vmnk, + cta_batch_addr, + e0, + bidx, + gdx, + num_tiles, + m_tiles, + ) + elif warp_idx == 1: + self.load_b( + ab_full, + ab_empty, + tma_atom_b, + mB_nkl, + sB, + sfb_base, + sfb_addr, + tiled_mma, + cluster_layout_vmnk, + bidx, + gdx, + num_tiles, + m_tiles, + ) + elif warp_idx == 2: + self.mma( + ab_full, + ab_empty, + acc_full, + acc_empty, + tmem_bar, + tmem_base_smem_ptr, + tiled_mma, + sA, + sB, + sSFA, + sSFB, + sfa_smem_layout_staged, + sfb_smem_layout_staged, + bidx, + gdx, + num_tiles, + ) + elif warp_idx == 3: + # L2 prefetch of this CTA's second tile's weights and of a late-launching CTA's first tile's + lane = cute.arch.lane_idx() + t = bidx + gdx # this CTA's second tile + if lane >= 2: + t = ( + gdx - 1 - bidx + ) # the first tile of a CTA that launches late (CTAs launch in index order) + if lane < 4: + if t < num_tiles: + if lane < 2 or bidx * 2 < gdx: + yq, mq = self._unit(t, m_tiles) + ey = Int64(_ld_s32(cta_batch_addr + Int64(yq) * 4)) + mt = Int64(mq) + a_tile = Int64(TILE_M) * Int64(k_total // 2) + s_tile = Int64(TILE_M) * Int64(k_total // SF_VEC) + if lane % 2 == 0: + _prefetch_bulk_l2( + a_base + (ey * Int64(m_tiles) + mt) * a_tile, Int32(a_tile) + ) + else: + _prefetch_bulk_l2( + sfa_base + (ey * Int64(m_tiles) + mt) * s_tile, Int32(s_tile) + ) + elif warp_idx >= EPI_WARP0: + self.epilogue( + acc_full, + acc_empty, + tmem_bar, + tmem_base_smem_ptr, + tiled_mma, + c_addr, + scale_addr, + cta_batch_addr, + cta_limit_addr, + tidx - EPI_WARP0 * 32, + bidx, + gdx, + num_tiles, + m_tiles, + h_total, + e0, + ) + cute.arch.barrier() + if warp_idx == 2: + tmem_ptr = cute.arch.retrieve_tmem_ptr(self.acc_dtype, 16, tmem_base_smem_ptr) + cute.arch.dealloc_tmem(tmem_ptr, self.num_tmem_cols) + return + + @cute.jit + def load_a( + self, + ab_full, + ab_empty, + tma_atom_a: cute.CopyAtom, + mA_mkl: cute.Tensor, + sA: cute.Tensor, + tma_atom_sfa: cute.CopyAtom, + mSFA_mkl: cute.Tensor, + sSFA: cute.Tensor, + tiled_mma: cute.TiledMma, + cluster_layout_vmnk: cute.Layout, + cta_batch_addr: Int64, + e0: Int32, + bidx: Int32, + gdx: Int32, + num_tiles: Int32, + m_tiles: Int32, + ): + """Weights + scales (constant): issued before griddepcontrol.wait, like the cubin (gridWaitForPrimaryA off); + the routing tables were complete before the previous kernel triggered this launch.""" + thr_mma = tiled_mma.get_slice(0) + a_cta_layout = cute.make_layout(cute.slice_(cluster_layout_vmnk, (0, 0, None, 0)).shape) + gA = cute.local_tile(mA_mkl, (TILE_M, self.tile_k), (None, None, None)) + tAsA, tAgA = cpasync.tma_partition( + tma_atom_a, + 0, + a_cta_layout, + cute.group_modes(sA, 0, 3), + cute.group_modes(thr_mma.partition_A(gA), 0, 3), + ) + gSFA = cute.local_tile(mSFA_mkl, (TILE_M, self.tile_k), (None, None, None)) + tAsSFA, tAgSFA = cpasync.tma_partition( + tma_atom_sfa, + 0, + a_cta_layout, + cute.group_modes(sSFA, 0, 3), + cute.group_modes(thr_mma.partition_A(gSFA), 0, 3), + ) + tAsSFA = cute.filter_zeros(tAsSFA) + tAgSFA = cute.filter_zeros(tAgSFA) + st = make_pipeline_state(PipelineUserType.Producer, self.num_stages) + ey = e0 + for t in cutlass.range(bidx, num_tiles, gdx, unroll=1): + ya, mt = self._unit(t, m_tiles) + if t != bidx: + ey = _ld_s32(cta_batch_addr + Int64(ya) * 4) + for kt in cutlass.range_constexpr(self.k_tiles): + cute.arch.mbarrier_wait(ab_empty + st.index, st.phase) + with cute.arch.elect_one(): + cute.arch.mbarrier_arrive_and_expect_tx(ab_full + st.index, self.tma_bytes_a) + cute.copy( + tma_atom_a, + tAgA[(None, mt, kt, ey)], + tAsA[(None, st.index)], + tma_bar_ptr=ab_full + st.index, + ) + cute.copy( + tma_atom_sfa, + tAgSFA[(None, mt, kt, ey)], + tAsSFA[(None, st.index)], + tma_bar_ptr=ab_full + st.index, + ) + st.advance() + + @cute.jit + def load_b( + self, + ab_full, + ab_empty, + tma_atom_b: cute.CopyAtom, + mB_nkl: cute.Tensor, + sB: cute.Tensor, + sfb_base: Int32, + sfb_addr: Int64, + tiled_mma: cute.TiledMma, + cluster_layout_vmnk: cute.Layout, + bidx: Int32, + gdx: Int32, + num_tiles: Int32, + m_tiles: Int32, + ): + """FC1 output + its 8x4 scales, after griddepcontrol.wait. Per tile: the activation TMA of every K tile first + (expect_tx only), then lane l loads the 4 scales of row l % 8, group 4 kt + l / 8 for every K tile at once, + writes them into the stage's 128x4 atom l / 8 (16-byte rows) and the warp arrives (the second producer).""" + thr_mma = tiled_mma.get_slice(0) + b_cta_layout = cute.make_layout(cute.slice_(cluster_layout_vmnk, (0, None, 0, 0)).shape) + gB = cute.local_tile(mB_nkl, (TILE_N, self.tile_k), (None, None, None)) + tBsB, tBgB = cpasync.tma_partition( + tma_atom_b, + 0, + b_cta_layout, + cute.group_modes(sB, 0, 3), + cute.group_modes(thr_mma.partition_B(gB), 0, 3), + ) + cute.arch.griddepcontrol_wait() + cute.arch.griddepcontrol_launch_dependents() + lane = cute.arch.lane_idx() + groups = self.k_groups + stage_bytes = self.sfb_n * (self.tile_k // SF_VEC) + gps = self.gps + own = lane // 8 < gps # lanes of the stage's 128x4 atoms + sf = cute.make_rmem_tensor((self.k_tiles,), Int32) + st = make_pipeline_state(PipelineUserType.Producer, self.num_stages) + for t in cutlass.range(bidx, num_tiles, gdx, unroll=1): + y, _mtb = self._unit(t, m_tiles) + if cutlass.const_expr(self.num_stages >= self.k_tiles): + # every K tile has its own stage: all activation TMAs, then the scales + i0 = st.index + for kt in cutlass.range_constexpr(self.k_tiles): + cute.arch.mbarrier_wait(ab_empty + st.index, st.phase) + with cute.arch.elect_one(): + _mbar_expect_tx((ab_full + st.index).toint(), Int32(self.tma_bytes_b)) + cute.copy( + tma_atom_b, + tBgB[(None, y, kt, 0)], + tBsB[(None, st.index)], + tma_bar_ptr=ab_full + st.index, + ) + st.advance() + for kt in cutlass.range_constexpr(self.k_tiles): + g = kt * gps + lane // 8 + sf[kt] = Int32(0) + if own: + if g < groups: + sf[kt] = _ld_b32( + sfb_addr + Int64(y * groups + g) * 32 + Int64(lane % 8) * 4 + ) + for kt in cutlass.range_constexpr(self.k_tiles): + idx = (i0 + kt) % self.num_stages + if own: + _st_shared( + sfb_base + idx * stage_bytes + (lane // 8) * 512 + (lane % 8) * 16, + sf[kt], + ) + _fence_proxy_async_smem() + cute.arch.sync_warp() + with cute.arch.elect_one(): + cute.arch.mbarrier_arrive(ab_full + idx) + else: + # fewer stages than K tiles: scales loaded up front, one stage at a time + for kt in cutlass.range_constexpr(self.k_tiles): + g = kt * gps + lane // 8 + sf[kt] = Int32(0) + if own: + if g < groups: + sf[kt] = _ld_b32( + sfb_addr + Int64(y * groups + g) * 32 + Int64(lane % 8) * 4 + ) + for kt in cutlass.range_constexpr(self.k_tiles): + cute.arch.mbarrier_wait(ab_empty + st.index, st.phase) + with cute.arch.elect_one(): + _mbar_expect_tx((ab_full + st.index).toint(), Int32(self.tma_bytes_b)) + cute.copy( + tma_atom_b, + tBgB[(None, y, kt, 0)], + tBsB[(None, st.index)], + tma_bar_ptr=ab_full + st.index, + ) + if own: + _st_shared( + sfb_base + st.index * stage_bytes + (lane // 8) * 512 + (lane % 8) * 16, + sf[kt], + ) + _fence_proxy_async_smem() + cute.arch.sync_warp() + with cute.arch.elect_one(): + cute.arch.mbarrier_arrive(ab_full + st.index) + st.advance() + + @cute.jit + def mma( + self, + ab_full, + ab_empty, + acc_full, + acc_empty, + tmem_bar, + tmem_base_smem_ptr, + tiled_mma: cute.TiledMma, + sA: cute.Tensor, + sB: cute.Tensor, + sSFA: cute.Tensor, + sSFB: cute.Tensor, + sfa_smem_layout_staged: cute.Layout, + sfb_smem_layout_staged: cute.Layout, + bidx: Int32, + gdx: Int32, + num_tiles: Int32, + ): + tCrA = tiled_mma.make_fragment_A(sA) + tCrB = tiled_mma.make_fragment_B(sB) + acc_shape = tiled_mma.partition_shape_C((TILE_M, TILE_N)) + tCtAcc_fake = tiled_mma.make_fragment_C(acc_shape) + cute.arch.alloc_tmem(self.num_tmem_cols, tmem_base_smem_ptr) + cute.arch.mbarrier_arrive(tmem_bar) + cute.arch.relinquish_tmem_alloc_permit() + tmem_ptr = cute.arch.retrieve_tmem_ptr(self.acc_dtype, 16, tmem_base_smem_ptr) + sfa_col = NUM_ACC * TILE_N + sfb_col = sfa_col + self.num_sfa_tmem_cols + tCtSFA_layout = blockscaled_utils.make_tmem_layout_sfa( + tiled_mma, + tiled_mma.shape_mnk, + SF_VEC, + cute.slice_(sfa_smem_layout_staged, (None, None, None, 0)), + ) + tCtSFB_layout = blockscaled_utils.make_tmem_layout_sfb( + tiled_mma, + tiled_mma.shape_mnk, + SF_VEC, + cute.slice_(sfb_smem_layout_staged, (None, None, None, 0)), + ) + tCtSFA = cute.make_tensor( + cute.recast_ptr(tmem_ptr + sfa_col, dtype=self.sf_dtype), tCtSFA_layout + ) + tCtSFB = cute.make_tensor( + cute.recast_ptr(tmem_ptr + sfb_col, dtype=self.sf_dtype), tCtSFB_layout + ) + copy_sfa, tCsSFA_s2t, tCtSFA_s2t = s2t_copy(sSFA, tCtSFA, self.cta_group, self.sf_dtype) + copy_sfb, tCsSFB_s2t, tCtSFB_s2t = s2t_copy(sSFB, tCtSFB, self.cta_group, self.sf_dtype) + num_kphases = cute.size(tCrA, mode=[2]) + ab_st = make_pipeline_state(PipelineUserType.Consumer, self.num_stages) + acc_st = make_pipeline_state(PipelineUserType.Producer, NUM_ACC) + for _t in cutlass.range(bidx, num_tiles, gdx, unroll=1): + cute.arch.mbarrier_wait(acc_empty + acc_st.index, acc_st.phase) + tCtAcc = cute.make_tensor(tmem_ptr + acc_st.index * TILE_N, tCtAcc_fake.layout) + tiled_mma.set(tcgen05.Field.ACCUMULATE, False) + for kt in cutlass.range_constexpr(self.k_tiles): + cute.arch.mbarrier_wait(ab_full + ab_st.index, ab_st.phase) + cute.copy(copy_sfa, tCsSFA_s2t[(None, None, None, None, ab_st.index)], tCtSFA_s2t) + cute.copy(copy_sfb, tCsSFB_s2t[(None, None, None, None, ab_st.index)], tCtSFB_s2t) + for kp in cutlass.range(num_kphases, unroll_full=True): + tiled_mma.set(tcgen05.Field.SFA, tCtSFA[(None, None, kp)].iterator) + tiled_mma.set(tcgen05.Field.SFB, tCtSFB[(None, None, kp)].iterator) + cute.gemm( + tiled_mma, + tCtAcc, + tCrA[(None, None, kp, ab_st.index)], + tCrB[(None, None, kp, ab_st.index)], + tCtAcc, + ) + tiled_mma.set(tcgen05.Field.ACCUMULATE, True) + with cute.arch.elect_one(): + tcgen05.commit(ab_empty + ab_st.index, None, self.cta_group) + ab_st.advance() + with cute.arch.elect_one(): + tcgen05.commit(acc_full + acc_st.index, None, self.cta_group) + acc_st.advance() + + @cute.jit + def epilogue( + self, + acc_full, + acc_empty, + tmem_bar, + tmem_base_smem_ptr, + tiled_mma: cute.TiledMma, + c_addr: Int64, + scale_addr: Int64, + cta_batch_addr: Int64, + cta_limit_addr: Int64, + epi_tid: Int32, + bidx: Int32, + gdx: Int32, + num_tiles: Int32, + m_tiles: Int32, + h_total: Int32, + e0: Int32, + ): + thr_mma = tiled_mma.get_slice(0) + acc_shape = tiled_mma.partition_shape_C((TILE_M, TILE_N)) + tCtAcc_fake = tiled_mma.make_fragment_C(acc_shape) + tCcL = thr_mma.partition_C(cute.make_identity_tensor((TILE_M, TILE_N))) + cute.arch.mbarrier_arrive(tmem_bar) + cute.arch.mbarrier_wait(tmem_bar, 0) + tmem_ptr = cute.arch.retrieve_tmem_ptr(self.acc_dtype, 16, tmem_base_smem_ptr) + copy_atom_t2r = cute.make_copy_atom( + tcgen05.Ld32x32bOp(tcgen05.Repetition(TILE_N), tcgen05.Pack.NONE), self.acc_dtype + ) + epi_tile = (TILE_M, TILE_N) + tAcc0 = cute.flat_divide( + cute.make_tensor(tmem_ptr, tCtAcc_fake.layout)[((None, None), 0, 0)], epi_tile + ) + tiled_copy_t2r = tcgen05.make_tmem_copy(copy_atom_t2r, tAcc0[(None, None, 0, 0)]) + thr_copy_t2r = tiled_copy_t2r.get_slice(epi_tid) + tTR_cL = thr_copy_t2r.partition_D(cute.flat_divide(tCcL[((None, None), 0, 0)], epi_tile)) + rAcc = cute.make_rmem_tensor(tTR_cL[(None, None, None, 0, 0)].shape, self.acc_dtype) + crd = tTR_cL[(None, None, None, 0, 0)] + row0, _c0 = crd[0] + q = row0 % 32 + hcol = ( + (row0 // 32) * 32 + (q % 8) * 4 + q // 8 + ) # hidden column of this TMEM lane (32-row block shuffle) + lead = ( + q // 8 + ) % 2 == 0 # owns the even hidden column of a pair (partner lane q + 8 has hcol + 1) + acc_st = make_pipeline_state(PipelineUserType.Consumer, NUM_ACC) + for t in cutlass.range(bidx, num_tiles, gdx, unroll=1): + y, mt = self._unit(t, m_tiles) + ey = e0 + if t != bidx: + ey = _ld_s32(cta_batch_addr + Int64(y) * 4) + limit = _ld_s32(cta_limit_addr + Int64(y) * 4) + s = _ld_nc_f32(scale_addr + Int64(ey) * 4) + cute.arch.mbarrier_wait(acc_full + acc_st.index, acc_st.phase) + tAcc = cute.flat_divide( + cute.make_tensor(tmem_ptr + acc_st.index * TILE_N, tCtAcc_fake.layout)[ + ((None, None), 0, 0) + ], + epi_tile, + ) + cute.copy( + tiled_copy_t2r, thr_copy_t2r.partition_S(tAcc)[(None, None, None, 0, 0)], rAcc + ) + cute.arch.fence_view_async_tmem_load() + cute.arch.mbarrier_arrive(acc_empty + acc_st.index) + acc_st.advance() + col = Int64(mt * TILE_M + hcol) + for j in cutlass.range_constexpr(TILE_N): + partner = _shfl_down8_f32(rAcc[j]) + r = y * TILE_N + j + if lead: + if r < limit: + _st_global_b32( + c_addr + (Int64(r) * Int64(h_total) + col) * 2, + _scale_pack_bf16x2(rAcc[j], partner, s), + ) + + +_COMPILED = {} + + +def num_sms(device: Optional[torch.device] = None) -> int: + """SMs of ``device`` the persistent grid spans: all but those ``cute_dsl_utils.sm_reserve()`` keeps out.""" + import torch + + from ...cute_dsl_utils import sm_reserve + + return torch.cuda.get_device_properties(device).multi_processor_count - sm_reserve() + + +def moe_lowm_fc2( + act: torch.Tensor, + act_sf: torch.Tensor, + w2: torch.Tensor, + w2_sf: torch.Tensor, + scale: torch.Tensor, + cta_batch: torch.Tensor, + cta_limit: torch.Tensor, + num_non_exiting: torch.Tensor, + out: torch.Tensor, +) -> torch.Tensor: + """FC2 of the trtllm-gen MoE path. ``act`` [rows, I/2] uint8 (E2M1 x2), ``act_sf`` 8x4 E4M3 (uint8), + ``w2`` [E, H, I/2] uint8, ``w2_sf`` [E, H, I/16] (128x4), ``scale`` [E] fp32, tables int32 (``cta_batch`` / + ``cta_limit`` per token tile, ``num_non_exiting`` [1]), ``out`` [padded rows, H] bf16 with at least the total padded + rows (rows of a tile past its limit are not written).""" + import torch + + rows, half_k = act.shape + e, h, half_k2 = w2.shape + k = 2 * half_k + if half_k2 != half_k or h % TILE_M or k % (4 * SF_VEC): + raise ValueError(f"unsupported FC2 shape rows {rows} H {h} I {k} E {e}") + if ( + out.dim() != 2 + or out.shape[1] != h + or out.dtype != torch.bfloat16 + or not out.is_contiguous() + ): + raise ValueError("out must be a contiguous bf16 [padded rows, H] tensor") + grid_ctas = num_sms(act.device) * CTAS_PER_SM + ptrs = ( + gmem_ptr(w2, cutlass.Float4E2M1FN, 32), + gmem_ptr(w2_sf, cutlass.Float8E4M3FN, 16), + gmem_ptr(act, cutlass.Float4E2M1FN, 32), + ) + addrs = ( + Int64(act_sf.data_ptr()), + Int64(out.data_ptr()), + Int64(scale.data_ptr()), + Int64(cta_batch.data_ptr()), + Int64(cta_limit.data_ptr()), + Int64(num_non_exiting.data_ptr()), + Int32(cta_batch.numel()), + ) + problem = (Int32(h), Int32(k), Int32(e), Int32(rows)) + stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream) + use_pdl = get_env_enable_pdl() + fn = _COMPILED.get((k, use_pdl)) + if fn is None: + if torch.cuda.is_current_stream_capturing(): + raise RuntimeError("compile the low-M MoE FC2 before CUDA graph capture") + kern = MoeLowMFc2Nvfp4(-(-k // TILE_K), k // (4 * SF_VEC), use_pdl) + fn = cute.compile(kern, *ptrs, *addrs, problem, Int32(grid_ctas), stream) + _COMPILED[(k, use_pdl)] = fn + fn(*ptrs, *addrs, problem, Int32(grid_ctas), stream) + return out diff --git a/tensorrt_llm/_torch/kernels/blackwell/moe_nvfp4_engine.py b/tensorrt_llm/_torch/kernels/blackwell/moe_nvfp4_engine.py new file mode 100644 index 000000000000..6b145685aabe --- /dev/null +++ b/tensorrt_llm/_torch/kernels/blackwell/moe_nvfp4_engine.py @@ -0,0 +1,1689 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Decode MoE engine for NVFP4 experts: the routed experts of one rank in one persistent launch, FC1 -> SwiGLU -> +NVFP4 -> FC2 on the decode front's pre-routed tables, bit for bit the trtllm-gen FP4 MoE runner's un-finalized gemm2 +rows: every MMA is block-scaled tcgen05 M128 x N n_max x K64 over the whole K in order, FC1's epilogue is trtllm-gen's +SwiGLU E2m1 epilogue operation for operation and FC2's is ``moe_lowm_fc2``'s (:func:`moe_nvfp4_engine`). Scheduling: +``moe_persistent_engine``. + +``route_top_k`` / ``route_lists`` (compile time): the engine routes the call itself after its dependency wait, from +each token's top ``route_top_k`` keys of each of its ``route_lists`` 128-expert tiles (``moe_router_gemm``'s +``route_top_k`` epilogue), and writes the top-k ids, the BF16 weights and the pre-routed tables bit for bit as the +route front (``moe_route_front``) would. +""" + +from __future__ import annotations + +from typing import Optional + +import cuda.bindings.driver as cuda +import cutlass +import cutlass.cute as cute +import cutlass.utils.blackwell_helpers as sm100_utils +import cutlass.utils.blockscaled_layout as blockscaled_utils +import torch +from cutlass import Int32, Int64 +from cutlass.cute.nvgpu import cpasync, tcgen05 +from cutlass.pipeline import ( + Agent, + CooperativeGroup, + PipelineAsync, + PipelineUmmaAsync, + PipelineUserType, + make_pipeline_state, + pipeline_init_arrive, + pipeline_init_wait, +) + +from ...cute_dsl_utils import gmem_ptr +from .moe_bf16_engine import _butterfly_sum +from .moe_decode_front import ( + _bit, + _div_bf16, + _exp_tr, + _key_val, + _ld_shared, + _ld_v4, + _max_u32, + _popc, + _red_or_shared, + _sel_eq, + _sel_lt, + _smem_addr, + _st_b16, + _st_shared, + _sub, +) +from .moe_persistent_engine import ( + EPI_BAR, + EPI_GROUPS, + EPI_WARP0, + LOG2E, + NUM_ACC, + QD, + THREADS, + TILE_M, + PersistentMoeEngine, + Release, + launch, + new_state, + ring_smem_bytes, +) +from .ptx_helpers import ( + _add_rn, + _bar_sync, + _cp_async_16, + _cp_async_arrive_noinc, + _cp_async_commit, + _ex2, + _ld_nc_f32, + _ld_s32, + _mul_rn, + _policy_evict_first, + _policy_evict_last, + _rcp, + _scale_pack_bf16x2, + _st_global_b32, + _st_global_b32_hint, + s2t_copy, + sum_tree, +) + +SF_VEC = 16 +SEG_CAP = 512 # segments per call (experts x row chunks); >= 128 + m * top_k / n_max for every supported m +RCP6 = 0.16666667163372039795 # fp32(1 / 6) +N_MAX = (16, 32, 64) # MMA N (rows per segment) the engine compiles for +MAX_LOCAL_EXPERTS = ( + 128 # per-expert scalars and segment tables are staged for this many local experts +) +# Tokens of a routing call: two token-mask words per expert. +ROUTE_MAX_ROWS = 64 +_ROUTE_BAR = EPI_BAR + EPI_GROUPS # named barrier: the epilogue warps release the activation loader + + +def route_error(top_k: int, lists: int) -> Optional[str]: + """Why the engine cannot route from ``lists`` candidate lists of ``top_k`` keys per token, or None.""" + if top_k < 1 or lists < 1: + return "route_top_k and route_lists must be positive" + if top_k > 32: + return "the weights' sum runs over the lanes of one warp: route_top_k <= 32" + if (lists * top_k) % 4: + return "a token's candidates load as 16-byte vectors: route_lists x route_top_k must be a multiple of 4" + if ROUTE_MAX_ROWS * lists * top_k > 8 * THREADS: + return f"the candidates of {ROUTE_MAX_ROWS} tokens load in two 16-byte vectors per thread" + return None + + +def _route_scratch(top_k: int, lists: int) -> tuple: + """Byte offsets of the routing scratch at the start of the activation ring, after the candidates: per local + expert its token mask (two words), its first tile, then a sink word for the mask ORs of other ranks' picks.""" + masks = ROUTE_MAX_ROWS * lists * top_k * 4 + starts = masks + MAX_LOCAL_EXPERTS * 8 + return masks, starts, starts + MAX_LOCAL_EXPERTS * 4 + + +__all__ = [ + "MAX_LOCAL_EXPERTS", + "N_MAX", + "ROUTE_MAX_ROWS", + "MoeNvfp4Engine", + "moe_nvfp4_engine", + "new_state", + "route_error", +] + + +# ---------------------------------------------------------------------------------------------------------------- +# PTX helpers +# ---------------------------------------------------------------------------------------------------------------- +def _st_global_u8(addr: Int64, v) -> None: + cute.arch.inline_ptx( + "{ .reg .b16 t; cvt.u16.u32 t, {$r1}; st.global.u8 [{$r0}], t; }", read_only_args=[addr, v] + ) + + +def _cp_async_4(dst: Int32, src: Int64) -> None: + cute.arch.inline_ptx( + "cp.async.ca.shared.global [{$r0}], [{$r1}], 4;", read_only_args=[dst, src] + ) + + +def _redux_max_abs_f32(x): + """max over the warp of |x| (redux.sync.max.abs.f32, sm_100a+); NaN inputs are ignored like fmax.""" + return cute.arch.inline_ptx( + "redux.sync.max.abs.f32 {$w0}, {$r0}, 0xffffffff;", + write_only_types=[cutlass.Float32], + read_only_args=[x], + ) + + +def _ballot(p): + return cute.arch.inline_ptx( + "{ .reg .pred q; setp.ne.s32 q, {$r0}, 0; vote.sync.ballot.b32 {$w0}, q, 0xffffffff; }", + write_only_types=[Int32], + read_only_args=[p], + ) + + +def _fma_rn(a, b, c): + return cute.arch.inline_ptx( + "fma.rn.f32 {$w0}, {$r0}, {$r1}, {$r2};", + write_only_types=[cutlass.Float32], + read_only_args=[a, b, c], + ) + + +def _e4m3_bits(x): + """e4m3 (nearest even, saturating) of x as 0..255.""" + return cute.arch.inline_ptx( + "{ .reg .b16 t; cvt.rn.satfinite.e4m3x2.f32 t, 0f00000000, {$r0}; cvt.u32.u16 {$w0}, t; }", + write_only_types=[Int32], + read_only_args=[x], + ) & Int32(0xFF) + + +def _e4m3_to_f32(b): + return cute.arch.inline_ptx( + "{ .reg .b16 t, l, u; .reg .b32 h; cvt.u16.u32 t, {$r0}; cvt.rn.f16x2.e4m3x2 h, t; mov.b32 {l, u}, h;" + " cvt.f32.f16 {$w0}, l; }", + write_only_types=[cutlass.Float32], + read_only_args=[b], + ) + + +def _e2m1x2(hi, lo): + """One byte of two E2M1 codes (lo in the low nibble), nearest even, saturating.""" + return cute.arch.inline_ptx( + "{ .reg .b8 t; cvt.rn.satfinite.e2m1x2.f32 t, {$r0}, {$r1}; cvt.u32.u8 {$w0}, t; }", + write_only_types=[Int32], + read_only_args=[hi, lo], + ) + + +def _sel_f32(p, a, b): + """p != 0 ? a : b.""" + return cute.arch.inline_ptx( + "{ .reg .pred q; setp.ne.s32 q, {$r0}, 0; selp.f32 {$w0}, {$r1}, {$r2}, q; }", + write_only_types=[cutlass.Float32], + read_only_args=[p, a, b], + ) + + +def _st_shared_v4(addr, a, b, c, d) -> None: + cute.arch.inline_ptx( + "st.shared.v4.b32 [{$r0}], {{$r1}, {$r2}, {$r3}, {$r4}};", read_only_args=[addr, a, b, c, d] + ) + + +def _bar_arrive(bar_id, n: int) -> None: + """Arrive on named barrier bar_id (a register) over n threads without waiting.""" + cute.arch.inline_ptx(f"bar.arrive {{$r0}}, {n};", read_only_args=[bar_id]) + + +def _fence_gpu() -> None: + cute.arch.inline_ptx("fence.acq_rel.gpu;") + + +def _max_tree(keys: list): + """The largest of ``keys`` (unsigned) as a pairwise tree: max(max(k0, k1), max(k2, k3)) for four.""" + if len(keys) == 1: + return keys[0] + half = (len(keys) + 1) // 2 + return _max_u32(_max_tree(keys[:half]), _max_tree(keys[half:])) + + +def _fence_cta_after(dep) -> None: + """fence.acq_rel.cta, issued once dep is computed.""" + cute.arch.inline_ptx( + "{ .reg .b32 d; mov.b32 d, {$r0}; fence.acq_rel.cta; }", read_only_args=[dep] + ) + + +def smem_views(storage): + """Tensor views of the engine's shared-memory int32 arrays (dynamic indexing): nseg, wsum, exp_e, exp_y0, + exp_lim, seg_e, seg_r0, seg_n, tok.""" + + def view(mr, n): + return mr.get_tensor(cute.make_layout(n)) + + return ( + view(storage.nseg, 4), + view(storage.wsum, 12), + view(storage.exp_e, 128), + view(storage.exp_y0, 129), + view(storage.exp_lim, 128), + view(storage.seg_e, SEG_CAP), + view(storage.seg_r0, SEG_CAP), + view(storage.seg_n, SEG_CAP), + view(storage.tok, 128), + ) + + +# ---------------------------------------------------------------------------------------------------------------- +class MoeNvfp4Engine(PersistentMoeEngine): + """Compile-time configuration: ``n_max`` (MMA N, rows per segment), ``num_stages`` (ring depth), ``tile`` (the + routing tables' token tile), ``tile_k`` (K per ring stage), ``release_after_wait`` (PDL release point: + ``Release.AFTER_WAIT``, else ``Release.POOL_SPENT``), ``route_top_k`` / ``route_lists`` (0: tables given; else the + engine routes the call, module doc). + + The scheduler queues an FC2 unit once its segment's FC1 counter is complete. Warps: 0 weight TMA, 1 activation + loader, 2 MMA, 3 unit scheduler, 4-11 two epilogue groups taking alternate units. + + Routing: every CTA merges each token's candidate lists and derives the experts' rows and segments + (:meth:`_route_prologue`); its epilogue warps then write their CTA's share of the routing outputs and the CTA's + own permuted index -> token copy, which its activation loader waits for (:meth:`_route_deferred`).""" + + fc2_wait_in_scheduler = True + + def __init__( + self, + hidden: int, + inter: int, + n_max: int, + num_stages: int, + tile: int, + tile_k: int, + release_after_wait: bool, + route_top_k: int = 0, + route_lists: int = 0, + ): + assert tile_k in (256, 512) and n_max in N_MAX + super().__init__(hidden, inter, n_max, num_stages, tile_k) + self.release = Release.AFTER_WAIT if release_after_wait else Release.POOL_SPENT + self.route = route_top_k > 0 + self.route_top_k = route_top_k + self.route_lists = route_lists + self.tile = tile + self.groups = inter // 64 # 4-scale groups per intermediate row (8x4 layout) + self.sfb_n = 128 + self.b_stage_bytes = n_max * tile_k // 2 + self.sfb_stage_bytes = self.sfb_n * (tile_k // SF_VEC) + self.kchunks = tile_k // 32 # 16-byte chunks of one activation row per stage + self.kgroups = tile_k // 64 # 4-scale groups per row per stage + if self.route: + err = route_error(route_top_k, route_lists) + assert err is None, err + self.route_masks, self.route_starts, self.route_sink = _route_scratch( + route_top_k, route_lists + ) + assert num_stages * self.b_stage_bytes >= self.route_sink + 4, "route scratch" + + def _setup(self): + self.tiled_mma = sm100_utils.make_blockscaled_trivial_tiled_mma( + self.a_dtype, + self.b_dtype, + self.a_major_mode, + self.b_major_mode, + self.sf_dtype, + SF_VEC, + self.cta_group, + (TILE_M, self.n_max), + ) + mma_inst_k = cute.size(self.tiled_mma.shape_mnk, mode=[2]) + self.mma_inst_tile_k = self.tile_k // mma_inst_k + self.num_sfa_tmem_cols = (TILE_M // 32) * self.mma_inst_tile_k + self.num_sfb_tmem_cols = self.mma_inst_tile_k * (self.sfb_n // 32) + total = NUM_ACC * self.n_max + self.num_sfa_tmem_cols + self.num_sfb_tmem_cols + assert total <= 512, f"TMEM: {NUM_ACC} x {self.n_max} accumulator columns + scales > 512" + cols = 32 + while cols < total: + cols *= 2 + self.num_tmem_cols = cols + self.cluster_layout_vmnk = cute.tiled_divide( + cute.make_layout((1, 1, 1)), (self.tiled_mma.thr_id.shape,) + ) + tiler = (TILE_M, self.n_max, self.tile_k) + self.a_smem_layout_staged = sm100_utils.make_smem_layout_a( + self.tiled_mma, tiler, self.a_dtype, self.num_stages + ) + self.b_smem_layout_staged = sm100_utils.make_smem_layout_b( + self.tiled_mma, tiler, self.b_dtype, self.num_stages + ) + self.sfa_smem_layout_staged = blockscaled_utils.make_smem_layout_sfa( + self.tiled_mma, tiler, SF_VEC, self.num_stages + ) + self.tiled_mma_sfb = sm100_utils.make_blockscaled_trivial_tiled_mma( + self.a_dtype, + self.b_dtype, + self.a_major_mode, + self.b_major_mode, + self.sf_dtype, + SF_VEC, + tcgen05.CtaGroup.ONE, + (TILE_M, self.sfb_n), + ) + self.sfb_smem_layout_staged = blockscaled_utils.make_smem_layout_sfb( + self.tiled_mma_sfb, (TILE_M, self.sfb_n, self.tile_k), SF_VEC, self.num_stages + ) + + def _a_atoms(self, w_ptr, wsf_ptr, rows, k, e): + w = cute.make_tensor(w_ptr, cute.make_ordered_layout((rows, k, e), order=(1, 0, 2))) + wsf = cute.make_tensor(wsf_ptr, blockscaled_utils.tile_atom_to_shape_SF(w.shape, SF_VEC)) + a_op = sm100_utils.cluster_shape_to_tma_atom_A((1, 1), self.tiled_mma.thr_id) + a_smem_layout = cute.slice_(self.a_smem_layout_staged, (None, None, None, 0)) + atom, tens = cute.nvgpu.make_tiled_tma_atom_A( + a_op, + w, + a_smem_layout, + (TILE_M, self.n_max, self.tile_k), + self.tiled_mma, + self.cluster_layout_vmnk.shape, + ) + sfa_smem_layout = cute.slice_(self.sfa_smem_layout_staged, (None, None, None, 0)) + atom_sf, tens_sf = cute.nvgpu.make_tiled_tma_atom_A( + a_op, + wsf, + sfa_smem_layout, + (TILE_M, self.n_max, self.tile_k), + self.tiled_mma, + self.cluster_layout_vmnk.shape, + internal_type=cutlass.Int16, + ) + self.tma_bytes_a = cute.size_in_bytes(self.a_dtype, a_smem_layout) + cute.size_in_bytes( + self.sf_dtype, sfa_smem_layout + ) + return atom, tens, atom_sf, tens_sf + + @cute.jit + def __call__( + self, + w1_ptr: cute.Pointer, + w1sf_ptr: cute.Pointer, + w2_ptr: cute.Pointer, + w2sf_ptr: cute.Pointer, + b_dummy_ptr: cute.Pointer, + xq_addr: Int64, + xsf_addr: Int64, + p2t_addr: Int64, + batch_addr: Int64, + limit_addr: Int64, + nctas_addr: Int64, + max_ctas: Int32, + scale_c_addr: Int64, + alpha1_addr: Int64, + alpha2_addr: Int64, + h_addr: Int64, + hsf_addr: Int64, + out_addr: Int64, + state_addr: Int64, + num_experts: Int32, + grid_ctas: Int32, + stream: cuda.CUstream, + cand_addr: Optional[Int64] = None, + ids_addr: Optional[Int64] = None, + wts_addr: Optional[Int64] = None, + e2p_addr: Optional[Int64] = None, + npad_addr: Optional[Int64] = None, + p2tp_addr: Optional[Int64] = None, + m_rows: Optional[Int32] = None, + local_start: Optional[Int32] = None, + ): + # route only: the candidates, the routing outputs (ids, weights, e2p, padded row count), the CTAs' permuted + # index -> token copies [grid, p2t rows], the call's tokens and the rank's first expert + e = num_experts + self.a_dtype = w1_ptr.value_type + self.b_dtype = b_dummy_ptr.value_type + self.sf_dtype = w1sf_ptr.value_type + w_probe = cute.make_tensor( + w1_ptr, cute.make_ordered_layout((2 * self.inter, self.hidden, e), order=(1, 0, 2)) + ) + b_probe = cute.make_tensor( + b_dummy_ptr, cute.make_ordered_layout((self.n_max, self.tile_k, 1), order=(1, 0, 2)) + ) + self.a_major_mode = cutlass.utils.LayoutEnum.from_tensor(w_probe).mma_major_mode() + self.b_major_mode = cutlass.utils.LayoutEnum.from_tensor(b_probe).mma_major_mode() + self._setup() + a1, t1, a1s, t1s = self._a_atoms(w1_ptr, w1sf_ptr, 2 * self.inter, self.hidden, e) + a2, t2, a2s, t2s = self._a_atoms(w2_ptr, w2sf_ptr, self.hidden, self.inter, e) + self.kernel( + self.tiled_mma, + a1, + t1, + a1s, + t1s, + a2, + t2, + a2s, + t2s, + self.cluster_layout_vmnk, + self.a_smem_layout_staged, + self.b_smem_layout_staged, + self.sfa_smem_layout_staged, + self.sfb_smem_layout_staged, + xq_addr, + xsf_addr, + p2t_addr, + batch_addr, + limit_addr, + nctas_addr, + max_ctas, + scale_c_addr, + alpha1_addr, + alpha2_addr, + h_addr, + hsf_addr, + out_addr, + state_addr, + num_experts, + cand_addr, + ids_addr, + wts_addr, + e2p_addr, + npad_addr, + p2tp_addr, + m_rows, + local_start, + ).launch( + grid=[grid_ctas, 1, 1], + block=[THREADS, 1, 1], + cluster=(1, 1, 1), + stream=stream, + use_pdl=self.use_pdl, + min_blocks_per_mp=1, + ) + + # ------------------------------------------------------------------------------------------------------------ + @cute.kernel + def kernel( + self, + tiled_mma: cute.TiledMma, + tma_a1: cute.CopyAtom, + mA1: cute.Tensor, + tma_a1s: cute.CopyAtom, + mA1s: cute.Tensor, + tma_a2: cute.CopyAtom, + mA2: cute.Tensor, + tma_a2s: cute.CopyAtom, + mA2s: cute.Tensor, + cluster_layout_vmnk: cute.Layout, + a_smem_layout_staged: cute.ComposedLayout, + b_smem_layout_staged: cute.ComposedLayout, + sfa_smem_layout_staged: cute.Layout, + sfb_smem_layout_staged: cute.Layout, + xq_addr: Int64, + xsf_addr: Int64, + p2t_addr: Int64, + batch_addr: Int64, + limit_addr: Int64, + nctas_addr: Int64, + max_ctas: Int32, + scale_c_addr: Int64, + alpha1_addr: Int64, + alpha2_addr: Int64, + h_addr: Int64, + hsf_addr: Int64, + out_addr: Int64, + state_addr: Int64, + n_exp: Int32, + cand_addr: Optional[Int64] = None, + ids_addr: Optional[Int64] = None, + wts_addr: Optional[Int64] = None, + e2p_addr: Optional[Int64] = None, + npad_addr: Optional[Int64] = None, + p2tp_addr: Optional[Int64] = None, + m_rows: Optional[Int32] = None, + local_start: Optional[Int32] = None, + ): + warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + tidx, _, _ = cute.arch.thread_idx() + bidx, _, _ = cute.arch.block_idx() + gdx, _, _ = cute.arch.grid_dim() + lane = cute.arch.lane_idx() + Stages = self.num_stages + NT = THREADS + + @cute.struct + class SharedStorage: + ab_bars: cute.struct.MemRange[cutlass.Int64, Stages * 2] + acc_bars: cute.struct.MemRange[cutlass.Int64, NUM_ACC * 2] + tmem_bar: cutlass.Int64 + tmem_base: cutlass.Int32 + nseg: cute.struct.MemRange[cutlass.Int32, 4] + wsum: cute.struct.MemRange[cutlass.Int32, 12] + wsplit: cute.struct.MemRange[cutlass.Int32, 12] + exp_e: cute.struct.MemRange[cutlass.Int32, 128] + exp_y0: cute.struct.MemRange[cutlass.Int32, 129] + exp_lim: cute.struct.MemRange[cutlass.Int32, 128] + seg_e: cute.struct.MemRange[cutlass.Int32, SEG_CAP] + seg_r0: cute.struct.MemRange[cutlass.Int32, SEG_CAP] + seg_n: cute.struct.MemRange[cutlass.Int32, SEG_CAP] + tok: cute.struct.MemRange[cutlass.Int32, 128] + uq: cute.struct.MemRange[cutlass.Int32, QD] + q_bars: cute.struct.MemRange[cutlass.Int64, 3 * QD] + ex_a1: cute.struct.MemRange[cutlass.Float32, 128] + ex_c: cute.struct.MemRange[cutlass.Float32, 128] + ex_a2: cute.struct.MemRange[cutlass.Float32, 128] + + smem = cutlass.utils.SmemAllocator() + storage = smem.allocate(SharedStorage) + s_nseg, s_wsum, s_exp_e, s_exp_y0, s_exp_lim, s_seg_e, s_seg_r0, s_seg_n, s_tok = ( + smem_views(storage) + ) + s_wsplit = storage.wsplit.get_tensor(cute.make_layout(12)) + if warp_idx == 0: + cpasync.prefetch_descriptor(tma_a1) + cpasync.prefetch_descriptor(tma_a1s) + cpasync.prefetch_descriptor(tma_a2) + cpasync.prefetch_descriptor(tma_a2s) + ab_pipeline = PipelineAsync.create( + barrier_storage=storage.ab_bars.data_ptr(), + num_stages=Stages, + producer_group=CooperativeGroup(Agent.Thread, 1 + 32), + consumer_group=CooperativeGroup(Agent.Thread), + defer_sync=True, + ) + ab_full = ab_pipeline.sync_object_full.barrier_storage + ab_empty = ab_pipeline.sync_object_empty.barrier_storage + acc_pipeline = PipelineUmmaAsync.create( + barrier_storage=storage.acc_bars.data_ptr(), + num_stages=NUM_ACC, + producer_group=CooperativeGroup(Agent.Thread), + consumer_group=CooperativeGroup(Agent.Thread, 128), + defer_sync=True, + ) + acc_full = acc_pipeline.sync_object_full.barrier_storage + acc_empty = acc_pipeline.sync_object_empty.barrier_storage + tmem_bar = storage.tmem_bar.ptr + tmem_base_smem_ptr = storage.tmem_base.ptr + s_q = storage.uq.get_tensor(cute.make_layout(QD)) + q_full = storage.q_bars.data_ptr() # full [QD], empty [QD], taken [QD] + self.init_barriers(warp_idx, tmem_bar, q_full) + sA = smem.allocate_tensor( + element_type=self.a_dtype, + layout=a_smem_layout_staged.outer, + byte_alignment=1024, + swizzle=a_smem_layout_staged.inner, + ) + sB = smem.allocate_tensor( + element_type=self.b_dtype, + layout=b_smem_layout_staged.outer, + byte_alignment=1024, + swizzle=b_smem_layout_staged.inner, + ) + sSFA = smem.allocate_tensor( + element_type=self.sf_dtype, layout=sfa_smem_layout_staged, byte_alignment=128 + ) + sSFB = smem.allocate_tensor( + element_type=self.sf_dtype, layout=sfb_smem_layout_staged, byte_alignment=128 + ) + if cutlass.const_expr(self.route): + # each token's merged keys, descending + s_pick = smem.allocate_tensor( + Int32, cute.make_layout(ROUTE_MAX_ROWS * self.route_top_k), byte_alignment=16 + ) + sb_base = sB.iterator.toint() + sfb_base = sSFB.iterator.toint() + route_done = None + if cutlass.const_expr(self.route): + # Completes once every epilogue thread wrote its routing outputs, which the MoE-output all-reduce reads + # before (Lamport FC2) or without its dependency wait: the scheduler releases the dependents after it. + route_done = smem.allocate_tensor( + cutlass.Int64, cute.make_layout(1), byte_alignment=8 + ).iterator + if warp_idx == 0: + with cute.arch.elect_one(): + cute.arch.mbarrier_init(route_done, 128 * EPI_GROUPS) + cute.arch.mbarrier_init_fence() + pipeline_init_arrive(cluster_shape_mn=None, is_relaxed=True) + pipeline_init_wait(cluster_shape_mn=None) + + s_a1 = storage.ex_a1.get_tensor(cute.make_layout(128)) + s_c = storage.ex_c.get_tensor(cute.make_layout(128)) + s_a2 = storage.ex_a2.get_tensor(cute.make_layout(128)) + if tidx >= 128: + if tidx < 256: + ei = tidx - 128 + if ei < n_exp: + # weights' constants: not written by the previous kernel, so read before the dependency wait + s_a1[ei] = _ld_nc_f32(alpha1_addr + Int64(ei) * 4) + s_c[ei] = _ld_nc_f32(scale_c_addr + Int64(ei) * 4) + s_a2[ei] = _ld_nc_f32(alpha2_addr + Int64(ei) * 4) + # gen is loaded here and used after the table scan, so its latency overlaps the scan's loads + gen = self.wait_dependency(state_addr, route_done) + + # tiles per n_max rows: an expert splits iff the tile RT after its first is still its own + RT = ( + self.n_max // self.tile + if self.n_max % self.tile == 0 and self.n_max >= self.tile + else 0 + ) + if cutlass.const_expr(self.route): + nexp, anysplit = self._route_prologue( + cand_addr, + m_rows, + local_start, + n_exp, + s_exp_e, + s_exp_y0, + s_exp_lim, + s_wsum, + s_pick, + tidx, + lane, + sb_base, + ) + else: + # ---- expert segments from the tile tables (whole CTA). Per 256 tiles one round of independent loads: the + # tile's expert, its neighbours' and its row limit; a tile starts an expert if its expert differs from the + # previous tile's and ends one if it differs from the next tile's (the end tile's limit closes the expert). + n_tiles = _ld_s32(nctas_addr) + warp_in = tidx // 32 + lane_lt = (Int32(1) << lane) - Int32(1) + nexp = Int32(0) + base = Int32(0) + more = Int32(1) + anysplit = Int32(0) # some expert has more than n_max rows + while more != 0: + y = base + tidx + bc = Int32(-1) + bp = Int32(-1) + bn = Int32(-1) + br = Int32(-2) + lim = Int32(0) + if y < max_ctas: + bc = _ld_s32(batch_addr + Int64(y) * 4) + lim = _ld_s32(limit_addr + Int64(y) * 4) + if y > 0: + bp = _ld_s32(batch_addr + Int64(y - 1) * 4) + if y + 1 < max_ctas: + bn = _ld_s32(batch_addr + Int64(y + 1) * 4) + if cutlass.const_expr(RT > 0): + if y + RT < max_ctas: + br = _ld_s32(batch_addr + Int64(y + RT) * 4) + nt = cutlass.min(n_tiles, max_ctas) + start = Int32(0) + end = Int32(0) + spl = Int32(0) + if y < nt: + if bc != bp: + start = Int32(1) + if cutlass.const_expr(RT > 0): + if y + RT < nt: + if br == bc: + spl = Int32(1) + if bn != bc: + end = Int32(1) + if y + 1 == nt: + end = Int32(1) + bal = _ballot(start) + sbal = Int32(0) + if cutlass.const_expr(RT > 0): + sbal = _ballot(spl) + pre = _popc(bal & lane_lt) + if lane == 0: + s_wsum[warp_in] = _popc(bal) + if cutlass.const_expr(RT > 0): + s_wsplit[warp_in] = sbal + cute.arch.barrier() + off = Int32(0) + tot = Int32(0) + for w in cutlass.range_constexpr(NT // 32): + v = s_wsum[w] + if w < warp_in: + off = off + v + tot = tot + v + if cutlass.const_expr(RT > 0): + anysplit = anysplit | s_wsplit[w] + incl = nexp + off + pre + start # experts started at or before tile y + if start != 0: + s_exp_e[incl - 1] = bc + s_exp_y0[incl - 1] = y + if end != 0: + s_exp_lim[incl - 1] = lim + nexp = nexp + tot + base = base + NT + more = Int32(0) + if base < nt: + more = Int32(1) + cute.arch.barrier() + # split experts into segments of <= n_max rows: with no expert above n_max rows the segments are the experts, + # written by every thread in one step; else warp 0 (4 experts per lane, warp prefix of the chunk counts) + slow = Int32(1) + if cutlass.const_expr(RT > 0): + if anysplit == 0: + slow = Int32(0) + for xi in cutlass.range(tidx, nexp, NT, unroll=1): + r0f = s_exp_y0[xi] * self.tile + s_seg_e[xi] = s_exp_e[xi] + s_seg_r0[xi] = r0f + s_seg_n[xi] = s_exp_lim[xi] - r0f + if tidx == 0: + s_nseg[0] = nexp + if warp_idx + Int32(32) * (Int32(1) - slow) == 0: + cnts = cute.make_rmem_tensor((4,), Int32) + mysum = Int32(0) + for qi in cutlass.range_constexpr(4): + xi = lane * 4 + qi + c = Int32(0) + if xi < nexp: + c = (s_exp_lim[xi] - s_exp_y0[xi] * self.tile + (self.n_max - 1)) // self.n_max + cnts[qi] = c + mysum = mysum + c + incl = mysum + for off2 in (1, 2, 4, 8, 16): + t = cute.arch.shuffle_sync_up(incl, off2) + if lane >= off2: + incl = incl + t + pos = incl - mysum + for qi in cutlass.range_constexpr(4): + xi = lane * 4 + qi + if xi < nexp: + r0 = s_exp_y0[xi] * self.tile + rows = s_exp_lim[xi] - r0 + for ch in cutlass.range(cnts[qi], unroll=1): + s_seg_e[pos] = s_exp_e[xi] + s_seg_r0[pos] = r0 + ch * self.n_max + s_seg_n[pos] = cutlass.min(rows - ch * self.n_max, self.n_max) + pos = pos + 1 + if lane == 31: + s_nseg[0] = incl + cute.arch.barrier() + nseg = s_nseg[0] + cnt_base, pool_addr, u1, u2, n1 = self.begin_call(state_addr, gen, nseg, bidx, tidx, gdx) + p2t_ld = p2t_addr + if cutlass.const_expr(self.route): + # the activation loader reads this CTA's own copy, which this CTA's epilogue warps write + p2t_rows = (max_ctas + Int32(1)) * Int32(self.tile) + p2t_ld = p2tp_addr + Int64(bidx) * Int64(p2t_rows) * Int64(4) + + if warp_idx == 0: + self.load_a( + ab_full, + ab_empty, + tma_a1, + mA1, + tma_a1s, + mA1s, + tma_a2, + mA2, + tma_a2s, + mA2s, + sA, + sSFA, + tiled_mma, + cluster_layout_vmnk, + s_seg_e, + s_q, + q_full, + u1, + bidx, + ) + elif warp_idx == 1: + if cutlass.const_expr(self.route): + _bar_sync(Int32(_ROUTE_BAR), 32 + 128 * EPI_GROUPS) + self.load_b( + ab_full, + ab_empty, + s_seg_r0, + s_seg_n, + s_tok, + sb_base, + sfb_base, + xq_addr, + xsf_addr, + p2t_ld, + h_addr, + hsf_addr, + s_q, + q_full, + u1, + lane, + bidx, + ) + elif warp_idx == 2: + self.mma( + ab_full, + ab_empty, + acc_full, + acc_empty, + tmem_bar, + tmem_base_smem_ptr, + tiled_mma, + sA, + sB, + sSFA, + sSFB, + sfa_smem_layout_staged, + sfb_smem_layout_staged, + s_q, + q_full, + u1, + ) + elif warp_idx == 3: + self.scheduler( + s_q, q_full, n1, u1, u2, bidx, gdx, pool_addr, cnt_base, lane, route_done + ) + elif warp_idx >= EPI_WARP0: + if cutlass.const_expr(self.route): + self._route_deferred( + s_pick, + s_wsum, + sb_base, + ids_addr, + wts_addr, + e2p_addr, + p2t_addr, + p2t_ld, + batch_addr, + limit_addr, + nctas_addr, + npad_addr, + m_rows, + local_start, + n_exp, + tidx - Int32(EPI_WARP0 * 32), + bidx, + gdx, + ) + _fence_gpu() + cute.arch.mbarrier_arrive(route_done) + self.epilogue( + acc_full, + acc_empty, + tmem_bar, + tmem_base_smem_ptr, + tiled_mma, + s_seg_e, + s_seg_r0, + s_seg_n, + s_a1, + s_c, + s_a2, + h_addr, + hsf_addr, + out_addr, + cnt_base, + (tidx - EPI_WARP0 * 32) % 128, + (tidx - EPI_WARP0 * 32) // 128, + s_q, + q_full, + u1, + ) + self.end_call(warp_idx, tidx, gdx, tmem_base_smem_ptr, state_addr, gen) + return + + # ------------------------------------------------------------------------------------------------------------ + @cute.jit + def _route_prologue( + self, + cand_addr: Int64, + m_rows: Int32, + local_start: Int32, + n_exp: Int32, + s_exp_e, + s_exp_y0, + s_exp_lim, + s_wsum, + s_pick, + tidx, + lane, + sb_base, + ): + """Routing, whole CTA, after the dependency wait: each token's top ``route_top_k`` keys merged from its + ``route_lists`` descending lists (s_pick), every local expert's token mask and first tile (sB scratch), and the + experts with rows in exp_e / exp_y0 / exp_lim as the tile-table scan leaves them. Returns (experts with rows, + some expert above n_max rows); s_wsum[0] holds the call's tiles.""" + NT: cutlass.Constexpr = THREADS + TK: cutlass.Constexpr = self.route_top_k + NL: cutlass.Constexpr = self.route_lists + tile: cutlass.Constexpr = self.tile + cbase = Int32(sb_base) + mask_base = cbase + Int32(self.route_masks) + start_base = cbase + Int32(self.route_starts) + sink = cbase + Int32(self.route_sink) + key_base = _smem_addr(s_pick.iterator) + warp_in = tidx // Int32(32) + # one round of loads: the m x NL x TK keys as 16-byte vectors (at most two per thread), both issued before + # the first store, so the copy pays one L2 round trip; the masks are zeroed meanwhile + nv = m_rows * Int32(NL * TK // 4) + i0 = tidx + i1 = tidx + Int32(NT) + a0 = Int32(0) + b0 = Int32(0) + c0 = Int32(0) + d0 = Int32(0) + a1 = Int32(0) + b1 = Int32(0) + c1 = Int32(0) + d1 = Int32(0) + if i0 < nv: + a0, b0, c0, d0 = _ld_v4(cand_addr + Int64(i0) * Int64(16)) + if i1 < nv: + a1, b1, c1, d1 = _ld_v4(cand_addr + Int64(i1) * Int64(16)) + for i in cutlass.range(tidx, 2 * MAX_LOCAL_EXPERTS, NT, unroll=1): + _st_shared(mask_base + i * Int32(4), Int32(0)) + if i0 < nv: + _st_shared_v4(cbase + i0 * Int32(16), a0, b0, c0, d0) + if i1 < nv: + _st_shared_v4(cbase + i1 * Int32(16), a1, b1, c1, d1) + cute.arch.barrier() + # one thread per token merges its NL lists: each keeps its head and next key in registers; the list whose + # head is picked advances. A list whose keys are all used reads past its end, a value that could only become + # a head after pick TK + 1. Picks stay in registers until their stores and mask ORs after the loop. + t = tidx + if t < m_rows: + p = [cbase + t * Int32(NL * TK * 4)] + for j in cutlass.range_constexpr(1, NL): + p.append(p[0] + Int32(j * TK * 4)) + h = [_ld_shared(p[j]) for j in range(NL)] + n = [_ld_shared(p[j] + Int32(4)) for j in range(NL)] + gk = [] + for k in cutlass.range_constexpr(TK): + g = _max_tree(h) + gk.append(g) + if cutlass.const_expr(k < TK - 1): + p = [_sel_eq(h[j], g, p[j] + Int32(4), p[j]) for j in range(NL)] + h = [_sel_eq(h[j], g, n[j], h[j]) for j in range(NL)] + n = [_ld_shared(p[j] + Int32(4)) for j in range(NL)] + kb = key_base + t * Int32(TK * 4) + mrow = mask_base + (t // Int32(32)) * Int32(4) + mbit = _bit(t % Int32(32)) + for k in cutlass.range_constexpr(TK): + _st_shared(kb + Int32(4 * k), gk[k]) + for k in cutlass.range_constexpr(TK): + lid = Int32(65535) - (gk[k] & Int32(65535)) - local_start + _red_or_shared(_sel_lt(lid, n_exp, mrow + lid * Int32(8), sink), mbit) + cute.arch.barrier() + # warp 0, local experts 4 lane .. 4 lane + 3: rows, tiles, first tile, and the experts with rows in order, from + # one warp scan of (tiles << 16 | experts with rows) + if warp_in == Int32(0): + cn = cute.make_rmem_tensor(cute.make_layout((4,)), Int32) + pk = Int32(0) + bigl = Int32(0) + for qi in cutlass.range_constexpr(4): + e = lane * Int32(4) + Int32(qi) + c = Int32(0) + if e < n_exp: + c = _popc(_ld_shared(mask_base + e * Int32(8))) + _popc( + _ld_shared(mask_base + e * Int32(8) + Int32(4)) + ) + cn[qi] = c + pk = ( + pk + + (((c + Int32(tile - 1)) // Int32(tile)) << Int32(16)) + + _sel_lt(Int32(0), c, Int32(1), Int32(0)) + ) + bigl = bigl | _sel_lt(Int32(self.n_max), c, Int32(1), Int32(0)) + incl = pk + for off2 in (1, 2, 4, 8, 16): + u = cute.arch.shuffle_sync_up(incl, off2) + if lane >= off2: + incl = incl + u + exl = incl - pk + toff = exl >> Int32(16) + aoff = exl & Int32(65535) + for qi in cutlass.range_constexpr(4): + e = lane * Int32(4) + Int32(qi) + c = cn[qi] + if e < n_exp: + _st_shared(start_base + e * Int32(4), toff) + if c > Int32(0): + s_exp_e[aoff] = e + s_exp_y0[aoff] = toff + s_exp_lim[aoff] = toff * Int32(tile) + c + aoff = aoff + _sel_lt(Int32(0), c, Int32(1), Int32(0)) + toff = toff + (c + Int32(tile - 1)) // Int32(tile) + bbal = _ballot(bigl) + if lane == Int32(31): + s_wsum[0] = incl >> Int32(16) # tiles + s_wsum[1] = incl & Int32(65535) # experts with rows + s_wsum[2] = bbal + cute.arch.barrier() + return s_wsum[1], s_wsum[2] + + @cute.jit + def _route_deferred( + self, + s_pick, + s_wsum, + sb_base, + ids_addr: Int64, + wts_addr: Int64, + e2p_addr: Int64, + p2t_addr: Int64, + p2t_cta: Int64, + batch_addr: Int64, + limit_addr: Int64, + nctas_addr: Int64, + npad_addr: Int64, + m_rows: Int32, + local_start: Int32, + n_exp: Int32, + q, + bidx, + gdx, + ): + """Routing, epilogue thread q of 128 x EPI_GROUPS, before its first accumulator: + 1. each local pick (expanded index token * TK + k) into this CTA's p2t copy; the token's owner CTA (token % + grid) also writes the call's p2t and e2p (-1: another rank's expert), one writer per word; + 2. release the activation loader (the copy's only reader) once the masks and first tiles are in registers; + 3. the tile tables (the expert's owner CTA) and their counts (CTA 0); + 4. ids and BF16 weights of the tokens this CTA owns, with the route front's arithmetic.""" + TK: cutlass.Constexpr = self.route_top_k + NE: cutlass.Constexpr = 128 * EPI_GROUPS + tile: cutlass.Constexpr = self.tile + key_base = _smem_addr(s_pick.iterator) + mask_base = Int32(sb_base) + Int32(self.route_masks) + start_base = Int32(sb_base) + Int32(self.route_starts) + for x in cutlass.range(q, m_rows * Int32(TK), NE, unroll=1): + tt = x // Int32(TK) + key = _ld_shared(key_base + x * Int32(4)) + lid = Int32(65535) - (key & Int32(65535)) - local_start + own = Int32(0) + if tt % gdx == bidx: + own = Int32(1) + row = Int32(-1) + if _sel_lt(lid, n_exp, Int32(1), Int32(0)) != Int32(0): + lo = _ld_shared(mask_base + lid * Int32(8)) + rank = Int32(0) + if tt < Int32(32): + rank = _popc(lo & ((Int32(1) << tt) - Int32(1))) + else: + hi = _ld_shared(mask_base + lid * Int32(8) + Int32(4)) + rank = _popc(lo) + _popc(hi & ((Int32(1) << (tt - Int32(32))) - Int32(1))) + row = _ld_shared(start_base + lid * Int32(4)) * Int32(tile) + rank + _st_global_b32(p2t_cta + Int64(row) * Int64(4), tt) + if own != Int32(0): + _st_global_b32(p2t_addr + Int64(row) * Int64(4), tt) + if own != Int32(0): + _st_global_b32(e2p_addr + Int64(x) * Int64(4), row) + e = q + cnt = Int32(0) + st0 = Int32(0) + if e < n_exp: + cnt = _popc(_ld_shared(mask_base + e * Int32(8))) + _popc( + _ld_shared(mask_base + e * Int32(8) + Int32(4)) + ) + st0 = _ld_shared(start_base + e * Int32(4)) + _fence_cta_after(cnt) + _bar_arrive(Int32(_ROUTE_BAR), 32 + NE) + if cnt > Int32(0): + if e % gdx == bidx: + for c in cutlass.range((cnt + Int32(tile - 1)) // Int32(tile), unroll=1): + _st_global_b32(batch_addr + Int64(st0 + c) * Int64(4), e) + lim1 = (st0 + c + Int32(1)) * Int32(tile) + lim2 = st0 * Int32(tile) + cnt + _st_global_b32(limit_addr + Int64(st0 + c) * Int64(4), cutlass.min(lim1, lim2)) + if bidx == Int32(0): + if q == Int32(0): + ntot = s_wsum[0] + _st_global_b32(nctas_addr, ntot) + _st_global_b32(npad_addr, ntot * Int32(tile)) + t = bidx + q * gdx + if t < m_rows: + kb = key_base + t * Int32(TK * 4) + val = [] + for k in cutlass.range_constexpr(TK): + g = _ld_shared(kb + Int32(4 * k)) + o = Int64(t) * Int64(TK) + Int64(k) + _st_global_b32(ids_addr + o * Int64(4), Int32(65535) - (g & Int32(65535))) + val.append(_key_val(g)) + ex = [] + for k in cutlass.range_constexpr(TK): + ex.append(_exp_tr(_sub(val[k], val[0]))) + ssum = sum_tree(ex, _butterfly_sum(TK)) + for k in cutlass.range_constexpr(TK): + o = Int64(t) * Int64(TK) + Int64(k) + _st_b16(wts_addr + o * Int64(2), _div_bf16(ex[k], ssum)) + + @cute.jit + def load_a( + self, + ab_full, + ab_empty, + tma_a1: cute.CopyAtom, + mA1: cute.Tensor, + tma_a1s: cute.CopyAtom, + mA1s: cute.Tensor, + tma_a2: cute.CopyAtom, + mA2: cute.Tensor, + tma_a2s: cute.CopyAtom, + mA2s: cute.Tensor, + sA: cute.Tensor, + sSFA: cute.Tensor, + tiled_mma: cute.TiledMma, + cluster_layout_vmnk: cute.Layout, + s_seg_e: cute.Tensor, + s_q: cute.Tensor, + q_full, + u1, + bidx, + ): + """Weights + scales of every unit, back to back through the ring (constant data).""" + thr_mma = tiled_mma.get_slice(0) + a_cta_layout = cute.make_layout(cute.slice_(cluster_layout_vmnk, (0, 0, None, 0)).shape) + g1 = cute.local_tile(mA1, (TILE_M, self.tile_k), (None, None, None)) + t1s, t1g = cpasync.tma_partition( + tma_a1, + 0, + a_cta_layout, + cute.group_modes(sA, 0, 3), + cute.group_modes(thr_mma.partition_A(g1), 0, 3), + ) + g1s = cute.local_tile(mA1s, (TILE_M, self.tile_k), (None, None, None)) + t1ss, t1sg = cpasync.tma_partition( + tma_a1s, + 0, + a_cta_layout, + cute.group_modes(sSFA, 0, 3), + cute.group_modes(thr_mma.partition_A(g1s), 0, 3), + ) + t1ss = cute.filter_zeros(t1ss) + t1sg = cute.filter_zeros(t1sg) + g2 = cute.local_tile(mA2, (TILE_M, self.tile_k), (None, None, None)) + t2s, t2g = cpasync.tma_partition( + tma_a2, + 0, + a_cta_layout, + cute.group_modes(sA, 0, 3), + cute.group_modes(thr_mma.partition_A(g2), 0, 3), + ) + g2s = cute.local_tile(mA2s, (TILE_M, self.tile_k), (None, None, None)) + t2ss, t2sg = cpasync.tma_partition( + tma_a2s, + 0, + a_cta_layout, + cute.group_modes(sSFA, 0, 3), + cute.group_modes(thr_mma.partition_A(g2s), 0, 3), + ) + t2ss = cute.filter_zeros(t2ss) + t2sg = cute.filter_zeros(t2sg) + st = make_pipeline_state(PipelineUserType.Producer, self.num_stages) + wp = _policy_evict_first() + k = Int32(0) + g = self.first_unit(s_q, q_full, u1, bidx) + self.take(q_full, 0) + while g >= 0: + is1, seg, mt = self.decode(g, u1) + ex = s_seg_e[seg] + if is1 != 0: + for kt in cutlass.range(self.k1_tiles, unroll=1): + cute.arch.mbarrier_wait(ab_empty + st.index, st.phase) + with cute.arch.elect_one(): + cute.arch.mbarrier_arrive_and_expect_tx( + ab_full + st.index, self.tma_bytes_a + ) + cute.copy( + tma_a1, + t1g[(None, mt, kt, ex)], + t1s[(None, st.index)], + tma_bar_ptr=ab_full + st.index, + cache_policy=wp, + ) + cute.copy( + tma_a1s, + t1sg[(None, mt, kt, ex)], + t1ss[(None, st.index)], + tma_bar_ptr=ab_full + st.index, + cache_policy=wp, + ) + st.advance() + else: + for kt in cutlass.range(self.k2_tiles, unroll=1): + cute.arch.mbarrier_wait(ab_empty + st.index, st.phase) + with cute.arch.elect_one(): + cute.arch.mbarrier_arrive_and_expect_tx( + ab_full + st.index, self.tma_bytes_a + ) + cute.copy( + tma_a2, + t2g[(None, mt, kt, ex)], + t2s[(None, st.index)], + tma_bar_ptr=ab_full + st.index, + cache_policy=wp, + ) + cute.copy( + tma_a2s, + t2sg[(None, mt, kt, ex)], + t2ss[(None, st.index)], + tma_bar_ptr=ab_full + st.index, + cache_policy=wp, + ) + st.advance() + k = k + 1 + g, slot = self.unit(s_q, q_full, k) + self.take(q_full, slot) + + @cute.jit + def _b_stage( + self, + is1, + kt, + rows, + r0, + sb_stage, + sfb_stage, + xq_addr, + xsf_addr, + h_addr, + hsf_addr, + s_tok, + lane, + ): + """Issue one stage's activation rows (cp.async, 128-byte swizzle: row n at 128 n, chunk c at c ^ (n % 8)) + and their scale words into the stage's 128x4 SFB atom (word g of row n at 512 g + 16 (n % 32) + 4 (n / 32)).""" + kc = self.kchunks + kg = self.kgroups + rb = (self.n_max // 8) * 1024 # bytes of one 128-byte-wide K column of swizzle atoms + if is1 != 0: + for n in cutlass.range(lane, rows, 32, unroll=1): + t = s_tok[n] + src = xq_addr + Int64(t) * Int64(self.hidden // 2) + Int64(kt * (kc * 16)) + ssrc = xsf_addr + Int64(t) * Int64(self.hidden // SF_VEC) + Int64(kt * (kg * 4)) + dbase = sb_stage + (n >> 3) * 1024 + (n & 7) * 128 + n7 = n & 7 + for c in cutlass.range_constexpr(kc): + _cp_async_16( + dbase + ((c >> 3) * rb) + (((c & 7) ^ n7) << 4), src + Int64(c * 16) + ) + sbase = sfb_stage + (n & 31) * 16 + (n >> 5) * 4 + for g in cutlass.range_constexpr(kg): + _cp_async_4(sbase + g * 512, ssrc + Int64(g * 4)) + else: + # the segment's intermediate scales: final once its counter read 8 (lines of one 8-row tile belong to one + # segment, so this SM has not cached them earlier in the call; L1 starts each kernel clean) + for n in cutlass.range(lane, rows, 32, unroll=1): + r = r0 + n + src = h_addr + Int64(r) * Int64(self.inter // 2) + Int64(kt * (kc * 16)) + ssrc = ( + hsf_addr + + (Int64(r >> 3) * Int64(self.groups) + Int64(kt * kg)) * 32 + + Int64(r & 7) * 4 + ) + dbase = sb_stage + (n >> 3) * 1024 + (n & 7) * 128 + n7 = n & 7 + for c in cutlass.range_constexpr(kc): + _cp_async_16( + dbase + ((c >> 3) * rb) + (((c & 7) ^ n7) << 4), src + Int64(c * 16) + ) + sbase = sfb_stage + (n & 31) * 16 + (n >> 5) * 4 + for g in cutlass.range_constexpr(kg): + _cp_async_4(sbase + g * 512, ssrc + Int64(g * 32)) + _cp_async_commit() + + @cute.jit + def load_b( + self, + ab_full, + ab_empty, + s_seg_r0, + s_seg_n, + s_tok, + sb_base, + sfb_base, + xq_addr, + xsf_addr, + p2t_addr, + h_addr, + hsf_addr, + s_q, + q_full, + u1, + lane, + bidx, + ): + """Activation rows of every unit: FC1 gathers x rows by permuted index -> token, FC2 reads the segment's + intermediate rows (ready: the scheduler acquired its counter before queueing the unit). Every lane arms an + asynchronous arrival on the stage's full barrier after issuing its copies (cp.async.mbarrier.arrive.noinc), + so the loader never waits for L2 and keeps the whole ring in flight.""" + st = make_pipeline_state(PipelineUserType.Producer, self.num_stages) + k = Int32(0) + g = self.first_unit(s_q, q_full, u1, bidx) + while g >= 0: + is1, seg, mt = self.decode(g, u1) + rows = s_seg_n[seg] + r0 = s_seg_r0[seg] + kts = self.k2_tiles + if is1 != 0: + kts = self.k1_tiles + # token of each row (read only while issuing: in-flight copies already hold their addresses) + cute.arch.sync_warp() + for n in cutlass.range(lane, rows, 32, unroll=1): + s_tok[n] = _ld_s32(p2t_addr + Int64(r0 + n) * 4) + cute.arch.sync_warp() + for kt in cutlass.range(kts, unroll=1): + cute.arch.mbarrier_wait(ab_empty + st.index, st.phase) + self._b_stage( + is1, + kt, + rows, + r0, + sb_base + st.index * self.b_stage_bytes, + sfb_base + st.index * self.sfb_stage_bytes, + xq_addr, + xsf_addr, + h_addr, + hsf_addr, + s_tok, + lane, + ) + _cp_async_arrive_noinc((ab_full + st.index).toint()) + st.advance() + k = k + 1 + g, slot = self.unit(s_q, q_full, k) + + @cute.jit + def mma( + self, + ab_full, + ab_empty, + acc_full, + acc_empty, + tmem_bar, + tmem_base_smem_ptr, + tiled_mma: cute.TiledMma, + sA: cute.Tensor, + sB: cute.Tensor, + sSFA: cute.Tensor, + sSFB: cute.Tensor, + sfa_smem_layout_staged: cute.Layout, + sfb_smem_layout_staged: cute.Layout, + s_q: cute.Tensor, + q_full, + u1, + ): + tCrA = tiled_mma.make_fragment_A(sA) + tCrB = tiled_mma.make_fragment_B(sB) + acc_shape = tiled_mma.partition_shape_C((TILE_M, self.n_max)) + tCtAcc_fake = tiled_mma.make_fragment_C(acc_shape) + cute.arch.alloc_tmem(self.num_tmem_cols, tmem_base_smem_ptr) + cute.arch.mbarrier_arrive(tmem_bar) + cute.arch.relinquish_tmem_alloc_permit() + tmem_ptr = cute.arch.retrieve_tmem_ptr(self.acc_dtype, 16, tmem_base_smem_ptr) + sfa_col = NUM_ACC * self.n_max + sfb_col = sfa_col + self.num_sfa_tmem_cols + tCtSFA_layout = blockscaled_utils.make_tmem_layout_sfa( + tiled_mma, + tiled_mma.shape_mnk, + SF_VEC, + cute.slice_(sfa_smem_layout_staged, (None, None, None, 0)), + ) + tCtSFB_layout = blockscaled_utils.make_tmem_layout_sfb( + tiled_mma, + tiled_mma.shape_mnk, + SF_VEC, + cute.slice_(sfb_smem_layout_staged, (None, None, None, 0)), + ) + tCtSFA = cute.make_tensor( + cute.recast_ptr(tmem_ptr + sfa_col, dtype=self.sf_dtype), tCtSFA_layout + ) + tCtSFB = cute.make_tensor( + cute.recast_ptr(tmem_ptr + sfb_col, dtype=self.sf_dtype), tCtSFB_layout + ) + copy_sfa, tCsSFA_s2t, tCtSFA_s2t = s2t_copy(sSFA, tCtSFA, self.cta_group, self.sf_dtype) + copy_sfb, tCsSFB_s2t, tCtSFB_s2t = s2t_copy(sSFB, tCtSFB, self.cta_group, self.sf_dtype) + num_kphases = cute.size(tCrA, mode=[2]) + ab_st = make_pipeline_state(PipelineUserType.Consumer, self.num_stages) + acc_st = make_pipeline_state(PipelineUserType.Producer, NUM_ACC) + k = Int32(0) + g, slot = self.unit(s_q, q_full, k) + while g >= 0: + kts = self.k2_tiles + if g < u1: + kts = self.k1_tiles + cute.arch.mbarrier_wait(acc_empty + acc_st.index, acc_st.phase) + tCtAcc = cute.make_tensor(tmem_ptr + acc_st.index * self.n_max, tCtAcc_fake.layout) + tiled_mma.set(tcgen05.Field.ACCUMULATE, False) + for _kt in cutlass.range(kts, unroll=1): + cute.arch.mbarrier_wait(ab_full + ab_st.index, ab_st.phase) + cute.copy(copy_sfa, tCsSFA_s2t[(None, None, None, None, ab_st.index)], tCtSFA_s2t) + cute.copy(copy_sfb, tCsSFB_s2t[(None, None, None, None, ab_st.index)], tCtSFB_s2t) + for kp in cutlass.range(num_kphases, unroll_full=True): + tiled_mma.set(tcgen05.Field.SFA, tCtSFA[(None, None, kp)].iterator) + tiled_mma.set(tcgen05.Field.SFB, tCtSFB[(None, None, kp)].iterator) + cute.gemm( + tiled_mma, + tCtAcc, + tCrA[(None, None, kp, ab_st.index)], + tCrB[(None, None, kp, ab_st.index)], + tCtAcc, + ) + tiled_mma.set(tcgen05.Field.ACCUMULATE, True) + with cute.arch.elect_one(): + tcgen05.commit(ab_empty + ab_st.index, None, self.cta_group) + ab_st.advance() + with cute.arch.elect_one(): + tcgen05.commit(acc_full + acc_st.index, None, self.cta_group) + acc_st.advance() + k = k + 1 + g, slot = self.unit(s_q, q_full, k) + + @cute.jit + def epilogue( + self, + acc_full, + acc_empty, + tmem_bar, + tmem_base_smem_ptr, + tiled_mma: cute.TiledMma, + s_seg_e, + s_seg_r0, + s_seg_n, + s_a1: cute.Tensor, + s_c: cute.Tensor, + s_a2: cute.Tensor, + h_addr, + hsf_addr, + out_addr, + cnt_base, + epi_tid, + grp, + s_q: cute.Tensor, + q_full, + u1, + ): + tmem_ptr, tCtAcc_fake, tiled_copy_t2r, thr_copy_t2r, rAcc, row0 = self.epilogue_tmem( + tiled_mma, tmem_bar, tmem_base_smem_ptr, epi_tid + ) + lane = cute.arch.lane_idx() + wq = row0 // 32 # epilogue warp = 32-row block of the weight tile + q = row0 % 32 + hcol = ( + wq * 32 + (q % 8) * 4 + q // 8 + ) # FC2: hidden column of this TMEM lane (32-row block shuffle) + lead = ( + q // 8 + ) % 2 == 0 # FC2: owns the even column of a pair (partner lane q + 8 has hcol + 1) + is_up = Int32(0) + if ((q >> 3) & 1) == 0: + is_up = Int32(1) # FC1: up lanes (gate partner at q ^ 8) + # this group's units: k = grp, grp + EPI_GROUPS, ...; unit k's accumulator is buffer k % NUM_ACC + bar_id = Int32(EPI_BAR) + grp + k = grp + g, slot = self.unit(s_q, q_full, k) + while g >= 0: + is1, seg, mt = self.decode(g, u1) + ex = s_seg_e[seg] + rows = s_seg_n[seg] + r0 = s_seg_r0[seg] + buf = k % NUM_ACC + cute.arch.mbarrier_wait(acc_full + buf, (k // NUM_ACC) & 1) + nch = (rows + 7) // 8 + if is1 != 0: + a = s_a1[ex] + c = s_c[ex] + c1 = _mul_rn(a, cutlass.Float32(LOG2E)) # a * (alpha * log2e), alpha = 1 + for ch in cutlass.range(nch, unroll=1): + self.load_acc( + tmem_ptr, tCtAcc_fake, tiled_copy_t2r, thr_copy_t2r, rAcc, buf, ch + ) + for t in cutlass.range_constexpr(8): + nrow = ch * 8 + t + xv = rAcc[t] + gate = cute.arch.shuffle_sync_bfly(xv, 8) + # trtllm-gen swiGlu E2m1 epilogue (no clamp: the selects of the clamped variant are identities) + sgm = _rcp(_add_rn(_ex2(-_mul_rn(gate, c1)), cutlass.Float32(1.0))) + gs = _mul_rn(gate, sgm) + hv = _mul_rn(_fma_rn(xv, a, _mul_rn(a, cutlass.Float32(0.0))), gs) + hv = _sel_f32(is_up, hv, cutlass.Float32(0.0)) + # |h c| = |h| c (c >= 0); gate lanes 0 + amax = _redux_max_abs_f32(_mul_rn(hv, c)) + sfb = _e4m3_bits(_mul_rn(amax, cutlass.Float32(RCP6))) + sff = _e4m3_to_f32(sfb) + osc = _sel_f32( + sfb, _rcp(sff), cutlass.Float32(0.0) + ) # sfb != 0 <=> scale != 0 + qv = _mul_rn(_mul_rn(hv, osc), c) + byte = _e2m1x2(cute.arch.shuffle_sync_down(qv, 16), qv) + # lane j < 8 holds code byte j of the row's 8 (columns 16 wq + 2 j, + 1) + if lane < 8: + if nrow < rows: + r = r0 + nrow + _st_global_u8( + h_addr + + Int64(r) * Int64(self.inter // 2) + + Int64(mt * 32 + wq * 8 + lane), + byte, + ) + if lane == 0: + saddr = ( + hsf_addr + + (Int64(r >> 3) * Int64(self.groups) + Int64(mt)) * 32 + + Int64(r & 7) * 4 + + Int64(wq) + ) + _st_global_u8(saddr, sfb) + cute.arch.fence_view_async_tmem_load() + cute.arch.mbarrier_arrive(acc_empty + buf) + self.free_unit(bar_id, epi_tid, q_full, slot, cnt_base, seg, True) + else: + s = s_a2[ex] + col = Int64(mt * TILE_M + hcol) + op = _policy_evict_last() + for ch in cutlass.range(nch, unroll=1): + self.load_acc( + tmem_ptr, tCtAcc_fake, tiled_copy_t2r, thr_copy_t2r, rAcc, buf, ch + ) + for t in cutlass.range_constexpr(8): + partner = cute.arch.shuffle_sync_down(rAcc[t], 8) + nrow = ch * 8 + t + if lead: + if nrow < rows: + r = r0 + nrow + _st_global_b32_hint( + out_addr + (Int64(r) * Int64(self.hidden) + col) * 2, + _scale_pack_bf16x2(rAcc[t], partner, s), + op, + ) + cute.arch.fence_view_async_tmem_load() + cute.arch.mbarrier_arrive(acc_empty + buf) + self.free_unit(bar_id, epi_tid, q_full, slot, cnt_base, seg, False) + k = k + EPI_GROUPS + g, slot = self.unit(s_q, q_full, k) + + +# ---------------------------------------------------------------------------------------------------------------- +def moe_nvfp4_engine( + xq: torch.Tensor, + xsf: torch.Tensor, + p2t: torch.Tensor, + cta_batch: torch.Tensor, + cta_limit: torch.Tensor, + num_ctas: torch.Tensor, + w31: torch.Tensor, + w31_sf: torch.Tensor, + w2: torch.Tensor, + w2_sf: torch.Tensor, + scale_c: torch.Tensor, + alpha1: torch.Tensor, + alpha2: torch.Tensor, + h: torch.Tensor, + hsf: torch.Tensor, + out: torch.Tensor, + state: torch.Tensor, + *, + tile: int, + n_max: int, + tile_k: int, + release_after_wait: bool = False, + spare_sms: int = 0, + candidates: Optional[torch.Tensor] = None, + topk_ids: Optional[torch.Tensor] = None, + topk_weights: Optional[torch.Tensor] = None, + e2p: Optional[torch.Tensor] = None, + num_padded: Optional[torch.Tensor] = None, + local_start: int = 0, +) -> torch.Tensor: + """Run the engine. ``xq`` [m, H/2] u8, ``xsf`` [m, H/16] u8 (linear), tables int32 for token tile ``tile``, + ``w31`` [E, 2I, H/2] u8, ``w31_sf`` [E, 2I, H/16] u8 (128x4), ``w2`` [E, H, I/2] u8, ``w2_sf`` [E, H, I/16] u8, + ``scale_c`` / ``alpha1`` / ``alpha2`` [E] fp32 (output1_scale_scalar, output1_scale_gate_scalar, + output2_scale_scalar), ``h`` [rows, I/2] u8 and ``hsf`` [rows * I/16] u8 (scratch), ``out`` [rows, H] bf16, + ``state`` from :func:`new_state`. Rows above n_max per expert split into segments. One CTA per SM but + ``spare_sms``. + + ``candidates`` [m, lists, top_k] int32 (m <= ROUTE_MAX_ROWS, ``moe_router_gemm``'s ``route_top_k`` epilogue over + lists x 128 experts): the engine routes the call for the local experts from ``local_start`` and writes + ``topk_ids`` [m, top_k] int32, ``topk_weights`` [m, top_k] bf16, ``e2p`` [m * top_k], ``p2t``, the tile tables + and ``num_ctas`` / ``num_padded`` (``prerouted_table_views`` of one buffer) before it reads them.""" + e, two_i, half_h = w31.shape + hidden, inter = 2 * half_h, two_i // 2 + assert e <= MAX_LOCAL_EXPERTS, "per-expert scalars are staged for <= 128 local experts" + per_stage = (128 + n_max) * tile_k // 2 + 2 * 128 * tile_k // SF_VEC + num_stages = min(10, ring_smem_bytes(xq.device) // per_stage) + args = ( + gmem_ptr(w31, cutlass.Float4E2M1FN, 32), + gmem_ptr(w31_sf, cutlass.Float8E4M3FN, 16), + gmem_ptr(w2, cutlass.Float4E2M1FN, 32), + gmem_ptr(w2_sf, cutlass.Float8E4M3FN, 16), + gmem_ptr(w2, cutlass.Float4E2M1FN, 32), + Int64(xq.data_ptr()), + Int64(xsf.data_ptr()), + Int64(p2t.data_ptr()), + Int64(cta_batch.data_ptr()), + Int64(cta_limit.data_ptr()), + Int64(num_ctas.data_ptr()), + Int32(cta_batch.numel()), + Int64(scale_c.data_ptr()), + Int64(alpha1.data_ptr()), + Int64(alpha2.data_ptr()), + Int64(h.data_ptr()), + Int64(hsf.data_ptr()), + Int64(out.data_ptr()), + Int64(state.data_ptr()), + Int32(e), + ) + route_lists, route_top_k = 0, 0 + route_args = () + if candidates is not None: + m = xq.shape[0] + assert candidates.dim() == 3 and candidates.shape[0] == m <= ROUTE_MAX_ROWS + _, route_lists, route_top_k = candidates.shape + assert route_error(route_top_k, route_lists) is None, route_error(route_top_k, route_lists) + assert candidates.dtype == torch.int32 and candidates.is_contiguous() + assert topk_ids.shape == (m, route_top_k) and topk_ids.dtype == torch.int32 + assert topk_weights.shape == (m, route_top_k) and topk_weights.dtype == torch.bfloat16 + assert topk_ids.is_contiguous() and topk_weights.is_contiguous() + assert e2p.numel() == m * route_top_k and num_padded.numel() == 1 + assert p2t.numel() == (cta_batch.numel() + 1) * tile + sms = torch.cuda.get_device_properties(xq.device).multi_processor_count + p2t_copies = torch.empty((sms, p2t.numel()), dtype=torch.int32, device=xq.device) + route_args = ( + Int64(candidates.data_ptr()), + Int64(topk_ids.data_ptr()), + Int64(topk_weights.data_ptr()), + Int64(e2p.data_ptr()), + Int64(num_padded.data_ptr()), + Int64(p2t_copies.data_ptr()), + Int32(m), + Int32(local_start), + ) + config = ( + hidden, + inter, + n_max, + num_stages, + tile, + tile_k, + release_after_wait, + route_top_k, + route_lists, + ) + launch( + lambda: MoeNvfp4Engine(*config), + (MoeNvfp4Engine, e, *config), + args, + xq.device, + spare_sms, + tail_args=route_args, + ) + return out diff --git a/tensorrt_llm/_torch/kernels/blackwell/moe_persistent_engine.py b/tensorrt_llm/_torch/kernels/blackwell/moe_persistent_engine.py new file mode 100644 index 000000000000..3c64612bbd37 --- /dev/null +++ b/tensorrt_llm/_torch/kernels/blackwell/moe_persistent_engine.py @@ -0,0 +1,337 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""The persistent unit scheduler of the decode MoE engines (``moe_nvfp4_engine``, ``moe_bf16_engine``); the PTX +helpers they share are in ``ptx_helpers``. + +An engine runs one call's routed experts FC1 -> activation -> FC2 in one persistent launch. A unit is one 128-row +weight tile of a segment (at most ``n_max`` rows of one expert): 2I / 128 FC1 and H / 128 FC2 units per segment share +one TMA ring. Each CTA takes its FC1 units round-robin, then claims FC2 units as tickets from a pool, each usable once +its segment's FC1 counter is complete. One scheduler thread per CTA queues the units (``QD`` slots); the weight +loader, activation loader, MMA warp and the two epilogue groups (alternate units) read the queue in order. + +Call state (``new_state``, int32): gen (the call's parity), done, the FC2 ticket pools [2] and the segment counters +[2][CNT_CAP], double-buffered by parity: every call zeroes the other parity's pool and counters, and its last CTA +advances gen. Calls on one state must be stream-ordered. +""" + +from __future__ import annotations + +import enum +from typing import Callable + +import cuda.bindings.driver as cuda +import cutlass +import cutlass.cute as cute +import torch +from cutlass import Int32, Int64 +from cutlass.cute.nvgpu import tcgen05 + +from .ptx_helpers import ( + _atom_add_acq_rel, + _atom_add_relaxed, + _bar_sync, + _ld_acquire_u32, + _ld_relaxed_u32, + _red_release_add, + _st_relaxed_u32, +) + +TILE_M = 128 +NUM_ACC = 2 # TMEM accumulator buffers (unit k uses buffer k % NUM_ACC) +EPI_GROUPS = 2 # groups of four epilogue warps taking alternate units +EPI_WARP0 = 4 +THREADS = 128 + 128 * EPI_GROUPS +CNT_CAP = 512 # segment counters per parity +QD = 8 # unit queue slots +QL = 2 # claimed entries the scheduler may hold ahead of the weight loader +EPI_BAR = 1 # named barrier of epilogue group 0 (group g: EPI_BAR + g) +LOG2E = 1.4426950216293334961 +# int32 words of the call state: gen, done, ticket pools [2], then the counters at byte 64 +_CNT_OFFSET = 64 +# Upper bound of an engine's shared memory outside its operand ring (tables, barriers, routing scratch, alignment) +NON_RING_SMEM = 27 * 1024 + + +# ---------------------------------------------------------------------------------------------------------------- +class Release(enum.Enum): + """Where an engine releases its PDL dependents (a dependent that waits still waits for the grid's completion).""" + + AFTER_WAIT = 0 # right after the engine's own dependency wait + POOL_SPENT = 1 # once a CTA's scheduler claimed the last FC2 ticket + END = 2 # as each CTA exits + + +class PersistentMoeEngine: + """The scheduling half of a decode MoE engine; a subclass adds its MMA, loaders, prologue and epilogue math. + + ``fc2_wait_in_scheduler``: the scheduler acquires an FC2 unit's segment counter before queueing it (the loaders' + reads are then ordered through the queue's mbarriers); otherwise the activation loader acquires it per lane + (``wait_fc1_done``) and the weight loader may stream the unit's weights before FC1 is complete.""" + + fc2_wait_in_scheduler: bool = True + release: Release = Release.END + # Launched as a programmatic dependent (TRTLLM_ENABLE_PDL); set by launch() before compiling. + use_pdl: bool = True + + def __init__(self, hidden: int, inter: int, n_max: int, num_stages: int, tile_k: int) -> None: + assert hidden % tile_k == 0 and inter % tile_k == 0 + assert (2 * inter) % TILE_M == 0 and hidden % TILE_M == 0 + self.hidden, self.inter = hidden, inter + self.n_max, self.num_stages, self.tile_k = n_max, num_stages, tile_k + self.k1_tiles, self.k2_tiles = hidden // tile_k, inter // tile_k + self.m1_tiles, self.m2_tiles = (2 * inter) // TILE_M, hidden // TILE_M + self.cta_group = tcgen05.CtaGroup.ONE + self.acc_dtype = cutlass.Float32 + + # ------------------------------------------------------------------------------------------------------------ + @cute.jit + def init_barriers(self, warp_idx, tmem_bar, q_full): + """The TMEM-address barrier (MMA warp + every epilogue thread) and the queue's full / empty / taken + barriers [3 QD].""" + if warp_idx == 0: + with cute.arch.elect_one(): + cute.arch.mbarrier_init(tmem_bar, 32 + 128 * EPI_GROUPS) + for i in cutlass.range_constexpr(QD): + cute.arch.mbarrier_init(q_full + i, 1) + cute.arch.mbarrier_init(q_full + QD + i, 1) + cute.arch.mbarrier_init(q_full + 2 * QD + i, 1) + cute.arch.mbarrier_init_fence() + + @cute.jit + def wait_dependency(self, state_addr, release_bar=None): + """The grid dependency wait (and the release, if ``AFTER_WAIT`` without ``release_bar``); returns gen. Read + after the wait: a PDL launch of the next call can start before this one's last CTA advanced gen, and every CTA + must see the same parity.""" + cute.arch.griddepcontrol_wait() + if cutlass.const_expr(self.release == Release.AFTER_WAIT and release_bar is None): + cute.arch.griddepcontrol_launch_dependents() + return _ld_relaxed_u32(state_addr) + + @cute.jit + def begin_call(self, state_addr, gen, nseg, bidx, tidx, gdx): + """Zero the other parity's counters and ticket pool for the next call (no CTA of this call touches them); + returns (this call's counters, its ticket pool, FC1 units, FC2 units, this CTA's FC1 units).""" + par = gen & Int32(1) + cnt_base = state_addr + Int64(_CNT_OFFSET) + Int64(par) * Int64(CNT_CAP * 4) + nxt_base = state_addr + Int64(_CNT_OFFSET) + Int64(1 - par) * Int64(CNT_CAP * 4) + for i in cutlass.range(bidx * THREADS + tidx, CNT_CAP, gdx * THREADS, unroll=1): + _st_relaxed_u32(nxt_base + Int64(i) * 4, Int32(0)) + pool_addr = state_addr + Int64(8) + Int64(par) * 4 + if bidx == 0: + if tidx == 0: + _st_relaxed_u32(state_addr + Int64(8) + Int64(1 - par) * 4, Int32(0)) + # FC1 unit u = bidx + j G (segment u / M1, tile u % M1), static; FC2 units as tickets, dynamic + u1 = nseg * self.m1_tiles + u2 = nseg * self.m2_tiles + n1 = Int32(0) + if bidx < u1: + n1 = (u1 - 1 - bidx) // gdx + 1 + return cnt_base, pool_addr, u1, u2, n1 + + @cute.jit + def end_call(self, warp_idx, tidx, gdx, tmem_base_smem_ptr, state_addr, gen): + """After every role returned: free TMEM, count this CTA done (the last one advances gen) and release the + dependents.""" + cute.arch.barrier() + if warp_idx == 2: + tmem_ptr = cute.arch.retrieve_tmem_ptr(self.acc_dtype, 16, tmem_base_smem_ptr) + cute.arch.dealloc_tmem(tmem_ptr, self.num_tmem_cols) + if tidx == 0: + old = _atom_add_acq_rel(state_addr + Int64(4), Int32(1)) + if old == gdx - 1: + _st_relaxed_u32(state_addr + Int64(4), Int32(0)) + _st_relaxed_u32(state_addr, gen + Int32(1)) + cute.arch.griddepcontrol_launch_dependents() + + # ------------------------------------------------------------------------------------------------------------ + @cute.jit + def decode(self, g, u1): + """(is_fc1, segment, weight tile) of global unit g: FC1 units are 0..u1-1, FC2 units u1 + ticket + (segment-major).""" + is1 = Int32(0) + seg = Int32(0) + mt = Int32(0) + if g < u1: + is1 = Int32(1) + seg = g // self.m1_tiles + mt = g % self.m1_tiles + else: + seg = (g - u1) // self.m2_tiles + mt = (g - u1) % self.m2_tiles + return is1, seg, mt + + @cute.jit + def _push(self, s_q, q_full, k, g): + """Entry k of the unit queue (one thread): at most QL entries untaken by the weight loader; a slot is reused + once the epilogue freed it.""" + slot = k % QD + if k >= QL: + kk = k - QL + cute.arch.mbarrier_wait(q_full + 2 * QD + (kk % QD), (kk // QD) & 1) + if k >= QD: + cute.arch.mbarrier_wait(q_full + QD + slot, ((k // QD) - 1) & 1) + s_q[slot] = g + cute.arch.mbarrier_arrive(q_full + slot) + + @cute.jit + def wait_fc1_done(self, cnt_base, seg): + """Acquire segment seg's FC1 counter once all its FC1 units released it.""" + ready = Int32(0) + while ready == 0: + if _ld_acquire_u32(cnt_base + Int64(seg) * 4) >= self.m1_tiles: + ready = Int32(1) + + @cute.jit + def scheduler( + self, s_q, q_full, n1, u1, u2, bidx, gdx, pool_addr, cnt_base, lane, release_bar=None + ): + """Warp 3, lane 0: this CTA's FC1 units, then FC2 tickets (claimed one ahead), then the end marker. + ``release_bar``: an mbarrier that completes once this CTA's outputs read by the dependents without their + dependency wait are written; the dependents are released only after it (also for ``AFTER_WAIT``).""" + if lane == 0: + k = Int32(0) + for j in cutlass.range(n1, unroll=1): + self._push(s_q, q_full, k, bidx + j * gdx) + k = k + 1 + if cutlass.const_expr(release_bar is not None and self.release == Release.AFTER_WAIT): + cute.arch.mbarrier_wait(release_bar, 0) + cute.arch.griddepcontrol_launch_dependents() + t = u2 + if u2 > 0: + t = _atom_add_relaxed(pool_addr, Int32(1)) + while t < u2: + tn = _atom_add_relaxed(pool_addr, Int32(1)) + if cutlass.const_expr(self.release == Release.POOL_SPENT): + if tn >= u2: + # the pool is spent and t is this CTA's last ticket: one thread's trigger counts for the CTA + if cutlass.const_expr(release_bar is not None): + cute.arch.mbarrier_wait(release_bar, 0) + cute.arch.griddepcontrol_launch_dependents() + if cutlass.const_expr(self.fc2_wait_in_scheduler): + self.wait_fc1_done(cnt_base, t // self.m2_tiles) + self._push(s_q, q_full, k, u1 + t) + k = k + 1 + t = tn + self._push(s_q, q_full, k, Int32(-1)) + # the group that does not own entry k reads entry k + 1 (the other roles stop at k) + self._push(s_q, q_full, k + 1, Int32(-1)) + + @cute.jit + def first_unit(self, s_q, q_full, u1, bidx): + """A loader's first unit: the static first FC1 unit without waiting for the queue (the scheduler queues the + same entry), else entry 0.""" + g = Int32(-1) + if bidx < u1: + g = bidx + else: + cute.arch.mbarrier_wait(q_full, 0) + g = s_q[0] + return g + + @cute.jit + def unit(self, s_q, q_full, k): + """(queue entry k, its slot), once it is queued.""" + slot = k % QD + cute.arch.mbarrier_wait(q_full + slot, (k // QD) & 1) + return s_q[slot], slot + + @cute.jit + def take(self, q_full, slot): + """The weight loader took the entry in ``slot`` (one arrival per entry).""" + with cute.arch.elect_one(): + cute.arch.mbarrier_arrive(q_full + 2 * QD + slot) + + @cute.jit + def free_unit(self, bar_id, epi_tid, q_full, slot, cnt_base, seg, fc1: cutlass.Constexpr): + """An epilogue group finished the entry in ``slot`` (every thread of the group stored its rows and read the + entry); an FC1 unit also releases its segment's counter.""" + _bar_sync(bar_id, 128) + if epi_tid == 0: + if cutlass.const_expr(fc1): + _red_release_add(cnt_base + Int64(seg) * 4, Int32(1)) + cute.arch.mbarrier_arrive(q_full + QD + slot) + + # ------------------------------------------------------------------------------------------------------------ + @cute.jit + def epilogue_tmem(self, tiled_mma, tmem_bar, tmem_base_smem_ptr, epi_tid): + """An epilogue thread's TMEM accumulator view: (tmem_ptr, accumulator layout, TMEM -> register copy, its + slice, the register fragment of one 8-column chunk, this thread's accumulator row).""" + thr_mma = tiled_mma.get_slice(0) + acc_shape = tiled_mma.partition_shape_C((TILE_M, self.n_max)) + tCtAcc_fake = tiled_mma.make_fragment_C(acc_shape) + tCcL = thr_mma.partition_C(cute.make_identity_tensor((TILE_M, self.n_max))) + cute.arch.mbarrier_arrive(tmem_bar) + cute.arch.mbarrier_wait(tmem_bar, 0) + tmem_ptr = cute.arch.retrieve_tmem_ptr(self.acc_dtype, 16, tmem_base_smem_ptr) + copy_atom_t2r = cute.make_copy_atom( + tcgen05.Ld32x32bOp(tcgen05.Repetition(8), tcgen05.Pack.NONE), self.acc_dtype + ) + tAcc0 = cute.flat_divide( + cute.make_tensor(tmem_ptr, tCtAcc_fake.layout)[((None, None), 0, 0)], (TILE_M, 8) + ) + tiled_copy_t2r = tcgen05.make_tmem_copy(copy_atom_t2r, tAcc0[(None, None, 0, 0)]) + thr_copy_t2r = tiled_copy_t2r.get_slice(epi_tid) + tTR_cL = thr_copy_t2r.partition_D(cute.flat_divide(tCcL[((None, None), 0, 0)], (TILE_M, 8))) + rAcc = cute.make_rmem_tensor(tTR_cL[(None, None, None, 0, 0)].shape, self.acc_dtype) + row0, _c0 = tTR_cL[(None, None, None, 0, 0)][0] + return tmem_ptr, tCtAcc_fake, tiled_copy_t2r, thr_copy_t2r, rAcc, row0 + + @cute.jit + def load_acc(self, tmem_ptr, tCtAcc_fake, tiled_copy_t2r, thr_copy_t2r, rAcc, buf, ch): + """Rows 8 ch .. 8 ch + 7 of accumulator buffer buf into rAcc (tcgen05.wait::ld included).""" + tAcc = cute.flat_divide( + cute.make_tensor(tmem_ptr + buf * self.n_max, tCtAcc_fake.layout)[((None, None), 0, 0)], + (TILE_M, 8), + ) + cute.copy(tiled_copy_t2r, thr_copy_t2r.partition_S(tAcc)[(None, None, None, 0, ch)], rAcc) + cute.arch.fence_view_async_tmem_load() + + +# ---------------------------------------------------------------------------------------------------------------- +def ring_smem_bytes(device: torch.device) -> int: + """Shared memory an engine's operand ring may take on ``device``: a block's opt-in maximum but NON_RING_SMEM.""" + from ...cute_dsl_utils import smem_optin_bytes + + return smem_optin_bytes(device) - NON_RING_SMEM + + +def new_state(device: torch.device) -> torch.Tensor: + """An engine's call state, zero-initialized; it must exist before CUDA-graph capture.""" + return torch.zeros(_CNT_OFFSET // 4 + 2 * CNT_CAP, dtype=torch.int32, device=device) + + +def launch( + make_engine: Callable[[], object], + key: tuple, + args: tuple, + device: torch.device, + spare_sms: int = 0, + tail_args: tuple = (), +) -> None: + """Compile ``make_engine()`` once per ``key`` (the engine class and its compile-time configuration) and the PDL + setting, and launch it with ``args`` on the current stream, one CTA per SM of ``device`` but ``spare_sms`` and the + SMs ``cute_dsl_utils.sm_reserve()`` keeps out of every persistent grid (the grid size is a launch argument; the + units balance over any grid). ``tail_args`` follow the stream (an engine option's parameters). The first call of a + key must precede CUDA graph capture.""" + from ...cute_dsl_utils import sm_reserve + from ...flashinfer_utils import get_env_enable_pdl + + use_pdl = get_env_enable_pdl() + key = (*key, use_pdl) + grid_ctas = Int32( + torch.cuda.get_device_properties(device).multi_processor_count - spare_sms - sm_reserve() + ) + stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream) + fn = _COMPILED.get(key) + if fn is None: + if torch.cuda.is_current_stream_capturing(): + raise RuntimeError( + f"compile the MoE engine {key[0].__name__} before CUDA graph capture" + ) + engine = make_engine() + engine.use_pdl = use_pdl + fn = _COMPILED[key] = cute.compile(engine, *args, grid_ctas, stream, *tail_args) + fn(*args, grid_ctas, stream, *tail_args) + + +_COMPILED = {} diff --git a/tensorrt_llm/_torch/kernels/blackwell/moe_route_front.py b/tensorrt_llm/_torch/kernels/blackwell/moe_route_front.py index 17483b4d3437..dc7e16861b91 100644 --- a/tensorrt_llm/_torch/kernels/blackwell/moe_route_front.py +++ b/tensorrt_llm/_torch/kernels/blackwell/moe_route_front.py @@ -1,15 +1,22 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""MoE decode route front above 32 tokens (512 experts, top-10). - -After the stock router GEMM, routing + trtllm-gen pre-routed tables + NVFP4 quantization of the MoE input run in -one launch of thread-block clusters. :mod:`moe_decode_front` covers M <= 32 with a single routing CTA. Outputs are +"""MoE decode route front (512 experts, top-10) for DecodeFront's steps above the one-launch front +(``decode_front.route_front_steps``: from ``ROUTER_MAX_TOKENS + 1`` rows, or from ``FUSED_FRONT_MAX_TOKENS + 1`` +where the model declares the TP decode kernels). + +After the router GEMM (the stock one; with the decode kernels, the CuTe router GEMM for ``ROUTER_MAX_TOKENS + 1`` to +``ROUTER_GEMM_MAX_TOKENS`` rows; constants of ``decode_front``), routing + +trtllm-gen pre-routed tables + NVFP4 quantization of the MoE input run in one launch of thread-block clusters. +:mod:`moe_decode_front` covers the smaller steps with a single routing CTA. Outputs are bitwise: ids / BF16 weights as :mod:`moe_decode_front`, xq / xsf as ``fp4_quantize`` (linear scale layout), tables -(``prerouted_table_sizes`` order) as the Triton route kernel's up to the row order inside an expert's block. +(``prerouted_table_sizes`` order) as the Triton route kernel's up to the row order inside an expert's block. ``lean`` +builds the same tables with a cheaper count exchange and releases its dependent (FC1) at kernel start. """ from __future__ import annotations +from typing import Optional, Union + import cutlass import cutlass.cute as cute from cutlass import Float32, Int32, Int64, const_expr @@ -100,6 +107,34 @@ def _cluster_wait_acquire(*, loc=None, ip=None) -> None: _asm(None, [], "barrier.cluster.wait.acquire.aligned;", "~{memory}", loc=loc, ip=ip) +@dsl_user_op +def _bulk_push( + dst: Int32, mbar: Int32, src: Int32, rank: Int32, nbytes: Int32, *, loc=None, ip=None +) -> None: + """cp.async.bulk of ``nbytes`` from this CTA's shared memory ``src`` to ``dst`` in cluster CTA ``rank``, + completing transaction bytes on that CTA's mbarrier ``mbar`` (dst / mbar are this CTA's offsets, mapped).""" + _asm( + None, + [ + _i32(dst, loc, ip), + _i32(mbar, loc, ip), + _i32(src, loc, ip), + _i32(rank, loc, ip), + _i32(nbytes, loc, ip), + ], + "{\n\t.reg .b32 rd, rb;\n\tmapa.shared::cluster.u32 rd, $0, $3;\n\tmapa.shared::cluster.u32 rb, $1, $3;\n\t" + "cp.async.bulk.shared::cluster.shared::cta.mbarrier::complete_tx::bytes [rd], [$2], $4, [rb];\n\t}", + "r,r,r,r,r,~{memory}", + loc=loc, + ip=ip, + ) + + +@dsl_user_op +def _bulk_commit(*, loc=None, ip=None) -> None: + _asm(None, [], "cp.async.bulk.commit_group;", "~{memory}", loc=loc, ip=ip) + + @dsl_user_op def _ld_dsmem_b32(addr: Int32, rank: Int32, *, loc=None, ip=None) -> Int32: """The word at shared-memory address ``addr`` of cluster CTA ``rank``.""" @@ -191,6 +226,52 @@ def _top4of8(a, b): return (v0, v1, v2, v3) +def _shape_error( + *, + num_rows: int, + k_extent: int, + num_experts: int, + top_k: int, + num_local: int, + tile: int, + a_stride: int, + quant_clusters: int = 7, + threads: int = ROUTE_THREADS, + cluster: int = ROUTE_CLUSTER, + lean: bool = False, +) -> Optional[str]: + """Why :class:`MoeRouteFrontKernel` does not take these arguments, or None.""" + if threads % 32 or not 256 <= threads <= 1024: + return f"threads={threads} must be a multiple of 32 in [256, 1024]" + if cluster not in (ROUTE_CLUSTER, ROUTE_CLUSTER_WIDE): + return f"cluster={cluster} must be {ROUTE_CLUSTER} or {ROUTE_CLUSTER_WIDE}" + max_tpc = 64 if cluster == ROUTE_CLUSTER_WIDE else 32 # token-mask words per expert: 2 / 1 + if not 1 <= num_rows <= cluster * max_tpc: + return f"num_rows={num_rows} must be in [1, {cluster * max_tpc}] with clusters of {cluster}" + if top_k != 10: + return "the renormalization tree is the route kernel's top-10 tree" + if num_experts != 32 * 16: + return "one warp per token holds 16 logits per lane: 512 experts" + if num_local % 32 or not 32 <= num_local <= min(num_experts, threads): + return f"num_local={num_local} must be a multiple of 32 in [32, {threads}]" + if tile & (tile - 1) or not 8 <= tile <= 256: + return f"tile={tile} must be a power of two in [8, 256]" + if k_extent % 16 or a_stride % 8 or a_stride < k_extent: + return "x rows must be 16-byte aligned blocks of 16" + if quant_clusters < 1: + return "at least one quantization cluster" + tpc = -(-num_rows // cluster) + mw = -(-tpc // 32) + if num_local * mw > threads: + return "one thread per token-mask word: num_local * ceil(TPC / 32) <= threads" + tpw = -(-tpc // (threads // 32)) + if tpw > 2: + return "at most two tokens per warp" + if lean and (cluster != ROUTE_CLUSTER or mw != 1 or tpw != 1): + return "the lean table build takes clusters of 8 with one token per warp (<= 256 rows)" + return None + + class MoeRouteFrontKernel: """Route-only big front: router logits [M, E] BF16 from the stock GEMM -> top-k ids / BF16 weights, the trtllm-gen pre-routed tables (``prerouted_table_sizes`` order, token order inside an expert's block) and the @@ -207,7 +288,20 @@ class MoeRouteFrontKernel: No CTA waits for another cluster, so nothing needs the clusters co-resident. PDL: everything after ``griddepcontrol.wait``; every CTA releases its dependents after a barrier that follows its last global - access.""" + access. + + ``lean`` (clusters of 8, one token per warp): before the dependency wait one thread arms a receive mbarrier for + the cluster's count vectors; after routing each CTA bulk-copies its counts into every peer's receive buffer + (instead of the cluster barrier + 8 remote loads) and sums the 8 vectors in slot order, the same integer sums. + It releases its dependent (FC1) at kernel start: FC1's grid is resident while this kernel runs, and its + ``griddepcontrol.wait`` still waits for this grid's completion.""" + + @staticmethod + def supports(**kw: Union[int, bool]) -> bool: + """Whether the constructor takes these keyword arguments (``use_pdl`` aside): ``__init__``'s integer shape + arguments and its ``lean`` / ``use_pdl`` flags.""" + kw.pop("use_pdl", None) + return _shape_error(**kw) is None def __init__( self, @@ -223,28 +317,23 @@ def __init__( quant_clusters: int = 7, threads: int = ROUTE_THREADS, cluster: int = ROUTE_CLUSTER, + lean: bool = False, ) -> None: - if threads % 32 or not 256 <= threads <= 1024: - raise ValueError(f"threads={threads} must be a multiple of 32 in [256, 1024]") - if cluster not in (ROUTE_CLUSTER, ROUTE_CLUSTER_WIDE): - raise ValueError(f"cluster={cluster} must be {ROUTE_CLUSTER} or {ROUTE_CLUSTER_WIDE}") - max_tpc = 64 if cluster == ROUTE_CLUSTER_WIDE else 32 # token-mask words per expert: 2 / 1 - if not 1 <= num_rows <= cluster * max_tpc: - raise ValueError( - f"num_rows={num_rows} must be in [1, {cluster * max_tpc}] with clusters of {cluster}" - ) - if top_k != 10: - raise ValueError("the renormalization tree is the route kernel's top-10 tree") - if num_experts != 32 * 16: - raise ValueError("one warp per token holds 16 logits per lane: 512 experts") - if num_local % 32 or not 32 <= num_local <= min(num_experts, threads): - raise ValueError(f"num_local={num_local} must be a multiple of 32 in [32, {threads}]") - if tile & (tile - 1) or not 8 <= tile <= 256: - raise ValueError(f"tile={tile} must be a power of two in [8, 256]") - if k_extent % 16 or a_stride % 8 or a_stride < k_extent: - raise ValueError("x rows must be 16-byte aligned blocks of 16") - if quant_clusters < 1: - raise ValueError("at least one quantization cluster") + err = _shape_error( + num_rows=num_rows, + k_extent=k_extent, + num_experts=num_experts, + top_k=top_k, + num_local=num_local, + tile=tile, + a_stride=a_stride, + quant_clusters=quant_clusters, + threads=threads, + cluster=cluster, + lean=lean, + ) + if err is not None: + raise ValueError(err) self.num_rows = num_rows self.k_extent = k_extent self.num_experts = num_experts @@ -257,14 +346,8 @@ def __init__( self.cluster = cluster self.tpc = -(-num_rows // cluster) self.mw = -(-self.tpc // 32) # token-mask words per expert (TPC > 32: two) - if num_local * self.mw > threads: - raise ValueError( - "one thread per token-mask word: num_local * ceil(TPC / 32) <= threads" - ) self.warps = threads // 32 self.tpw = -(-self.tpc // self.warps) - if self.tpw > 2: - raise ValueError("at most two tokens per warp") self.quant_clusters = quant_clusters self.ctas = cluster * (1 + quant_clusters) self.q_ctas = cluster * quant_clusters @@ -289,6 +372,13 @@ def __init__( self.o_wsum = (mw + 4) * nl self.o_pick = (mw + 4) * nl + 32 self.smem_words = self.o_pick + self.tpc * top_k + 16 + self.lean = lean + if lean: + # receive buffer: cluster x num_local count words (16-byte aligned), then the mbarrier (8-byte aligned) + self.o_rbuf = -(-self.smem_words // 4) * 4 + self.o_mbar = self.o_rbuf + self.cluster * self.num_local + self.smem_words = self.o_mbar + 4 + self.cnt_bytes = self.num_local * 4 @cute.jit def __call__( @@ -339,13 +429,41 @@ def kernel( ) -> None: tidx, _, _ = cute.arch.thread_idx() bidx, _, _ = cute.arch.block_idx() - smem = _SmemAllocator() - buf = smem.allocate_tensor(Int32, cute.make_layout((self.smem_words,)), byte_alignment=16) - base = _smem_addr(buf.iterator) - if bidx < self.cluster: - self._route_cta(logits_ptr, ids_ptr, wts_ptr, tab_ptr, local_start, base, bidx, tidx) + if const_expr(self.lean): + if const_expr(self.use_pdl): + _gdc_launch() + smem = _SmemAllocator() + # the word buffer (everything up to o_mbar), then the mbarrier in its own 8-byte allocation; smem_words + # counts 4 words for it, so the launch's shared-memory size covers both + buf = smem.allocate_tensor(Int32, cute.make_layout((self.o_mbar,)), byte_alignment=16) + mbar = smem.allocate_tensor(Int64, cute.make_layout((1,)), byte_alignment=8) + base = _smem_addr(buf.iterator) + if bidx < self.cluster: + self._route_cta_lean( + logits_ptr, + ids_ptr, + wts_ptr, + tab_ptr, + local_start, + mbar.iterator, + base, + bidx, + tidx, + ) + else: + self._quant_cta(x_ptr, gs_ptr, xq_ptr, xsf_ptr, bidx - self.cluster, tidx) else: - self._quant_cta(x_ptr, gs_ptr, xq_ptr, xsf_ptr, bidx - self.cluster, tidx) + smem = _SmemAllocator() + buf = smem.allocate_tensor( + Int32, cute.make_layout((self.smem_words,)), byte_alignment=16 + ) + base = _smem_addr(buf.iterator) + if bidx < self.cluster: + self._route_cta( + logits_ptr, ids_ptr, wts_ptr, tab_ptr, local_start, base, bidx, tidx + ) + else: + self._quant_cta(x_ptr, gs_ptr, xq_ptr, xsf_ptr, bidx - self.cluster, tidx) @cute.jit def _quant_cta( @@ -527,6 +645,148 @@ def _route_cta( if const_expr(self.use_pdl): _gdc_launch() + @cute.jit + def _route_cta_lean( + self, + logits_ptr: Int64, + ids_ptr: Int64, + wts_ptr: Int64, + tab_ptr: Int64, + local_start: Int32, + mbar_ptr: cute.Pointer, + base: Int32, + c, + tidx, + ) -> None: + num_local: cutlass.Constexpr = self.num_local + top_k: cutlass.Constexpr = self.top_k + tile: cutlass.Constexpr = self.tile + tpc: cutlass.Constexpr = self.tpc + cluster: cutlass.Constexpr = self.cluster + cnt_bytes: cutlass.Constexpr = self.cnt_bytes + warp = tidx // 32 + lane = tidx % 32 + smask = base + Int32(self.o_mask * 4) + scnt = base + Int32(self.o_cnt * 4) + spre = base + Int32(self.o_pre * 4) + stot = base + Int32(self.o_tot * 4) + soffs = base + Int32(self.o_offs * 4) + swsum = base + Int32(self.o_wsum * 4) + spick = base + Int32(self.o_pick * 4) + srbuf = base + Int32(self.o_rbuf * 4) + smbar = _smem_addr(mbar_ptr) + if tidx < num_local: + _st_shared(smask + tidx * 4, Int32(0)) + # The receive mbarrier, before the dependency wait: off the critical path while the router GEMM runs. + if warp == 0: + with cute.arch.elect_one(): + cute.arch.mbarrier_init(mbar_ptr, 1) + cute.arch.mbarrier_arrive_and_expect_tx(mbar_ptr, cluster * cnt_bytes) + cute.arch.mbarrier_init_fence() + _cluster_arrive_release() # peers copy into this CTA only after the matching wait below + # this CTA's tokens [c TPC, c TPC + n_tok) + t_first = c * tpc + n_tok = cutlass.min(Int32(tpc), Int32(self.num_rows) - t_first) + if const_expr(self.use_pdl): + _gdc_wait() + cute.arch.sync_threads() + my_sel = Int32(0) + my_w = Int32(0) + if warp < n_tok: + my_sel, my_w = self._route_warp_fast( + logits_ptr, local_start, smask, spick, t_first, warp, lane + ) + cute.arch.sync_threads() + if tidx < num_local: + _st_shared(scnt + tidx * 4, _popc(_ld_shared(smask + tidx * 4))) + # Every peer's mbarrier is initialized (they all arrived at their start); the counts are written by generic + # stores and read by the bulk-copy (async) proxy. + _cluster_wait_acquire() + cute.arch.fence_proxy("async.shared", space="cta") + cute.arch.sync_threads() + if warp == 0: + with cute.arch.elect_one(): + for k in cutlass.range_constexpr(cluster): + _bulk_push( + srbuf + c * Int32(cnt_bytes), smbar, scnt, Int32(k), Int32(cnt_bytes) + ) + _bulk_commit() + if warp < n_tok: + if lane < top_k: + o = Int64(t_first + warp) * Int64(top_k) + Int64(lane) + _st_b32(ids_ptr + o * Int64(4), my_sel) + _st_b16(wts_ptr + o * Int64(2), my_w) + cute.arch.mbarrier_wait(mbar_ptr, 0) + _cluster_arrive_relaxed() # this CTA's counts have arrived (waited at the end) + tot = Int32(0) + nct = Int32(0) + e = tidx + if e < num_local: + cnts = [] + for k in cutlass.range_constexpr(cluster): + cnts.append(_ld_shared(srbuf + (Int32(k * num_local) + e) * 4)) + pre = Int32(0) + for k in cutlass.range_constexpr(cluster): + tot = tot + cnts[k] + pre = pre + _sel_lt(Int32(k), c, cnts[k], Int32(0)) + _st_shared(spre + e * 4, pre) + _st_shared(stot + e * 4, tot) + nct = (tot + Int32(tile - 1)) // Int32(tile) + # Exclusive scan of the per-expert CTA counts (one expert per thread): as _route_cta. + incl = nct + for d in cutlass.range_constexpr(5): + incl = _scan_add(incl, 1 << d) + if lane == 31: + _st_shared(swsum + warp * 4, incl) + cute.arch.sync_threads() + n_warps_exp: cutlass.Constexpr = -(-num_local // 32) + wpre = Int32(0) + total = Int32(0) + for w in cutlass.range_constexpr(n_warps_exp): + ws = _ld_shared(swsum + w * 4) + wpre = wpre + _sel_lt(Int32(w), warp, ws, Int32(0)) + total = total + ws + offs = incl - nct + wpre + if e < num_local: + _st_shared(soffs + e * 4, offs) + if c == 0: + for cc in cutlass.range_constexpr(self.max_ctas_per_expert): + if Int32(cc) < nct: + cta_i = offs + Int32(cc) + _st_b32(tab_ptr + Int64(self.off_cte + cta_i) * Int64(4), e) + _st_b32( + tab_ptr + Int64(self.off_ctl + cta_i) * Int64(4), + cutlass.min((cta_i + 1) * Int32(tile), offs * Int32(tile) + tot), + ) + if c == 0: + if tidx == 0: + _st_b32(tab_ptr + Int64(self.off_nct) * Int64(4), total) + _st_b32(tab_ptr + Int64(self.off_npd) * Int64(4), total * Int32(tile)) + cute.arch.sync_threads() + # This CTA's picks: expanded -> permuted, permuted -> token (token order inside a block): as _route_cta. + for u in cutlass.range_constexpr(-(-(tpc * top_k) // self.threads)): + i = tidx + u * self.threads + if i < n_tok * top_k: + tl = i // top_k + tok = t_first + tl + pick = _ld_shared(spick + i * 4) + perm = Int32(-1) + if pick >= Int32(0): + rank = _ld_shared(spre + pick * 4) + _popc( + _ld_shared(smask + pick * 4) & _below(tl) + ) + perm = _ld_shared(soffs + pick * 4) * Int32(tile) + rank + _st_b32(tab_ptr + Int64(self.off_p2t + perm) * Int64(4), tok) + _st_b32( + tab_ptr + (Int64(tok) * Int64(top_k) + Int64(i - tl * top_k)) * Int64(4), perm + ) + # Every peer received this CTA's counts, so no outgoing copy still reads them (the bulk wait_group does not + # track copies that complete on an mbarrier). + _cluster_wait_acquire() + cute.arch.sync_threads() + if const_expr(self.use_pdl): + _gdc_launch() + @cute.jit def _route_warp_fast( self, logits_ptr: Int64, local_start: Int32, smask: Int32, spick: Int32, t_first, warp, lane diff --git a/tensorrt_llm/_torch/kernels/blackwell/moe_router_gemm.py b/tensorrt_llm/_torch/kernels/blackwell/moe_router_gemm.py new file mode 100644 index 000000000000..c7fcb595f061 --- /dev/null +++ b/tensorrt_llm/_torch/kernels/blackwell/moe_router_gemm.py @@ -0,0 +1,587 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""MoE router GEMM of decode steps: BF16 x [M, K] @ W [E, K].T -> BF16 logits [M, E] in one launch. + +tcgen05 MMA with the router weight as the M operand (128 experts per CTA, "swap AB") and token tiles of 32 or 64 as +N; a cluster of ``SPLITS`` CTAs splits K and sums the partials in split order (``MoeRouterGemmKernel``), so a token's +logits do not depend on the batch it runs in. Weight TMA loads go out before ``griddepcontrol.wait``, x after it. +The compile-time ``route_top_k`` epilogue feeds a MoE engine that routes itself: per token the top ``route_top_k`` +keys of each 128-expert tile, the NVFP4 quantization of x, and the PDL release right after the dependency wait. +""" + +from __future__ import annotations + +from typing import Optional + +import cutlass +import cutlass.cute as cute +import cutlass.utils as utils +from cutlass import BFloat16, Float32, Int32, Int64, const_expr +from cutlass._mlir.dialects import llvm +from cutlass.cute.nvgpu import cpasync, tcgen05 +from cutlass.cutlass_dsl import T, dsl_user_op + +from ...cute_dsl_utils import smem_optin_bytes +from .moe_decode_front import ( + _add, + _asm, + _gdc_launch, + _gdc_wait, + _i32, + _ld_f32, + _ld_shared, + _max_u32, + _nvfp4_block, + _redux_max_u32, + _sel_eq, + _smem_addr, + _st_b32, + _st_shared, + _st_u8, + _st_v2, + _struct, + _unpack, +) +from .moe_route_front import ( + _bulk_commit, + _bulk_push, + _cluster_arrive_relaxed, + _cluster_arrive_release, + _cluster_wait_acquire, + _keys2, +) +from .ptx_helpers import _pack_bf16x2_rn + +EXPERT_TILE = 128 # UMMA M (cta_group 1): TMEM lane = expert +K_TILE = 64 # one 128-byte swizzle atom of BF16 per row +SPLITS = 8 # K ranges = CTAs per cluster +TOKEN_TILES = (32, 64) # UMMA N +# The ``route_top_k`` epilogue: one lane stores each key of a token's tile, and each expert tile's CTA quantizes +# this many rows of its token tile (threads / 16 lanes per row). +ROUTE_MAX_TOP_K = 32 +QUANT_ROWS_PER_TILE = 8 + + +@dsl_user_op +def _tmem_ld16(taddr: Int32, *, loc=None, ip=None): + """16 consecutive TMEM columns of this thread's lane (32x32b shape), as raw 32-bit words.""" + regs = ", ".join(f"${i}" for i in range(16)) + out = _asm( + _struct(16), + [_i32(taddr, loc, ip)], + f"tcgen05.ld.sync.aligned.32x32b.x16.b32 {{{regs}}}, [$16];\n\ttcgen05.wait::ld.sync.aligned;", + ",".join(["=r"] * 16) + ",r,~{memory}", + loc=loc, + ip=ip, + ) + return _unpack(out, 16, loc, ip) + + +@dsl_user_op +def _ld_shared_v4_f32(addr: Int32, *, loc=None, ip=None): + out = _asm( + llvm.StructType.get_literal([T.f32()] * 4), + [_i32(addr, loc, ip)], + "ld.shared.v4.f32 {$0, $1, $2, $3}, [$4];", + "=f,=f,=f,=f,r,~{memory}", + loc=loc, + ip=ip, + ) + return tuple(Float32(llvm.extractvalue(T.f32(), out, [i], loc=loc, ip=ip)) for i in range(4)) + + +@dsl_user_op +def _ld_shared_v4_b32(addr: Int32, *, loc=None, ip=None): + out = _asm( + _struct(4), + [_i32(addr, loc, ip)], + "ld.shared.v4.b32 {$0, $1, $2, $3}, [$4];", + "=r,=r,=r,=r,r,~{memory}", + loc=loc, + ip=ip, + ) + return _unpack(out, 4, loc, ip) + + +@dsl_user_op +def _tcgen05_after_sync(*, loc=None, ip=None) -> None: + _asm(None, [], "tcgen05.fence::after_thread_sync;", "~{memory}", loc=loc, ip=ip) + + +class MoeRouterGemmKernel: + """logits [M, E] (BF16, row-major, contiguous) = x [M, K] (BF16, row stride ``a_stride``) @ w [E, K].T. + + Grid: ``E / 128`` expert tiles x ``ceil(M / token_tile)`` token tiles x ``SPLITS`` K ranges; clusters of + ``SPLITS`` CTAs along the K ranges (block index = split + SPLITS * (expert tile + E / 128 * token tile)). + 128 threads: warp 0 issues the TMA loads, warp 1 allocates TMEM and issues the MMAs, all four warps run the + epilogue (thread i = TMEM lane i = expert i of the tile). + + Split-K reduction: each CTA stages its FP32 partial tile [token][expert] in the shared memory that held x + (the MMAs are done with it), then pushes token slice o (``token_tile / SPLITS`` tokens) to CTA o with one + bulk copy that completes bytes on CTA o's receive mbarrier; each CTA waits for its ``SPLITS`` slices and + sums them in split order 0 .. SPLITS - 1. + + ``route_top_k`` (compile time; 0 is the plain GEMM): the epilogue a routing MoE engine reads. + + * Each token's top ``route_top_k`` reduceTopK keys of every expert tile, descending (``cand`` [M, E / 128, + route_top_k] int32: twiddled BF16 logit << 16 | 65535 - expert, as the route front's). + * The NVFP4 quantization of x (``xq`` [M, K / 2] u8, linear ``xsf`` [M, K / 16] u8, global scale ``gs``) from + the x tiles in shared memory, bitwise ``fp4_quantize``: CTA (e, s) quantizes rows 8 e .. 8 e + 7 of its token + tile over its K range, the K tiles the staging tile overwrites before it is written. + * The PDL dependents are released right after the dependency wait.""" + + threads = 128 + + @staticmethod + def _shape_error( + *, + num_rows: int, + k_extent: int, + num_experts: int, + a_stride: int, + token_tile: int, + route_top_k: int = 0, + ) -> Optional[str]: + if num_experts % EXPERT_TILE: + return f"num_experts={num_experts} must be a multiple of {EXPERT_TILE}" + if token_tile not in TOKEN_TILES: + return f"token_tile must be one of {TOKEN_TILES}" + if k_extent % (SPLITS * K_TILE): + return f"k_extent={k_extent} must split into {SPLITS} ranges of whole {K_TILE} tiles" + if a_stride % 8 or a_stride < k_extent: + return "x rows must be 16-byte aligned" + if k_extent // SPLITS // K_TILE < 4: + return "the staging tile reuses the x buffers: at least 4 K tiles per split" + smem_bytes = (k_extent // SPLITS // K_TILE) * (EXPERT_TILE + token_tile) * K_TILE * 2 + if smem_bytes + token_tile * EXPERT_TILE * 4 + 2048 > smem_optin_bytes(): + return "shared memory over budget" + if route_top_k and not 0 < route_top_k <= ROUTE_MAX_TOP_K: + return f"route_top_k must be in 1..{ROUTE_MAX_TOP_K}" + if route_top_k and ( + token_tile != QUANT_ROWS_PER_TILE * (num_experts // EXPERT_TILE) + or (k_extent // SPLITS // K_TILE) % 4 + ): + return f"route_top_k takes {QUANT_ROWS_PER_TILE} token rows per expert tile and K tiles in 4s" + return None + + @classmethod + def supports(cls, **shape: int) -> bool: + """Whether the constructor takes these shape arguments (the integer keyword arguments of ``__init__`` other + than ``use_pdl``).""" + return cls._shape_error(**shape) is None + + def __init__( + self, + *, + num_rows: int, + k_extent: int, + num_experts: int, + a_stride: int, + token_tile: int, + use_pdl: bool = True, + route_top_k: int = 0, + ) -> None: + err = self._shape_error( + num_rows=num_rows, + k_extent=k_extent, + num_experts=num_experts, + a_stride=a_stride, + token_tile=token_tile, + route_top_k=route_top_k, + ) + if err is not None: + raise ValueError(err) + self.num_rows = num_rows + self.k_extent = k_extent + self.num_experts = num_experts + self.a_stride = a_stride + self.splits = SPLITS + self.tn = token_tile + self.token_tiles = -(-num_rows // token_tile) + self.use_pdl = use_pdl + self.route_top_k = route_top_k + self.route = route_top_k > 0 + self.n_etiles = num_experts // EXPERT_TILE + self.k_tiles = k_extent // SPLITS // K_TILE + self.tps = token_tile // SPLITS # tokens of a CTA's output slice + self.slice_bytes = self.tps * EXPERT_TILE * 4 + self.ctas = self.n_etiles * self.token_tiles * SPLITS + self.tmem_cols = max(32, token_tile) + self.smem_bytes = ( + self.k_tiles * (EXPERT_TILE + token_tile) * K_TILE * 2 + token_tile * EXPERT_TILE * 4 + ) + + @cute.jit + def __call__( + self, + x_ptr: cute.Pointer, + w_ptr: cute.Pointer, + out_ptr: Int64, + stream, + cand_ptr: Optional[Int64] = None, + gs_ptr: Optional[Int64] = None, + xq_ptr: Optional[Int64] = None, + xsf_ptr: Optional[Int64] = None, + ) -> None: + # route_top_k only: the candidates (cand_ptr), global scale and quantized x (gs_ptr / xq_ptr / xsf_ptr). + # Swap AB: MMA A = router weight (M = experts), MMA B = x (N = tokens); both K-major. L = 1. + mA = cute.make_tensor( + w_ptr, + cute.make_layout( + (self.num_experts, self.k_extent, 1), + stride=(self.k_extent, 1, self.num_experts * self.k_extent), + ), + ) + mB = cute.make_tensor( + x_ptr, + cute.make_layout( + (self.num_rows, self.k_extent, 1), + stride=(self.a_stride, 1, self.num_rows * self.a_stride), + ), + ) + a_major = utils.LayoutEnum.from_tensor(mA).mma_major_mode() + b_major = utils.LayoutEnum.from_tensor(mB).mma_major_mode() + tiled_mma = utils.sm100.make_trivial_tiled_mma( + BFloat16, + BFloat16, + a_major, + b_major, + Float32, + tcgen05.CtaGroup.ONE, + (EXPERT_TILE, self.tn), + ) + mma_inst_k = cute.size(tiled_mma.shape_mnk, mode=[2]) + mma_tiler = (EXPERT_TILE, self.tn, K_TILE) + cluster_layout_vmnk = cute.tiled_divide( + cute.make_layout((1, 1, 1)), (tiled_mma.thr_id.shape,) + ) + a_smem_staged = utils.sm100.make_smem_layout_a(tiled_mma, mma_tiler, BFloat16, self.k_tiles) + b_smem_staged = utils.sm100.make_smem_layout_b(tiled_mma, mma_tiler, BFloat16, self.k_tiles) + a_smem_one = cute.slice_(a_smem_staged, (None, None, None, 0)) + b_smem_one = cute.slice_(b_smem_staged, (None, None, None, 0)) + a_op = utils.sm100.cluster_shape_to_tma_atom_A((1, 1), tiled_mma.thr_id) + b_op = utils.sm100.cluster_shape_to_tma_atom_B((1, 1), tiled_mma.thr_id) + tma_atom_a, tma_tensor_a = cute.nvgpu.make_tiled_tma_atom_A( + a_op, mA, a_smem_one, mma_tiler, tiled_mma, cluster_layout_vmnk.shape + ) + tma_atom_b, tma_tensor_b = cute.nvgpu.make_tiled_tma_atom_B( + b_op, mB, b_smem_one, mma_tiler, tiled_mma, cluster_layout_vmnk.shape + ) + a_bytes = cute.size_in_bytes(BFloat16, a_smem_one) + b_bytes = cute.size_in_bytes(BFloat16, b_smem_one) + self.kernel( + tiled_mma, + tma_atom_a, + tma_tensor_a, + tma_atom_b, + tma_tensor_b, + out_ptr, + a_smem_staged, + b_smem_staged, + a_bytes + b_bytes, + mma_inst_k, + cand_ptr, + gs_ptr, + xq_ptr, + xsf_ptr, + ).launch( + grid=[self.ctas, 1, 1], + block=[self.threads, 1, 1], + cluster=[self.splits, 1, 1], + stream=stream, + use_pdl=self.use_pdl, + min_blocks_per_mp=1, + ) + + @cute.jit + def _quant_phase( + self, + sB, + full_mbar, + gs_ptr: Int64, + xq_ptr: Int64, + xsf_ptr: Int64, + s, + e_tile, + t_tile, + tidx, + phase: cutlass.Constexpr, + ) -> None: + """NVFP4 block 16 phase + tidx % 16 of this CTA's K range (K tile = block // 4) for row 8 e_tile + tidx // 16 + of the token tile. sB is K-major with the 128-byte swizzle: row r is a 128-byte line of a K tile, its 16-byte + chunk c at c ^ (r % 8).""" + tn: cutlass.Constexpr = self.tn + r_loc = e_tile * Int32(QUANT_ROWS_PER_TILE) + tidx // Int32(16) + cbl = Int32(16 * phase) + tidx % Int32(16) + kt = cbl // Int32(4) + row = t_tile * Int32(tn) + r_loc + if row < Int32(self.num_rows): + gs = _ld_f32(gs_ptr) + cute.arch.mbarrier_wait(full_mbar + kt, 0) + c0 = (cbl % Int32(4)) * Int32(2) + line = _smem_addr(sB.iterator) + kt * Int32(tn * K_TILE * 2) + r_loc * Int32(128) + sw = r_loc % Int32(8) + w0, w1, w2, w3 = _ld_shared_v4_b32(line + ((c0 ^ sw) * Int32(16))) + w4, w5, w6, w7 = _ld_shared_v4_b32(line + (((c0 + Int32(1)) ^ sw) * Int32(16))) + lo, hi, sf = _nvfp4_block(w0, w1, w2, w3, w4, w5, w6, w7, gs) + cb = s * Int32(self.k_tiles * 4) + cbl + _st_v2(xq_ptr + Int64(row) * Int64(self.k_extent // 2) + Int64(cb) * Int64(8), lo, hi) + _st_u8(xsf_ptr + Int64(row) * Int64(self.k_extent // 16) + Int64(cb), sf) + + @cute.jit + def _tile_candidates(self, cand_ptr: Int64, row, e_tile, e4, lane, p01, p23) -> None: + """The warp's token row: its top ``route_top_k`` keys among this expert tile's 128 BF16 logits (4 per lane, + packed in p01 / p23), descending, lane r storing key r.""" + k0, k1 = _keys2(p01, e_tile * Int32(EXPERT_TILE) + e4) + k2, k3 = _keys2(p23, e_tile * Int32(EXPERT_TILE) + e4 + Int32(2)) + zero = Int32(0) + mine = zero + for r in cutlass.range_constexpr(self.route_top_k): + # keys are unique and never 0, so clearing the picked one takes it out + g = _redux_max_u32(_max_u32(_max_u32(k0, k1), _max_u32(k2, k3))) + k0 = _sel_eq(k0, g, zero, k0) + k1 = _sel_eq(k1, g, zero, k1) + k2 = _sel_eq(k2, g, zero, k2) + k3 = _sel_eq(k3, g, zero, k3) + mine = _sel_eq(lane, Int32(r), g, mine) + if lane < Int32(self.route_top_k): + base = Int64(row) * Int64(self.n_etiles) + Int64(e_tile) + _st_b32(cand_ptr + (base * Int64(self.route_top_k) + Int64(lane)) * Int64(4), mine) + + @cute.kernel + def kernel( + self, + tiled_mma: cute.TiledMma, + tma_atom_a: cute.CopyAtom, + mA: cute.Tensor, + tma_atom_b: cute.CopyAtom, + mB: cute.Tensor, + out_ptr: Int64, + a_smem_staged: cute.ComposedLayout, + b_smem_staged: cute.ComposedLayout, + tx_bytes: cutlass.Constexpr, + mma_inst_k: cutlass.Constexpr, + cand_ptr: Optional[Int64] = None, + gs_ptr: Optional[Int64] = None, + xq_ptr: Optional[Int64] = None, + xsf_ptr: Optional[Int64] = None, + ) -> None: + tidx, _, _ = cute.arch.thread_idx() + bidx, _, _ = cute.arch.block_idx() + warp = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + splits: cutlass.Constexpr = self.splits + k_tiles: cutlass.Constexpr = self.k_tiles + tps: cutlass.Constexpr = self.tps + tn: cutlass.Constexpr = self.tn + slice_bytes: cutlass.Constexpr = self.slice_bytes + s = bidx % Int32(splits) # rank in the cluster (1-D clusters along x) + tile = bidx // Int32(splits) + e_tile = tile % Int32(self.n_etiles) + t_tile = tile // Int32(self.n_etiles) + + if warp == 0: + cpasync.prefetch_descriptor(tma_atom_a) + cpasync.prefetch_descriptor(tma_atom_b) + + @cute.struct + class SharedStorage: + full_mbar: cute.struct.MemRange[cutlass.Int64, k_tiles] + acc_mbar: cute.struct.MemRange[cutlass.Int64, 1] + recv_mbar: cute.struct.MemRange[cutlass.Int64, 1] + tmem_holding_buf: cutlass.Int32 + + smem = utils.SmemAllocator() + storage = smem.allocate(SharedStorage) + sA = smem.allocate_tensor( + element_type=BFloat16, + layout=a_smem_staged.outer, + byte_alignment=1024, + swizzle=a_smem_staged.inner, + ) + sB = smem.allocate_tensor( + element_type=BFloat16, + layout=b_smem_staged.outer, + byte_alignment=1024, + swizzle=b_smem_staged.inner, + ) + recv = smem.allocate_tensor( + Float32, cute.make_layout((tn * EXPERT_TILE,)), byte_alignment=128 + ) + full_mbar = storage.full_mbar.data_ptr() + acc_mbar = storage.acc_mbar.data_ptr() + recv_mbar = storage.recv_mbar.data_ptr() + + if warp == 0: + with cute.arch.elect_one(): + for kt in cutlass.range_constexpr(k_tiles): + cute.arch.mbarrier_init(full_mbar + kt, 1) + cute.arch.mbarrier_init(acc_mbar, 1) + cute.arch.mbarrier_init(recv_mbar, 1) + # This CTA's own arrive: one slice from every split of the cluster. + cute.arch.mbarrier_arrive_and_expect_tx(recv_mbar, splits * slice_bytes) + cute.arch.mbarrier_init_fence() + if warp == 1: + cute.arch.alloc_tmem(self.tmem_cols, storage.tmem_holding_buf) + # Peers push into the receive buffer only after this arrive (barrier inits released). + _cluster_arrive_release() + cute.arch.sync_threads() + + # Tile views: A (weights) tile e_tile, B (x) tile t_tile, K tiles [s * k_tiles, (s + 1) * k_tiles). + gA = cute.local_tile( + mA, cute.slice_((EXPERT_TILE, tn, K_TILE), (None, 0, None)), (None, None, None) + ) + gB = cute.local_tile( + mB, cute.slice_((EXPERT_TILE, tn, K_TILE), (0, None, None)), (None, None, None) + ) + thr_mma = tiled_mma.get_slice(0) + tCgA = thr_mma.partition_A(gA) + tCgB = thr_mma.partition_B(gB) + tAsA, tAgA = cpasync.tma_partition( + tma_atom_a, + 0, + cute.make_layout(1), + cute.group_modes(sA, 0, 3), + cute.group_modes(tCgA, 0, 3), + ) + tBsB, tBgB = cpasync.tma_partition( + tma_atom_b, + 0, + cute.make_layout(1), + cute.group_modes(sB, 0, 3), + cute.group_modes(tCgB, 0, 3), + ) + tAgA_t = tAgA[(None, e_tile, None, 0)] + tBgB_t = tBgB[(None, t_tile, None, 0)] + k0 = s * Int32(k_tiles) + + # Producer: static weights before the dependency wait, x after it. + if warp == 0: + for kt in cutlass.range_constexpr(k_tiles): + with cute.arch.elect_one(): + cute.arch.mbarrier_arrive_and_expect_tx(full_mbar + kt, tx_bytes) + cute.copy( + tma_atom_a, + tAgA_t[(None, k0 + kt)], + tAsA[(None, kt)], + tma_bar_ptr=full_mbar + kt, + ) + if const_expr(self.use_pdl): + _gdc_wait() + if const_expr(self.route): + _gdc_launch() + if warp == 0: + for kt in cutlass.range_constexpr(k_tiles): + cute.copy( + tma_atom_b, + tBgB_t[(None, k0 + kt)], + tBsB[(None, kt)], + tma_bar_ptr=full_mbar + kt, + ) + + # MMA warp: K tiles in order, 4 instructions each, one accumulator. + tmem_ptr = cute.arch.retrieve_tmem_ptr(Float32, 16, storage.tmem_holding_buf) + tCrA = tiled_mma.make_fragment_A(sA) + tCrB = tiled_mma.make_fragment_B(sB) + acc_shape = tiled_mma.partition_shape_C((EXPERT_TILE, tn)) + tCtAcc = cute.make_tensor(tmem_ptr, tiled_mma.make_fragment_C(acc_shape).layout) + if warp == 1: + tiled_mma.set(tcgen05.Field.ACCUMULATE, False) + for kt in cutlass.range_constexpr(k_tiles): + cute.arch.mbarrier_wait(full_mbar + kt, 0) + for kb in cutlass.range_constexpr(K_TILE // mma_inst_k): + cute.gemm( + tiled_mma, + tCtAcc, + tCrA[(None, None, kb, kt)], + tCrB[(None, None, kb, kt)], + tCtAcc, + ) + tiled_mma.set(tcgen05.Field.ACCUMULATE, True) + with cute.arch.elect_one(): + tcgen05.commit(acc_mbar) + + if const_expr(self.route): + # K tiles 0-3 of x now: the staging tile overwrites them next + self._quant_phase(sB, full_mbar, gs_ptr, xq_ptr, xsf_ptr, s, e_tile, t_tile, tidx, 0) + cute.arch.sync_threads() + # Epilogue: thread = TMEM lane = expert. Stage the partial as [token][expert] FP32 over the x buffers. + cute.arch.mbarrier_wait(acc_mbar, 0) + _tcgen05_after_sync() + tmem_base = _ld_shared(_smem_addr(storage.tmem_holding_buf.ptr)) + taddr = tmem_base + ((warp * Int32(32)) << Int32(16)) + stage_addr = _smem_addr(sB.iterator) + recv_addr = _smem_addr(recv.iterator) + for c in cutlass.range_constexpr(tn // 16): + words = _tmem_ld16(taddr + Int32(c * 16)) + for j in cutlass.range_constexpr(16): + _st_shared( + stage_addr + (Int32((c * 16 + j) * EXPERT_TILE) + tidx) * Int32(4), words[j] + ) + cute.arch.fence_proxy("async.shared", space="cta") + cute.arch.sync_threads() + _cluster_wait_acquire() # every peer's receive mbarrier is initialized + # Token slice o of the staging tile goes to slot s of CTA o's receive buffer. + if warp == 0: + with cute.arch.elect_one(): + for o in cutlass.range_constexpr(splits): + _bulk_push( + recv_addr + s * Int32(slice_bytes), + _smem_addr(recv_mbar), + stage_addr + Int32(o * slice_bytes), + Int32(o), + Int32(slice_bytes), + ) + _bulk_commit() + if const_expr(self.route): + # the K tiles the staging tile left alone, while the split-K slices are in flight + for phase in cutlass.range_constexpr(1, k_tiles // 4): + self._quant_phase( + sB, full_mbar, gs_ptr, xq_ptr, xsf_ptr, s, e_tile, t_tile, tidx, phase + ) + cute.arch.mbarrier_wait(recv_mbar, 0) + _cluster_arrive_relaxed() # this CTA's slices have arrived (waited at the end) + + # Reduce this CTA's slice (tokens [s tps, (s + 1) tps) of the tile, all 128 experts) in split order. + lane = tidx % Int32(32) + e4 = lane * Int32(4) + for i in cutlass.range_constexpr(-(-tps // 4)): + lt = warp + Int32(4 * i) + if lt < Int32(tps): + base = recv_addr + (lt * Int32(EXPERT_TILE) + e4) * Int32(4) + a0, a1, a2, a3 = _ld_shared_v4_f32(base) + for p in cutlass.range_constexpr(1, splits): + b0, b1, b2, b3 = _ld_shared_v4_f32(base + Int32(p * slice_bytes)) + a0 = _add(a0, b0) + a1 = _add(a1, b1) + a2 = _add(a2, b2) + a3 = _add(a3, b3) + row = t_tile * Int32(tn) + s * Int32(tps) + lt + if row < Int32(self.num_rows): + dst = out_ptr + ( + Int64(row) * Int64(self.num_experts) + + Int64(e_tile * Int32(EXPERT_TILE) + e4) + ) * Int64(2) + p01 = _pack_bf16x2_rn(a0, a1) + p23 = _pack_bf16x2_rn(a2, a3) + _st_v2(dst, p01, p23) + if const_expr(self.route): + self._tile_candidates(cand_ptr, row, e_tile, e4, lane, p01, p23) + # Every peer received its slices, so no outgoing copy still reads the staging tile (the bulk wait_group does + # not track copies that complete on an mbarrier). + _cluster_wait_acquire() + cute.arch.sync_threads() + if warp == 1: + cute.arch.relinquish_tmem_alloc_permit() + cute.arch.dealloc_tmem(tmem_ptr, self.tmem_cols) + if const_expr(self.use_pdl and not self.route): + _gdc_launch() + + +def router_gemm_token_tile(m: int) -> Optional[int]: + """Token tile for m rows, or None where the stock GEMM stays: 32 while it takes at most 3 per expert tile, so + the clusters launch early (PDL) beside the producer in one wave, then 64 up to 128 rows.""" + if m <= 3 * 32: + return 32 + if m <= 2 * 64: + return 64 + return None diff --git a/tensorrt_llm/_torch/kernels/blackwell/ptx_helpers.py b/tensorrt_llm/_torch/kernels/blackwell/ptx_helpers.py new file mode 100644 index 000000000000..23598d6cf35f --- /dev/null +++ b/tensorrt_llm/_torch/kernels/blackwell/ptx_helpers.py @@ -0,0 +1,196 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Device helpers shared by the Blackwell CuTe DSL kernels (the decode MoE engines, the low-M MoE FC2, the MoE +router GEMM): inline PTX and small tracing helpers. + +The helpers stay inline PTX where ``cute.arch`` has an equivalent operation (``barrier``, ``exp2``, ``rcp_approx``, +``cp_async_commit_group``, ``load`` / ``store`` / ``atomic_add`` on pointers): those lower to other MLIR / LLVM +operations and change the engines' generated PTX, while ``nvvm.inline_ptx`` is a side-effecting ``asm`` the compiler +neither merges nor moves across another, which the engines' cross-CTA protocols (counter polls, release / acquire +pairs) and their bit-exact epilogues are written against. +""" + +from __future__ import annotations + +from typing import Tuple, Union + +import cutlass +import cutlass.cute as cute +from cutlass import Int32, Int64 +from cutlass.cute.nvgpu import tcgen05 + +from .moe_decode_front import _add + +# A tree of value indices: an index, or a pair of trees summed left + right. +SumTree = Union[int, Tuple["SumTree", "SumTree"]] + + +# ---------------------------------------------------------------------------------------------------------------- +# Global memory +# ---------------------------------------------------------------------------------------------------------------- +def _ld_s32(addr: Int64) -> Int32: + return cute.arch.inline_ptx( + "ld.global.s32 {$w0}, [{$r0}];", write_only_types=[Int32], read_only_args=[addr] + ) + + +def _ld_relaxed_u32(addr: Int64) -> Int32: + return cute.arch.inline_ptx( + "ld.relaxed.gpu.global.u32 {$w0}, [{$r0}];", write_only_types=[Int32], read_only_args=[addr] + ) + + +def _ld_acquire_u32(addr: Int64) -> Int32: + return cute.arch.inline_ptx( + "ld.acquire.gpu.global.u32 {$w0}, [{$r0}];", write_only_types=[Int32], read_only_args=[addr] + ) + + +def _ld_nc_f32(addr: Int64) -> cutlass.Float32: + return cute.arch.inline_ptx( + "ld.global.nc.f32 {$w0}, [{$r0}];", + write_only_types=[cutlass.Float32], + read_only_args=[addr], + ) + + +def _st_relaxed_u32(addr: Int64, v: Int32) -> None: + cute.arch.inline_ptx("st.relaxed.gpu.global.u32 [{$r0}], {$r1};", read_only_args=[addr, v]) + + +def _st_global_b32(addr: Int64, v: Int32) -> None: + cute.arch.inline_ptx("st.global.b32 [{$r0}], {$r1};", read_only_args=[addr, v]) + + +def _red_release_add(addr: Int64, v: Int32) -> None: + cute.arch.inline_ptx("red.release.gpu.global.add.u32 [{$r0}], {$r1};", read_only_args=[addr, v]) + + +def _atom_add_acq_rel(addr: Int64, v: Int32) -> Int32: + return cute.arch.inline_ptx( + "atom.acq_rel.gpu.global.add.u32 {$w0}, [{$r0}], {$r1};", + write_only_types=[Int32], + read_only_args=[addr, v], + ) + + +def _atom_add_relaxed(addr: Int64, v: Int32) -> Int32: + return cute.arch.inline_ptx( + "atom.relaxed.gpu.global.add.u32 {$w0}, [{$r0}], {$r1};", + write_only_types=[Int32], + read_only_args=[addr, v], + ) + + +def _policy_evict_first() -> Int64: + """An L2 cache policy: evict first (createpolicy.fractional, fraction 1.0).""" + return cute.arch.inline_ptx( + "createpolicy.fractional.L2::evict_first.b64 {$w0}, 1.0;", write_only_types=[Int64] + ) + + +def _policy_evict_last() -> Int64: + """An L2 cache policy: evict last (createpolicy.fractional, fraction 1.0).""" + return cute.arch.inline_ptx( + "createpolicy.fractional.L2::evict_last.b64 {$w0}, 1.0;", write_only_types=[Int64] + ) + + +def _st_global_b32_hint(addr: Int64, v: Int32, pol: Int64) -> None: + cute.arch.inline_ptx( + "st.global.L2::cache_hint.b32 [{$r0}], {$r1}, {$r2};", read_only_args=[addr, v, pol] + ) + + +def _cp_async_16(dst: Int32, src: Int64) -> None: + cute.arch.inline_ptx( + "cp.async.cg.shared.global [{$r0}], [{$r1}], 16;", read_only_args=[dst, src] + ) + + +def _cp_async_arrive_noinc(bar: Int32) -> None: + """Arrive on bar once this thread's earlier cp.async copies complete (the barrier's count includes it).""" + cute.arch.inline_ptx( + "cp.async.mbarrier.arrive.noinc.shared::cta.b64 [{$r0}];", read_only_args=[bar] + ) + + +def _cp_async_commit() -> None: + cute.arch.inline_ptx("cp.async.commit_group;") + + +def _bar_sync(bar_id: Int32, n: int) -> None: + """Named barrier bar_id (a register) over n threads.""" + cute.arch.inline_ptx(f"bar.sync {{$r0}}, {n};", read_only_args=[bar_id]) + + +# ---------------------------------------------------------------------------------------------------------------- +# Arithmetic +# ---------------------------------------------------------------------------------------------------------------- +def _pack_bf16x2_rn(lo: cutlass.Float32, hi: cutlass.Float32) -> Int32: + """{bf16(hi), bf16(lo)} by cvt.rn.bf16x2.f32 (no saturation).""" + return cute.arch.inline_ptx( + "cvt.rn.bf16x2.f32 {$w0}, {$r1}, {$r0};", write_only_types=[Int32], read_only_args=[lo, hi] + ) + + +def _mul_rn(a: cutlass.Float32, b: cutlass.Float32) -> cutlass.Float32: + return cute.arch.inline_ptx( + "mul.rn.f32 {$w0}, {$r0}, {$r1};", write_only_types=[cutlass.Float32], read_only_args=[a, b] + ) + + +def _add_rn(a: cutlass.Float32, b: cutlass.Float32) -> cutlass.Float32: + return cute.arch.inline_ptx( + "add.rn.f32 {$w0}, {$r0}, {$r1};", write_only_types=[cutlass.Float32], read_only_args=[a, b] + ) + + +def _rcp(a: cutlass.Float32) -> cutlass.Float32: + return cute.arch.inline_ptx( + "rcp.approx.ftz.f32 {$w0}, {$r0};", write_only_types=[cutlass.Float32], read_only_args=[a] + ) + + +def _ex2(a: cutlass.Float32) -> cutlass.Float32: + return cute.arch.inline_ptx( + "ex2.approx.ftz.f32 {$w0}, {$r0};", write_only_types=[cutlass.Float32], read_only_args=[a] + ) + + +def _scale_pack_bf16x2(lo: cutlass.Float32, hi: cutlass.Float32, s: cutlass.Float32) -> Int32: + """{bf16_sat(hi * s), bf16_sat(lo * s)}: one IEEE mul.rn.f32 each, then cvt.rn.satfinite.bf16x2.f32 (the + trtllm-gen FC2 cubins' FMUL2 + F2FP.SATFINITE.BF16.F32.PACK_AB).""" + return cute.arch.inline_ptx( + "{ .reg .f32 a, b; mul.rn.f32 a, {$r0}, {$r2}; mul.rn.f32 b, {$r1}, {$r2};" + " cvt.rn.satfinite.bf16x2.f32 {$w0}, b, a; }", + write_only_types=[Int32], + read_only_args=[lo, hi, s], + ) + + +def sum_tree(vals: list, tree: SumTree) -> cutlass.Float32: + """``vals`` summed (``add.f32``) in the order of ``tree`` (nested pairs of indices, e.g. + ``moe_bf16_engine._butterfly_sum``).""" + if isinstance(tree, int): + return vals[tree] + return _add(sum_tree(vals, tree[0]), sum_tree(vals, tree[1])) + + +# ---------------------------------------------------------------------------------------------------------------- +# Tensor memory +# ---------------------------------------------------------------------------------------------------------------- +def s2t_copy( + sSF: cute.Tensor, tSF: cute.Tensor, cta_group: tcgen05.CtaGroup, sf_dtype: type +) -> Tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]: + """The shared memory -> TMEM copy of block scales ``sSF`` into ``tSF`` (``tcgen05.cp`` 4x32x128b): the tiled + copy, its shared-memory descriptor source and its TMEM destination.""" + tCsSF_compact = cute.filter_zeros(sSF) + tCtSF_compact = cute.filter_zeros(tSF) + copy_atom_s2t = cute.make_copy_atom(tcgen05.Cp4x32x128bOp(cta_group), sf_dtype) + tiled_copy_s2t = tcgen05.make_s2t_copy(copy_atom_s2t, tCtSF_compact) + thr_copy_s2t = tiled_copy_s2t.get_slice(0) + tCsSF_compact_s2t_ = thr_copy_s2t.partition_S(tCsSF_compact) + tCsSF_compact_s2t = tcgen05.get_s2t_smem_desc_tensor(tiled_copy_s2t, tCsSF_compact_s2t_) + tCtSF_compact_s2t = thr_copy_s2t.partition_D(tCtSF_compact) + return tiled_copy_s2t, tCsSF_compact_s2t, tCtSF_compact_s2t diff --git a/tensorrt_llm/_torch/kernels/blackwell/resident_fp8_gemm.py b/tensorrt_llm/_torch/kernels/blackwell/resident_fp8_gemm.py new file mode 100644 index 000000000000..a5fabb9fc2d3 --- /dev/null +++ b/tensorrt_llm/_torch/kernels/blackwell/resident_fp8_gemm.py @@ -0,0 +1,720 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""FP8 decode projection with its weights loaded before the PDL wait, bitwise equal to cuBLAS' nvjet +(``cublas_scaled_mm``): ``y[M, N] = bf16((x[M, K] @ W[N, K].T) * (sa * sb))`` in ``cta_group::2`` tcgen05 MMAs over +the whole K in order. Behind a producer that releases its dependents early, most weight K tiles are already in shared +memory when ``griddepcontrol.wait`` returns. Conv mode (``conv=``) also applies the GDN causal conv1d update of an MTP +target-verify step to the first output columns, bitwise as Triton's ``causal_conv1d_update`` (``supports_conv``). +""" + +from __future__ import annotations + +from typing import NamedTuple + +import cutlass +import cutlass.cute as cute +import cutlass.experimental.cuda as cuda_exp +import torch +from cuda.bindings import driver as cuda +from cutlass import Float32, Int32, Int64 +from cutlass._mlir.dialects import llvm +from cutlass.cutlass_dsl import T, dsl_user_op +from cutlass.experimental import primitives as prims + +from ...flashinfer_utils import get_env_enable_pdl +from .low_m_mma_gemm import _gdn_conv_silu +from .moe_decode_front import _ld_f32 + +K_BOX = 128 # E4M3 per 128-byte TMA row (s128b swizzle) +K_GRANULE = 32 # K per tcgen05 f8f6f4 MMA +FEAT_PAIR = 128 # collective MMA M +FEAT_CTA = 64 +W_TILE = FEAT_CTA * K_BOX # 8 KB +SW_ALIGN = 1024 +TMA_WARP, MMA_WARP, EPI_WARP0 = 0, 1, 2 +TCOLS = 32 +XG = 8 # K tiles per x TMA box / barrier +# x + weight slots + barriers per CTA: with its 1 KB reserved a CTA stays within the 196 KB shared-memory split beside +# three 512 B all-reduce CTAs, so it can start early on an SM that has not drained (an SM changes its split only idle). +SMEM_BUDGET = 190 * 1024 +MAX_ROWS = 128 + + +@dsl_user_op +def _mul_rn(a: Float32, b: Float32, *, loc=None, ip=None) -> Float32: + return Float32( + llvm.inline_asm( + T.f32(), + [Float32(a).ir_value(loc=loc, ip=ip), Float32(b).ir_value(loc=loc, ip=ip)], + "mul.rn.f32 $0, $1, $2;", + "=f,f,f", + has_side_effects=False, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def _st_bf16(addr: Int64, v: Float32, off: int = 0, *, loc=None, ip=None) -> None: + """bf16(v) (round to nearest even) to [addr + off]; ``off`` is a compile-time byte offset folded into the store.""" + llvm.inline_asm( + None, + [Int64(addr).ir_value(loc=loc, ip=ip), Float32(v).ir_value(loc=loc, ip=ip)], + f"{{\n\t.reg .b16 h;\n\tcvt.rn.bf16.f32 h, $1;\n\tst.global.b16 [$0+{off}], h;\n\t}}", + "l,f,~{memory}", + has_side_effects=True, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + + +@dsl_user_op +def _st_bf16_exact(addr: Int64, v: Float32, off: int = 0, *, loc=None, ip=None) -> None: + """An FP32 value that is exactly a BF16 value, stored as its high half to [addr + off] (no conversion; the same + bits as rounding it).""" + llvm.inline_asm( + None, + [Int64(addr).ir_value(loc=loc, ip=ip), Float32(v).ir_value(loc=loc, ip=ip)], + f"{{\n\t.reg .b32 r;\n\t.reg .b16 l, h;\n\tmov.b32 r, $1;\n\tmov.b32 {{l, h}}, r;\n\t" + f"st.global.b16 [$0+{off}], h;\n\t}}", + "l,f,~{memory}", + has_side_effects=True, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + + +@dsl_user_op +def _ld_bf16(addr: Int64, *, loc=None, ip=None) -> Float32: + return Float32( + llvm.inline_asm( + T.f32(), + [Int64(addr).ir_value(loc=loc, ip=ip)], + "{\n\t.reg .b16 h, z;\n\tmov.b16 z, 0;\n\tld.global.b16 h, [$1];\n\t" + "mov.b32 $0, {z, h};\n\t}", + "=f,l,~{memory}", + has_side_effects=True, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def _ld_s32(addr: Int64, *, loc=None, ip=None) -> Int32: + return Int32( + llvm.inline_asm( + T.i32(), + [Int64(addr).ir_value(loc=loc, ip=ip)], + "ld.global.s32 $0, [$1];", + "=r,l,~{memory}", + has_side_effects=True, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def _bf16r(v: Float32, *, loc=None, ip=None) -> Float32: + """v rounded to BF16 (round to nearest even), returned as the exact FP32 value.""" + return Float32( + llvm.inline_asm( + T.f32(), + [Float32(v).ir_value(loc=loc, ip=ip)], + "{\n\t.reg .b16 b, z;\n\tmov.b16 z, 0;\n\tcvt.rn.bf16.f32 b, $1;\n\t" + "mov.b32 $0, {z, b};\n\t}", + "=f,f", + has_side_effects=False, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + +def _resident(kt: int, tn: int, budget: int = SMEM_BUDGET) -> int: + """Weight K tiles kept in smem (the rest stream through the same slots).""" + return min(kt, (budget - kt * (tn // 2) * K_BOX - 2048) // W_TILE) + + +def _covers(k: int, n: int) -> bool: + """Whole x TMA boxes of ``XG`` K tiles, whole 128-feature CTA pairs.""" + return k > 0 and k % (XG * K_BOX) == 0 and n > 0 and n % FEAT_PAIR == 0 + + +def plan(m: int, k: int, n: int, budget: int = SMEM_BUDGET): + """(token_tiles, tile_rows, TN, resident weight tiles) or None when the kernel does not cover the shape.""" + if not _covers(k, n) or m < 1 or m > MAX_ROWS: + return None + tiles = 1 if m <= 32 else (2 if m <= 64 else 3) + ts = -(-m // tiles) + tn = 32 if ts <= 32 else 48 + r_res = _resident(k // K_BOX, tn, budget) + if r_res < 1: # no weight slot to stream through + return None + return tiles, ts, tn, r_res + + +class ConvUpdate(NamedTuple): + """Conv mode's operands (GDN in_proj_qkvz of an MTP target-verify step): ``weight`` [C, 4] BF16, ``state`` [slots, + C, 3] BF16 (any strides), ``slots`` [R] int32 (negative = padding: no window / state writes), ``windows`` [>= R, + >= tokens, C, 3] BF16, ``tokens`` per request.""" + + weight: torch.Tensor + state: torch.Tensor + slots: torch.Tensor + windows: torch.Tensor + tokens: int + + +def _operands_ok(x: torch.Tensor, w: torch.Tensor) -> bool: + """E4M3 x [M, K] and w [N, K], contiguous, at the compiled kernel's 128-byte alignment.""" + return ( + x.dtype == torch.float8_e4m3fn + and w.dtype == torch.float8_e4m3fn + and x.dim() == 2 + and w.dim() == 2 + and x.shape[1] == w.shape[1] + and x.is_contiguous() + and w.is_contiguous() + and x.data_ptr() % 128 == 0 + and w.data_ptr() % 128 == 0 + ) + + +def supports(x: torch.Tensor, w: torch.Tensor, budget: int = SMEM_BUDGET) -> bool: + """Whether :func:`resident_fp8_gemm` takes x [M, K] and w [N, K] (``_operands_ok``) at a shape :func:`plan` + covers.""" + return _operands_ok(x, w) and plan(x.shape[0], x.shape[1], w.shape[0], budget) is not None + + +def plan_conv(m: int, qt: int, k: int, n: int, budget: int = SMEM_BUDGET): + """Conv mode (GDN in_proj_qkvz of an MTP target-verify step, m = requests x qt rows): (token_tiles, tile_rows, TN, + resident weight tiles, rows per CTA half) with whole requests in every CTA half (each epilogue thread owns a + channel's tokens of TN / 2 // qt requests; TN 32 while three token tiles suffice, else 48), or None.""" + if not _covers(k, n) or qt < 1 or qt > 16 or m % qt: + return None + for tn in (32, 48): + rph = (tn // 2) // qt + tiles = -(-(m // qt) // (2 * rph)) + if tiles <= 3: + r_res = _resident(k // K_BOX, tn, budget) + return (tiles, 2 * rph * qt, tn, r_res, rph * qt) if r_res >= 1 else None + return None + + +def supports_conv(x: torch.Tensor, w: torch.Tensor, conv: ConvUpdate) -> bool: + """Whether :func:`resident_fp8_gemm` takes x and w (``_operands_ok``) in conv mode: dtypes and shapes of + ``conv``, rows = requests x tokens, whole 128-channel feature pairs inside the output columns; callers fall back + to their unfused path otherwise.""" + if not _operands_ok(x, w): + return False + m, k = x.shape + n = w.shape[0] + qt = conv.tokens + cw, cs, win, sl = conv.weight, conv.state, conv.windows, conv.slots + c_dim = cw.shape[0] + return ( + plan_conv(m, qt, k, n) is not None + and cw.dtype == torch.bfloat16 + and cw.is_contiguous() + and cw.dim() == 2 + and cw.shape[1] == 4 + and c_dim % FEAT_PAIR == 0 + and c_dim <= n + and cs.dtype == torch.bfloat16 + and cs.dim() == 3 + and cs.shape[1] == c_dim + and cs.shape[2] == 3 + and win.dtype == torch.bfloat16 + and win.dim() == 4 + and win.shape[0] >= m // qt + and win.shape[1] >= qt + and win.shape[2] == c_dim + and win.shape[3] == 3 + and sl.dtype == torch.int32 + and sl.dim() == 1 + and sl.is_contiguous() + and sl.shape[0] == m // qt + ) + + +@cute.kernel +def _kernel( + tma_x_desc: cutlass.GridConstant[cuda_exp.TensorMap], + tma_w_desc: cutlass.GridConstant[cuda_exp.TensorMap], + gSa: cute.Tensor, + gSb: cute.Tensor, + gOut: cute.Tensor, + gCw: cute.Tensor, + gCs: cute.Tensor, + gWin: cute.Tensor, + gSlot: cute.Tensor, + m_rows: cutlass.Constexpr[int], + n_out: cutlass.Constexpr[int], + kt: cutlass.Constexpr[int], + ts: cutlass.Constexpr[int], + tn: cutlass.Constexpr[int], + r_res: cutlass.Constexpr[int], + hrw: cutlass.Constexpr[int], + cv: cutlass.Constexpr, +): + AB: cutlass.Constexpr = tma_w_desc.dtype + SWZ: cutlass.Constexpr = tma_w_desc.swizzle.to(prims.Tcgen05SmemSwizzle) + XR: cutlass.Constexpr[int] = tn // 2 # x rows per CTA + X_TILE: cutlass.Constexpr[int] = XR * K_BOX + NKB: cutlass.Constexpr[int] = K_BOX // K_GRANULE + S: cutlass.Constexpr[int] = kt - r_res # streamed weight tiles + NB: cutlass.Constexpr[int] = max(1, S) # slot releases, one per streamed tile + NPAIRS_F: cutlass.Constexpr[int] = n_out // FEAT_PAIR + HALF: cutlass.Constexpr[int] = tn // 2 # accumulator columns per CTA (2x2 mapping) + CHUNKS: cutlass.Constexpr = tuple(1 << b for b in range(6, -1, -1) if HALF & (1 << b)) + CONV: cutlass.Constexpr[bool] = cv is not None + QT: cutlass.Constexpr[int] = cv[0] if CONV else 1 + RPH: cutlass.Constexpr[int] = (hrw // QT) if CONV else 1 + + smem_w = cutlass.Array(AB, r_res * W_TILE, space=cutlass.AddressSpace.smem, alignment=SW_ALIGN) + smem_x = cutlass.Array(AB, kt * X_TILE, space=cutlass.AddressSpace.smem, alignment=SW_ALIGN) + w_full = cutlass.Array(cutlass.Int64, kt, space=cutlass.AddressSpace.smem, alignment=8) + x_full = cutlass.Array(cutlass.Int64, kt // XG, space=cutlass.AddressSpace.smem, alignment=8) + w_empty = cutlass.Array(cutlass.Int64, NB, space=cutlass.AddressSpace.smem, alignment=8) + acc_bar = cutlass.Array(cutlass.Int64, 1, space=cutlass.AddressSpace.smem, alignment=8) + tmem_i32 = cutlass.Array(Int32, 1, space=cutlass.AddressSpace.smem, alignment=4) + + warp_idx = cute.arch.warp_idx() + tidx, _, _ = cute.arch.thread_idx() + bidx, _, _ = cute.arch.block_idx() + lane = tidx % Int32(32) + rank = cute.arch.block_idx_in_cluster() + is_leader = rank == Int32(0) + pair = bidx // Int32(2) + tok_tile = pair // Int32(NPAIRS_F) + fpair = pair % Int32(NPAIRS_F) + feat0 = fpair * Int32(FEAT_PAIR) + rank * Int32( + FEAT_CTA + ) # this CTA's first output feature (W row) + tok0 = tok_tile * Int32(ts) # first token of the tile + xrow0 = tok0 + rank * Int32(hrw) # this CTA's first x row (B half) + sa_ptr = Int64(gSa.iterator.toint()) + sb_ptr = Int64(gSb.iterator.toint()) + out_ptr = Int64(gOut.iterator.toint()) + + # ---- barriers, TMEM (CTA / cluster state only: allowed before the dependency wait) ---- + if warp_idx == TMA_WARP: + if prims.elect_sync(): + for t in cutlass.range_constexpr(kt): + prims.mbarrier_init(w_full.subview(t), 1) + for g in cutlass.range_constexpr(kt // XG): + prims.mbarrier_init(x_full.subview(g), 1) + for b in cutlass.range_constexpr(NB): + prims.mbarrier_init(w_empty.subview(b), 1) + prims.mbarrier_init(acc_bar, 1) + prims.fence_mbarrier_init() + prims.barrier_cluster_arrive_relaxed() + prims.barrier_cluster_wait() + if warp_idx == MMA_WARP: + prims.tcgen05_alloc(tmem_i32, TCOLS, group="cta_2") + prims.barrier_cta_sync(0) + tmem_raw = tmem_i32.load() + tmem_ptr = cutlass.inttoptr(tmem_raw, 6, Float32) + if warp_idx == MMA_WARP: + prims.tcgen05_relinquish_alloc_permit(group="cta_2") + + x_ptr = tma_x_desc.get_ptr() + w_ptr = tma_w_desc.get_ptr() + w_bytes = tma_w_desc.global_tx_bytes() + x_bytes = tma_x_desc.global_tx_bytes() + + # ---- TMA warp: resident weights + L2 prefetch before the wait, x right after it, then the streamed tiles ---- + if warp_idx == TMA_WARP: + if prims.elect_sync(): + if is_leader: + # the pair's transaction bytes land on the leader's barriers (cta_group::2 TMA) + for t in cutlass.range_constexpr(kt): + prims.mbarrier_arrive_expect_tx(w_full.subview(t), 2 * w_bytes) + for g in cutlass.range_constexpr(kt // XG): + prims.mbarrier_arrive_expect_tx(x_full.subview(g), 2 * x_bytes) + for t in cutlass.range_constexpr(r_res): + prims.cp_async_bulk_tensor_shared_cluster_global( + smem_w.subview(t * W_TILE), + w_ptr, + (Int32(t * K_BOX), feat0), + w_full.subview(t), + [], + l2_cache_hint=None, + group=prims.CTAGroup.CTA_2, + ) + for t in cutlass.range_constexpr(r_res, kt): + prims.cp_async_bulk_tensor_prefetch( + w_ptr, [Int32(t * K_BOX), feat0], [], l2_cache_hint=None + ) + cute.arch.griddepcontrol_wait() + for g in cutlass.range_constexpr(kt // XG): + prims.cp_async_bulk_tensor_shared_cluster_global( + smem_x.subview(g * XG * X_TILE), + x_ptr, + (Int32(0), xrow0, Int32(g * XG)), + x_full.subview(g), + [], + group=prims.CTAGroup.CTA_2, + ) + # streamed tile j (K tile r_res + j) into slot j % r_res once the MMAs of K tile j (the slot's previous + # occupant) have completed; whole-warp polls, elect only around the issue + for j in cutlass.range_constexpr(S): + while not prims.mbarrier_try_wait_parity(w_empty.subview(j), 0, time_limit=10_000_000): + pass + if prims.elect_sync(): + prims.cp_async_bulk_tensor_shared_cluster_global( + smem_w.subview((j % r_res) * W_TILE), + w_ptr, + (Int32((r_res + j) * K_BOX), feat0), + w_full.subview(r_res + j), + [], + l2_cache_hint=None, + group=prims.CTAGroup.CTA_2, + ) + + # ---- MMA warp (leader of the pair issues): the K chain in order ---- + if warp_idx == MMA_WARP: + if is_leader: + idesc = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, a_dtype=AB, b_dtype=AB, n_dim=tn, m_dim=FEAT_PAIR + ) + desc_w = prims.Tcgen05SmemDesc.build( + start_address=smem_w, + leading_byte_offset=K_BOX, + stride_byte_offset=8 * K_BOX, + layout=SWZ, + ) + desc_x = prims.Tcgen05SmemDesc.build( + start_address=smem_x, + leading_byte_offset=K_BOX, + stride_byte_offset=8 * K_BOX, + layout=SWZ, + ) + for t in cutlass.range_constexpr(kt): + slot = t if t < r_res else (t - r_res) % r_res + while not prims.mbarrier_try_wait_parity( + w_full.subview(t), 0, time_limit=10_000_000 + ): + pass + if cutlass.const_expr(t % XG == 0): + while not prims.mbarrier_try_wait_parity( + x_full.subview(t // XG), 0, time_limit=10_000_000 + ): + pass + for kb in cutlass.range_constexpr(NKB): + if prims.elect_sync(): + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F8F6F4, + prims.CTAGroup.CTA_2, + tmem_ptr, + desc_w.advance_start_address(Int32(slot * W_TILE + kb * K_GRANULE)), + desc_x.advance_start_address(Int32(t * X_TILE + kb * K_GRANULE)), + idesc, + (t > 0) or (kb > 0), + ) + if cutlass.const_expr(t < S): + if prims.elect_sync(): + prims.tcgen05_commit( + w_empty.subview(t), multicast_mask=3, group=prims.CTAGroup.CTA_2 + ) + if prims.elect_sync(): + prims.tcgen05_commit(acc_bar, multicast_mask=3, group=prims.CTAGroup.CTA_2) + + # ---- epilogue: TMEM -> * (sa * sb) -> BF16 -> y (conv mode: the causal conv1d update of the q|k|v columns) ---- + if warp_idx >= Int32(EPI_WARP0): + cute.arch.griddepcontrol_wait() # sa / sb / the conv state are data of earlier kernels + alpha = _mul_rn(_ld_f32(sa_ptr), _ld_f32(sb_ptr)) + sp = warp_idx % Int32(4) # TMEM lane quarter this warp may access + m_stripe = sp % Int32(2) + n_stripe = sp // Int32(2) + feat = feat0 + m_stripe * Int32(32) + lane + cv_w = [] + cv_slot = [] + cv_st = [] + if cutlass.const_expr(CONV): + # After the wait, before the accumulator: hidden under the MMAs. Indices are clamped so z-channel CTAs + # load harmlessly; they never use the values. + cvf = cutlass.min(feat, Int32(cv[1] - 1)) + cw_addr = Int64(gCw.iterator.toint()) + Int64(cvf) * Int64(8) + for i in cutlass.range_constexpr(4): + cv_w.append(_ld_bf16(cw_addr + Int64(2 * i))) + for j in cutlass.range_constexpr(RPH): + req = tok_tile * Int32(2 * RPH) + n_stripe * Int32(RPH) + Int32(j) + sl = _ld_s32( + Int64(gSlot.iterator.toint()) + + Int64(cutlass.min(req, Int32(cv[2] - 1))) * Int64(4) + ) + cv_slot.append(sl) + st_addr = Int64(gCs.iterator.toint()) + ( + Int64(cutlass.max(sl, Int32(0))) * Int64(cv[3][0]) + + Int64(cvf) * Int64(cv[3][1]) + ) * Int64(2) + stj = [] + for i in cutlass.range_constexpr(3): + stj.append(_ld_bf16(st_addr + Int64(2 * i * cv[3][2]))) + cv_st.append(stj) + while not prims.mbarrier_try_wait_parity(acc_bar, 0, time_limit=10_000_000): + pass + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + if tidx == Int32(EPI_WARP0 * 32): + cute.arch.griddepcontrol_launch_dependents() + base = prims.TmemAddr(tmem_raw) + acc = cutlass.Array(Float32, HALF, alignment=32) + for ci in cutlass.range_constexpr(len(CHUNKS)): # tcgen05.ld widths must be powers of 2 + cwid = CHUNKS[ci] + c0 = sum(CHUNKS[:ci]) + acc.store( + prims.tcgen05_ld( + "32x32b", + prims.TmemAddr.from_row_col( + base.row_id + sp * Int32(32), base.col_id + Int32(c0) + ).as_ptr(Float32), + num=cwid, + ), + c0, + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + if cutlass.const_expr(CONV): + if fpair < Int32(cv[1] // FEAT_PAIR): + # GDN causal conv1d update of this channel for the RPH requests of this half: the outputs replace the + # raw q|k|v projection, plus the window after every token and the conv state after the last one. + win_base = Int64(gWin.iterator.toint()) + cs_base = Int64(gCs.iterator.toint()) + y = [] + for c in cutlass.range_constexpr(RPH * QT): + y.append(_bf16r(_mul_rn(acc[c], alpha))) + for j in cutlass.range_constexpr(RPH): + req = tok_tile * Int32(2 * RPH) + n_stripe * Int32(RPH) + Int32(j) + if req < Int32(cv[2]): + ext = list(cv_st[j]) + y[j * QT : (j + 1) * QT] + # one base address per store group; the per-token / per-tap byte offsets are compile-time + ob = out_ptr + ( + Int64(tok0 + n_stripe * Int32(hrw) + Int32(j * QT)) * Int64(n_out) + + Int64(feat) + ) * Int64(2) + for t in cutlass.range_constexpr(QT): + o = _gdn_conv_silu( + ext[t], + ext[t + 1], + ext[t + 2], + ext[t + 3], + cv_w[0], + cv_w[1], + cv_w[2], + cv_w[3], + ) + _st_bf16_exact(ob, o, 2 * t * n_out) + if cv_slot[j] >= Int32(0): + wb = win_base + ( + Int64(req) * Int64(cv[4][0]) + Int64(feat) * Int64(cv[4][2]) + ) * Int64(2) + for t in cutlass.range_constexpr(QT): + for i in cutlass.range_constexpr(3): + _st_bf16_exact( + wb, ext[t + 1 + i], 2 * (t * cv[4][1] + i * cv[4][3]) + ) + sb_ = cs_base + ( + Int64(cv_slot[j]) * Int64(cv[3][0]) + Int64(feat) * Int64(cv[3][1]) + ) * Int64(2) + for i in cutlass.range_constexpr(3): + _st_bf16_exact(sb_, ext[QT + i], 2 * i * cv[3][2]) + else: + ob = out_ptr + ( + Int64(tok0 + n_stripe * Int32(hrw)) * Int64(n_out) + Int64(feat) + ) * Int64(2) + for c in cutlass.range_constexpr(HALF): + tok_local = n_stripe * Int32(hrw) + Int32(c) + tok = tok0 + tok_local + if (Int32(c) < Int32(hrw)) & (tok_local < Int32(ts)) & (tok < Int32(m_rows)): + _st_bf16(ob, _mul_rn(acc[c], alpha), 2 * c * n_out) + else: + ob = out_ptr + ( + Int64(tok0 + n_stripe * Int32(hrw)) * Int64(n_out) + Int64(feat) + ) * Int64(2) + for c in cutlass.range_constexpr(HALF): + tok_local = n_stripe * Int32(hrw) + Int32(c) + tok = tok0 + tok_local + if (Int32(c) < Int32(hrw)) & (tok_local < Int32(ts)) & (tok < Int32(m_rows)): + _st_bf16(ob, _mul_rn(acc[c], alpha), 2 * c * n_out) + # Reconverge every warp before the CTA barrier (warp 0's lanes otherwise arrive in two groups). + cute.arch.sync_warp() + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + prims.barrier_cta_sync(0) + prims.barrier_cluster_arrive_relaxed() + prims.barrier_cluster_wait() + if warp_idx == MMA_WARP: + prims.tcgen05_dealloc(tmem_ptr, TCOLS, group="cta_2") + + +@cute.jit +def _launch( + x: cute.Tensor, + w: cute.Tensor, + sa: cute.Tensor, + sb: cute.Tensor, + out: cute.Tensor, + cw: cute.Tensor, + cs: cute.Tensor, + win: cute.Tensor, + slot: cute.Tensor, + stream: cuda.CUstream, + m_rows: cutlass.Constexpr[int], + n_out: cutlass.Constexpr[int], + k_total: cutlass.Constexpr[int], + tiles: cutlass.Constexpr[int], + ts: cutlass.Constexpr[int], + tn: cutlass.Constexpr[int], + r_res: cutlass.Constexpr[int], + hrw: cutlass.Constexpr[int], + cv: cutlass.Constexpr, + use_pdl: cutlass.Constexpr[bool], +): + # [128 K][rows][K / 128] view of x: one box = 8 K tiles of this CTA's rows, landing as [8][rows][128] + tma_x = cuda_exp.create_tensor_map_tiled( + global_address=x.iterator.toint(), + dtype=cutlass.Float8E4M3FN, + global_dims=[K_BOX, m_rows, k_total // K_BOX], + global_strides=[k_total // 16, K_BOX // 16], + box_dims=[K_BOX, tn // 2, XG], + swizzle=cuda_exp.TensorMapSwizzle.s128b, + ) + tma_w = cuda_exp.create_tensor_map_tiled( + global_address=w.iterator.toint(), + dtype=cutlass.Float8E4M3FN, + global_dims=[k_total, n_out], + global_strides=[k_total // 16], + box_dims=[K_BOX, FEAT_CTA], + swizzle=cuda_exp.TensorMapSwizzle.s128b, + ) + _kernel( + tma_x, + tma_w, + sa, + sb, + out, + cw, + cs, + win, + slot, + m_rows, + n_out, + k_total // K_BOX, + ts, + tn, + r_res, + hrw, + cv, + ).launch( + grid=(2 * (n_out // FEAT_PAIR) * tiles, 1, 1), + block=(6 * 32, 1, 1), + cluster=(2, 1, 1), + stream=stream, + use_pdl=use_pdl, + ) + + +def _compile( + m: int, k: int, n: int, tiles: int, ts: int, tn: int, r_res: int, hrw: int, cv, use_pdl: bool +): + mk = cute.runtime.make_fake_compact_tensor + u8 = cutlass.Uint8 + return cute.compile( + _launch, + mk(u8, (m, k), stride_order=(1, 0), assumed_align=128), + mk(u8, (n, k), stride_order=(1, 0), assumed_align=128), + mk(cutlass.Float32, (1,), assumed_align=4), + mk(cutlass.Float32, (1,), assumed_align=4), + mk(cutlass.BFloat16, (m, n), stride_order=(1, 0), assumed_align=16), + mk(cutlass.BFloat16, (1,), assumed_align=2), + mk(cutlass.BFloat16, (1,), assumed_align=2), + mk(cutlass.BFloat16, (1,), assumed_align=2), + mk(cutlass.Int32, (1,), assumed_align=4), + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + m_rows=m, + n_out=n, + k_total=k, + tiles=tiles, + ts=ts, + tn=tn, + r_res=r_res, + hrw=hrw, + cv=cv, + use_pdl=use_pdl, + options="--enable-tvm-ffi", + ) + + +_COMPILED = {} + + +def _compiled(*key): + """``_compile(*key)``, once per key; the first call of a key must precede CUDA graph capture.""" + fn = _COMPILED.get(key) + if fn is None: + if torch.cuda.is_current_stream_capturing(): + raise RuntimeError(f"compile the resident FP8 GEMM {key[:3]} before CUDA graph capture") + fn = _COMPILED[key] = _compile(*key) + return fn + + +def resident_fp8_gemm( + x: torch.Tensor, + w: torch.Tensor, + sa: torch.Tensor, + sb: torch.Tensor, + out: torch.Tensor | None = None, + conv: ConvUpdate | None = None, + budget: int = SMEM_BUDGET, +) -> torch.Tensor: + """y [M, N] BF16 = (x [M, K] E4M3 @ w [N, K].T E4M3) * sa * sb (sa, sb: FP32 device scalars). + + ``conv``: the first C output columns then hold the convolved q|k|v (silu), the windows and the state are updated, + and the rows must be R x tokens. ``budget``: smem bytes for x + weight slots (SMEM_BUDGET).""" + m, k = x.shape + n = w.shape[0] + assert x.dtype == torch.float8_e4m3fn and w.dtype == torch.float8_e4m3fn + assert x.is_contiguous() and w.is_contiguous() + if out is None: + out = torch.empty((m, n), dtype=torch.bfloat16, device=x.device) + if conv is None: + cfg = plan(m, k, n, budget) + assert cfg is not None + tiles, ts, tn, r_res = cfg + hrw, cv = tn // 2, None + # the conv operands are never read without conv: views of the output stand in for them + head = torch.as_strided(out, (2,), (1,)) + cargs = (head[:1],) * 3 + (head.view(torch.int32),) + else: + qt = conv.tokens + cfg = plan_conv(m, qt, k, n, budget) + assert cfg is not None + tiles, ts, tn, r_res, hrw = cfg + assert supports_conv(x, w, conv) + cw, cs, win, sl = conv.weight, conv.state, conv.windows, conv.slots + cv = (qt, cw.shape[0], m // qt, tuple(cs.stride()), tuple(win.stride())) + cargs = tuple(torch.as_strided(t, (1,), (1,)) for t in (cw, cs, win, sl)) + fn = _compiled(m, k, n, tiles, ts, tn, r_res, hrw, cv, get_env_enable_pdl()) + fn( + x.view(torch.uint8), + w.view(torch.uint8), + sa.reshape(1).float(), + sb.reshape(1).float(), + out, + *cargs, + ) + return out diff --git a/tensorrt_llm/_torch/kernels/blackwell/tp2_allreduce_norm.py b/tensorrt_llm/_torch/kernels/blackwell/tp2_allreduce_norm.py new file mode 100644 index 000000000000..e77290a8086a --- /dev/null +++ b/tensorrt_llm/_torch/kernels/blackwell/tp2_allreduce_norm.py @@ -0,0 +1,427 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""TP2 large-message all-reduce + residual + RMSNorm (+ FP8) in one launch, one warp per row. + +Persistent grid; warp ``gw`` of ``G`` owns rows gw, gw + G, ... of each half (rank r owns half r): + A. push my partial of its peer-half rows to the peer's LA (lane l writes vectors l + 32 i: 512 B per warp + store), then __syncwarp + system fence + the peer's flag A[gw] = epoch; + B. wait for my flag A[gw]; for its own-half rows: sum = RN_bf16(FP32 mine + FP32 peer's) (NCCL's 2-rank sum), + push the sums to the peer's LB, finalize; then the peer's flag B[gw] = epoch; + C. wait for my flag B[gw]; finalize its peer-half rows from LB. +finalize reproduces ``reduce_fusion::rms_norm_kernel`` (H / 8 threads x one vector) +bit for bit: BF16 residual add; per reference thread (= one vector here) an FP32 FMA chain over its 8 elements; +the reference warp k's butterfly (16..1) is this warp's butterfly over its k-th vectors; the reference's final +reduction (lanes below its warp count hold the warp sums, butterfly) is replayed; ``rsqrt(sum / H + eps)``; +``bf16((x * rstd) * w)``; FP8 = satfinite(norm_bf16 * (1 / scale)) as ``scaleMatrixPerTensorVec``. +Flags carry an epoch (the call count): nothing is cleared between calls; the last warp to finish advances it. +""" + +from __future__ import annotations + +import cutlass +import cutlass.cute as cute +from cutlass import Float32, Int32, Int64, const_expr +from cutlass._mlir import ir +from cutlass._mlir.dialects import llvm +from cutlass.cutlass_dsl import T, dsl_user_op + +from .mnnvl_allreduce_norm import ( + _add, + _div_rn, + _e4m3x2, + _fma, + _hi, + _ld_s64, + _ld_v4, + _lo, + _mul, + _pack_bf16, + _rsqrt, + _shfl_bfly, + _st_v2, + _st_v4, +) +from .utils import griddepcontrol_launch_dependents, griddepcontrol_wait + +VEC = 8 +REF_MAX_THREADS = 1024 # the reference launch's largest block (one vector per thread up to it) + + +def _asm(res, operands, text, constraints, side_effects=True, *, loc=None, ip=None): + return llvm.inline_asm( + res, + operands, + text, + constraints, + has_side_effects=side_effects, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + + +def _v(x, loc=None, ip=None): + return x.ir_value(loc=loc, ip=ip) + + +@dsl_user_op +def _ld_cg_v4(addr: Int64, *, loc=None, ip=None): + """Four words at a 16-byte aligned global address, cached in L2 only (data another GPU wrote).""" + words = _asm( + ir.Type.parse("!llvm.struct<(i32,i32,i32,i32)>"), + [_v(Int64(addr), loc, ip)], + "ld.global.cg.v4.b32 {$0, $1, $2, $3}, [$4];", + "=r,=r,=r,=r,l,~{memory}", + loc=loc, + ip=ip, + ) + return tuple(Int32(llvm.extractvalue(T.i32(), words, [i], loc=loc, ip=ip)) for i in range(4)) + + +@dsl_user_op +def _ld_acquire_sys(addr: Int64, *, loc=None, ip=None) -> Int32: + return Int32( + _asm( + T.i32(), + [_v(Int64(addr), loc, ip)], + "ld.acquire.sys.global.b32 $0, [$1];", + "=r,l,~{memory}", + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def _st_release_sys(addr: Int64, value: Int32, *, loc=None, ip=None) -> None: + _asm( + None, + [_v(Int64(addr), loc, ip), _v(Int32(value), loc, ip)], + "st.release.sys.global.b32 [$0], $1;", + "l,r,~{memory}", + loc=loc, + ip=ip, + ) + + +@dsl_user_op +def _fence_sys(*, loc=None, ip=None) -> None: + _asm(None, [], "fence.acq_rel.sys;", "~{memory}", loc=loc, ip=ip) + + +@dsl_user_op +def _atom_add_acq_rel_gpu(addr: Int64, value: Int32, *, loc=None, ip=None) -> Int32: + return Int32( + _asm( + T.i32(), + [_v(Int64(addr), loc, ip), _v(Int32(value), loc, ip)], + "atom.acq_rel.gpu.global.add.u32 $0, [$1], $2;", + "=r,l,r,~{memory}", + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def _ld_relaxed_gpu(addr: Int64, *, loc=None, ip=None) -> Int32: + return Int32( + _asm( + T.i32(), + [_v(Int64(addr), loc, ip)], + "ld.relaxed.gpu.global.b32 $0, [$1];", + "=r,l,~{memory}", + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def _st_relaxed_gpu(addr: Int64, value: Int32, *, loc=None, ip=None) -> None: + _asm( + None, + [_v(Int64(addr), loc, ip), _v(Int32(value), loc, ip)], + "st.relaxed.gpu.global.b32 [$0], $1;", + "l,r,~{memory}", + loc=loc, + ip=ip, + ) + + +@dsl_user_op +def _add_bf16x2(a: Int32, b: Int32, *, loc=None, ip=None) -> Int32: + """BF16x2 add (``__hadd2``: exact sum, one RN rounding).""" + return Int32( + _asm( + T.i32(), + [_v(Int32(a), loc, ip), _v(Int32(b), loc, ip)], + "{\n\t.reg .b32 one;\n\tmov.b32 one, 0x3f803f80;\n\tfma.rn.bf16x2 $0, $1, one, $2;\n\t}", + "=r,r,r", + False, + loc=loc, + ip=ip, + ) + ) + + +class Tp2WarpAllReduceNormKernel: + """Tensors: x [M, H] BF16, residual [M, H], weight [H] BF16, scale [1] FP32, residual_out / norm_out [M, H], + quant_out [M, H] uint8, table int64 [8] (``Tp2AllReduceNorm.table``). ``ctas`` x ``warps`` warps.""" + + @staticmethod + def supports_hidden(hidden: int) -> bool: + """The reference block spans the row in whole warps, one vector per thread.""" + return hidden % (VEC * 32) == 0 and 0 < hidden // VEC <= REF_MAX_THREADS + + def __init__( + self, + *, + hidden: int, + norm_eps: float, + ctas: int, + warps: int, + norm_out: bool, + quant: bool, + use_pdl: bool, + ): + if not self.supports_hidden(hidden): + raise ValueError(f"H {hidden} is not one reference block of {VEC}-element vectors") + self.hidden = hidden + self.vpl = hidden // VEC // 32 # vectors per lane = reference warps + self.norm_eps = float(norm_eps) + self.ctas = ctas + self.warps = warps + self.norm_out = norm_out + self.quant = quant + self.use_pdl = use_pdl + + @cute.jit + def __call__( + self, + gX: cute.Tensor, + gRes: cute.Tensor, + gW: cute.Tensor, + gScale: cute.Tensor, + gResOut: cute.Tensor, + gOut: cute.Tensor, + gQuant: cute.Tensor, + gWs: cute.Tensor, + rank: Int32, + stream, + ): + self.kernel(gX, gRes, gW, gScale, gResOut, gOut, gQuant, gWs, rank).launch( + grid=[self.ctas, 1, 1], + block=[32 * self.warps, 1, 1], + stream=stream, + use_pdl=self.use_pdl, + ) + + @cute.kernel + def kernel( + self, + gX: cute.Tensor, + gRes: cute.Tensor, + gW: cute.Tensor, + gScale: cute.Tensor, + gResOut: cute.Tensor, + gOut: cute.Tensor, + gQuant: cute.Tensor, + gWs: cute.Tensor, + rank: Int32, + ): + tidx, _, _ = cute.arch.thread_idx() + cta, _, _ = cute.arch.block_idx() + H: cutlass.Constexpr = self.hidden + VPL: cutlass.Constexpr = self.vpl + WPC: cutlass.Constexpr = self.warps + G: cutlass.Constexpr = self.ctas * self.warps + warp = tidx // 32 + lane = tidx % 32 + gw = cta * Int32(WPC) + warp + m = cute.size(gRes, mode=[0]) + h0 = (m + 1) // 2 + own_base = rank * h0 + own_n = h0 + rank * (m - Int32(2) * h0) + peer_base = h0 - own_base + peer_n = m - own_n + row_bytes = Int64(H * 2) + lv = Int64(lane) * Int64(16) # this lane's first vector, bytes + + tbl = Int64(gWs.iterator.toint()) + la_own = _ld_s64(tbl) + lb_own = _ld_s64(tbl + Int64(8)) + fl_own = _ld_s64(tbl + Int64(16)) + la_peer = _ld_s64(tbl + Int64(24)) + lb_peer = _ld_s64(tbl + Int64(32)) + fl_peer = _ld_s64(tbl + Int64(40)) + epoch_p = _ld_s64(tbl + Int64(48)) + arrive_p = _ld_s64(tbl + Int64(56)) + xb = Int64(gX.iterator.toint()) + rb = Int64(gRes.iterator.toint()) + + if const_expr(self.use_pdl): + griddepcontrol_wait() + ep = _ld_relaxed_gpu(epoch_p) + Int32(1) + + # ---- A: my partial of the peer half's rows -> peer LA ---- + r = gw + while r < peer_n: + src = xb + Int64(peer_base + r) * row_bytes + lv + dst = la_peer + Int64(r) * row_bytes + lv + buf = cute.make_rmem_tensor((4 * VPL,), Int32) + for i in cutlass.range_constexpr(VPL): + a0, a1, a2, a3 = _ld_v4(src + Int64(512 * i)) + buf[4 * i + 0] = a0 + buf[4 * i + 1] = a1 + buf[4 * i + 2] = a2 + buf[4 * i + 3] = a3 + for i in cutlass.range_constexpr(VPL): + _st_v4( + dst + Int64(512 * i), + buf[4 * i + 0], + buf[4 * i + 1], + buf[4 * i + 2], + buf[4 * i + 3], + ) + r = r + Int32(G) + cute.arch.sync_warp() + if lane == Int32(0): + _fence_sys() + _st_release_sys(fl_peer + Int64(gw) * Int64(4), ep) + + # ---- B: own half: wait for the peer's partials, sum, push the sums, finalize ---- + if lane == Int32(0): + while _ld_acquire_sys(fl_own + Int64(gw) * Int64(4)) != ep: + pass + cute.arch.sync_warp() + r = gw + while r < own_n: + row = own_base + r + mine = cute.make_rmem_tensor((4 * VPL,), Int32) + theirs = cute.make_rmem_tensor((4 * VPL,), Int32) + for i in cutlass.range_constexpr(VPL): + a0, a1, a2, a3 = _ld_v4(xb + Int64(row) * row_bytes + lv + Int64(512 * i)) + mine[4 * i + 0] = a0 + mine[4 * i + 1] = a1 + mine[4 * i + 2] = a2 + mine[4 * i + 3] = a3 + b0, b1, b2, b3 = _ld_cg_v4(la_own + Int64(r) * row_bytes + lv + Int64(512 * i)) + theirs[4 * i + 0] = b0 + theirs[4 * i + 1] = b1 + theirs[4 * i + 2] = b2 + theirs[4 * i + 3] = b3 + for w in cutlass.range_constexpr(4 * VPL): + mine[w] = _pack_bf16( + _add(_lo(mine[w]), _lo(theirs[w])), _add(_hi(mine[w]), _hi(theirs[w])) + ) + for i in cutlass.range_constexpr(VPL): + _st_v4( + lb_peer + Int64(r) * row_bytes + lv + Int64(512 * i), + mine[4 * i + 0], + mine[4 * i + 1], + mine[4 * i + 2], + mine[4 * i + 3], + ) + self._finalize(mine, row, lane, rb, gW, gScale, gResOut, gOut, gQuant) + r = r + Int32(G) + cute.arch.sync_warp() + if lane == Int32(0): + _fence_sys() + _st_release_sys(fl_peer + Int64(G + gw) * Int64(4), ep) + + # ---- C: peer half: wait for the peer's sums, finalize ---- + if lane == Int32(0): + while _ld_acquire_sys(fl_own + Int64(G + gw) * Int64(4)) != ep: + pass + cute.arch.sync_warp() + r = gw + while r < peer_n: + sums = cute.make_rmem_tensor((4 * VPL,), Int32) + for i in cutlass.range_constexpr(VPL): + q0, q1, q2, q3 = _ld_cg_v4(lb_own + Int64(r) * row_bytes + lv + Int64(512 * i)) + sums[4 * i + 0] = q0 + sums[4 * i + 1] = q1 + sums[4 * i + 2] = q2 + sums[4 * i + 3] = q3 + self._finalize(sums, peer_base + r, lane, rb, gW, gScale, gResOut, gOut, gQuant) + r = r + Int32(G) + + # ---- epoch: the last warp to finish advances it ---- + if const_expr(self.use_pdl): + griddepcontrol_launch_dependents() + if lane == Int32(0): + old = _atom_add_acq_rel_gpu(arrive_p, Int32(1)) + if old == Int32(G - 1): + _st_relaxed_gpu(arrive_p, Int32(0)) + _st_relaxed_gpu(epoch_p, ep) + + @cute.jit + def _finalize(self, sums, row, lane, rb, gW, gScale, gResOut, gOut, gQuant): + """Residual add + RMSNorm (+ FP8) of ``row`` from its BF16 sums (lane holds vectors lane + 32 i).""" + H: cutlass.Constexpr = self.hidden + VPL: cutlass.Constexpr = self.vpl + row_bytes = Int64(H * 2) + base = Int64(row) * row_bytes + Int64(lane) * Int64(16) + res = cute.make_rmem_tensor((4 * VPL,), Int32) + for i in cutlass.range_constexpr(VPL): + c0, c1, c2, c3 = _ld_v4(rb + base + Int64(512 * i)) + res[4 * i + 0] = _add_bf16x2(sums[4 * i + 0], c0) + res[4 * i + 1] = _add_bf16x2(sums[4 * i + 1], c1) + res[4 * i + 2] = _add_bf16x2(sums[4 * i + 2], c2) + res[4 * i + 3] = _add_bf16x2(sums[4 * i + 3], c3) + for i in cutlass.range_constexpr(VPL): + _st_v4( + Int64(gResOut.iterator.toint()) + base + Int64(512 * i), + res[4 * i + 0], + res[4 * i + 1], + res[4 * i + 2], + res[4 * i + 3], + ) + # reference warp k = this warp's k-th vectors: per-thread FMA chain, butterfly 16..1 + wsum = cute.make_rmem_tensor((VPL,), Float32) + for k in cutlass.range_constexpr(VPL): + a = Float32(0.0) + for j in cutlass.range_constexpr(4): + a = _fma(_lo(res[4 * k + j]), _lo(res[4 * k + j]), a) + a = _fma(_hi(res[4 * k + j]), _hi(res[4 * k + j]), a) + for s in cutlass.range_constexpr(5): + a = _add(a, _shfl_bfly(a, Int32(16 >> s))) + wsum[k] = a + # reference block reduction: lanes < VPL hold the warp sums (VPL warps), the rest 0, butterfly + v = Float32(0.0) + for k in cutlass.range_constexpr(VPL): + if lane == Int32(k): + v = wsum[k] + for s in cutlass.range_constexpr(5): + v = _add(v, _shfl_bfly(v, Int32(16 >> s))) + rstd = _rsqrt(_add(_div_rn(v, Float32(float(H))), Float32(self.norm_eps))) + inv = Float32(1.0) + if const_expr(self.quant): + inv = _div_rn(Float32(1.0), gScale[0]) + wb = Int64(gW.iterator.toint()) + Int64(lane) * Int64(16) + for i in cutlass.range_constexpr(VPL): + w0, w1, w2, w3 = _ld_v4(wb + Int64(512 * i)) + ww = (w0, w1, w2, w3) + o = cute.make_rmem_tensor((4,), Int32) + for j in cutlass.range_constexpr(4): + o[j] = _pack_bf16( + _mul(_mul(_lo(res[4 * i + j]), rstd), _lo(ww[j])), + _mul(_mul(_hi(res[4 * i + j]), rstd), _hi(ww[j])), + ) + if const_expr(self.norm_out): + _st_v4(Int64(gOut.iterator.toint()) + base + Int64(512 * i), o[0], o[1], o[2], o[3]) + if const_expr(self.quant): + q01 = _e4m3x2(_mul(_lo(o[0]), inv), _mul(_hi(o[0]), inv)) + q23 = _e4m3x2(_mul(_lo(o[1]), inv), _mul(_hi(o[1]), inv)) + q45 = _e4m3x2(_mul(_lo(o[2]), inv), _mul(_hi(o[2]), inv)) + q67 = _e4m3x2(_mul(_lo(o[3]), inv), _mul(_hi(o[3]), inv)) + _st_v2( + Int64(gQuant.iterator.toint()) + + Int64(row) * Int64(H) + + Int64(lane) * Int64(8) + + Int64(256 * i), + q01 | (q23 << 16), + q45 | (q67 << 16), + ) diff --git a/tensorrt_llm/_torch/kernels/nvfp4_quant.py b/tensorrt_llm/_torch/kernels/nvfp4_quant.py index 73b40ee97423..96c8a8272ce5 100644 --- a/tensorrt_llm/_torch/kernels/nvfp4_quant.py +++ b/tensorrt_llm/_torch/kernels/nvfp4_quant.py @@ -16,12 +16,16 @@ Matches the CUDA arithmetic in ``torch.ops.trtllm.fp4_quantize(x, global_scale, 16, False, False)``: it follows ``cvt_warp_fp16_to_fp4`` step for step, including the ``rcp.approx.ftz`` reciprocals and the ``cvt.rn.satfinite`` -conversions. +conversions. ``nvfp4_fp8_dual_quant`` also writes the per-tensor E4M3 copy of the same read, as +``static_quantize_e4m3_per_tensor`` (``scaleMatrixPerTensorVec``: ``x * (1.0f / s)``, RN, saturating). """ +from typing import Optional + import torch import triton import triton.language as tl +import triton.language.extra.libdevice as tldevice from ..flashinfer_utils import get_env_enable_pdl @@ -54,10 +58,13 @@ def _nvfp4_quant_kernel( global_scale_ptr: tl.tensor, q_ptr: tl.tensor, sf_ptr: tl.tensor, + fp8_scale_ptr, # None unless write_fp8 + fp8_ptr, # None unless write_fp8 num_tokens: tl.tensor, hidden: tl.constexpr, block_t: tl.constexpr, block_h: tl.constexpr, + write_fp8: tl.constexpr, launch_with_pdl: tl.constexpr, ) -> None: if launch_with_pdl: @@ -93,6 +100,13 @@ def _nvfp4_quant_kernel( sf.to(tl.uint8, bitcast=True), mask=mask, ) + if write_fp8: + fp8_factor = tldevice.rcp_rn(tl.load(fp8_scale_ptr)) + tl.store( + fp8_ptr + rows[:, None] * hidden + cols[None, :], + (x * fp8_factor).to(tl.float8e4nv), + mask=mask, + ) if launch_with_pdl: # Publish both outputs before any warp signals completion to a consumer. @@ -134,29 +148,55 @@ def can_use_nvfp4_quant(x: torch.Tensor, global_scale: torch.Tensor) -> bool: ) -def nvfp4_quant(x: torch.Tensor, global_scale: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: - """Quantize BF16 ``[T, H]`` with a float32 CUDA scalar global scale. - - Requires a Blackwell-or-later FP4 ISA and ``can_use_nvfp4_quant`` inputs. - Returns packed FP4 ``[T, H/2]`` and linear E4M3 scales ``[T * H/16]``, - both uint8, as ``fp4_quantize(x, global_scale, 16, False, False)``. - """ +def _launch( + x: torch.Tensor, + global_scale: torch.Tensor, + fp8_scale: Optional[torch.Tensor], +) -> tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: num_tokens, hidden = x.shape q = torch.empty((num_tokens, hidden // 2), dtype=torch.uint8, device=x.device) sf = torch.empty((num_tokens * (hidden // 16),), dtype=torch.uint8, device=x.device) + fp8 = None if fp8_scale is None else torch.empty_like(x, dtype=torch.float8_e4m3fn) launch_with_pdl = get_env_enable_pdl() _nvfp4_quant_kernel[(triton.cdiv(num_tokens, 4), hidden // _BLOCK_H)]( x, global_scale, q, sf, + fp8_scale, + fp8, num_tokens, hidden=hidden, block_t=4, block_h=_BLOCK_H, + write_fp8=fp8 is not None, launch_with_pdl=launch_with_pdl, launch_pdl=launch_with_pdl, num_warps=2, enable_fp_fusion=False, ) + return q, sf, fp8 + + +def nvfp4_quant(x: torch.Tensor, global_scale: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """Quantize BF16 ``[T, H]`` with a float32 CUDA scalar global scale. + + Requires a Blackwell-or-later FP4 ISA and ``can_use_nvfp4_quant`` inputs. + Returns packed FP4 ``[T, H/2]`` and linear E4M3 scales ``[T * H/16]``, + both uint8, as ``fp4_quantize(x, global_scale, 16, False, False)``. + """ + q, sf, _ = _launch(x, global_scale, None) return q, sf + + +def nvfp4_fp8_dual_quant( + x: torch.Tensor, global_scale: torch.Tensor, fp8_scale: torch.Tensor +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """``nvfp4_quant`` plus the per-tensor E4M3 copy of the same input, in one read. + + Requires ``can_use_nvfp4_quant(x, global_scale)`` and a one-element float32 + ``fp8_scale`` on the same device. Returns ``(q, sf, fp8)``: ``q`` and ``sf`` + as ``nvfp4_quant``, and ``fp8`` ``[T, H]`` equal to + ``static_quantize_e4m3_per_tensor(x, fp8_scale)``. + """ + return _launch(x, global_scale, fp8_scale) diff --git a/tensorrt_llm/_torch/mmap_utils.py b/tensorrt_llm/_torch/mmap_utils.py index 3de561b69355..ce2ef726b1fd 100644 --- a/tensorrt_llm/_torch/mmap_utils.py +++ b/tensorrt_llm/_torch/mmap_utils.py @@ -37,8 +37,13 @@ _MADV_DONTNEED = 4 _MADV_PAGEOUT = 21 -_MADV_ADVICE_BY_MODE = {"dontneed": _MADV_DONTNEED, "pageout": _MADV_PAGEOUT} _MADV_POPULATE_READ = 22 # Requires Linux >= 5.14. +_MADV_POPULATE_WRITE = 23 # Requires Linux >= 5.14. +_MADV_ADVICE_BY_MODE = { + "dontneed": _MADV_DONTNEED, + "pageout": _MADV_PAGEOUT, + "populate_write": _MADV_POPULATE_WRITE, +} _MMAP_FAILED = ctypes.c_void_p(-1).value @@ -59,6 +64,7 @@ def madvise_range(addr: int, size: int, mode: str = "dontneed") -> None: mode : str, optional "dontneed" -> MADV_DONTNEED (immediate discard, default) "pageout" -> MADV_PAGEOUT (asynchronous pageout, Linux 4.5+) + "populate_write" -> MADV_POPULATE_WRITE (fault every page in writable, Linux 5.14+) Raises ------ @@ -72,7 +78,7 @@ def madvise_range(addr: int, size: int, mode: str = "dontneed") -> None: try: advice = _MADV_ADVICE_BY_MODE[mode] except KeyError: - raise ValueError("mode must be 'pageout' or 'dontneed'.") + raise ValueError("mode must be 'pageout', 'dontneed' or 'populate_write'.") libc = ctypes.CDLL("libc.so.6", use_errno=True) ret = libc.madvise(ctypes.c_void_p(addr), ctypes.c_size_t(size), ctypes.c_int(advice)) if ret != 0: diff --git a/tensorrt_llm/_torch/models/modeling_qwen3.py b/tensorrt_llm/_torch/models/modeling_qwen3.py index ad9ab8911ab9..b168e5bcf8ba 100644 --- a/tensorrt_llm/_torch/models/modeling_qwen3.py +++ b/tensorrt_llm/_torch/models/modeling_qwen3.py @@ -1,3 +1,5 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 import copy from typing import Optional @@ -40,6 +42,9 @@ def __init__( mapping_with_cp: Optional[Mapping] = None, use_gqa_decode_fmha: bool = False, cache_context_plan: bool = False, + fp8_output_gate: bool = False, + context_fmha_head_dim_per_stage_kv: int = 0, + context_last_rows_only: bool = False, ): config = model_config.pretrained_config self.pretrained_config = config @@ -87,6 +92,10 @@ def __init__( mapping_with_cp=mapping_with_cp, use_gqa_decode_fmha=use_gqa_decode_fmha, cache_context_plan=cache_context_plan, + fp8_output_gate=fp8_output_gate, + context_fmha_head_dim_per_stage_kv= + context_fmha_head_dim_per_stage_kv, + context_last_rows_only=context_last_rows_only, ) diff --git a/tensorrt_llm/_torch/models/modeling_qwen3_5.py b/tensorrt_llm/_torch/models/modeling_qwen3_5.py index 13a83f336b81..102a22056502 100644 --- a/tensorrt_llm/_torch/models/modeling_qwen3_5.py +++ b/tensorrt_llm/_torch/models/modeling_qwen3_5.py @@ -694,6 +694,9 @@ class Qwen3_5MoeForCausalLM(Qwen3NextForCausalLM): class that serves the vanilla Qwen3NextForCausalLM architecture. """ + prefill_kernels = True + decode_kernels = True + @classmethod def get_model_defaults(cls, llm_args: "TorchLlmArgs") -> dict: return _get_qwen35_moe_model_defaults(llm_args) @@ -715,6 +718,8 @@ class Qwen3_5ForCausalLM(Qwen3NextForCausalLM): Qwen3NextModel selects GatedMLP for the feed-forward layers. """ + decode_kernels = True + def __init__(self, model_config): keep_lm_head_quant = _lm_head_nvfp4_enabled(model_config) _normalize_qwen35_exclude_modules(model_config, keep_lm_head_quant=keep_lm_head_quant) diff --git a/tensorrt_llm/_torch/models/modeling_qwen3_next.py b/tensorrt_llm/_torch/models/modeling_qwen3_next.py index 555663dc6a98..84bfaac48ccc 100644 --- a/tensorrt_llm/_torch/models/modeling_qwen3_next.py +++ b/tensorrt_llm/_torch/models/modeling_qwen3_next.py @@ -24,7 +24,7 @@ import os from types import SimpleNamespace from typing import (TYPE_CHECKING, Dict, List, Literal, NamedTuple, Optional, - Tuple, Union) + Sequence, Tuple, Union) import torch @@ -41,39 +41,54 @@ fused_sigmoid_gate_mul_add from tensorrt_llm._torch.pyexecutor.config_utils import \ get_qwen3_hybrid_layer_types +from tensorrt_llm._torch.pyexecutor.runtime_hooks import RuntimeHooks from tensorrt_llm._utils import is_blackwell_datacenter, is_sm_120f from tensorrt_llm.models.modeling_utils import QuantConfig from ...logger import logger from ..attention.backends import AttentionMetadata from ..attention.backends.interface import PredefinedAttentionMask +from ..autotuner import AutoTuner from ..distributed import (AllReduce, AllReduceFusionOp, AllReduceParams, MoEAllReduceParams, allgather) +from ..distributed.mnnvl_fused_allreduce import SLOT_MAX_ROWS, TWO_SHOT_ROWS from ..distributed.ops import MNNVLAllReduce +from ..kernels.nvfp4_quant import can_use_nvfp4_quant, nvfp4_fp8_dual_quant from ..model_config import ModelConfig from ..modules.decoder_layer import DecoderLayer -from ..modules.embedding import Embedding +from ..modules.embedding import Embedding, LMHead +from ..modules.expert_l2_prefetch import ExpertL2Prefetch from ..modules.gated_mlp import GatedMLP from ..modules.linear import (FP8QDQLinearMethod, FP8RowwiseLinearMethod, Linear, TensorParallelMode, is_static_nvfp4_input_eligible) -from ..modules.low_m_gemm import (_should_apply_low_m_gemm, apply_low_m_gemm, - low_m_gemm_dispatcher, prepare_low_m_gemm) -from ..modules.low_m_mma_gemm import (fused_shared_expert, +from ..modules.low_m_gemm import (LowMGemmDispatcher, _should_apply_low_m_gemm, + apply_low_m_gemm, low_m_gemm_dispatcher, + low_m_gemm_takes_rows, prepare_low_m_gemm) +from ..modules.low_m_mma_gemm import MAX_M as LOW_M_MAX_ROWS +from ..modules.low_m_mma_gemm import (SHARED_EXPERT_MAX_M, default_tactic, + fused_shared_expert, fused_shared_expert_weights, - warp_mma_supported) + raced_shared_expert, warp_mma_supported) from ..modules.mamba.gdn_mixer import Qwen3NextGatedDeltaNet from ..modules.multi_stream_utils import (do_multi_stream, maybe_execute_in_parallel) from ..modules.rms_norm import RMSNorm -from ..moe.fused_moe import (BaseMoeRoutingMethod, MoEWeightLoadingMode, - RenormalizeMoeRoutingMethod, +from ..moe.fused_moe import (BaseMoeRoutingMethod, ConfigurableMoE, + MoEWeightLoadingMode, RenormalizeMoeRoutingMethod, RenormalizeNaiveMoeRoutingMethod, RoutingMethodType, create_moe) -from ..moe.fused_moe.trtllm_gen.decode_front import (DecodeFront, +from ..moe.fused_moe.impl_contract import MOE_DECODE_OPTIONS, MoEDecodeOptions +from ..moe.fused_moe.trtllm_gen.decode_front import (FUSED_FRONT_MAX_TOKENS, + ROUTER_MAX_TOKENS, + DecodeFront, route_front_steps) +from ..moe.fused_moe.trtllm_gen.decode_moe import (LamportFc2Buffer, + rows_in_lamport) from ..speculative import SpecMetadata -from ..utils import AuxStreamType, EventType, create_lm_head_tp_mapping +from ..speculative.kept_rows import DraftKeptRows, gather_rows2 +from ..utils import (AuxStreamType, EventType, Fp4QuantizedTensor, + create_lm_head_tp_mapping) from .modeling_qwen3 import Qwen3Attention from .modeling_speculative import SpecDecOneEngineForCausalLM from .modeling_utils import (DecoderModel, EagerFusionConfig, @@ -82,6 +97,10 @@ # Most rows of the MTP fc all-reduce fused with the input RMSNorm. _FC_FUSED_NORM_MAX_TOKENS = 1024 +# Most rows of an MTP draft LM head call that races cuBLAS against the low-M +# GEMMs. +_DRAFT_HEAD_LOW_M_MAX_ROWS = 8 + def _is_qwen3_5(model_config: ModelConfig) -> bool: """A Qwen3.5 checkpoint (the Qwen3Next architecture with Qwen3.5 weights).""" @@ -90,9 +109,128 @@ def _is_qwen3_5(model_config: ModelConfig) -> bool: def _uses_decode_kernels(model_config: ModelConfig) -> bool: - """Whether the Qwen3.5 attention / GDN / draft decode paths are built: - a Qwen3.5 checkpoint on SM 10.0 / 10.3.""" - return _is_qwen3_5(model_config) and is_blackwell_datacenter() + """Whether the model class declares the attention / GDN / draft decode + paths (``Qwen3NextForCausalLM.decode_kernels``) on SM 10.0 / 10.3, in a + layout they were tuned for (``_decode_kernels_layout``).""" + return bool(model_config.extra_attrs.get("qwen3_next_decode_kernels", + False)) + + +def _decode_kernels_layout(model_config: ModelConfig) -> bool: + """Whether the layout is one the decode kernels were tuned for: attention + DP, or a TP layout on a multi-node NVLink fabric (GB200 / GB300 NVL + racks), where the MNNVL all-reduce kernels that the TP decode paths + overlap with and fuse into can run, whatever all-reduce strategy is set. + A TP layout without one (the NVLink of an HGX node) keeps the stock + paths. + + Args: + model_config: The target model's config (mapping, torch dtype). + + Returns: + True for attention DP or a TP layout with MNNVL. + """ + mapping = model_config.mapping + if mapping.enable_attention_dp: + return True + return MNNVLAllReduce.is_mnnvl(mapping, + model_config.pretrained_config.torch_dtype, + explicitly_requested=True) + + +def _uses_prefill_kernels(model_config: ModelConfig) -> bool: + """Whether the model class declares the kernels of prefill-sized calls + (``Qwen3NextForCausalLM.prefill_kernels``).""" + return bool( + model_config.extra_attrs.get("qwen3_next_prefill_kernels", False)) + + +def _uses_tp_decode_kernels(model_config: ModelConfig) -> bool: + """The decode kernels of the tensor-parallel layout (no attention DP): the + ones that overlap a layer's GEMMs with its all-reduces.""" + return (_uses_decode_kernels(model_config) + and not model_config.mapping.enable_attention_dp) + + +def _rows_per_request(model_config: ModelConfig) -> int: + """Rows a generation request adds to a decode step (1 + draft tokens).""" + spec_config = model_config.spec_config + return spec_config.tokens_per_gen_step if spec_config is not None else 1 + + +def _decode_step_rows(model_config: ModelConfig) -> int: + """Rows of the largest CUDA-graph decode step (0 without generation CUDA + graphs).""" + return _rows_per_request(model_config) * max( + model_config.cuda_graph_batch_sizes, default=0) + + +# From this many requests of a TP decode step, the input projection after a +# MoE-output all-reduce leaves the low-M race for the resident-weight GEMM, or +# for cuBLAS with its weight pulled into L2 by that all-reduce. +_RESIDENT_MIN_REQUESTS = 2 + + +def _resident_min_rows(model_config: ModelConfig) -> int: + """Rows from which the input projections after a MoE-output all-reduce + take the resident-weight GEMM (``_RESIDENT_MIN_REQUESTS`` requests of a TP + decode step); 0 without the TP decode kernels. + + Args: + model_config: The target model's config. + + Returns: + The band's first row count, or 0. + """ + if not _uses_tp_decode_kernels(model_config): + return 0 + return _RESIDENT_MIN_REQUESTS * _rows_per_request(model_config) + + +# The routed experts' cross-step L2 prefetch (ExpertL2Prefetch) runs from 2 +# requests below the all-reduces' two-shot rows: beside their slot transport at +# more rows, its burst slows the layer chain more than the experts gain. +_EXPERT_PREFETCH_MIN_REQUESTS = 2 +_EXPERT_PREFETCH_MAX_ROWS = TWO_SHOT_ROWS - 1 +# Steps above the one-launch front's rows of at most this many requests +# rank the prefetched experts by routed rows and stop each layer's prefetch +# after its issue budget: there the engine starts streaming soon after. +_EXPERT_PREFETCH_BUDGET_MAX_REQUESTS = 5 +# Issue budget (ns) of a GDN layer's prefetch: measured at 3-5 requests, a +# longer issue overlaps the layer's MoE front and costs chain time. +_EXPERT_PREFETCH_GDN_BUDGET_NS = 18500 +# Same for a full-attention layer, whose mixer reaches the MoE front sooner. +_EXPERT_PREFETCH_ATTN_BUDGET_NS = 12500 +# From this many requests of an MTP decode step, the GDN layers verify on the +# tcgen05 kernel and the decode MoE engine leaves SMs to the shared expert +# running beside it. +_LARGE_STEP_MIN_REQUESTS = 64 + + +def _expert_prefetch_budget_rows(model_config: ModelConfig) -> Tuple[int, int]: + """Rows (exclusive, inclusive) of the steps whose expert prefetch ranks + by routed rows and stops after the layer's issue budget.""" + return (FUSED_FRONT_MAX_TOKENS, _EXPERT_PREFETCH_BUDGET_MAX_REQUESTS * + _rows_per_request(model_config)) + + +def _large_step_rows(model_config: ModelConfig) -> int: + """Rows of a decode step of _LARGE_STEP_MIN_REQUESTS requests (0 without + MTP).""" + if model_config.spec_config is None: + return 0 + return _LARGE_STEP_MIN_REQUESTS * _rows_per_request(model_config) + + +def _verify_tcgen05_min_rows(model_config: ModelConfig) -> int: + """Rows from which an MTP verify step runs the GDN replay on the tcgen05 + kernel: every step under attention DP (a rank holds all of a layer's + heads), large steps with TP attention (0 without MTP).""" + if model_config.spec_config is None: + return 0 + if model_config.mapping.enable_attention_dp: + return _rows_per_request(model_config) + return _large_step_rows(model_config) def _fused_norm_weight(norm: RMSNorm) -> torch.Tensor: @@ -185,6 +323,15 @@ def _allreduce_fp8_payload(model_config: ModelConfig) -> bool: return False +def _fp8_input_projection(layer: nn.Module) -> Optional[Linear]: + """A decoder layer's input projection (GDN in_proj_qkvz / attention qkv_proj), or None.""" + if isinstance(layer, Qwen3NextLinearDecoderLayer): + return layer.linear_attn.in_proj_qkvz + if isinstance(layer, Qwen3NextFullAttentionDecoderLayer): + return layer.self_attn.qkv_proj + return None + + def _fp8_input_scale(layer: nn.Module) -> Optional[torch.Tensor]: """Static input scale of a decoder layer's FP8 per-tensor input projection (GDN in_proj_qkvz / attention qkv_proj), or None.""" @@ -202,6 +349,49 @@ def _fp8_input_scale(layer: nn.Module) -> Optional[torch.Tensor]: return scale.detach() if scale is not None else None +def _next_layer_l2_prefetch(layer: nn.Module, + rows: int) -> Optional[torch.Tensor]: + """The weight the MoE-output all-reduce pulls into L2 for the next layer's + input projection at ``rows`` rows, or None: below ``l2_prefetch_min_rows`` + and where the resident-weight GEMM takes the projection, it loads its + weight itself.""" + w = layer.next_layer_prefetch_weight + if w is None or rows < layer.l2_prefetch_min_rows: + return None + lo, hi = layer.next_layer_resident_rows + if lo <= rows <= hi: + return None + return w + + +def _takes_resident_band(layer: nn.Module, projection: Optional[Linear], + min_rows: int, max_rows: int) -> bool: + """Whether ``projection`` (the next layer's input projection) takes the + resident-weight GEMM from ``min_rows`` to ``max_rows`` rows: this layer's + MoE-output all-reduce hands it an E4M3 input (TP > 1 with POST_MOE_FUSION + and the next layer's FP8 input scale), and ``resident_fp8_gemm`` covers + its (K, N) at every row count of the band. + + Args: + layer: The decoder layer whose MoE-output all-reduce feeds ``projection``. + projection: The next layer's FP8 input projection, or None. + min_rows: The band's first row count (``_resident_min_rows``). + max_rows: Its last (``resident_fp8_gemm.MAX_ROWS``). + + Returns: + True where the band applies. + """ + from ..kernels.blackwell.resident_fp8_gemm import plan + if (projection is None or not min_rows + or layer.next_layer_input_scale is None + or not layer.fusion_config.POST_MOE_FUSION + or layer.mapping.tp_size == 1 or projection._weights_removed): + return False + n, k = projection.weight.shape + return all( + plan(rows, k, n) is not None for rows in range(min_rows, max_rows + 1)) + + def _post_moe_allreduce(layer: nn.Module, mlp_output, residual: torch.Tensor): """The MoE-output all-reduce + residual + ``next_layer_layernorm``; returns (hidden, residual). @@ -226,7 +416,8 @@ def _post_moe_allreduce(layer: nn.Module, mlp_output, residual: torch.Tensor): residual=residual, norm_weight=_fused_norm_weight(norm), scale=scale, - eps=norm.variance_epsilon) + eps=norm.variance_epsilon, + l2_prefetch=_next_layer_l2_prefetch(layer, residual.shape[0])) if isinstance(mlp_output, _DeferredSharedExpertFinalize): routed = mlp_output.routed_output if isinstance(routed, tuple): @@ -238,6 +429,7 @@ def _post_moe_allreduce(layer: nn.Module, mlp_output, residual: torch.Tensor): expert_scale_factor=topk_weights, shared_expert_output=mlp_output.shared_output, shared_expert_gate=mlp_output.shared_gate_logits, + fc2_lamport=mlp_output.fc2_lamport, **common) outputs = layer.allreduce(routed, all_reduce_params=params) else: @@ -251,6 +443,26 @@ def _post_moe_allreduce(layer: nn.Module, mlp_output, residual: torch.Tensor): return outputs +def _post_moe_norm_fold(layer: nn.Module, + mlp_output: "_DeferredSharedExpertFinalize", + residual: torch.Tensor): + """Without a MoE-output all-reduce: the shared-expert gate, residual add, + ``next_layer_layernorm`` and the next layer's FP8 quant in one launch; + returns (hidden, residual) as ``_post_moe_allreduce`` does.""" + from ..kernels.blackwell.gate_add_rmsnorm_fp8 import gate_add_rmsnorm_fp8 + norm = layer.next_layer_layernorm + write_y = layer.next_layer_reads_bf16 + norm_out, fp8 = gate_add_rmsnorm_fp8(mlp_output.routed_output, + mlp_output.shared_output, + mlp_output.shared_gate_logits, + residual, + norm.weight, + norm.variance_epsilon, + layer.next_layer_input_scale, + write_y=write_y) + return (_Fp8HiddenStates(norm_out, fp8) if write_y else fp8), residual + + def _experts_excluded_from_quant(model_config: ModelConfig[Qwen3NextConfig], layer_idx: Optional[int]) -> bool: """Is this layer's routed-experts module listed in ``exclude_modules``? @@ -354,6 +566,9 @@ class _DeferredSharedExpertFinalize(NamedTuple): torch.Tensor] shared_output: torch.Tensor shared_gate_logits: torch.Tensor + # The un-finalized fc2 rows are in the Lamport FC2 buffer (the shared + # expert's stream fenced): the all-reduce polls them. + fc2_lamport: bool = False def _with_moe_backend(model_config: ModelConfig, backend: str) -> ModelConfig: @@ -367,10 +582,63 @@ def _with_moe_backend(model_config: ModelConfig, backend: str) -> ModelConfig: return layer_config +# Context-sized MoE inputs (at least this many tokens) are quantized for the +# routed experts (NVFP4) and the shared expert (FP8) in one pass. +_MOE_INPUT_DUAL_QUANT_MIN_TOKENS = 1024 + + +def _shared_expert_default_tactics_exist(gate_up_weight: torch.Tensor, + down_weight: torch.Tensor) -> bool: + """Whether the warp-MMA kernel has a heuristic tactic (``low_m_mma_gemm.default_tactic``, which an untuned + launch runs) for both launches of the shared expert's low-M path at up to ``SHARED_EXPERT_MAX_M`` rows (the + shared memory grows with the rows): the SwiGLU gate_up launch over the [2I, K] weight and down_proj over + [H, I]. + + Args: + gate_up_weight: The fused gate_up weight [2I, K]. + down_weight: The down_proj weight [H, I]. + + Returns: + False where ``default_tactic`` raises for either launch. + """ + try: + default_tactic(SHARED_EXPERT_MAX_M, gate_up_weight.shape[0], + gate_up_weight.shape[1], True, True) + default_tactic(SHARED_EXPERT_MAX_M, down_weight.shape[0], + down_weight.shape[1], True) + except ValueError: + return False + return True + + class Qwen3NextSparseMoeBlock(nn.Module): # The shared-expert combine can be handed to the MoE-output all-reduce. has_shared_expert = True + # The Qwen3.5 decode kernels (_uses_decode_kernels): the BF16 draft experts' output is finalized in the + # MoE-output all-reduce too. + decode_kernels = False + # Context-sized inputs may be quantized once for both expert paths + # (_moe_input_dual_quant_supported). + moe_input_dual_quant = False + # TP decode kernels: the model's shared Lamport FC2 buffer, which the + # experts of a fold call write and the MoE-output all-reduce polls. + lamport_fc2: Optional[LamportFc2Buffer] = None + # Decided once the weights are loaded: the experts take lamport_fc2. + _experts_take_lamport_fc2 = False + # TP decode: up to this many rows (the largest CUDA-graph decode step's) the + # shared expert's two launches run on their own warp-MMA races + # (raced_shared_expert); 0: the low-M race of the plain projections decides. + _shared_expert_raced_rows = 0 + # Zeroed after the shared expert of a Lamport FC2 call (allocated on first use). + _lamport_fence: Optional[torch.Tensor] = None + # Whether a context-sized input is quantized once for both expert paths + # (_moe_input_dual_quant); decided in cache_derived_state. + _dual_quant_input = False + # Decode kernels with MTP: rows from which the shared expert running beside + # the routed experts takes the SMs their persistent grid can leave free + # (_reserve_sms_for_shared_expert); 0: never. + _shared_expert_reserve_rows = 0 def __init__( self, @@ -378,9 +646,11 @@ def __init__( aux_stream: torch.cuda.Stream, layer_idx: Optional[int] = None, shared_gate_stream: Optional[torch.cuda.Stream] = None, + moe_input_dual_quant: bool = False, ): """``shared_gate_stream``: the shared-expert gate GEMV runs there, beside - the shared expert, instead of after it.""" + the shared expert, instead of after it. ``moe_input_dual_quant``: see + ``_moe_input_dual_quant`` (not with attention DP).""" super().__init__() config = model_config.pretrained_config self.model_config = model_config @@ -391,12 +661,17 @@ def __init__( self.top_k = config.num_experts_per_tok self.enable_attention_dp = model_config.mapping.enable_attention_dp self.mapping = model_config.mapping + self.decode_kernels = _uses_decode_kernels(model_config) + self.moe_input_dual_quant = (moe_input_dual_quant + and not self.enable_attention_dp) self.allreduce = AllReduce(mapping=model_config.mapping, strategy=model_config.allreduce_strategy, dtype=config.torch_dtype) self.aux_stream = aux_stream + if self.decode_kernels: + self._shared_expert_reserve_rows = _large_step_rows(model_config) self.gate = Qwen3NextGate( hidden_size=self.hidden_dim, @@ -476,11 +751,20 @@ def __init__( logger.info(f"Layer {layer_idx} (MTP) MoE experts: bf16 checkpoint " "weights quantized to NVFP4 at load time for " "moe_backend=TRTLLM") + # Qwen3.5's TP decode takes the route front right above the one-launch + # front's steps. self._decode_front = DecodeFront( route_front_steps( model_config.cuda_graph_batch_sizes, spec_config.tokens_per_gen_step - if spec_config is not None else 1)) + if spec_config is not None else 1, + min_rows=(FUSED_FRONT_MAX_TOKENS + + 1) if _uses_tp_decode_kernels(model_config) else + ROUTER_MAX_TOKENS + 1), + decode_kernels=_uses_decode_kernels(model_config), + # The decode engine routes the steps it takes from the router + # GEMM's per-tile candidates. + engine_route=_uses_tp_decode_kernels(model_config)) self.shared_expert = GatedMLP( hidden_size=self.hidden_dim, @@ -516,23 +800,33 @@ def __init__( # padded to 8 rows), or None when the shared expert does not qualify. self._shared_expert_low_m: Optional[Tuple[torch.Tensor, torch.Tensor]] = None + self._shared_expert_raced_rows = ( + min(SHARED_EXPERT_MAX_M, _decode_step_rows(model_config)) + if _uses_tp_decode_kernels(model_config) else 0) def cache_derived_state(self) -> None: self.can_defer_finalize = self._experts_defer_finalize() + self._experts_take_lamport_fc2 = self._experts_take_lamport() self._shared_expert_low_m = self._shared_expert_low_m_weights() + self._dual_quant_input = self._moe_input_dual_quant_supported() def post_load_weights(self) -> None: self.cache_derived_state() def _experts_defer_finalize(self) -> bool: """trtllm-gen NVFP4 experts with in-kernel routing (their do_finalize=False output carries valid top-k - weights) and no MoE communication / load balancer.""" + weights) and no MoE communication / load balancer. With the Qwen3.5 decode kernels also the BF16 + trtllm-gen experts (the MTP draft layer), whose routing kernel writes the BF16 top-k weights it returns with + ``do_finalize=False`` whether it routes from the logits or from precomputed top-k.""" from ..moe.fused_moe.configurable_moe import ConfigurableMoE from ..moe.fused_moe.fused_moe_trtllm_gen import TRTLLMGenFusedMoE from ..moe.fused_moe.interface import FORCE_SEPARATED_ROUTING experts = self.experts backend = experts.backend if isinstance(experts, ConfigurableMoE) else experts + if self.decode_kernels and self._bf16_experts_defer_finalize( + experts, backend): + return True return (isinstance(backend, TRTLLMGenFusedMoE) and backend.has_nvfp4 and not self.enable_attention_dp and not backend._supports_load_balancer() and @@ -541,10 +835,68 @@ def _experts_defer_finalize(self) -> bool: and not experts.routing_method.requires_separated_routing and not FORCE_SEPARATED_ROUTING) - def _shared_expert_low_m_weights(self): + def _reserve_sms_for_shared_expert(self, num_rows: int) -> None: + """Ask the routed experts' backend to keep SMs free of its persistent + grid for the shared expert on this forward + (``MoEImplBase.reserve_sms_for_concurrent_kernels``, up to its + ``sm_reserve_ceiling()``): only where the shared expert runs beside them + (multi-stream on the aux stream) on a decode step of at least + ``_shared_expert_reserve_rows`` rows; otherwise 0, so the grid keeps + every SM. Re-asked per forward: a captured graph bakes the launch's + reserve in.""" + from ..moe.fused_moe.configurable_moe import ConfigurableMoE + if (not self._shared_expert_reserve_rows + or not isinstance(self.experts, ConfigurableMoE) + or torch.compiler.is_compiling()): + return + backend = self.experts.backend + beside = (do_multi_stream() and self.aux_stream is not None + and num_rows >= self._shared_expert_reserve_rows) + backend.reserve_sms_for_concurrent_kernels( + backend.sm_reserve_ceiling() if beside else 0) + + def _experts_take_lamport(self) -> bool: + """Experts that take ``lamport_fc2`` (``takes_lamport_fc2_out``): an + un-finalized call may write its FC2 rows there and then returns the + buffer as its rows, else its own rows.""" + from ..moe.fused_moe.configurable_moe import ConfigurableMoE + experts = self.experts + return (self.can_defer_finalize and isinstance(experts, ConfigurableMoE) + and experts.backend.takes_lamport_fc2_out) + + def _bf16_experts_defer_finalize(self, experts: nn.Module, + backend: nn.Module) -> bool: + """BF16 trtllm-gen experts, no attention DP, no MoE communication, load balancer or + model-owned combine: the MoE-output all-reduce can finalize their (fc2 rows, BF16 top-k weights, + expanded -> permuted index) output. + + Args: + experts: The routed experts module (a ``ConfigurableMoE`` or a backend). + backend: Its MoE backend (``experts`` itself when it is not a ``ConfigurableMoE``). + + Returns: + Whether the MoE-output all-reduce can finalize these experts' un-finalized output. + """ + from ..moe.fused_moe.configurable_moe import ConfigurableMoE + from ..moe.fused_moe.trtllm_gen.trtllm_bf16 import \ + TrtllmTrtllmGenBf16Impl + if not isinstance(backend, TrtllmTrtllmGenBf16Impl): + return False + if not backend.supports_unfinalized_output( + ) or self.enable_attention_dp: + return False + if isinstance(experts, ConfigurableMoE) and ( + experts.comm is not None or experts.layer_load_balancer + is not None or experts.unfinalized_combine_fn is not None): + return False + return True + + def _shared_expert_low_m_weights( + self) -> Optional[Tuple[torch.Tensor, torch.Tensor]]: """Weights of the shared expert's two-launch low-M path (``fused_shared_expert``), built from the loaded - (rescaled) weights, or None when the shared expert does not qualify. A rebuild (weight reload) writes - into the existing copies, whose addresses captured graphs hold. + (rescaled) weights, or None when the shared expert does not qualify (also where the warp-MMA kernel has + no heuristic tactic for a launch, ``_shared_expert_default_tactics_exist``). A rebuild (weight reload) + writes into the existing copies, whose addresses captured graphs hold. """ mlp = self.shared_expert gate_up = getattr(mlp, "gate_up_proj", None) @@ -564,19 +916,44 @@ def _shared_expert_low_m_weights(self): or not mlp._is_plain_swiglu() or mlp.swiglu_limit is not None or gate.bias is not None): return None + if not _shared_expert_default_tactics_exist(gate_up.weight, + down.weight): + return None return fused_shared_expert_weights(gate_up.weight.data, gate.weight, down.weight, out=self._shared_expert_low_m) - def _shared_expert_low_m_forward(self, x: torch.Tensor): - """(shared expert output, gate logits [M, 1]) from two warp-MMA launches, where the low-M race picked - the warp-MMA GEMM for gate_up_proj and down_proj; else None.""" + def _shared_expert_low_m_forward( + self, + x: torch.Tensor) -> Optional[Tuple[torch.Tensor, torch.Tensor]]: + """(shared expert output, gate logits [M, 1]) from two warp-MMA launches: up to + ``_shared_expert_raced_rows`` rows on their own races, else where the low-M race picked the warp-MMA + GEMM for gate_up_proj and down_proj; else None (also for 0 rows, which the warp-MMA GEMM refuses, and + under torch.compile: AutoTuner and CuTe DSL host code).""" weights = self._shared_expert_low_m - if weights is None or x.dim() != 2 or x.dtype != torch.bfloat16: + if (weights is None or x.dim() != 2 or x.dtype != torch.bfloat16 + or x.shape[0] == 0 or torch.compiler.is_compiling()): return None mlp = self.shared_expert gate_up, down = mlp.gate_up_proj, mlp.down_proj + down_input_scale = down.quant_method.get_static_input_scale(down) + if (x.shape[0] <= self._shared_expert_raced_rows + or (self._shared_expert_raced_rows + and AutoTuner.get().is_tuning_mode)): + if self._shared_expert_raced_rows and AutoTuner.get( + ).is_tuning_mode: + self._tune_fused_shared_expert(x, gate_up, down, + down_input_scale) + return raced_shared_expert( + x, + weights, + gate_up_weight_scale=gate_up.weight_scale, + gate_up_input_scale=gate_up.quant_method.get_static_input_scale( + gate_up), + down_weight=down.weight, + down_weight_scale=down.weight_scale, + down_input_scale=down_input_scale) dispatcher = low_m_gemm_dispatcher(gate_up) if dispatcher is None: return None @@ -590,7 +967,89 @@ def _shared_expert_low_m_forward(self, x: torch.Tensor): gate_up), down_weight=down.weight, down_weight_scale=down.weight_scale, - down_input_scale=down.quant_method.get_static_input_scale(down)) + down_input_scale=down_input_scale) + + def _tune_fused_shared_expert(self, x: torch.Tensor, gate_up: Linear, + down: Linear, + down_input_scale: torch.Tensor) -> None: + """Tuning mode: time the low-M races that ``fused_shared_expert`` reads for the rows above + ``_shared_expert_raced_rows`` (the FP8 race of gate_up_proj with a BF16 input and of down_proj with an + E4M3 input), whose stock calls never run while the raced path takes every tuning call. Nothing to tune + where the raced rows reach the low-M GEMM's row bound, so fused_shared_expert never runs. + + Args: + x: The tuning call's [M, K] BF16 shared-expert input. + gate_up: The shared expert's fused gate_up projection (FP8, static input scale). + down: Its down projection (FP8, static input scale). + down_input_scale: down_proj's static input scale. + """ + dispatcher = low_m_gemm_dispatcher(gate_up) + if dispatcher is None or not low_m_gemm_takes_rows( + gate_up, self._shared_expert_raced_rows + 1): + return + # The races time every row bucket of the low-M GEMM whatever rows they are called with. + rows = min(x.shape[0], LOW_M_MAX_ROWS) + dispatcher.apply_fp8( + x[:rows], gate_up.weight, gate_up.weight_scale, + gate_up.quant_method.get_static_input_scale(gate_up), x.dtype) + hidden = torch.zeros((rows, down.weight.shape[1]), + dtype=torch.float8_e4m3fn, + device=x.device) + dispatcher.apply_fp8(hidden, down.weight, down.weight_scale, + down_input_scale, x.dtype) + + def _moe_input_dual_quant_supported(self) -> bool: + """Whether one pass can quantize the MoE input for both expert paths: + the routed experts take an NVFP4 input quantized ahead of them + (``ConfigurableMoE.nvfp4_input_scale``), and the shared expert's fused + gate_up is an FP8 projection with a static input scale.""" + from ..moe.fused_moe.configurable_moe import ConfigurableMoE + if not self.moe_input_dual_quant or not isinstance( + self.experts, ConfigurableMoE): + return False + fp4_scale = self.experts.nvfp4_input_scale(1) + if fp4_scale is None: + return False + mlp = self.shared_expert + if mlp.split_gate_up or mlp._can_fuse_gate_up_swiglu(): + return False + gate_up = mlp.gate_up_proj + if (not isinstance(gate_up.quant_method, FP8QDQLinearMethod) + or gate_up.dtype != torch.bfloat16 + or gate_up._locality_domain_weight_shards is not None): + return False + fp8_scale = gate_up.quant_method.get_static_input_scale(gate_up) + if (fp8_scale is None or fp8_scale.dtype != torch.float32 + or fp8_scale.numel() != 1 + or fp8_scale.device != fp4_scale.device): + return False + return True + + def _moe_input_dual_quant( + self, hidden_states: torch.Tensor, lora_params: Optional[dict] + ) -> Optional[Tuple[Fp4QuantizedTensor, torch.Tensor]]: + """(the routed experts' input as an unswizzled Fp4QuantizedTensor, the + shared expert's E4M3 gate_up input) from one read of a context-sized + BF16 MoE input, or None to quantize per path. The values equal + fp4_quantize (linear SF) and static_quantize_e4m3_per_tensor.""" + # The compile check before the row count: under torch.compile the + # count is symbolic, and comparing it would guard on the row bound. + if (not self._dual_quant_input or lora_params + or torch.compiler.is_compiling() + or hidden_states.shape[0] < _MOE_INPUT_DUAL_QUANT_MIN_TOKENS): + return None + # None as well when the forward would run in more than one MoE chunk. + fp4_scale = self.experts.nvfp4_input_scale(hidden_states.shape[0]) + if fp4_scale is None or not can_use_nvfp4_quant(hidden_states, + fp4_scale): + return None + gate_up = self.shared_expert.gate_up_proj + fp4, sf, fp8 = nvfp4_fp8_dual_quant( + hidden_states, fp4_scale, + gate_up.quant_method.get_static_input_scale(gate_up)) + return Fp4QuantizedTensor(fp4, + sf.view(fp4.shape[0], -1), + is_sf_swizzled=False), fp8 def forward( self, @@ -627,6 +1086,36 @@ def forward( and lora_params is None): raise NotImplementedError( "do_finalize=False needs experts that can defer the finalize") + if (not do_finalize and isinstance(self.experts, ConfigurableMoE) + and hidden_states.shape[0] > self.experts.moe_max_num_tokens): + # The MoE scheduler concatenates the outputs of its chunks, so a + # chunked call hands the fold its finalized output. + do_finalize = True + + # Context sizes: NVFP4 for the routed experts and E4M3 for the shared + # expert's gate_up from one pass; the router and the shared-expert gate + # keep the BF16 input. + # Not with the SM120 attention-DP padding: the routed input then has more rows than the shared one. + dual_quant = None if use_dp_padding else self._moe_input_dual_quant( + hidden_states, lora_params) + shared_input = hidden_states if dual_quant is None else dual_quant[1] + + # On the fold path the experts may write their FC2 rows into the + # Lamport buffer, which the MoE-output all-reduce polls; the shared + # expert's stream is then fenced (shared_fn below). + lamport_out = None + if (self.lamport_fc2 is not None and self._experts_take_lamport_fc2 + and not do_finalize + and hidden_states.shape[0] <= self.lamport_fc2.max_rows + and do_multi_stream() and self.aux_stream is not None + and not torch.compiler.is_compiling()): + lamport_out = self.lamport_fc2.get( + self.hidden_dim, self.experts.intermediate_size_per_partition, + self.top_k, self.experts.expert_size_per_partition, + hidden_states.device) + experts_kwargs = {} if lamport_out is None else { + "lamport_fc2_out": lamport_out + } def _compute_routed_output(): experts = self.experts @@ -637,17 +1126,19 @@ def _compute_routed_output(): all_rank_num_tokens=all_rank_num_tokens, use_dp_padding=use_dp_padding, do_finalize=do_finalize, + **experts_kwargs, ) if out is not None: return out router_logits = self.gate(routed_hidden_states) return experts( - routed_hidden_states, + routed_hidden_states if dual_quant is None else dual_quant[0], router_logits, output_dtype=routed_hidden_states.dtype, all_rank_num_tokens=all_rank_num_tokens, use_dp_padding=use_dp_padding, do_finalize=do_finalize, + **experts_kwargs, ) def _compute_shared_output(): @@ -667,26 +1158,43 @@ def _compute_shared_output(): hidden_states) gate_done.record() shared_expert_output = self.shared_expert( - hidden_states, + shared_input, lora_params=lora_params, ) gate_done.wait() return shared_expert_output, shared_expert_gate_logits shared_expert_output = self.shared_expert( - hidden_states, + shared_input, lora_params=lora_params, ) shared_expert_gate_logits = self.shared_expert_gate(hidden_states) return shared_expert_output, shared_expert_gate_logits - final_hidden_states, shared_expert_outputs = maybe_execute_in_parallel( - _compute_routed_output, - _compute_shared_output, - self.event_dict[EventType.Main], - self.event_dict[EventType.MoeShared], - self.aux_stream, - disable_on_compile=True, - ) + shared_fn = _compute_shared_output + if lamport_out is not None: + if self._lamport_fence is None: + self._lamport_fence = torch.zeros((1, ), + dtype=torch.int32, + device=hidden_states.device) + + def shared_fn(): + outputs = _compute_shared_output() + # The Lamport fold reads these outputs without a dependency + # wait: this plain (non-PDL) kernel orders the all-reduce after + # the aux-stream kernels. + self._lamport_fence.zero_() + return outputs + + self._reserve_sms_for_shared_expert(hidden_states.shape[0]) + (final_hidden_states, + shared_expert_outputs) = maybe_execute_in_parallel( + _compute_routed_output, + shared_fn, + self.event_dict[EventType.Main], + self.event_dict[EventType.MoeShared], + self.aux_stream, + disable_on_compile=True, + ) shared_expert_output, shared_expert_gate_logits = shared_expert_outputs if not do_finalize: @@ -694,6 +1202,8 @@ def _compute_shared_output(): tuple(final_hidden_states), shared_expert_output, shared_expert_gate_logits, + fc2_lamport=rows_in_lamport(final_hidden_states[0], + lamport_out), ) if fold_shared_expert: return _DeferredSharedExpertFinalize( @@ -780,10 +1290,12 @@ def _create_mlp(model_config, aux_stream, layer_idx, shared_gate_stream=None): config = model_config.pretrained_config num_experts = getattr(config, "num_experts", 0) or 0 if num_experts > 0: - return Qwen3NextSparseMoeBlock(model_config, - aux_stream, - layer_idx=layer_idx, - shared_gate_stream=shared_gate_stream) + return Qwen3NextSparseMoeBlock( + model_config, + aux_stream, + layer_idx=layer_idx, + shared_gate_stream=shared_gate_stream, + moe_input_dual_quant=_uses_prefill_kernels(model_config)) return _DenseMlpAdapter( GatedMLP( hidden_size=config.hidden_size, @@ -803,6 +1315,21 @@ class _Qwen3NextDecoderLayerBase(DecoderLayer): decoder layers; ``forward`` runs ``mixer_forward`` (attention / GDN) and the MLP around them.""" + # Set from the next layer by Qwen3NextModel.cache_derived_state: the static + # scale of its FP8 input projection, which the MoE-output all-reduce then + # quantizes for, and whether it also reads the BF16 input. + next_layer_input_scale: Optional[torch.Tensor] = None + next_layer_reads_bf16 = False + # TP decode kernels: the weight of the next layer's input projection, which + # the MNNVL MoE-output all-reduce pulls into L2 from l2_prefetch_min_rows + # rows, except in the rows the resident-weight GEMM takes it. + next_layer_prefetch_weight: Optional[torch.Tensor] = None + l2_prefetch_min_rows = 0 + next_layer_resident_rows: Tuple[int, int] = (1, 0) + # Attention-DP decode kernels: the post-MoE chain runs as one launch + # (_post_moe_norm_fold). + post_moe_norm_fold = False + def _init_common(self, model_config: ModelConfig[Qwen3NextConfig], layer_idx: int, aux_stream: torch.cuda.Stream, shared_gate_stream: Optional[torch.cuda.Stream]) -> None: @@ -834,11 +1361,6 @@ def _init_common(self, model_config: ModelConfig[Qwen3NextConfig], self.allreduce_fp8_payload = _allreduce_fp8_payload(model_config) self.next_layer_layernorm: RMSNorm = None - # Set from the next layer by Qwen3NextForCausalLM.cache_derived_state: - # the static scale of its FP8 input projection, which the MoE-output - # all-reduce then quantizes for, and whether it also reads the BF16 input. - self.next_layer_input_scale: Optional[torch.Tensor] = None - self.next_layer_reads_bf16 = False self.fusion_config = EagerFusionConfig() self.enable_fusion = _eager_fusion_enabled(self.enable_attention_dp) @@ -863,6 +1385,26 @@ def mixer_forward(self, position_ids, hidden_states, attn_metadata, spec_metadata, lora_params, all_reduce_params, **kwargs): raise NotImplementedError + def set_expert_prefetch(self, + prefetch: ExpertL2Prefetch, + issue_budget_ns: int = 0) -> None: + """Prefetch the routed experts this layer used at the previous decode + step into L2, early in the layer (the mixer's own hook point), issuing + for at most ``issue_budget_ns`` in budgeted steps (0: no limit).""" + mlp = self.mlp + if not isinstance(mlp, Qwen3NextSparseMoeBlock): + return + from ..moe.fused_moe.configurable_moe import ConfigurableMoE + experts = mlp.experts + prefetch.register( + self.layer_idx, experts.backend if isinstance( + experts, ConfigurableMoE) else experts, issue_budget_ns) + mlp._decode_front.set_expert_prefetch(prefetch, self.layer_idx) + self._attach_expert_prefetch(prefetch) + + def _attach_expert_prefetch(self, prefetch: ExpertL2Prefetch) -> None: + raise NotImplementedError + def forward( self, position_ids: torch.IntTensor, @@ -871,8 +1413,12 @@ def forward( residual: Optional[torch.Tensor], spec_metadata: Optional[SpecMetadata] = None, lora_params: Optional[dict] = None, + kept_rows: Optional[DraftKeptRows] = None, **kwargs, ) -> torch.Tensor: + """``kept_rows``: the MLP and what follows it run on these rows only + (an MTP draft pass, speculative/kept_rows.py); the caller restores + ``attn_metadata.all_rank_num_tokens``.""" if residual is None: residual = hidden_states hidden_states = self.input_layernorm(hidden_states) @@ -902,6 +1448,12 @@ def forward( hidden_states, residual = self.post_attention_layernorm( hidden_states, residual) + if kept_rows is not None: + hidden_states, residual = gather_rows2(hidden_states, residual, + kept_rows.ids) + if kept_rows.all_rank_counts is not None: + attn_metadata.all_rank_num_tokens = kept_rows.all_rank_counts + # The MoE-output all-reduce combines the shared expert, and finalizes # the experts' output where they can hand it back un-finalized. fold_shared_expert = (self.fusion_config.POST_MOE_FUSION @@ -910,6 +1462,15 @@ def forward( hidden_states.shape[0], self.hidden_size)) do_finalize = not (fold_shared_expert and lora_params is None and self.mlp.can_defer_finalize) + # do_finalize=False only on the fold path: _post_moe_allreduce below + # consumes the un-finalized rows (and resets a Lamport FC2 buffer). + # The MoE block defers its shared-expert finalize to + # _post_moe_norm_fold where no all-reduce follows. + defer_shared_expert_finalize = ( + self.post_moe_norm_fold and lora_params is None + and not torch.compiler.is_compiling() + and not (spec_metadata is not None + and spec_metadata.is_layer_capture(self.layer_idx))) hidden_states = self.mlp( hidden_states, attn_metadata, @@ -918,12 +1479,16 @@ def forward( or self.mapping.tp_size == 1)), do_finalize=do_finalize, lora_params=lora_params, + defer_shared_expert_finalize=defer_shared_expert_finalize, fold_shared_expert=fold_shared_expert, ) if self.fusion_config.POST_MOE_FUSION: hidden_states, residual = _post_moe_allreduce( self, hidden_states, residual) + elif isinstance(hidden_states, _DeferredSharedExpertFinalize): + hidden_states, residual = _post_moe_norm_fold( + self, hidden_states, residual) else: if spec_metadata and spec_metadata.is_layer_capture(self.layer_idx): spec_metadata.maybe_capture_hidden_states( @@ -935,6 +1500,9 @@ def forward( class Qwen3NextLinearDecoderLayer(_Qwen3NextDecoderLayerBase): + # Issues the expert prefetch at the layer's start, while the projections, + # the mixer and the all-reduce leave DRAM idle. + expert_prefetch: Optional[ExpertL2Prefetch] = None linear_attn_cls = Qwen3NextGatedDeltaNet @@ -946,11 +1514,19 @@ def __init__( shared_gate_stream: Optional[torch.cuda.Stream] = None, ): super().__init__() + resident_min_rows = _resident_min_rows(model_config) + # in_proj_ba's replica from one request more. + resident_ba_min_rows = resident_min_rows + 1 if resident_min_rows else 0 self.linear_attn = self.linear_attn_cls( model_config, aux_stream, layer_idx, - fused_verify=_uses_decode_kernels(model_config)) + fused_verify=_uses_decode_kernels(model_config), + resident_min_rows=resident_min_rows, + resident_ba_min_rows=resident_ba_min_rows, + verify_tcgen05_min_rows=_verify_tcgen05_min_rows(model_config) + if _uses_decode_kernels(model_config) else 0, + fused_prefill=_uses_prefill_kernels(model_config)) self._init_common(model_config, layer_idx, aux_stream, shared_gate_stream) @@ -966,9 +1542,15 @@ def forward( if isinstance(hidden_states, _Fp8HiddenStates): # in_proj_qkvz's E4M3 input, made by the previous layer's all-reduce. hidden_states, kwargs["h_fp8"] = hidden_states + if self.expert_prefetch is not None: + self.expert_prefetch.prefetch(self.layer_idx, + hidden_states.shape[0]) return super().forward(position_ids, hidden_states, attn_metadata, residual, *args, **kwargs) + def _attach_expert_prefetch(self, prefetch: ExpertL2Prefetch) -> None: + self.expert_prefetch = prefetch + def mixer_forward(self, position_ids, hidden_states, attn_metadata, spec_metadata, lora_params, all_reduce_params, **kwargs): if hidden_states.shape[0] == 0: @@ -984,9 +1566,16 @@ def mixer_forward(self, position_ids, hidden_states, attn_metadata, class Qwen3NextAttention(Qwen3Attention): - def __init__(self, model_config: ModelConfig[Qwen3NextConfig], - layer_idx: int, fuse_qk_norm_rope: bool): + def __init__(self, + model_config: ModelConfig[Qwen3NextConfig], + layer_idx: int, + fuse_qk_norm_rope: bool, + context_last_rows_only: bool = False): decode_kernels = _uses_decode_kernels(model_config) + prefill_kernels = _uses_prefill_kernels(model_config) + # FP8 paged context attention stages each K / V tile's whole head. + stage_kv_head_dim = (model_config.pretrained_config.head_dim + if prefill_kernels else 0) super().__init__(model_config, layer_idx, fuse_qk_norm_rope=fuse_qk_norm_rope, @@ -994,9 +1583,37 @@ def __init__(self, model_config: ModelConfig[Qwen3NextConfig], use_gemma_rms_norm=True, use_gqa_decode_fmha=decode_kernels, cache_context_plan=decode_kernels - and not model_config.mapping.enable_attention_dp) + and not model_config.mapping.enable_attention_dp, + fp8_output_gate=prefill_kernels, + context_fmha_head_dim_per_stage_kv=stage_kv_head_dim, + context_last_rows_only=context_last_rows_only) self._fuse_qk_norm_rope_gate = True + # Issues the layer's expert prefetch right before o_proj, after the + # attention's KV stream, so that the two do not compete for DRAM. + expert_prefetch: Optional[ExpertL2Prefetch] = None + + def forward_impl(self, q: torch.Tensor, k: Optional[torch.Tensor], + v: Optional[torch.Tensor], *args: object, + **kwargs: object) -> torch.Tensor: + """``Attention.forward_impl``, then this layer's expert prefetch (on + its side stream). + + Args: + q: Query (or fused QKV) rows. + k: Key rows, or None with fused QKV. + v: Value rows, or None with fused QKV. + *args: ``Attention.forward_impl``'s other positional arguments. + **kwargs: Its keyword arguments. + + Returns: + The attention output rows. + """ + attn_output = super().forward_impl(q, k, v, *args, **kwargs) + if self.expert_prefetch is not None: + self.expert_prefetch.prefetch(self.layer_idx, attn_output.shape[0]) + return attn_output + class Qwen3NextFullAttentionDecoderLayer(_Qwen3NextDecoderLayerBase): @@ -1006,7 +1623,8 @@ def __init__(self, model_config: ModelConfig[Qwen3NextConfig], layer_idx: int, aux_stream: torch.cuda.Stream, - shared_gate_stream: Optional[torch.cuda.Stream] = None): + shared_gate_stream: Optional[torch.cuda.Stream] = None, + context_last_rows_only: bool = False): super().__init__() self.self_attn = Qwen3NextAttention( model_config, @@ -1015,10 +1633,14 @@ def __init__(self, # kernel (use_gemma path), so fuse instead of running separate # split + q/k RMSNorm + RoPE kernels. fuse_qk_norm_rope=True, + context_last_rows_only=context_last_rows_only, ) self._init_common(model_config, layer_idx, aux_stream, shared_gate_stream) + def _attach_expert_prefetch(self, prefetch: ExpertL2Prefetch) -> None: + self.self_attn.expert_prefetch = prefetch + def mixer_forward(self, position_ids, hidden_states, attn_metadata, spec_metadata, lora_params, all_reduce_params, **kwargs): kwargs.setdefault("attention_mask", self.attention_mask) @@ -1034,6 +1656,8 @@ def mixer_forward(self, position_ids, hidden_states, attn_metadata, class Qwen3NextMTPHead(nn.Module): + _draft_head_low_m: Optional[LowMGemmDispatcher] = None + def __init__(self, model_config: ModelConfig[Qwen3NextConfig]): super().__init__() config = model_config.pretrained_config @@ -1045,6 +1669,11 @@ def __init__(self, model_config: ModelConfig[Qwen3NextConfig]): use_gemma=True, ) self.mapping_lm_head_tp = None + # This head's own low-M dispatcher (Qwen3.5 decode kernels, no attention DP). Only the draft passes call this + # head (the target's logits come from the LM head directly), so the verify GEMM keeps its path. + self._draft_head_low_m = ( + LowMGemmDispatcher() if _uses_decode_kernels(model_config) + and not model_config.mapping.enable_attention_dp else None) @torch.compile(options={"max-autotune": True}) def get_last_token_states(self, hidden_states, attn_metadata): @@ -1079,9 +1708,24 @@ def forward(self, if not enable_attention_dp or enable_lm_head_tp_in_adp: lm_head.gather_output = False - logits = lm_head(hidden_states, - mapping_lm_head_tp=self.mapping_lm_head_tp, - is_spec_decoding_head=True) + logits = None + if (self._draft_head_low_m is not None + and hidden_states.shape[0] <= _DRAFT_HEAD_LOW_M_MAX_ROWS + and isinstance(lm_head, LMHead) + and lm_head.tp_mode == TensorParallelMode.COLUMN + and lm_head.bias is None and lm_head.lora is None + and not lm_head._writes_output_dtype()): + # This rank's vocabulary shard, the GEMM lm_head(...) runs below with gather_output off. None when the + # rows are not a low-M candidate (more than 32 rows, alignment): then the normal path runs. + logits = self._draft_head_low_m.apply(lm_head, + hidden_states, + lm_head.weight, + None, + force_active=True) + if logits is None: + logits = lm_head(hidden_states, + mapping_lm_head_tp=self.mapping_lm_head_tp, + is_spec_decoding_head=True) if not enable_attention_dp or enable_lm_head_tp_in_adp: lm_head.gather_output = True return logits @@ -1095,9 +1739,14 @@ def __init__(self, model_config: ModelConfig[Qwen3NextConfig], # Some HF checkpoints (e.g. Qwen3.5 NVFP4) keep the whole MTP layer in # bf16. Qwen3NextSparseMoeBlock handles that for every layer, MTP # included, so nothing layer-specific is needed here. - super().__init__(model_config, layer_idx, - aux_stream_dict[AuxStreamType.Attention], - aux_stream_dict.get(AuxStreamType.MoeSharedGate)) + # Only each context request's last row feeds the draft token, so with the prefill kernels this layer's + # context attention computes only those rows. + super().__init__( + model_config, + layer_idx, + aux_stream_dict[AuxStreamType.Attention], + aux_stream_dict.get(AuxStreamType.MoeSharedGate), + context_last_rows_only=_uses_prefill_kernels(model_config)) config = model_config.pretrained_config # The one-launch fc input (modules/q35_mtp_glue.py). self.decode_kernels = _uses_decode_kernels(model_config) @@ -1151,6 +1800,22 @@ def __init__(self, model_config: ModelConfig[Qwen3NextConfig], # (cache_derived_state); its residual output is then the fc sum. self._fc_zero_residual: Optional[torch.Tensor] = None + @staticmethod + def takes_kept_rows(model_config: ModelConfig) -> bool: + """Whether the draft loop hands pass 0 its kept rows (``forward``'s + ``kept_rows``): the decode kernels, with CUDA-graph decode steps of + more than one request.""" + return (_uses_decode_kernels(model_config) + and _decode_step_rows(model_config) + > _rows_per_request(model_config)) + + @staticmethod + def promotes_target_state_beside(model_config: ModelConfig) -> bool: + """Whether the target's recurrent-state promotion after acceptance runs + beside the draft loop: this layer (full attention + MoE) reads no + recurrent state; with the TP decode kernels.""" + return _uses_tp_decode_kernels(model_config) + def cache_derived_state(self) -> None: fc = self.fc if (fc.tp_mode == TensorParallelMode.ROW and fc.tp_size > 1 @@ -1174,12 +1839,15 @@ def forward( all_rank_num_tokens: Optional[List[int]] = None, spec_metadata: Optional[SpecMetadata] = None, kv_lens_increment: int = 0, + kept_rows: Optional[DraftKeptRows] = None, **kwargs, ) -> torch.Tensor: """``kv_lens_increment``: ``attn_metadata.kv_lens_cuda[:n] += 1`` with ``n = kv_lens_increment``, deferred by the draft loop to this pass and applied before anything reads kv_lens (inside the fused input launch - when this pass takes it).""" + when this pass takes it). ``kept_rows``: past attention only these rows + are computed; they come back compact or at their positions (the other + rows zero).""" # Install this draft step's attention-DP token distribution: the draft # loop passes it as a kwarg and leaves attn_metadata alone, matching # Eagle3DraftModel.forward. The MoE below reads the per-rank counts off @@ -1244,8 +1912,13 @@ def forward( attn_metadata=attn_metadata, residual=residual, spec_metadata=spec_metadata, + kept_rows=kept_rows, **kwargs, ) + if kept_rows is not None and not kept_rows.compact: + full = hidden_states.new_zeros((rows, hidden_states.shape[-1])) + full.index_copy_(0, kept_rows.ids, hidden_states) + hidden_states = full # The base forward applied shared_head.norm (next_layer_layernorm). if spec_metadata is not None: spec_metadata.maybe_capture_hidden_states( @@ -1255,7 +1928,7 @@ def forward( finally: # Shared with the target forward, so restore on the exception path # too; otherwise a failed draft step corrupts every later forward. - if all_rank_num_tokens is not None: + if all_rank_num_tokens is not None or kept_rows is not None: attn_metadata.all_rank_num_tokens = previous_all_rank_num_tokens def _fc_input(self, input_ids, hidden_states, embed_tokens, chunked, @@ -1290,6 +1963,10 @@ def norm_hidden(): class Qwen3NextModel(DecoderModel): + # TP decode kernels: the Lamport FC2 buffer its MoE layers share. + lamport_fc2: Optional[LamportFc2Buffer] = None + # TP decode kernels: the routed experts' cross-step L2 prefetch. + expert_prefetch: Optional[ExpertL2Prefetch] = None decoder_layer_types = ALL_DECODER_LAYER_TYPES def __init__(self, model_config: ModelConfig[Qwen3NextConfig]): @@ -1350,6 +2027,15 @@ def __init__(self, model_config: ModelConfig[Qwen3NextConfig]): for layer_idx in range(pretrained_config.num_hidden_layers) ]) self.num_hidden_layers = pretrained_config.num_hidden_layers + if _uses_tp_decode_kernels(model_config): + # Dense (GatedMLP) models have no routed experts to prefetch. + if any( + isinstance(layer.mlp, Qwen3NextSparseMoeBlock) + for layer in self.layers): + self._init_expert_prefetch(model_config) + # Lamport FC2 calls: the slot all-reduce's rows, which poll per token. + self.lamport_fc2 = LamportFc2Buffer(SLOT_MAX_ROWS) + self.share_lamport_fc2(self.layers) self.norm = RMSNorm( hidden_size=pretrained_config.hidden_size, @@ -1358,6 +2044,30 @@ def __init__(self, model_config: ModelConfig[Qwen3NextConfig]): use_gemma=True, ) + def _init_expert_prefetch(self, model_config: ModelConfig) -> None: + """The routed-expert L2 prefetch of the TP decode layouts, attached to every MoE layer.""" + self.aux_stream_dict[ + AuxStreamType.MoeExpertPrefetch] = torch.cuda.Stream() + self.expert_prefetch = ExpertL2Prefetch( + self.num_hidden_layers, + min_rows=_EXPERT_PREFETCH_MIN_REQUESTS * + _rows_per_request(model_config), + max_rows=_EXPERT_PREFETCH_MAX_ROWS, + top_k=model_config.pretrained_config.num_experts_per_tok, + stream=self.aux_stream_dict[AuxStreamType.MoeExpertPrefetch], + budget_rows=_expert_prefetch_budget_rows(model_config)) + for layer in self.layers: + layer.set_expert_prefetch( + self.expert_prefetch, _EXPERT_PREFETCH_GDN_BUDGET_NS + if isinstance(layer, Qwen3NextLinearDecoderLayer) else + _EXPERT_PREFETCH_ATTN_BUDGET_NS) + + def share_lamport_fc2(self, layers: Sequence[nn.Module]) -> None: + """Hand ``lamport_fc2`` to the MoE blocks of ``layers``.""" + for layer in layers: + if isinstance(layer.mlp, Qwen3NextSparseMoeBlock): + layer.mlp.lamport_fc2 = self.lamport_fc2 + def cache_derived_state(self) -> None: # A layer's MoE-output all-reduce also quantizes the next layer's # input for its FP8 input projection (not with LoRA, whose adapters @@ -1369,6 +2079,90 @@ def cache_derived_state(self) -> None: is None else None) layer.next_layer_reads_bf16 = isinstance( next_layer, Qwen3NextLinearDecoderLayer) + if _uses_tp_decode_kernels(self.model_config): + self._cache_tp_decode_gates(layers) + self._drop_expert_prefetch_without_record(layers) + elif _uses_decode_kernels(self.model_config): + self._cache_post_moe_norm_folds(layers) + + def _drop_expert_prefetch_without_record( + self, layers: Sequence[nn.Module]) -> None: + """Unregister from the expert prefetch the layers whose decode front + never records their experts, so that they launch no prefetch on an + empty or stale selection: the front records only in an un-finalized + MoE call, which needs POST_MOE_FUSION, a shared expert, experts that + defer their finalize and an all-reduce that folds the MoE output at + some row count the prefetch takes (``_Qwen3NextDecoderLayerBase.forward``). + + Args: + layers: The decoder layers (not the MTP layers). + """ + prefetch = self.expert_prefetch + if prefetch is None: + return + rows = range(prefetch.min_rows, prefetch.max_rows + 1) + for layer in layers: + mlp = layer.mlp + if (not isinstance(mlp, Qwen3NextSparseMoeBlock) + or not prefetch.registered(layer.layer_idx)): + continue + # The MoE block's own cache_derived_state (can_defer_finalize) may + # run after this one: ask the experts directly. + records = ( + layer.fusion_config.POST_MOE_FUSION and mlp.has_shared_expert + and mlp._experts_defer_finalize() and any( + layer.allreduce.supports_moe_fold(r, layer.hidden_size) + for r in rows)) + if not records: + prefetch.unregister(layer.layer_idx) + + def _cache_post_moe_norm_folds(self, layers: Sequence[nn.Module]) -> None: + """Attention DP: the layers whose MoE output, residual add, + ``next_layer_layernorm`` and the next layer's FP8 quant run as one + launch (_post_moe_norm_fold).""" + from ..kernels.blackwell.gate_add_rmsnorm_fp8 import supports_hidden + config = self.model_config.pretrained_config + if (config.torch_dtype != torch.bfloat16 + or not supports_hidden(config.hidden_size)): + return + for layer in layers: + norm = layer.next_layer_layernorm + layer.post_moe_norm_fold = (layer.next_layer_input_scale is not None + and isinstance(layer.mlp, + Qwen3NextSparseMoeBlock) + and layer.mlp.has_shared_expert + and norm is not None and norm.use_gemma + and not norm.use_cuda_tile) + + def _cache_tp_decode_gates(self, layers: Sequence[nn.Module]) -> None: + """Row gates of the input projections that follow a MoE-output + all-reduce (see _RESIDENT_MIN_REQUESTS).""" + from ..kernels.blackwell.resident_fp8_gemm import \ + MAX_ROWS as resident_max_rows + min_rows = _resident_min_rows(self.model_config) + for layer, next_layer in zip(layers, layers[1:]): + projection = _fp8_input_projection(next_layer) + # Only the MNNVL all-reduce prefetches; remove_weights (layer-wise + # benchmark) leaves the projection without a weight. + prefetch = (projection is not None + and layer.allreduce.mnnvl_allreduce is not None + and not projection._weights_removed) + # A tensor, not the module: a module attribute would register the + # projection as a second child of this layer. + weight = projection.weight.detach() if prefetch else None + layer.next_layer_prefetch_weight = ( + weight if weight is not None and weight.is_cuda + and weight.is_contiguous() and weight.numel() > 0 else None) + layer.l2_prefetch_min_rows = min_rows + if _takes_resident_band(layer, projection, min_rows, + resident_max_rows): + # Its input arrives in E4M3 from this all-reduce: from min_rows + # the resident-weight GEMM takes it instead of the low-M race. + projection.resident_fp8_min_rows = min_rows + layer.next_layer_resident_rows = (min_rows, resident_max_rows) + dispatcher = low_m_gemm_dispatcher(projection) + if dispatcher is not None: + dispatcher.limit_rows(projection, min_rows - 1) def post_load_weights(self) -> None: self.cache_derived_state() @@ -1407,8 +2201,16 @@ def forward( spec_metadata=spec_metadata, mamba_metadata=mamba_metadata, lora_params=lora_params) + self.after_decoder_layers() return hidden_states + def after_decoder_layers(self) -> None: + """What a forward runs after its last decoder layer, also for a caller + that runs the layers itself (the layer-wise benchmark): join the side + stream the layers fork for the expert L2 prefetch.""" + if self.expert_prefetch is not None: + self.expert_prefetch.join() + @register_auto_model("Qwen3NextForCausalLM") class Qwen3NextForCausalLM(SpecDecOneEngineForCausalLM[Qwen3NextModel, @@ -1418,6 +2220,27 @@ class Qwen3NextForCausalLM(SpecDecOneEngineForCausalLM[Qwen3NextModel, load_weights_strips_compile_wrapper = True model_specific_llm_args = frozenset( {"replicate_embedding", "mnnvl_allreduce_fp8_payload"}) + # The fast paths' TP key exchange: temperature rows take the four-draws Gumbel kernel; argmax splits rows. + spec_decode_fast_gumbel = True + spec_decode_argmax_row_split = True + # Declared by a subclass (Qwen3_5MoeForCausalLM): prefill-sized calls run the fused GDN prefill conv, the MoE + # input dual quant, FP8-output attention gates and staged-KV FP8 context attention (_uses_prefill_kernels). + prefill_kernels = False + # Declared by the Qwen3.5 subclasses: on SM 10.0 / 10.3 the attention, GDN, MoE and MTP draft layers build their + # decode paths (_uses_decode_kernels). + decode_kernels = False + # The step-loop hooks of the speculative fast paths (supports_spec_decode_fast_paths): the overlap loop on the + # execution stream, the sampler's Philox state staged with the step inputs, the timing events off the current + # stream. + spec_decode_fast_path_runtime_hooks = RuntimeHooks( + loop_on_execution_stream=True, + pack_spec_rng_uploads=True, + iteration_timing_one_event=True, + perf_metrics_timing_side_stream=True) + # Construction-time declarations of its decode kernels in extra_attrs, kept out of a drafter built from another + # checkpoint (which shares extra_attrs): the MoE decode options and the fused-norm all-reduces. + target_only_extra_attrs = (MOE_DECODE_OPTIONS, "allreduce_mnnvl_fused_norm", + "allreduce_tp2_fused_norm") @classmethod def supports_spec_decode_fast_paths( @@ -1428,12 +2251,37 @@ def __init__( self, model_config: ModelConfig[Qwen3NextConfig], ): + # The prefill and decode kernels were tuned on SM 10.0 / 10.3 only; the + # decode kernels also only in the layouts _decode_kernels_layout names. + if self.prefill_kernels and is_blackwell_datacenter(): + model_config.extra_attrs["qwen3_next_prefill_kernels"] = True + if self.decode_kernels and is_blackwell_datacenter(): + if _decode_kernels_layout(model_config): + model_config.extra_attrs["qwen3_next_decode_kernels"] = True + else: + logger.info("Qwen3.5 decode kernels off: a TP layout " + "without MNNVL (e.g. an HGX node)") decode_kernels = _uses_decode_kernels(model_config) if decode_kernels: - # Its FP4 MoE layers tune for the decode steps. - model_config.extra_attrs["moe_decode_tuning"] = True # Its MNNVL all-reduces run the residual RMSNorm fusions on the CuTe DSL kernels. model_config.extra_attrs["allreduce_mnnvl_fused_norm"] = True + # Its TP2 all-reduces without MNNVL run large residual RMSNorm fusions on Tp2AllReduceNorm. + model_config.extra_attrs["allreduce_tp2_fused_norm"] = True + # FP4 MoE: decode tuning; the engine releases the MoE-output all-reduce after its own wait from its + # two-shot rows; CuTe DSL decode steps (every attention-DP rank's rows) stream FC2 weights evict-first. + # Without attention DP its BF16 TRTLLM-Gen MoE layers (the MTP draft experts) take the BF16 decode MoE + # engine for small logits-routed calls. The SMs the engine leaves to the shared expert are asked per + # forward (Qwen3NextSparseMoeBlock._reserve_sms_for_shared_expert). + no_adp = not model_config.mapping.enable_attention_dp + model_config.extra_attrs[MOE_DECODE_OPTIONS] = MoEDecodeOptions( + tuning=True, + early_release_rows=TWO_SHOT_ROWS, + fc2_weights_evict_first_rows=_decode_step_rows(model_config) * + model_config.mapping.dp_size, + bf16_decode_engine=no_adp) + if no_adp: + # Its temperature verify steps sample and accept in one launch where that launch takes the step. + model_config.extra_attrs["spec_fused_sample_accept"] = True logger.info("Qwen3.5 decode kernels enabled") if (model_config.spec_config is not None and model_config.spec_config.spec_dec_mode.is_mtp_one_model()): @@ -1457,13 +2305,16 @@ def __init__( and model_config.spec_config.spec_dec_mode.is_mtp_one_model()): self.model.layers.extend(self.draft_model.mtp_layers) + if self.model.lamport_fc2 is not None: + self.model.share_lamport_fc2(self.draft_model.mtp_layers) if _is_qwen3_5(model_config): # Decode-sized projections race cuBLAS against the low-M GEMMs. prepare_low_m_gemm( self, force=True, - per_rank_tuning=model_config.mapping.enable_attention_dp) + per_rank_tuning=model_config.mapping.enable_attention_dp, + whole_bucket_direct_tiles=_uses_tp_decode_kernels(model_config)) @classmethod def get_model_defaults(cls, llm_args: 'TorchLlmArgs') -> dict: diff --git a/tensorrt_llm/_torch/models/modeling_speculative.py b/tensorrt_llm/_torch/models/modeling_speculative.py index 4dbe03efac19..5d6468c358f9 100644 --- a/tensorrt_llm/_torch/models/modeling_speculative.py +++ b/tensorrt_llm/_torch/models/modeling_speculative.py @@ -1,11 +1,12 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # +import contextlib import copy import inspect import os from dataclasses import replace -from typing import Dict, Generic, Iterator, List, Optional, Tuple +from typing import ClassVar, Dict, Generic, Iterator, List, Optional, Tuple import torch import torch.nn.functional as F @@ -36,7 +37,7 @@ from ..speculative import (SpecMetadata, get_spec_worker, should_use_separate_draft_kv_cache) from ..speculative.interface import SpeculativeDecodingMode -from ..utils import AuxStreamType +from ..utils import AuxStreamType, is_torch_compiling from .checkpoints.base_weight_mapper import BaseWeightMapper from .modeling_auto import AutoModelForCausalLM from .modeling_utils import (DecoderModel, DecoderModelForCausalLM, TModel, @@ -1450,6 +1451,15 @@ def __init__( raise ValueError( f"Model type {model_type} not supported for MTP") + # Optional layer capabilities: whether its forward takes pass 0's + # ``kept_rows``, and whether the target's recurrent-state promotion + # may run beside the draft loop. + takes_kept_rows = getattr(mtp_layer, "takes_kept_rows", + lambda _: False)(model_config) + promotes_target_state_beside = getattr(mtp_layer, + "promotes_target_state_beside", + lambda _: False)(model_config) + if (spec_config.uses_replacement_heads and getattr(mtp_layer, "uses_shared_lm_head", True)): if model_config.quant_config_dict is not None: @@ -1483,6 +1493,8 @@ def __init__( for layer_idx in range(mtp_num_layers) ]) self.folds_kv_lens_increment = folds_kv_lens_increment + self.takes_kept_rows = takes_kept_rows + self.promotes_target_state_beside = promotes_target_state_beside dwdp_manager = get_global_dwdp_manager() if dwdp_manager is not None and mtp_repeat_count > 1: for layer_idx in range(mtp_num_layers): @@ -1751,8 +1763,47 @@ def get_draft_model(model_config, draft_config, lm_head, model): return builder(model_config, draft_config, lm_head, model) -# The step-loop hooks of a model with the one-engine speculative fast paths. -_FAST_PATH_RUNTIME_HOOKS = RuntimeHooks(loop_on_execution_stream=True) +def drafter_hidden_extra_attrs( + model_cls: type, spec_config: object, + draft_config: Optional[ModelConfig]) -> Tuple[str, ...]: + """The target's ``extra_attrs`` keys to hide while its drafter is built: + the model's ``target_only_extra_attrs`` when the drafter comes from + another checkpoint (an Eagle3 head, an external MTP or PARD / + draft-target drafter; its ``draft_config`` shares the target's + ``extra_attrs``), none for the target's own MTP layers (no + ``draft_config``, or replacement MTP heads of the same architecture). + + Args: + model_cls: The target model class. + spec_config: The speculative config. + draft_config: The drafter's config, or None. + + Returns: + The keys to hide (possibly empty). + """ + if draft_config is None or spec_config.uses_replacement_heads: + return () + return tuple(model_cls.target_only_extra_attrs) + + +@contextlib.contextmanager +def hidden_extra_attrs(extra_attrs: Dict, keys: Tuple[str, + ...]) -> Iterator[None]: + """Remove ``keys`` from ``extra_attrs`` for the block and put back the + values they had (also when the block raises). + + Args: + extra_attrs: A model config's ``extra_attrs``. + keys: The keys to hide; absent ones are skipped. + + Yields: + None. + """ + saved = {key: extra_attrs.pop(key) for key in keys if key in extra_attrs} + try: + yield + finally: + extra_attrs.update(saved) class SpecDecOneEngineForCausalLM(DecoderModelForCausalLM[TModel, TConfig], @@ -1760,11 +1811,27 @@ class SpecDecOneEngineForCausalLM(DecoderModelForCausalLM[TModel, TConfig], # Set per instance from supports_spec_decode_fast_paths in __init__. spec_decode_fast_paths: bool = False + # Declared by the model: under the fast paths, temperature rows of the TP + # key exchange draw Gumbel noise four entries per Philox call (another + # noise stream; TPKeyExchange fast_gumbel). + spec_decode_fast_gumbel: ClassVar[bool] = False + # Declared by the model: under the fast paths, the TP key exchange's + # argmax splits rows by its row-split bounds (TPKeyExchange + # argmax_row_split; same tokens, another launch shape). + spec_decode_argmax_row_split: ClassVar[bool] = False + # Declared by the model: its step-loop hooks under the fast paths (None: + # the defaults). + spec_decode_fast_path_runtime_hooks: ClassVar[Optional[RuntimeHooks]] = None + # Declared by the model: ``extra_attrs`` keys its construction writes for + # its own modules, hidden while a drafter from another checkpoint is built + # (drafter_hidden_extra_attrs). + target_only_extra_attrs: ClassVar[Tuple[str, ...]] = () @property def runtime_hooks(self) -> Optional[RuntimeHooks]: - """The fast paths run the overlap loop on the execution stream.""" - return (_FAST_PATH_RUNTIME_HOOKS + """The model's ``spec_decode_fast_path_runtime_hooks`` under the fast + paths, else None.""" + return (self.spec_decode_fast_path_runtime_hooks if self.spec_decode_fast_paths else None) @classmethod @@ -1811,7 +1878,10 @@ def __init__(self, # only; None elsewhere). from ..distributed import ll_exchange key_exchange = ll_exchange.create_tp_key_exchange( - model_config.mapping, model_config.max_num_tokens) + model_config.mapping, + model_config.max_num_tokens, + fast_gumbel=self.spec_decode_fast_gumbel, + argmax_row_split=self.spec_decode_argmax_row_split) # Only create draft_model for modes MTP, Eagle3 (not SA) if not spec_config.spec_dec_mode.is_sa(): requested_draft_moe_backend = _get_requested_draft_moe_backend( @@ -1890,9 +1960,15 @@ def __init__(self, self.use_separate_draft_kv_cache = should_use_separate_draft_kv_cache( spec_config) - self.draft_model = get_draft_model(model_config, - self.draft_config, - self.lm_head, self.model) + # A drafter of another checkpoint shares extra_attrs: it must + # not build the target's declared decode kernels. + with hidden_extra_attrs( + model_config.extra_attrs, + drafter_hidden_extra_attrs(type(self), spec_config, + self.draft_config)): + self.draft_model = get_draft_model(model_config, + self.draft_config, + self.lm_head, self.model) if spec_config.uses_replacement_heads: self.draft_config = self.draft_model.model_config if self.draft_model is not None: @@ -1954,10 +2030,14 @@ def forward( # copy here instead of one per attention layer that needs them dense. # Not with context requests: a breakable prefill CUDA graph replays its # body against the capture-time position tensor. + # Not under torch.compile: the inference-mode copy differs from the + # position-buffer view context batches pass, so every switch between + # them would recompile; the compiled graph makes its own dense copies. hoist_positions = (self.spec_decode_fast_paths and self.spec_worker is not None and position_ids is not None - and attn_metadata.num_contexts == 0) + and attn_metadata.num_contexts == 0 + and not is_torch_compiling()) if hoist_positions: position_ids = position_ids.contiguous() hidden_states = self.model( diff --git a/tensorrt_llm/_torch/modules/expert_l2_prefetch.py b/tensorrt_llm/_torch/modules/expert_l2_prefetch.py new file mode 100644 index 000000000000..4642cea5eed5 --- /dev/null +++ b/tensorrt_llm/_torch/modules/expert_l2_prefetch.py @@ -0,0 +1,328 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Cross-step L2 prefetch of the routed experts a MoE layer is likely to use at the next decode step. + +At small decode batches DRAM idles through most of a layer's dependency chain, while the experts a layer touches +change slowly between steps; so their FC1 weights are read into L2 while the chain runs, on a side stream forked from +the current one (the main chain's kernels and PDL edges are untouched): + +- record: after the decode front has built a layer's routing tables, a 1-CTA kernel stores the ``num_experts`` local + experts with the most token tiles, or in a budgeted forward the most routed rows (ties: lower id), for the next step; +- prefetch: early in the layer, ``num_ctas`` 1-warp CTAs issue ``cp.async.bulk.prefetch.L2`` of those experts' + ``w3_w1_weight`` / ``w3_w1_weight_scale`` in 64 KiB pieces, in rank order; in a budgeted forward only for the + layer's issue budget after the CTA starts; +- join: the model's forward joins the side stream once, after its last decoder layer. + +The selection only steers prefetches, so outputs are unchanged by construction. Forwards outside +``min_rows``..``max_rows`` rows neither record nor prefetch (decided per captured batch size). +""" + +from types import MappingProxyType +from typing import Mapping, Optional, Tuple + +import torch +import triton +import triton.language as tl + +PIECE = 65536 # bytes per bulk prefetch +NUM_LOCAL_MAX = 128 + + +@triton.jit +def _record_kernel( + batch_ptr, + nct_ptr, + limit_ptr, + sel_ptr, + K: tl.constexpr, + NL: tl.constexpr, + BLOCK: tl.constexpr, + BY_ROWS: tl.constexpr, + TILE: tl.constexpr, +): + """sel[0:K] = the K local experts with the most token tiles in this call, or (BY_ROWS) the most routed rows: + row r of the padded permuted order belongs to tile r // TILE and counts while r < that tile's row limit; -1 + where fewer are touched.""" + n = tl.load(nct_ptr) + if BY_ROWS: + r = tl.arange(0, BLOCK) + t = r // TILE + e = tl.load(batch_ptr + t, mask=t < n, other=NL) + lim = tl.load(limit_ptr + t, mask=t < n, other=0) + e = tl.where((r < lim) & (e >= 0) & (e < NL), e, NL) + else: + offs = tl.arange(0, BLOCK) + e = tl.load(batch_ptr + offs, mask=offs < n, other=NL) + e = tl.where((e >= 0) & (e < NL), e, NL) + cnt = tl.histogram(e, 2 * NL) # bin NL holds the padding + ids = tl.arange(0, 2 * NL) + # key: count high, then the lower id first; experts with no count and the padding bins get key 0 + key = tl.where((ids < NL) & (cnt > 0), cnt * 1024 + (1023 - ids), 0) + key = tl.sort(key, descending=True) + sel = tl.where(key > 0, 1023 - (key % 1024), -1) + tl.store(sel_ptr + ids, sel, mask=ids < K) + + +@triton.jit +def _globaltimer(): + return tl.inline_asm_elementwise( + "mov.u64 $0, %globaltimer;", "=l", [], dtype=tl.int64, is_pure=False, pack=1 + ) + + +@triton.jit +def _issue( + w_ptr, sf_ptr, sel_ptr, per_w, per_sf, piece, k, lane, NPW: tl.constexpr, NPP: tl.constexpr +): + """Item k = (selection slot k // NPP, piece k % NPP) of that expert's [FC1 weight (NPW pieces), FC1 block scales + (NPP - NPW pieces)]: one fire-and-forget bulk L2 prefetch of ``piece`` bytes from lane 0.""" + i = k // NPP + p = k % NPP + e = tl.load(sel_ptr + i) + e64 = tl.maximum(e, 0).to(tl.int64) + pw = tl.minimum(p, NPW - 1).to(tl.int64) + ps = tl.maximum(p - NPW, 0).to(tl.int64) + aw = w_ptr + (e64 * per_w + pw * piece) + lane * 0 + asf = sf_ptr + (e64 * per_sf + ps * piece) + lane * 0 + go = (lane == 0) & (e >= 0) + sz = lane * 0 + piece + rw = tl.inline_asm_elementwise( + "{ .reg .pred q; setp.ne.b32 q, $2, 0; @q cp.async.bulk.prefetch.L2.global [$1], $3; mov.u32 $0, 0; }", + "=r,l,r,r", + [aw, (go & (p < NPW)).to(tl.int32), sz], + dtype=tl.int32, + is_pure=False, + pack=1, + ) + rs = tl.inline_asm_elementwise( + "{ .reg .pred q; setp.ne.b32 q, $2, 0; @q cp.async.bulk.prefetch.L2.global [$1], $3; mov.u32 $0, 0; }", + "=r,l,r,r", + [asf, (go & (p >= NPW)).to(tl.int32), sz], + dtype=tl.int32, + is_pure=False, + pack=1, + ) + return rw + rs + + +@triton.jit(do_not_specialize=["budget_ns"]) +def _prefetch_kernel( + w_ptr, + sf_ptr, + sel_ptr, + sink_ptr, + per_w, + per_sf, + piece, + n_items, + budget_ns, + NPW: tl.constexpr, + NPP: tl.constexpr, + G: tl.constexpr, + TIMED: tl.constexpr, +): + """CTA c issues items c, c + G, ... in rank order (``_issue``) from thread 0 (one thread per CTA in a loop issues + faster than several lanes of one instruction). TIMED: a CTA stops issuing once ``budget_ns`` have passed since + it started (%globaltimer); the prefetches already issued still land.""" + c = tl.program_id(0) + lane = tl.arange(0, 32) + acc = tl.zeros([32], tl.int32) + if TIMED: + t0 = _globaltimer() + t = t0 + k = c + while (k < n_items) & (t - t0 < budget_ns): + acc += _issue(w_ptr, sf_ptr, sel_ptr, per_w, per_sf, piece, k, lane, NPW, NPP) + k += G + t = _globaltimer() + acc += (t - t0).to(tl.int32) + else: + for k in range(c, n_items, G): + acc += _issue(w_ptr, sf_ptr, sel_ptr, per_w, per_sf, piece, k, lane, NPW, NPP) + tl.store(sink_ptr + c * 32 + lane, acc) + + +class _DeviceState: + def __init__(self, device: torch.device, num_layers: int, num_experts: int) -> None: + if torch.cuda.is_current_stream_capturing(): + raise RuntimeError( + "the expert prefetch state must exist before CUDA-graph capture (run one eager " + "forward first)" + ) + self.sel = torch.full((num_layers, num_experts), -1, dtype=torch.int32, device=device) + self.sink = torch.zeros(1 << 12, dtype=torch.int32, device=device) + + +class ExpertL2Prefetch: + """Cross-step expert prefetch of one model (module docstring), for forwards of ``min_rows``..``max_rows`` rows + of a router picking ``top_k`` experts per row, on the model's side ``stream``. Budgeted forwards, of more than + ``budget_rows[0]`` and at most ``budget_rows[1]`` rows, record the experts with the most routed rows instead of + token tiles and stop each layer's prefetch after its issue budget. + + Layers ``register`` the MoE backend that holds their routed FC1 weights (``w3_w1_weight``, + ``w3_w1_weight_scale``: [local experts, ...], contiguous), and the ns after which their prefetch CTAs stop + issuing (0: no limit).""" + + # Each layer prefetches the experts of this many rows' picks, from one CTA per two experts: a slower, gentler + # burst than the whole grid, so the prefetch competes less with the latency-bound chain for DRAM. + PICK_ROWS = 4 + + _state: Optional[_DeviceState] = None + _forked = False # this forward forked the side stream; join() clears it + budget_rows = (0, 0) + num_layers = 0 + min_rows = 0 + max_rows = 0 + num_experts = 0 + num_ctas = 0 + stream: Optional[torch.cuda.Stream] = None + _backends: Mapping[int, torch.nn.Module] = MappingProxyType({}) + _budget_ns: Mapping[int, int] = MappingProxyType({}) + + def __init__( + self, + num_layers: int, + min_rows: int, + max_rows: int, + top_k: int, + stream: torch.cuda.Stream, + budget_rows: Tuple[int, int] = (0, 0), + ) -> None: + self.num_layers = num_layers + self.min_rows = min_rows + self.max_rows = max_rows + self.budget_rows = budget_rows + self.num_experts = min(self.PICK_ROWS * top_k, NUM_LOCAL_MAX) + self.num_ctas = -(-self.num_experts // 2) + self.stream = stream + self._backends = {} + self._budget_ns = {} + + def register(self, layer_idx: int, backend: torch.nn.Module, issue_budget_ns: int = 0) -> None: + if 0 <= layer_idx < self.num_layers: + self._backends[layer_idx] = backend + self._budget_ns[layer_idx] = issue_budget_ns + + def unregister(self, layer_idx: int) -> None: + """Neither record nor prefetch for ``layer_idx`` any more: for a layer whose decode front never records + its experts, a prefetch would only launch on an empty or stale selection. + + Args: + layer_idx: The layer registered with :meth:`register`. + """ + self._backends.pop(layer_idx, None) + self._budget_ns.pop(layer_idx, None) + + def registered(self, layer_idx: int) -> bool: + """Whether ``layer_idx`` records and prefetches (registered and not unregistered).""" + return layer_idx in self._backends + + def takes_rows(self, rows: int) -> bool: + """Whether a forward of ``rows`` rows records and prefetches. Side-stream forks and Triton launches: not + under torch.compile, which is tested first so that a symbolic row count is not compared (dynamo would + guard on the row bounds and recompile when a count crosses one).""" + return not torch.compiler.is_compiling() and self.min_rows <= rows <= self.max_rows + + def budgeted(self, rows: int) -> bool: + lo, hi = self.budget_rows + return lo < rows <= hi + + def _device_state(self, device: torch.device) -> _DeviceState: + if self._state is None: + self._state = _DeviceState(device, self.num_layers, self.num_experts) + return self._state + + def _fork(self) -> None: + self.stream.wait_stream(torch.cuda.current_stream()) + self._forked = True + + def prefetch(self, layer_idx: int, rows: int) -> None: + """Issue the FC1 prefetch of the experts recorded for ``layer_idx`` at the previous step (on the side + stream), for a forward of ``rows`` rows.""" + backend = self._backends.get(layer_idx) + # NVFP4 experts only: the pieces are FC1 weights and their block scales. + if backend is None or not self.takes_rows(rows) or not backend.has_nvfp4: + return + w, sf = backend.w3_w1_weight, backend.w3_w1_weight_scale + if ( + w.dim() != 3 + or w.shape[0] > NUM_LOCAL_MAX + or not w.is_contiguous() + or not sf.is_contiguous() + ): + return + wb, sb = ( + w.view(torch.uint8).view(w.shape[0], -1), + sf.view(torch.uint8).view(sf.shape[0], -1), + ) + per_w, per_sf = wb.shape[1], sb.shape[1] + if per_w % PIECE or per_sf % PIECE: + return + state = self._device_state(w.device) + npw, nps = per_w // PIECE, per_sf // PIECE + budget_ns = self._budget_ns[layer_idx] if self.budgeted(rows) else 0 + self._fork() + with torch.cuda.stream(self.stream): + _prefetch_kernel[(self.num_ctas,)]( + wb, + sb, + state.sel[layer_idx], + state.sink, + per_w, + per_sf, + PIECE, + self.num_experts * (npw + nps), + budget_ns, + NPW=npw, + NPP=npw + nps, + G=self.num_ctas, + TIMED=budget_ns > 0, + num_warps=1, + ) + + def record( + self, + layer_idx: int, + cta_batch: torch.Tensor, + cta_limit: torch.Tensor, + num_ctas: torch.Tensor, + tile: int, + num_local: int, + keep: torch.Tensor, + rows: int, + ) -> None: + """Store the top experts of this call's routing tables for ``tile`` (``cta_batch``: local expert per token + tile, ``cta_limit``: its row limit in the padded permuted order, ``num_ctas``: tile count) for ``layer_idx``'s + next prefetch. ``keep``: the tensor that owns the tables, held for the side stream's read.""" + if ( + layer_idx not in self._backends + or not self.takes_rows(rows) + or num_local > NUM_LOCAL_MAX + ): + return + state = self._device_state(cta_batch.device) + by_rows = self.budgeted(rows) + entries = cta_batch.numel() * tile if by_rows else cta_batch.numel() + block = max(256, triton.next_power_of_2(entries)) + self._fork() + with torch.cuda.stream(self.stream): + _record_kernel[(1,)]( + cta_batch, + num_ctas, + cta_limit, + state.sel[layer_idx], + K=self.num_experts, + NL=NUM_LOCAL_MAX, + BLOCK=block, + BY_ROWS=by_rows, + TILE=tile, + num_warps=4, + ) + keep.record_stream(self.stream) + + def join(self) -> None: + """Join the side stream into the current stream (once per forward, after the last decoder layer). Only a + stream this forward forked: a CUDA-graph capture may not wait on a stream it never forked.""" + if self._forked: + torch.cuda.current_stream().wait_stream(self.stream) + self._forked = False diff --git a/tensorrt_llm/_torch/modules/fla/flashinfer_chunk.py b/tensorrt_llm/_torch/modules/fla/flashinfer_chunk.py index 12b93f668069..4d295d2295b6 100644 --- a/tensorrt_llm/_torch/modules/fla/flashinfer_chunk.py +++ b/tensorrt_llm/_torch/modules/fla/flashinfer_chunk.py @@ -366,7 +366,15 @@ def chunk_gated_delta_rule( # otherwise FI skips the final-state aggregation entirely. need_state = inplace_indexed_state_update or output_final_state final_to_return: Optional[torch.Tensor] = None - if output_final_state and not inplace_indexed_state_update: + # Without a workspace the batch is one group, and FlashInfer writes the final state into this call's own buffer: + # when that buffer is already in the pool dtype it is returned as is (the cast-scatter would be a plain copy). + hand_over_final = ( + output_final_state + and not inplace_indexed_state_update + and state_workspace is None + and state_dtype == initial_state.dtype + ) + if output_final_state and not inplace_indexed_state_update and not hand_over_final: final_to_return = initial_state.new_empty(num_seqs, *initial_state.shape[1:]) # Sequences are independent, so a batch larger than the workspace runs in @@ -400,12 +408,23 @@ def chunk_gated_delta_rule( # --- Step 5: gather initial state (+ cast dtype only when required) # Fuse gather (+ optional cast) and contiguous into a single Triton kernel. - gathered_init = gather_cast_vk_to_fp32_vk( - group_state, - group_indices, - out_dtype=state_dtype, - output=state_workspace[0][:group_seqs] if state_workspace is not None else None, - ) + if ( + group_indices is None + and state_workspace is None + and group_state.dtype == state_dtype + and group_state.is_contiguous() + and group_state.shape[0] == group_seqs + ): + # Already packed [num_seqs, H, V, K] in the kernel's I/O dtype (the in-forward snapshot split gathers + # its rows itself): FlashInfer only reads it, so the gather would be a plain copy. + gathered_init = group_state + else: + gathered_init = gather_cast_vk_to_fp32_vk( + group_state, + group_indices, + out_dtype=state_dtype, + output=state_workspace[0][:group_seqs] if state_workspace is not None else None, + ) # --- Step 6: call FlashInfer with pre-allocated output/state buffers # A q/k/v/output token row is heads x head_size (128) 16-bit values, a multiple @@ -446,6 +465,8 @@ def chunk_gated_delta_rule( # slots named by ``initial_state_indices`` and leaves the rest untouched. if inplace_indexed_state_update: cast_scatter_fp32_vk_to_vk(out_state, group_state, group_indices) + elif hand_over_final: + final_to_return = out_state elif output_final_state: cast_scatter_fp32_vk_to_vk(out_state, final_to_return[seq_lo:seq_hi], None) diff --git a/tensorrt_llm/_torch/modules/linear.py b/tensorrt_llm/_torch/modules/linear.py index 98ace61ec9e8..a674a3da6893 100644 --- a/tensorrt_llm/_torch/modules/linear.py +++ b/tensorrt_llm/_torch/modules/linear.py @@ -52,7 +52,7 @@ get_model_extra_attrs, is_torch_compiling, replace_parameter_and_save_metadata, unswizzle_sf) from .low_m_gemm import (_should_apply_low_m_gemm, apply_low_m_gemm, - low_m_gemm_dispatcher) + low_m_gemm_dispatcher, low_m_gemm_takes_rows) class WeightMode(str, enum.Enum): @@ -895,6 +895,17 @@ def apply(self, module: Linear, input: torch.Tensor, module.dtype or torch.bfloat16) if dispatcher else None if output is not None: return output + if (module.resident_fp8_min_rows > 0 and bias is None + and not torch.compiler.is_compiling() + and input.dtype == torch.float8_e4m3fn and input.dim() == 2 + and input.shape[0] >= module.resident_fp8_min_rows + and (module.dtype or torch.bfloat16) == torch.bfloat16): + # Weights loaded before the PDL wait; bitwise equal to cublas_scaled_mm. + from ..kernels.blackwell import resident_fp8_gemm + if resident_fp8_gemm.supports(input, module.weight): + return resident_fp8_gemm.resident_fp8_gemm( + input, module.weight, module.input_scale, + module.weight_scale) # Handle multi-dimensional inputs (e.g., 3D: batch, seq, hidden) # GEMM ops require 2D matrices original_shape = input.shape @@ -972,8 +983,22 @@ def apply_linear_allreduce_norm( all_reduce_params: AllReduceParams ) -> Optional[Tuple[torch.Tensor, ...]]: """The MNNVL GEMM + all-reduce + residual RMSNorm kernel, where the low-M race picked the warp-MMA - GEMM for this projection (same summation order as the plain projection).""" + GEMM for this projection (same summation order as the plain projection), or, for an E4M3 or BF16 input of + the rows the two-shot kernel takes, the tcgen05 GEMM + two-shot all-reduce kernel (a BF16 input is quantized + as apply() would).""" + # Both kernels are CuTe DSL host launches that torch.compile cannot trace. + if torch.compiler.is_compiling(): + return None static_input_scale = self.get_static_input_scale(module) + if (static_input_scale is not None and module.bias is None + and input.dim() == 2 + and input.dtype in (torch.float8_e4m3fn, torch.bfloat16) + and module.all_reduce is not None): + fused = module.all_reduce.gemm_twoshot_allreduce_norm( + input, module.weight, module.weight_scale, static_input_scale, + all_reduce_params) + if fused is not None: + return fused dispatcher = low_m_gemm_dispatcher(module) if (static_input_scale is None or module.bias is not None or dispatcher is None or input.dim() != 2 @@ -4251,6 +4276,12 @@ def get_quant_method(quant_config: Optional[QuantConfig] = None): class Linear(nn.Module): + # Rows from which an E4M3 input runs the resident-weight FP8 GEMM (0: never); the model sets it on projections + # fed by an all-reduce that releases its dependents early. + resident_fp8_min_rows: int = 0 + # Set by modeling_utils.remove_weights (layer-wise benchmark): the parameters are gone. + _weights_removed: bool = False + def __init__( self, in_features: int, @@ -4732,6 +4763,19 @@ def has_mxfp8(self): return self.quant_config is not None and self.quant_config.layer_quant_mode.has_mxfp8( ) + def static_fp8_input_scale(self, rows: int) -> Optional[torch.Tensor]: + """The static per-tensor scale with which a producer may hand this FP8 QDQ layer its E4M3 input for ``rows`` + rows (the bytes apply() would quantize), or None: other quantization, LoRA, bias, or rows on the low-M + path, whose BF16- and E4M3-input runners are tuned apart.""" + if (type(self.quant_method) is not FP8QDQLinearMethod + or self.lora is not None or self.bias is not None + or low_m_gemm_takes_rows(self, rows)): + return None + scale = self.quant_method.get_static_input_scale(self) + if scale is None or scale.dtype != torch.float32 or scale.numel() != 1: + return None + return scale + def apply_linear(self, input, bias, diff --git a/tensorrt_llm/_torch/modules/low_m_gemm.py b/tensorrt_llm/_torch/modules/low_m_gemm.py index eb6255130c24..0440ac3a8f43 100644 --- a/tensorrt_llm/_torch/modules/low_m_gemm.py +++ b/tensorrt_llm/_torch/modules/low_m_gemm.py @@ -3,7 +3,7 @@ import functools import os -from typing import Any, List, Optional, Tuple +from typing import Any, Dict, List, Optional, Tuple import torch @@ -162,11 +162,16 @@ class _DirectGemmRunner(TunableRunner): inputs: ``[a [M,K] BF16, b_t [K,N] col-major BF16]``. """ - def __init__(self, *, pdl: bool) -> None: + def __init__(self, *, pdl: bool, whole_bucket_tiles: bool = False) -> None: self.pdl = pdl + # Above the exact buckets, offer only 1-row tiles: a tactic timed at a coarse bucket's top must also serve + # every smaller row count of the bucket, or apply() falls back to cuBLAS where it does not. + self.whole_bucket_tiles = whole_bucket_tiles def unique_id(self) -> tuple: - return ("direct", bool(self.pdl)) + return ("direct", bool(self.pdl)) + ( + ("whole_bucket_tiles",) if self.whole_bucket_tiles else () + ) def is_tactic_compatible( self, @@ -210,6 +215,8 @@ def get_valid_tactics( seen.setdefault(dataclasses.astuple(t), None) except ValueError: pass + if self.whole_bucket_tiles and m > _MAX_EXACT_DIRECT_M: + seen = dict.fromkeys((block, outputs, 1) for block, outputs, _ in seen) return list(seen) def forward( @@ -460,15 +467,29 @@ def forward( LOW_M_GEMM_ACTIVE = _parse_enabled() +def low_m_gemm_takes_rows(module: Optional[torch.nn.Module], rows: int) -> bool: + """Whether a GEMM of ``rows`` rows takes the low-M path: the global enable flag (or a dispatcher attached to + ``module``) and the M upper bound (``_MAX_M``, or the module's own ceiling, ``LowMGemmDispatcher.limit_rows``).""" + dispatcher = getattr(module, "_low_m_gemm_dispatcher", None) + if not LOW_M_GEMM_ACTIVE and dispatcher is None: + return False + # The AutoTuner race is host code that torch.compile cannot trace. + if torch.compiler.is_compiling() or rows > _MAX_M: + return False + return dispatcher is None or dispatcher.takes_rows(module, rows) + + def _should_apply_low_m_gemm(input: torch.Tensor, module: Optional[torch.nn.Module] = None) -> bool: - """Fast pre-filter: the global enable flag (or a dispatcher attached to ``module``) and the M upper bound.""" + """Fast pre-filter: :func:`low_m_gemm_takes_rows` for the rows of ``input``, after the enable flag (or a + dispatcher attached to ``module``) and the compile check, which cost no shape reads.""" if not LOW_M_GEMM_ACTIVE and getattr(module, "_low_m_gemm_dispatcher", None) is None: return False - # The AutoTuner race is host code that torch.compile cannot trace. if input.ndim < 1 or torch.compiler.is_compiling(): return False k = int(input.shape[-1]) - return k > 0 and input.numel() <= _MAX_M * k + if k <= 0: + return False + return low_m_gemm_takes_rows(module, input.numel() // k) class LowMGemmDispatcher: @@ -491,6 +512,11 @@ class LowMGemmDispatcher: (M-bucket, K, N) shape it encounters and caches the winner. """ + # The direct kernel's coarse buckets offer only tactics that serve every row count of the bucket. + whole_bucket_direct_tiles: bool = False + # Per module: the most rows it takes on the low-M path (limit_rows); None: no limits. + _max_rows: Optional[Dict[torch.nn.Module, int]] = None + def __init__(self) -> None: # _prepared: runners + TuningConfig have been created (set by _init_runners). self._prepared = False @@ -547,6 +573,10 @@ def attach( if not LOW_M_GEMM_ACTIVE and not force: return for name, module in model.named_modules(): + if getattr(module, "_low_m_gemm_dispatcher", None) is not None: + # A model that prepared its own dispatcher (e.g. Qwen3.5, with its row limits and tactics) keeps it: + # the loader's generic one must not replace it. + continue if module.__class__.__name__.endswith("Linear") or getattr( module, LOW_M_GEMM_OPT_IN_ATTR, False ): @@ -571,7 +601,7 @@ def _init_runners(self) -> None: self._runner_no_bias = _SplitKGemmRunner(has_bias=False, pdl=pdl) self._runner_with_bias = _SplitKGemmRunner(has_bias=True, pdl=pdl) # Direct SIMT runner: no-bias only; wins for M=1 with narrow N on K=8192. - self._direct = _DirectGemmRunner(pdl=pdl) + self._direct = _DirectGemmRunner(pdl=pdl, whole_bucket_tiles=self.whole_bucket_direct_tiles) self._warp_mma = _WarpMmaGemmRunner() # cuBLAS runners — always included as competitors so the AutoTuner can # fall back to cuBLAS for shapes where neither custom kernel is fastest. @@ -617,6 +647,18 @@ def _init_runners(self) -> None: "(split-K tensor-core + SIMT direct vs cuBLAS AutoTuner; best kernel per shape)." ) + def limit_rows(self, module: torch.nn.Module, max_rows: int) -> None: + """Keep ``module`` off the low-M path above ``max_rows`` rows.""" + if self._max_rows is None: + self._max_rows = {} + self._max_rows[module] = max_rows + + def takes_rows(self, module: torch.nn.Module, rows: int) -> bool: + """Whether ``module`` takes the low-M path at ``rows`` rows under its ``limit_rows`` ceiling.""" + if self._max_rows is None: + return True + return rows <= self._max_rows.get(module, _MAX_M) + def prepare( self, model: torch.nn.Module, @@ -906,6 +948,7 @@ def prepare_low_m_gemm( model: torch.nn.Module, force: bool = False, per_rank_tuning: bool = False, + whole_bucket_direct_tiles: bool = False, ) -> LowMGemmDispatcher: """Create a per-engine dispatcher and attach it to every eligible submodule. @@ -926,12 +969,15 @@ def prepare_low_m_gemm( LLM arg). per_rank_tuning: Tune each rank on its own (attention DP: the ranks' projections see different token counts). + whole_bucket_direct_tiles: Race the direct kernel at the coarse M + buckets only with tactics that serve every row count of the bucket. Returns: The newly created :class:`LowMGemmDispatcher` for this engine. """ dispatcher = LowMGemmDispatcher() dispatcher.per_rank_tuning = per_rank_tuning + dispatcher.whole_bucket_direct_tiles = whole_bucket_direct_tiles dispatcher.attach(model, force=force) return dispatcher diff --git a/tensorrt_llm/_torch/modules/low_m_mma_gemm.py b/tensorrt_llm/_torch/modules/low_m_mma_gemm.py index 04d86300d89b..b1cb4a20026e 100644 --- a/tensorrt_llm/_torch/modules/low_m_mma_gemm.py +++ b/tensorrt_llm/_torch/modules/low_m_mma_gemm.py @@ -10,15 +10,24 @@ from __future__ import annotations import functools -from typing import List, Optional, Tuple, Union +from typing import Any, List, Optional, Tuple, Union import torch from ..._utils import is_blackwell_datacenter +from ..autotuner import ( + AutoTuner, + DistributedTuningStrategy, + DynamicTensorSpec, + TunableRunner, + TuningConfig, +) from ..cute_dsl_utils import IS_CUTLASS_DSL_AVAILABLE, graph_safe_cute_tensor from ..flashinfer_utils import get_env_enable_pdl _NUM_SMS_DEFAULT = 148 +# SM100/SM103 opt-in shared memory per block; stands in for the device without CUDA (CPU-only test collection). +_MAX_SMEM_BYTES_DEFAULT = 232448 # Most rows of one launch. MAX_M = 32 @@ -37,6 +46,22 @@ def _num_sms() -> int: return torch.cuda.get_device_properties(torch.cuda.current_device()).multi_processor_count +@functools.lru_cache(maxsize=None) +def _max_smem_bytes() -> int: + """A block's opt-in shared memory on the current device (no tactic fits without one).""" + if not torch.cuda.is_available(): + return _MAX_SMEM_BYTES_DEFAULT + props = torch.cuda.get_device_properties(torch.cuda.current_device()) + return props.shared_memory_per_block_optin + + +def _smem_fits(m: int, k_warps: int, n_tiles: int, ksplit: int) -> bool: + """Whether the kernel's shared memory for ``m`` rows fits a block; mirrors ``LowMMmaGemmKernel.__call__`` + ((k_warps [+ 1 with a K split]) x 16-row tiles x columns per CTA x 4 B).""" + row_tiles = -(-m // 16) + return (k_warps + (ksplit > 1)) * row_tiles * 16 * 8 * n_tiles * 4 <= _max_smem_bytes() + + Tactic = Tuple[int, int, int, int, int] # (k_warps, n_tiles, ksplit, swap_ab, min_blocks) @@ -80,7 +105,7 @@ def default_tactic(m: int, n: int, k: int, fp8: bool = True, even_tiles: bool = continue ctas = n // (8 * n_tiles) for k_warps in (1, 2, 4, 8, 16): - if chunks % k_warps: + if chunks % k_warps or not _smem_fits(m, k_warps, n_tiles, 1): continue per_warp = chunks // k_warps if per_warp * n_tiles * per_chunk > lane_budget: @@ -94,6 +119,20 @@ def default_tactic(m: int, n: int, k: int, fp8: bool = True, even_tiles: bool = return best[1] +def tactic_fits(n: int, k: int, tactic: Tactic, even_tiles: bool = False, m: int = 1) -> bool: + """Whether ``tactic`` (k_warps, n_tiles[, ksplit[, ...]]) tiles an ``m x n x k`` launch (n = weight rows): K in + whole 64-wide chunks per warp and split (the kernel's K check), N in whole 8-row tiles per CTA, an even n_tiles for + a SwiGLU segment, and the shared memory of ``m`` rows within a block's.""" + k_warps, n_tiles = tactic[0], tactic[1] + ksplit = tactic[2] if len(tactic) > 2 else 1 + return ( + k % (64 * k_warps * ksplit) == 0 + and n % (8 * n_tiles) == 0 + and not (even_tiles and n_tiles % 2) + and _smem_fits(m, k_warps, n_tiles, ksplit) + ) + + def candidate_tactics(m: int, n: int, k: int, fp8: bool) -> List[Tactic]: """The tactics the low-M GEMM race times for a plain projection, heuristic first: half, the same and twice the heuristic's warps over K, times 1, 2 or 4 tiles per CTA and K split over a cluster of 1, 2, 4 or 8 CTAs @@ -196,8 +235,9 @@ def _compiled( import cuda.bindings.driver as cuda import cutlass.cute as cute - from ..kernels.blackwell.low_m_mma_gemm import LowMMmaGemmKernel + from ..kernels.blackwell.low_m_mma_gemm import MAX_ROWS, LowMMmaGemmKernel + assert SHARED_EXPERT_MAX_M <= MAX_ROWS kernel = LowMMmaGemmKernel( num_rows=m, k_extent=k, @@ -555,14 +595,161 @@ def fused_shared_expert( return out, gate_logits +# Most rows of the shared expert's raced two-launch path: the kernel's row bound +# (kernels/blackwell/low_m_mma_gemm.MAX_ROWS, checked where the kernel is built). +SHARED_EXPERT_MAX_M = 128 +_SHARED_EXPERT_BUCKETS = (1, 2, 3, 4, 5, 6, 7, 8, 16, 32, 64, SHARED_EXPERT_MAX_M) + + +def _shared_expert_bucket(m: int) -> int: + return next((b for b in _SHARED_EXPERT_BUCKETS if b >= m), SHARED_EXPERT_MAX_M) + + +def _shared_expert_tuning_config() -> TuningConfig: + return TuningConfig( + dynamic_tensor_specs=( + DynamicTensorSpec( + input_idx=0, + dim_idx=0, + gen_tuning_buckets=_SHARED_EXPERT_BUCKETS, + map_to_tuning_buckets=_shared_expert_bucket, + ), + ), + use_cold_l2_cache=True, + use_cuda_graph=True, + # The ranks split the race and all run its winner, as the low-M GEMM race. + distributed_tuning_strategy=DistributedTuningStrategy.PARALLEL, + ) + + +def _shared_expert_tactics(m: int, n: int, k: int, swiglu: bool) -> List[Tactic]: + """The low-M race's warp-MMA candidates for an ``m x n x k`` launch of the shared expert, with whole (gate, up) + tile pairs per CTA for the SwiGLU launch; only tactics that fit this shard and row count.""" + out = {} + for t in candidate_tactics(min(m, MAX_M), n, k, fp8=True): + k_warps, n_tiles, ksplit, swap, min_blocks = t + if swiglu and n_tiles % 2: + n_tiles *= 2 + if m > 8: + swap = 0 + t = (k_warps, n_tiles, ksplit, swap, min_blocks) + if tactic_fits(n, k, t, even_tiles=swiglu, m=m): + out[t] = None + return list(out) + + +class _SharedExpertLaunchRunner(TunableRunner): + """AutoTuner runner of one launch of ``raced_shared_expert``: the SwiGLU gate_up launch (inputs [x [M, K] BF16, + paired gate_up weight, gate rows, weight scale, input scale, down's input scale]) or the down launch (inputs + [E4M3 hidden [M, I], weight, weight scale, input scale]). Tactics: ``_shared_expert_tactics``.""" + + def __init__(self, swiglu: bool) -> None: + self.swiglu = swiglu + + def unique_id(self) -> Tuple[str]: + return ("shared_expert_swiglu" if self.swiglu else "shared_expert_down",) + + def get_valid_tactics( + self, inputs: List[torch.Tensor], profile: Any, **kwargs: Any + ) -> List[Any]: + x, w = inputs[0], inputs[1] + if not warp_mma_supported(): + return [] + return _shared_expert_tactics( + int(x.shape[0]), int(w.shape[0]), int(x.shape[1]), self.swiglu + ) + + def forward( + self, + inputs: List[torch.Tensor], + *, + tactic: Any = -1, + do_preparation: bool = False, + **kwargs: Any, + ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: + x, w = inputs[0], inputs[1] + m, k = int(x.shape[0]), int(x.shape[1]) + if tactic == -1: + tactic = default_tactic(m, int(w.shape[0]), k, True, self.swiglu) + if self.swiglu: + _, gate_rows, weight_scale, input_scale, out_scale = inputs[1:] + inter = w.shape[0] // 2 + return low_m_mma_gemm( + x16=x, + w_fp8=w, + weight_scale=weight_scale, + input_scale=input_scale, + swiglu_fp8=True, + w_bf16=gate_rows, + split_out=inter, + n_valid=inter + 1, + out_scale=out_scale, + out_dtype=torch.bfloat16, + tactic=tuple(tactic), + ) + weight_scale, input_scale = inputs[2], inputs[3] + return low_m_mma_gemm( + x8=x, + w_fp8=w, + weight_scale=weight_scale, + input_scale=input_scale, + fp8_act="fp8", + out_dtype=torch.bfloat16, + tactic=tuple(tactic), + ) + + +def raced_shared_expert( + x: torch.Tensor, + weights: Tuple[torch.Tensor, torch.Tensor], + *, + gate_up_weight_scale: torch.Tensor, + gate_up_input_scale: torch.Tensor, + down_weight: torch.Tensor, + down_weight_scale: torch.Tensor, + down_input_scale: torch.Tensor, +) -> Optional[Tuple[torch.Tensor, torch.Tensor]]: + """``fused_shared_expert``'s two launches for 1-``SHARED_EXPERT_MAX_M`` rows, each on the tactic of its own + AutoTuner race among the warp-MMA candidates (no cuBLAS fallback, so the fused path always runs). Tuning + mode times the races over every row bucket; a call of more rows than the kernel takes returns None.""" + tuner = AutoTuner.get() + if x.shape[0] > SHARED_EXPERT_MAX_M and not tuner.is_tuning_mode: + return None + config = _shared_expert_tuning_config() + pairs, gate_rows = weights + x_in = x[:SHARED_EXPERT_MAX_M] + runner, tactic = tuner.choose_one( + "trtllm::low_m_shared_expert_swiglu", + [_SharedExpertLaunchRunner(swiglu=True)], + config, + [x_in, pairs, gate_rows, gate_up_weight_scale, gate_up_input_scale, down_input_scale], + ) + hidden, gate_logits = runner( + [x_in, pairs, gate_rows, gate_up_weight_scale, gate_up_input_scale, down_input_scale], + tactic=tactic, + ) + runner, tactic = tuner.choose_one( + "trtllm::low_m_shared_expert_down", + [_SharedExpertLaunchRunner(swiglu=False)], + config, + [hidden, down_weight, down_weight_scale, down_input_scale], + ) + out = runner([hidden, down_weight, down_weight_scale, down_input_scale], tactic=tactic) + if x_in.shape[0] != x.shape[0]: + return None + return out, gate_logits + + __all__ = [ "MAX_M", + "SHARED_EXPERT_MAX_M", "candidate_tactics", "conv_supported", "default_tactic", "fused_shared_expert", "fused_shared_expert_weights", "low_m_mma_gemm", + "raced_shared_expert", "swiglu_pairs", "warp_mma_supported", ] diff --git a/tensorrt_llm/_torch/modules/mamba/gdn_inforward_split.py b/tensorrt_llm/_torch/modules/mamba/gdn_inforward_split.py new file mode 100644 index 000000000000..47e969039972 --- /dev/null +++ b/tensorrt_llm/_torch/modules/mamba/gdn_inforward_split.py @@ -0,0 +1,374 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Data movement of the GDN in-forward Mamba snapshot split as four Triton launches. + +Each kernel does the copies of several ``index_select`` / ``index_copy_`` calls of ``_inforward_split_conv_states`` +and ``_inforward_split_prefill_core`` (gdn_mixer.py) at the point in the layer where their inputs are ready. They only +copy (no arithmetic, no dtype change), so every value is bit-identical to the index ops. + +Index tensors are ``InforwardSnapshotSplit`` fields (int64 views of one persistent device buffer); the launch sizes +depend only on host-known counts, so the kernels capture into CUDA graphs. +""" + +from typing import TYPE_CHECKING + +import torch +import triton +import triton.language as tl + +if TYPE_CHECKING: + from .mamba2_metadata import InforwardSnapshotSplit + +# Elements per program along a row. +_BLOCK = 4096 + + +@triton.jit +def _split_conv_state_kernel( + cs_ptr, + stage_ptr, + x_ptr, + tail_slots_ptr, + stage_rows_ptr, + conv_win_ptr, + conv_dim, + stride_cs_b, + stride_cs_c, + stride_cs_l, + stride_st_b, + stride_st_c, + stride_st_l, + stride_x_tok, + W: tl.constexpr, + BLOCK_C: tl.constexpr, +) -> None: + """Split request j: stage its live conv state (the window that ends at the prompt end), then load the window that + ends at P, i.e. the W raw inputs before P (rows conv_win[j * W : (j + 1) * W] of x, oldest first).""" + j = tl.program_id(0) + cols = tl.program_id(1) * BLOCK_C + tl.arange(0, BLOCK_C) + m = cols < conv_dim + slot = tl.load(tail_slots_ptr + j) + row = tl.load(stage_rows_ptr + j) + cs = cs_ptr + slot * stride_cs_b + cols * stride_cs_c + st = stage_ptr + row * stride_st_b + cols * stride_st_c + for w in tl.static_range(W): + tl.store(st + w * stride_st_l, tl.load(cs + w * stride_cs_l, mask=m), mask=m) + tok = tl.load(conv_win_ptr + j * W + w) + tl.store(cs + w * stride_cs_l, tl.load(x_ptr + tok * stride_x_tok + cols, mask=m), mask=m) + + +# The per-batch counts (n_live here, k in _tail_scatter_kernel) only pick a row's branch: not specialized, so one +# compiled variant serves every batch (Triton would otherwise compile 1, multiples of 16 and other counts apart). +@triton.jit(do_not_specialize=["n_live"]) +def _split_state_rows_kernel( + final_ptr, + ssm_ptr, + tail_init_ptr, + live_ptr, + main_rows_ptr, + split_rows_ptr, + n_live, + stride_final, + stride_ssm, + ROW: tl.constexpr, + BLOCK: tl.constexpr, +) -> None: + """Rows r < n_live: ssm[live[r]] = final[main_rows[r]]; rows n_live + j: tail_init[j] = final[split_rows[j]].""" + r = tl.program_id(0) + cols = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK) + m = cols < ROW + if r < n_live: + src = tl.load(main_rows_ptr + r) + dst = ssm_ptr + tl.load(live_ptr + r) * stride_ssm + else: + j = r - n_live + src = tl.load(split_rows_ptr + j) + dst = tail_init_ptr + j.to(tl.int64) * ROW + tl.store(dst + cols, tl.load(final_ptr + src * stride_final + cols, mask=m), mask=m) + + +@triton.jit +def _tail_token_gather_kernel( + q_ptr, + k_ptr, + v_ptr, + g_ptr, + beta_ptr, + qt_ptr, + kt_ptr, + vt_ptr, + gt_ptr, + bt_ptr, + tok_ptr, + stride_q, + stride_k, + stride_v, + stride_g, + stride_beta, + QK_ROW: tl.constexpr, + V_ROW: tl.constexpr, + G_ROW: tl.constexpr, + BLOCK: tl.constexpr, +) -> None: + """Tail token t: q / k / v / g / beta rows of token tail_tok[t] into row t of the compact tail tensors.""" + t = tl.program_id(0) + cols = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK) + tok = tl.load(tok_ptr + t) + t64 = t.to(tl.int64) + mv = cols < V_ROW + tl.store(vt_ptr + t64 * V_ROW + cols, tl.load(v_ptr + tok * stride_v + cols, mask=mv), mask=mv) + mq = cols < QK_ROW + tl.store(qt_ptr + t64 * QK_ROW + cols, tl.load(q_ptr + tok * stride_q + cols, mask=mq), mask=mq) + tl.store(kt_ptr + t64 * QK_ROW + cols, tl.load(k_ptr + tok * stride_k + cols, mask=mq), mask=mq) + mg = cols < G_ROW + tl.store(gt_ptr + t64 * G_ROW + cols, tl.load(g_ptr + tok * stride_g + cols, mask=mg), mask=mg) + tl.store( + bt_ptr + t64 * G_ROW + cols, tl.load(beta_ptr + tok * stride_beta + cols, mask=mg), mask=mg + ) + + +@triton.jit(do_not_specialize=["k"]) +def _tail_scatter_kernel( + tail_final_ptr, + stage_ptr, + tail_out_ptr, + out_ptr, + stage_rows_ptr, + tok_ptr, + k, + stride_stage, + stride_out, + STATE_ROW: tl.constexpr, + OUT_ROW: tl.constexpr, + BLOCK: tl.constexpr, +) -> None: + """Rows r < k: stage[stage_rows[r]] = tail_final[r]; rows k + t: out[tail_tok[t]] = tail_out[t].""" + r = tl.program_id(0) + cols = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK) + if r < k: + m = cols < STATE_ROW + dst = stage_ptr + tl.load(stage_rows_ptr + r) * stride_stage + tl.store( + dst + cols, tl.load(tail_final_ptr + r.to(tl.int64) * STATE_ROW + cols, mask=m), mask=m + ) + else: + t = r - k + m = cols < OUT_ROW + dst = out_ptr + tl.load(tok_ptr + t) * stride_out + tl.store( + dst + cols, tl.load(tail_out_ptr + t.to(tl.int64) * OUT_ROW + cols, mask=m), mask=m + ) + + +def _rows_contiguous(x: torch.Tensor, first: int) -> bool: + """Dims first.. of x are packed (each row of them is one contiguous run).""" + expected = 1 + for d in range(x.dim() - 1, first - 1, -1): + if x.shape[d] != 1 and x.stride(d) != expected: + return False + expected *= x.shape[d] + return True + + +def split_conv_states_ok( + conv_states: torch.Tensor, mixed_qkv: torch.Tensor, stage_conv: torch.Tensor +) -> bool: + """Layout / dtype conditions of split_conv_states (else keep the index ops).""" + return ( + conv_states.dim() == 3 + and stage_conv.dim() == 3 + and mixed_qkv.dim() == 2 + and conv_states.dtype == stage_conv.dtype == mixed_qkv.dtype + and conv_states.shape[1] == stage_conv.shape[1] == mixed_qkv.shape[1] + and conv_states.shape[2] == stage_conv.shape[2] + and mixed_qkv.stride(1) == 1 + ) + + +def split_conv_states( + conv_states: torch.Tensor, + mixed_qkv: torch.Tensor, + split: "InforwardSnapshotSplit", + stage_conv: torch.Tensor, +) -> None: + """``_inforward_split_conv_states`` with the window read from ``mixed_qkv`` itself: stage the split requests' + conv states, then load the raw ``d_conv - 1`` inputs before P. ``mixed_qkv`` must still hold the raw inputs + (the fused prefill conv does not write it).""" + if split.k == 0: + return + width = conv_states.shape[2] + conv_dim = conv_states.shape[1] + block_c = 1024 + _split_conv_state_kernel[(split.k, triton.cdiv(conv_dim, block_c))]( + conv_states, + stage_conv, + mixed_qkv, + split.tail_slots, + split.stage_rows, + split.conv_win, + conv_dim, + conv_states.stride(0), + conv_states.stride(1), + conv_states.stride(2), + stage_conv.stride(0), + stage_conv.stride(1), + stage_conv.stride(2), + mixed_qkv.stride(0), + W=width, + BLOCK_C=block_c, + num_warps=4, + ) + + +def split_core_ok( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + g: torch.Tensor, + beta: torch.Tensor, + final: torch.Tensor, + ssm_states: torch.Tensor, + stage_ssm: torch.Tensor, + core_out: torch.Tensor, +) -> bool: + """Layout / dtype conditions of the three core-side copies (else keep the index ops).""" + qkv_ok = all( + x.dim() == 4 and x.shape[0] == 1 and _rows_contiguous(x, 2) for x in (query, key, value) + ) + gb_ok = all(x.dim() == 3 and x.shape[0] == 1 and x.stride(2) == 1 for x in (g, beta)) + state_ok = ( + final.dim() == 4 + and ssm_states.dim() == 4 + and stage_ssm.dim() == 4 + and final.is_contiguous() + and _rows_contiguous(ssm_states, 1) + and _rows_contiguous(stage_ssm, 1) + and final.dtype == ssm_states.dtype == stage_ssm.dtype + and final.shape[1:] == ssm_states.shape[1:] == stage_ssm.shape[1:] + ) + out_ok = core_out.dim() == 4 and core_out.shape[0] == 1 and _rows_contiguous(core_out, 2) + return ( + qkv_ok + and gb_ok + and state_ok + and out_ok + and query.shape == key.shape + and g.shape == beta.shape + and g.dtype == beta.dtype + and query.dtype == key.dtype + ) + + +def split_state_rows( + final: torch.Tensor, ssm_states: torch.Tensor, split: "InforwardSnapshotSplit" +) -> torch.Tensor: + """``ssm_states.index_copy_(0, live, final.index_select(0, main_rows))`` and + ``final.index_select(0, split_rows)`` (returned: the tails' initial states) in one launch.""" + row = final[0].numel() + tail_init = torch.empty((split.k, *final.shape[1:]), dtype=final.dtype, device=final.device) + n_live = split.live.shape[0] + rows = n_live + split.k + if rows > 0: + _split_state_rows_kernel[(rows, triton.cdiv(row, _BLOCK))]( + final, + ssm_states, + tail_init, + split.live, + split.main_rows, + split.split_rows, + n_live, + final.stride(0), + ssm_states.stride(0), + ROW=row, + BLOCK=_BLOCK, + num_warps=4, + ) + return tail_init + + +def gather_tail_tokens( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + g: torch.Tensor, + beta: torch.Tensor, + split: "InforwardSnapshotSplit", +) -> list[torch.Tensor]: + """``x.index_select(1, tail_tok)`` for query, key, value, g and beta in one launch (contiguous outputs).""" + nt = split.tail_tok.shape[0] + outs = [ + torch.empty((1, nt, *x.shape[2:]), dtype=x.dtype, device=x.device) + for x in (query, key, value, g, beta) + ] + if nt > 0: + qk_row = query.shape[2] * query.shape[3] + v_row = value.shape[2] * value.shape[3] + g_row = g.shape[2] + _tail_token_gather_kernel[(nt, triton.cdiv(max(qk_row, v_row, g_row), _BLOCK))]( + query, + key, + value, + g, + beta, + *outs, + split.tail_tok, + query.stride(1), + key.stride(1), + value.stride(1), + g.stride(1), + beta.stride(1), + QK_ROW=qk_row, + V_ROW=v_row, + G_ROW=g_row, + BLOCK=_BLOCK, + num_warps=4, + ) + return outs + + +def scatter_tail( + tail_final: torch.Tensor, + stage_ssm: torch.Tensor, + tail_out: torch.Tensor, + core_out: torch.Tensor, + split: "InforwardSnapshotSplit", +) -> bool: + """``stage_ssm.index_copy_(0, stage_rows, tail_final)`` and ``core_out[0].index_copy_(0, tail_tok, + tail_out[0])`` in one launch. Returns False (nothing written) when the tensors do not match its conditions.""" + nt = split.tail_tok.shape[0] + if not ( + tail_final.dtype == stage_ssm.dtype + and tail_out.dtype == core_out.dtype + and tail_final.is_contiguous() + and tail_out.is_contiguous() + and tail_final.shape[0] == split.k + and tail_final.shape[1:] == stage_ssm.shape[1:] + and _rows_contiguous(stage_ssm, 1) + and tail_out.dim() == 4 + and tail_out.shape[1] == nt + and core_out.dim() == 4 + and core_out.shape[0] == 1 + and _rows_contiguous(core_out, 2) + and tail_out.shape[2:] == core_out.shape[2:] + ): + return False + state_row = stage_ssm[0].numel() + out_row = core_out.shape[2] * core_out.shape[3] + rows = split.k + nt + if rows > 0: + _tail_scatter_kernel[(rows, triton.cdiv(max(state_row, out_row), _BLOCK))]( + tail_final, + stage_ssm, + tail_out, + core_out, + split.stage_rows, + split.tail_tok, + split.k, + stage_ssm.stride(0), + core_out.stride(1), + STATE_ROW=state_row, + OUT_ROW=out_row, + BLOCK=_BLOCK, + num_warps=4, + ) + return True diff --git a/tensorrt_llm/_torch/modules/mamba/gdn_mixer.py b/tensorrt_llm/_torch/modules/mamba/gdn_mixer.py index ce14f010f5c4..37573335814d 100644 --- a/tensorrt_llm/_torch/modules/mamba/gdn_mixer.py +++ b/tensorrt_llm/_torch/modules/mamba/gdn_mixer.py @@ -60,7 +60,7 @@ ) from ..low_m_gemm import low_m_gemm_dispatcher from ..low_m_mma_gemm import conv_supported, low_m_mma_gemm, warp_mma_supported -from ..multi_stream_utils import maybe_execute_in_parallel_deferred_join +from ..multi_stream_utils import maybe_execute_in_parallel, maybe_execute_in_parallel_deferred_join from ..rms_norm_fp8_per_token import ( rms_norm_gated_fp8_per_token, rms_norm_gated_fp8_per_token_eligible, @@ -72,6 +72,19 @@ fused_gdn_post_conv, pack_gdn_decode_qkv, ) +from .gdn_inforward_split import ( + gather_tail_tokens, + scatter_tail, + split_conv_states, + split_conv_states_ok, + split_core_ok, + split_state_rows, +) +from .gdn_prefill_conv import ( + gdn_prefill_conv_eligible, + gdn_prefill_conv_post, + gdn_prefill_conv_supported, +) from .layernorm_gated import RMSNorm as RMSNormGated from .layernorm_gated import rms_norm_gated_token_major from .mamba2_metadata import InforwardSnapshotSplit, Mamba2Metadata @@ -222,6 +235,7 @@ def _inforward_split_prefill_core( output: Optional[torch.Tensor], *, g_is_linear: bool, + fused_copies: bool = False, ) -> torch.Tensor: """Chunked GDN prefill of a context-only batch with in-forward Mamba snapshots. @@ -240,6 +254,7 @@ def _inforward_split_prefill_core( output: Optional preallocated output. g_is_linear: ``g`` holds ``alpha = exp(g)`` (the FlashInfer gate convention) instead of log space; applies to both scans. Required: the wrong convention gives wrong outputs and states silently. + fused_copies: Run the state / token copies as the bit-identical Triton launches of gdn_inforward_split.py. """ initial = ssm_states.index_select(0, split.gather) core_out, final = chunk_gated_delta_rule( @@ -257,23 +272,39 @@ def _inforward_split_prefill_core( g_is_linear=g_is_linear, ) final = final.to(ssm_states.dtype) - ssm_states.index_copy_(0, split.live, final.index_select(0, split.main_rows)) tail = split.tail_tok + fused = fused_copies and split_core_ok( + query, key, value, g, beta, final, ssm_states, stage_ssm, core_out + ) + if fused: + tail_initial = split_state_rows(final, ssm_states, split) + tail_q, tail_k, tail_v, tail_g, tail_beta = gather_tail_tokens( + query, key, value, g, beta, split + ) + else: + ssm_states.index_copy_(0, split.live, final.index_select(0, split.main_rows)) + tail_q, tail_k, tail_v, tail_g, tail_beta = ( + x.index_select(1, tail) for x in (query, key, value, g, beta) + ) + tail_initial = final.index_select(0, split.split_rows) tail_out, tail_final = chunk_gated_delta_rule( - q=query.index_select(1, tail), - k=key.index_select(1, tail), - v=value.index_select(1, tail), - g=g.index_select(1, tail), - beta=beta.index_select(1, tail), - initial_state=final.index_select(0, split.split_rows), + q=tail_q, + k=tail_k, + v=tail_v, + g=tail_g, + beta=tail_beta, + initial_state=tail_initial, output_final_state=True, cu_seqlens=split.cu_tail, head_first=False, use_qk_l2norm_in_kernel=False, g_is_linear=g_is_linear, ) - stage_ssm.index_copy_(0, split.stage_rows, tail_final.to(stage_ssm.dtype)) - core_out[0].index_copy_(0, tail, tail_out[0].to(core_out.dtype)) + tail_final = tail_final.to(stage_ssm.dtype) + tail_out = tail_out.to(core_out.dtype) + if not (fused and scatter_tail(tail_final, stage_ssm, tail_out, core_out, split)): + stage_ssm.index_copy_(0, split.stage_rows, tail_final) + core_out[0].index_copy_(0, tail, tail_out[0]) return core_out @@ -601,6 +632,18 @@ def post_conv( self._views[("packed",) + key[1:]] = _PackedPostConv(t.squeeze(0) for t in views) return views + def log_gate(self, num_tokens: int, num_v_heads: int, device) -> torch.Tensor: + """``[1, num_tokens, num_v_heads]`` FP32 for a log-space gate nobody reads: gdn_prefill_conv_post's g when + its linear-space alpha goes into ``post_conv``'s g (the buffer FlashInfer's packed views read).""" + key = ("glog", num_tokens, num_v_heads, device) + view = self._views.get(key) + if view is None: + n = num_tokens * num_v_heads + buf = self._flat(("glog", device), n, torch.float32, device) + view = buf[:n].view(1, num_tokens, num_v_heads) + self._views[key] = view + return view + def post_conv_packed( self, num_tokens: int, @@ -799,9 +842,35 @@ def _verify_intermediate_state_indices( return indices[:num_decodes] +def _verify_conv_launch(num_decodes: int, conv_dim: int) -> tuple[Optional[int], Optional[int]]: + """(BLOCK_N, num_warps) of the verify step's conv1d update, or (None, None) for the kernel's default (128, 4). + + Every launch shape computes the same values; steps of many requests take 64-channel programs, whose serial + store chains are half as long. + """ + programs = num_decodes * triton.cdiv(conv_dim, 128) + if num_decodes >= 24 and programs <= 1024: + return 64, 4 + if num_decodes >= 12 and programs <= 1024: + return 64, 2 + return None, None + + class Qwen3NextGatedDeltaNet(nn.Module): # Token-major prefill conv, shared with main's Mamba2 switch (default 1). _token_major_conv = os.environ.get("TRTLLM_MAMBA_TOKEN_MAJOR_CONV", "1") == "1" + # Context-only prefill runs gdn_prefill_conv_post (conv1d + post-conv in one pass over the token-major in_proj + # output); not bitwise to the stock kernels in q / k / v (SiLU form, FP32 order of the q / k L2 norms) and alpha + # (libdevice expf vs tl.exp), see gdn_prefill_conv.py. + fused_prefill_conv: bool = False + # The in-forward snapshot split runs its state / token copies as bit-identical Triton launches. + fused_split_copies: bool = False + # Row gates of the verify step's resident-weight in_proj_qkvz and split-K in_proj_ba (0: never). + resident_min_rows: int = 0 + resident_ba_min_rows: int = 0 + # Row gate of the verify replay + gated norm on the tcgen05 kernel (0: never), and its draft rows per request. + verify_tcgen05_min_rows: int = 0 + verify_tcgen05_tokens: int = 0 def __init__( self, @@ -810,11 +879,24 @@ def __init__( layer_idx: Optional[int] = None, *, fused_verify: bool = False, + resident_min_rows: int = 0, + resident_ba_min_rows: int = 0, + verify_tcgen05_min_rows: int = 0, + fused_prefill: bool = False, ): """Gated DeltaNet mixer. Args: fused_verify: Verify MTP drafts with the fused target-verify kernels where the layer's shapes allow it. + resident_min_rows: From this many rows (0: never), a verify step with an E4M3 input runs in_proj_qkvz + on the resident-weight FP8 GEMM with the conv1d update in its epilogue. The caller keeps it above + the rows the low-M race takes for in_proj_qkvz. + resident_ba_min_rows: From this many rows (0: never), that step's in_proj_ba runs the split-K replica + of cuBLAS with its weights loaded before the PDL wait. + verify_tcgen05_min_rows: From this many rows (0: never), a fused verify step that writes the E4M3 + out_proj input runs the replay + gated RMSNorm on the tcgen05 kernel (gdn_verify_tcgen05). + fused_prefill: Run context-only prefill on the fused conv1d + post-conv kernel and the in-forward + snapshot split's copies on the fused copy kernels, where the layer's shapes allow it. """ super().__init__() config = model_config.pretrained_config @@ -985,6 +1067,8 @@ def __init__( self.aux_stream = aux_stream self._out_proj_fp8_per_token = False + self.resident_min_rows = resident_min_rows + self.resident_ba_min_rows = resident_ba_min_rows self.fused_verify = ( fused_verify and self.head_k_dim == 128 @@ -997,6 +1081,28 @@ def __init__( # The verify in_proj always runs the warp-MMA GEMM with the conv1d update in its epilogue: its low-M race # takes only the tactics that epilogue supports (no split-K), instead of the separate conv1d kernel. self.fuse_conv1d_into_in_proj = self.fused_verify and warp_mma_supported() + if ( + self.fused_verify + and verify_tcgen05_min_rows > 0 + and model_config.spec_config is not None + ): + from ...kernels.blackwell import gdn_verify_tcgen05 as tcgen05 + + tokens = model_config.spec_config.tokens_per_gen_step + hv, hk = self.num_v_heads_per_tp, self.num_k_heads_per_tp + if tcgen05.gdn_verify_tcgen05_supported(tokens, hv, hk, fp8_out=True): + # Compiled by cache_derived_state, once the out_proj quantization is known. + self.verify_tcgen05_min_rows = verify_tcgen05_min_rows + self.verify_tcgen05_tokens = tokens + self.fused_split_copies = fused_prefill + self.fused_prefill_conv = fused_prefill and gdn_prefill_conv_supported( + self.head_k_dim, + self.head_v_dim, + self.conv_kernel_size, + self.activation, + self.conv_dim_per_tp, + self.num_k_heads_per_tp, + ) def setup_aliases(self) -> None: """Move ``in_proj_qkvz.weight`` into the fused projection buffer. @@ -1019,6 +1125,14 @@ def cache_derived_state(self) -> None: # does not register the derived scale into norm's state_dict; the # detached view still shares storage with out_proj.input_scale. self.norm.fp8_scale = scale.detach() if scale is not None else None + if self.verify_tcgen05_min_rows > 0 and self.norm.fp8_scale is not None: + # The tcgen05 verify runs only with an E4M3 out_proj input (_fused_verify_replay_norm): compile it here, + # after loading and before any warm-up step or CUDA-graph capture, for an FP8QDQ out_proj only. + from ...kernels.blackwell import gdn_verify_tcgen05 as tcgen05 + + tcgen05.compile_gdn_verify_tcgen05( + self.verify_tcgen05_tokens, self.num_v_heads_per_tp, self.num_k_heads_per_tp + ) self._refresh_fused_in_proj() def _fused_in_proj_eligible(self) -> bool: @@ -1113,6 +1227,7 @@ def _lowm_in_proj( dispatcher = low_m_gemm_dispatcher(qkvz) if ( dispatcher is None + or not dispatcher.takes_rows(qkvz, hidden_states.shape[0]) or not isinstance(qkvz.quant_method, FP8QDQLinearMethod) or qkvz.bias is not None or ba.bias is not None @@ -1212,16 +1327,28 @@ def _compute_projected_states_qkvz(): def _compute_projected_states_ba(): return self.in_proj_ba(hidden_states_ba) - projected_states_qkvz, projected_states_ba, ba_ready = ( - maybe_execute_in_parallel_deferred_join( - _compute_projected_states_qkvz, + if h_fp8 is not None and self.mapping.enable_attention_dp: + # No quant launch precedes in_proj_qkvz after the post-MoE fold, so in_proj_ba goes first on this + # stream and in_proj_qkvz on the aux stream; otherwise in_proj_qkvz would take the SMs ahead of it. + projected_states_ba, projected_states_qkvz = maybe_execute_in_parallel( _compute_projected_states_ba, + _compute_projected_states_qkvz, self.event_dict[EventType.Main], self.event_dict[EventType.Attention], self.aux_stream, disable_on_compile=True, ) - ) + else: + projected_states_qkvz, projected_states_ba, ba_ready = ( + maybe_execute_in_parallel_deferred_join( + _compute_projected_states_qkvz, + _compute_projected_states_ba, + self.event_dict[EventType.Main], + self.event_dict[EventType.Attention], + self.aux_stream, + disable_on_compile=True, + ) + ) # The weight mapper reorders in_proj rows into the dense per-rank # layouts [Q|K|V|Z] and [b|a] (see grouped_to_dense_in_proj_qkvz_perm), @@ -1344,7 +1471,14 @@ def _fused_verify_replay_norm( ) -> torch.Tensor: """Replay + gated RMSNorm (+ FP8) of convolved q|k|v rows; returns the out_proj input.""" layer_cache = plan.layer_cache - return torch.ops.trtllm.gdn_verify( + verify = torch.ops.trtllm.gdn_verify + if ( + 0 < self.verify_tcgen05_min_rows <= mixed_qkv.shape[0] + and plan.draft_token_num == self.verify_tcgen05_tokens + and self.norm.fp8_scale is not None + ): + from ...kernels.blackwell.gdn_verify_tcgen05 import gdn_verify_tcgen05 as verify + return verify( mixed_qkv, z, a, @@ -1368,17 +1502,13 @@ def _fused_verify_inproj( self, hidden_states: torch.Tensor, h_fp8: Optional[torch.Tensor], - attn_metadata: AttentionMetadata, - spec_metadata: Optional[SpecMetadata], + plan: FusedVerifyPlan, ) -> Optional[torch.Tensor]: """The low-M in_proj with the conv1d update in its epilogue (convolved q|k|v, intermediate windows and conv - state written by the GEMM), then the fused replay + gated RMSNorm: the out_proj input of a decode-only MTP - target-verify step, or None when the step or the in_proj does not qualify.""" + state written by the GEMM), then the fused replay + gated RMSNorm: the out_proj input of the decode-only MTP + target-verify step ``plan`` describes, or None when the in_proj does not qualify.""" if low_m_gemm_dispatcher(self.in_proj_qkvz) is None: return None - plan = self._fused_verify_plan(attn_metadata, spec_metadata, hidden_states.shape[0]) - if plan is None: - return None layer_cache = plan.layer_cache res = self._lowm_in_proj( hidden_states, @@ -1403,6 +1533,89 @@ def _fused_verify_inproj( a = out_ba[:, self.num_v_heads_per_tp :] return self._fused_verify_replay_norm(plan, mixed_qkv, z, a, b) + def _resident_verify_inproj( + self, + hidden_states: torch.Tensor, + h_fp8: Optional[torch.Tensor], + plan: FusedVerifyPlan, + ) -> Optional[torch.Tensor]: + """in_proj_qkvz on the resident-weight FP8 GEMM with the conv1d update in its epilogue (convolved q|k|v, + intermediate windows and conv state written by the GEMM), in_proj_ba on the aux stream, then the fused replay + + gated RMSNorm: the out_proj input of the decode-only MTP target-verify step ``plan`` describes when it has + at least ``resident_min_rows`` rows, or None when the shapes or the caches do not qualify.""" + if ( + not self.resident_min_rows + or h_fp8 is None + or is_torch_compiling() + or hidden_states.shape[0] < self.resident_min_rows + ): + return None + qkvz = self.in_proj_qkvz + if ( + not isinstance(qkvz.quant_method, FP8QDQLinearMethod) + or qkvz.bias is not None + or h_fp8.dtype != torch.float8_e4m3fn + or h_fp8.dim() != 2 + or not h_fp8.is_contiguous() + or qkvz.weight.dtype != torch.float8_e4m3fn + ): + return None + from ...kernels.blackwell import resident_fp8_gemm as resident + + layer_cache = plan.layer_cache + conv = resident.ConvUpdate( + weight=plan.conv_weight, + state=layer_cache.conv, + slots=plan.state_indices, + windows=layer_cache.intermediate_conv_window, + tokens=plan.draft_token_num, + ) + weight = qkvz.weight + if plan.conv_weight.shape[0] != self.conv_dim_per_tp or not resident.supports_conv( + h_fp8, weight, conv + ): + return None + input_scale = qkvz.quant_method.get_static_input_scale(qkvz) + if input_scale is None: + return None + + def _qkvz(): + return resident.resident_fp8_gemm( + h_fp8, weight, input_scale, qkvz.weight_scale, conv=conv + ) + + ba = self.in_proj_ba + ba_replica = None + if 0 < self.resident_ba_min_rows <= hidden_states.shape[0] and ba.bias is None: + from ...kernels.blackwell import inproj_ba_splitk + + if inproj_ba_splitk.supports(hidden_states, ba.weight): + ba_replica = inproj_ba_splitk.ba_splitk + + def _ba(): + if ba_replica is not None: + return ba_replica(hidden_states, ba.weight) + return ba(hidden_states) + + out_qkvz, out_ba, ba_ready = maybe_execute_in_parallel_deferred_join( + _qkvz, + _ba, + self.event_dict[EventType.Main], + self.event_dict[EventType.Attention], + self.aux_stream, + disable_on_compile=True, + ) + num_tokens = out_qkvz.shape[0] + mixed_qkv = out_qkvz[:, : self.conv_dim_per_tp] + z = out_qkvz[:, self.conv_dim_per_tp :].view( + num_tokens, self.num_v_heads_per_tp, self.head_v_dim + ) + b = out_ba[:, : self.num_v_heads_per_tp] + a = out_ba[:, self.num_v_heads_per_tp :] + if ba_ready is not None: + ba_ready.wait() + return self._fused_verify_replay_norm(plan, mixed_qkv, z, a, b) + def _fused_verify( self, mixed_qkv: torch.Tensor, @@ -1410,18 +1623,15 @@ def _fused_verify( a: torch.Tensor, b: torch.Tensor, ba_ready: Optional[torch.cuda.Event], - attn_metadata: AttentionMetadata, - spec_metadata: Optional[SpecMetadata], - ) -> Optional[torch.Tensor]: - """The conv1d update kernel, then the fused replay + gated RMSNorm: the out_proj input of a decode-only MTP - target-verify step whose in_proj did not take the low-M kernel, or None (separate kernels).""" - plan = self._fused_verify_plan(attn_metadata, spec_metadata, mixed_qkv.shape[0]) - if plan is None: - return None + plan: FusedVerifyPlan, + ) -> torch.Tensor: + """The conv1d update kernel, then the fused replay + gated RMSNorm: the out_proj input of the decode-only MTP + target-verify step ``plan`` describes, when its in_proj did not take the low-M kernel.""" num_decodes = plan.num_decodes draft_token_num = plan.draft_token_num layer_cache = plan.layer_cache # As forward_decode's replay branch: PDL chain conv1d -> fused replay. + block_n, num_warps = _verify_conv_launch(num_decodes, mixed_qkv.shape[-1]) conv_out = causal_conv1d_update_triton( mixed_qkv.reshape(num_decodes, draft_token_num, -1).transpose(1, 2), layer_cache.conv, @@ -1436,6 +1646,8 @@ def _fused_verify( launch_dependent_kernels=True, launch_with_pdl_wait=True, hoist_x=True, + _block_n=block_n, + _num_warps=num_warps, ) mixed_qkv = conv_out.transpose(1, 2).reshape(num_decodes * draft_token_num, -1) if ba_ready is not None: @@ -1817,11 +2029,32 @@ def forward_extend( packed: Optional[_PackedPostConv] = None conv_states_to_use = conv_states + # Context-only batches may take the fused prefill conv, which leaves mixed_qkv untouched. Not under + # FORCE_DETERMINISTIC: its q / k L2 norms differ from the stock kernels that prefill next to decodes. + fused_conv = ( + num_decode_tokens == 0 + and self.fused_prefill_conv + and os.getenv("FORCE_DETERMINISTIC", "0") != "1" + and gdn_prefill_conv_eligible( + mixed_qkv, + self.conv1d.weight, + conv_states_to_use, + query_start_loc, + cache_indices, + has_initial_states, + ) + ) + inforward_window = None if inforward_split is not None: if num_decode_tokens > 0 or is_target_verify: raise RuntimeError("In-forward Mamba snapshots need a context-only batch") - # The convolution state at P: the d_conv - 1 raw inputs before P. - inforward_window = mixed_qkv.index_select(0, inforward_split.conv_win) + if not ( + fused_conv + and self.fused_split_copies + and split_conv_states_ok(conv_states, mixed_qkv, kwargs["inforward_stage"][1]) + ): + # The convolution state at P: the d_conv - 1 raw inputs before P. + inforward_window = mixed_qkv.index_select(0, inforward_split.conv_win) if num_decode_tokens > 0: mixed_qkv_p = mixed_qkv[:num_prefill_tokens] @@ -1923,6 +2156,27 @@ def forward_extend( query, key, value, g, beta, packed = self._post_conv( mixed_qkv_p_t, None, a[:num_prefill_tokens], b[:num_prefill_tokens], g_linear ) + elif fused_conv: + query, key, value, g, beta, packed = self._fused_prefill_conv_post( + mixed_qkv, + conv_states_to_use, + query_start_loc, + cache_indices, + has_initial_states, + a, + b, + g_linear, + ) + if inforward_split is not None: + if inforward_window is None: + # One launch: stage the live states, then load the window at P straight from mixed_qkv. + split_conv_states( + conv_states, mixed_qkv, inforward_split, kwargs["inforward_stage"][1] + ) + else: + _inforward_split_conv_states( + conv_states, inforward_window, inforward_split, kwargs["inforward_stage"][1] + ) else: mixed_qkv_t = self._prefill_conv( mixed_qkv, conv_states_to_use, has_initial_states, cache_indices, query_start_loc @@ -2073,6 +2327,7 @@ def forward_extend( kwargs["inforward_stage"][0], output, g_is_linear=g_linear, + fused_copies=self.fused_split_copies, ) if ( @@ -2342,6 +2597,67 @@ def _post_conv(self, prefill_t: torch.Tensor, decode, a, b, g_linear: bool): ) return q, k, v, g, beta, packed + def _fused_prefill_conv_post( + self, + mixed_qkv: torch.Tensor, + conv_states: torch.Tensor, + query_start_loc: torch.Tensor, + cache_indices: torch.Tensor, + has_initial_states: torch.Tensor, + a: torch.Tensor, + b: torch.Tensor, + g_linear: bool, + ) -> Tuple[ + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + Optional[_PackedPostConv], + ]: + """gdn_prefill_conv_post on the scratch buffers ``_post_conv`` fills: ``(q, k, v, g, beta, packed)`` with + ``packed`` the ``_PackedPostConv`` of the same buffers. With ``g_linear`` the kernel writes alpha = exp(g) + into the scratch g (what the scans and ``packed`` read) and its log-space g into a scratch nobody reads.""" + num_tokens = mixed_qkv.shape[0] + shape = ( + num_tokens, + self.num_k_heads_per_tp, + self.head_k_dim, + self.num_v_heads_per_tp, + self.head_v_dim, + mixed_qkv.dtype, + mixed_qkv.device, + ) + scratch = _prefill_scratch() + log_g = ( + scratch.log_gate(num_tokens, self.num_v_heads_per_tp, mixed_qkv.device) + if g_linear + else None + ) + q, k, v, g, beta = scratch.post_conv(*shape) + packed = scratch.post_conv_packed(*shape) + gdn_prefill_conv_post( + mixed_qkv, + self.conv1d.weight, + self.conv1d.bias, + conv_states, + query_start_loc, + cache_indices, + has_initial_states, + a, + b, + self.A_log, + self.dt_bias, + self.num_k_heads_per_tp, + self.head_k_dim, + self.num_v_heads_per_tp, + self.head_v_dim, + activation=self.activation, + alpha_out=g if g_linear else None, + out=(q, k, v, log_g if g_linear else g, beta), + ) + return q, k, v, g, beta, packed + def _reset_prefill_states( self, attn_metadata: AttentionMetadata, @@ -2392,13 +2708,18 @@ def forward( all_reduce_params: Optional[AllReduceParams] = None, h_fp8: Optional[torch.Tensor] = None, ): - fused = self._fused_verify_inproj(hidden_states, h_fp8, attn_metadata, spec_metadata) - if fused is not None: - return self.out_proj(fused, all_reduce_params=all_reduce_params) + # Built once per layer and step; the three fused verify paths below share it. + plan = self._fused_verify_plan(attn_metadata, spec_metadata, hidden_states.shape[0]) + if plan is not None: + fused = self._fused_verify_inproj(hidden_states, h_fp8, plan) + if fused is None: + fused = self._resident_verify_inproj(hidden_states, h_fp8, plan) + if fused is not None: + return self.out_proj(fused, all_reduce_params=all_reduce_params) mixed_qkv, z, a, b, ba_ready = self._compute_tokenwise_inputs(hidden_states, h_fp8) - fused = self._fused_verify(mixed_qkv, z, a, b, ba_ready, attn_metadata, spec_metadata) - if fused is not None: + if plan is not None: + fused = self._fused_verify(mixed_qkv, z, a, b, ba_ready, plan) return self.out_proj(fused, all_reduce_params=all_reduce_params) # Every path below reads a / b. if ba_ready is not None: diff --git a/tensorrt_llm/_torch/modules/mamba/gdn_prefill_conv.py b/tensorrt_llm/_torch/modules/mamba/gdn_prefill_conv.py new file mode 100644 index 000000000000..3eff13884920 --- /dev/null +++ b/tensorrt_llm/_torch/modules/mamba/gdn_prefill_conv.py @@ -0,0 +1,688 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""GDN prefill causal conv1d + post-conv in one pass over the token-major in_proj output. + +Replaces extract_transpose_prefill_slice + causal_conv1d_fn + fused_gdn_post_conv for a context-only batch with +two Triton launches: conv + SiLU + q / k L2 norm + gates, then the new conv states. g, beta and the conv states equal +the stock pipeline's bit for bit; q / k / v differ in the SiLU (the stock CUDA conv takes tanh.approx above -7, this +kernel the exact form) and in the FP32 summation order of the q / k L2 norms; the optional linear-space gate +alpha = exp(g) is libdevice expf (torch.exp's value), up to a few tens of FP32 ulp (relative 3e-6) from the +stock Triton ``tl.exp`` of ``fused_gdn_post_conv(g_linear=True)``. +""" + +from typing import Optional, Tuple + +import torch +import triton +import triton.language as tl +import triton.language.extra.libdevice as tldevice + +# Conv kernel: tokens per program, channels per program (8 consecutive channels per thread), rows per pipelined +# load and its pipeline depth. +_CHUNK = 64 +_BLOCK_C = 1024 +_NUM_WARPS = 4 +_STEP = 4 +_NUM_STAGES = 3 + + +# PTX of v * __frcp_rn(1 + __expf(-v)) (causal_conv1d_fwd_kernel's SiLU) for operand $i, result $o. The fast form +# is rcp.rn's own fast path (rcp.approx + one Newton step) without its range checks: exact for v > -87, where +# ex2's flushed denormals round to the same 1 + e. +_SILU_FAST = ( + "mul.rn.f32 t, $i, 0fBFB8AA3B; ex2.approx.ftz.f32 e, t; add.rn.f32 d, e, 0f3F800000; " + "rcp.approx.ftz.f32 r, d; fma.rn.f32 q, d, r, 0fBF800000; sub.ftz.f32 q, 0f80000000, q; " + "fma.rn.f32 r, r, q, r; mul.rn.f32 $o, $i, r;" +) +_SILU_EXACT = ( + "mul.rn.f32 t, $i, 0fBFB8AA3B; ex2.approx.f32 e, t; add.rn.f32 d, e, 0f3F800000; rcp.rn.f32 r, d; " + "mul.rn.f32 $o, $i, r;" +) + + +def _silu8_asm() -> str: + """SiLU of a thread's 8 values ($8..$15 -> $0..$7): the fast form unless some value of the warp is <= -87.""" + each = lambda form: "\n".join( # noqa: E731 + form.replace("$i", f"${8 + k}").replace("$o", f"${k}") for k in range(8) + ) + return ( + "{\n.reg .pred fast, all_fast;\n.reg .f32 m, t, e, d, r, q;\nmin.f32 m, $8, $9;\n" + + "\n".join(f"min.f32 m, m, ${k};" for k in range(10, 16)) + + "\nsetp.gt.f32 fast, m, 0fC2AE0000;\nvote.sync.all.pred all_fast, fast, 0xffffffff;\n" + + "@!all_fast bra SLOW;\n" + + each(_SILU_FAST) + + "\nbra DONE;\nSLOW:\n" + + each(_SILU_EXACT) + + "\nDONE:\n}" + ) + + +_SILU8_ASM = tl.constexpr(_silu8_asm()) + + +@triton.jit +def _silu(v, BLOCK_C: tl.constexpr): + """_SILU8_ASM over v [BLOCK_C] (8 consecutive values per thread).""" + c0, c1 = tl.split(tl.reshape(v, (BLOCK_C // 8, 2, 2, 2))) # value bits 2, 1, 0 + c00, c01 = tl.split(c0) + c10, c11 = tl.split(c1) + e0, e4 = tl.split(c00) + e2, e6 = tl.split(c01) + e1, e5 = tl.split(c10) + e3, e7 = tl.split(c11) + y0, y1, y2, y3, y4, y5, y6, y7 = tl.inline_asm_elementwise( + _SILU8_ASM, + "=f,=f,=f,=f,=f,=f,=f,=f,f,f,f,f,f,f,f,f", + [e0, e1, e2, e3, e4, e5, e6, e7], + dtype=(tl.float32,) * 8, + is_pure=False, + pack=1, + ) + y = tl.join( + tl.join(tl.join(y0, y4), tl.join(y2, y6)), tl.join(tl.join(y1, y5), tl.join(y3, y7)) + ) + return tl.reshape(y, (BLOCK_C,)) + + +@triton.jit +def _inv_norm(s, eps): + """1 / sqrt(s + eps) as Triton's fp32 1.0 / tl.sqrt(s + eps).""" + return tl.inline_asm_elementwise( + """{ + .reg .f32 t, r; + add.f32 t, $1, $2; + sqrt.approx.ftz.f32 r, t; + div.full.f32 $0, 0f3F800000, r; + }""", + "=f,f,f", + [s, eps], + dtype=tl.float32, + is_pure=True, + pack=1, + ) + + +@triton.jit +def _l2_normalize(o, eps, BLOCK_C: tl.constexpr): + """o [BLOCK_C] (128-channel heads, BF16) L2-normalized per head in FP32. A head is 16 runs of 8 channels (one + thread each): a run's squares add in channel order, then the runs' sums in a butterfly across the 16 lanes.""" + f = tl.reshape(o.to(tl.float32), (BLOCK_C // 128, 16, 8)) + c0, c1 = tl.split(tl.reshape(f, (BLOCK_C // 128, 16, 2, 2, 2))) # channel bits 2, 1, 0 + c00, c01 = tl.split(c0) + c10, c11 = tl.split(c1) + e0, e4 = tl.split(c00) + e2, e6 = tl.split(c01) + e1, e5 = tl.split(c10) + e3, e7 = tl.split(c11) + s = e0 * e0 + s = tl.fma(e1, e1, s) + s = tl.fma(e2, e2, s) + s = tl.fma(e3, e3, s) + s = tl.fma(e4, e4, s) + s = tl.fma(e5, e5, s) + s = tl.fma(e6, e6, s) + s = tl.fma(e7, e7, s) + s = tl.sum(s, axis=1) + inv = _inv_norm(s, tl.full(s.shape, eps, tl.float32)) + return tl.reshape(f * inv[:, None, None], (BLOCK_C,)).to(o.dtype) + + +@triton.jit +def _seq_state(seq, qsl_ptr, cidx_ptr, hinit_ptr, num_seqs, pad_slot): + """(next sequence start, slot, has_initial_state, conv_ok) of sequence seq (or of the padding past the last + one).""" + in_seq = seq < num_seqs + next_start = tl.load(qsl_ptr + seq + 1, mask=in_seq, other=2147483647) + slot = tl.load(cidx_ptr + seq, mask=in_seq, other=pad_slot) + hinit = tl.load(hinit_ptr + seq, mask=in_seq, other=0) != 0 + return next_start, slot, hinit, in_seq & (slot != pad_slot) + + +@triton.jit +def _window_tap(x_rows, p, start, stride_x, cs_row, cs_l, conv_ok, hinit, cols): + """Raw input at p as the conv of a later row of the sequence starting at start sees it.""" + from_x = (cols >= 0) & conv_ok & (p >= start) + from_state = (cols >= 0) & conv_ok & (p < start) & hinit + xv = tl.load(x_rows + p.to(tl.int64) * stride_x, mask=from_x, other=0.0) + sv = tl.load(cs_row + (p - start + 3) * cs_l, mask=from_state, other=0.0) + return tl.where(from_x, xv, sv).to(tl.float32) + + +@triton.jit +def _tile_rows(tile, BLOCK_C: tl.constexpr): + """The 4 rows of tile [4, BLOCK_C] as a tuple.""" + h0, h1 = tl.split(tl.reshape(tl.permute(tile, (1, 0)), (BLOCK_C, 2, 2))) + r0, r2 = tl.split(h0) + r1, r3 = tl.split(h1) + return (r0, r1, r2, r3) + + +@triton.jit +def _conv_post_chunk( + x_ptr, + stride_x, + w_ptr, + bias_ptr, + cs_ptr, + cs_b, + cs_c, + cs_l, + qsl_ptr, + cidx_ptr, + hinit_ptr, + out_ptrs, + out_row, + cols, + t0, + num_tokens, + num_seqs, + pad_slot, + eps, + HAS_BIAS: tl.constexpr, + SILU: tl.constexpr, + QK: tl.constexpr, + CHUNK: tl.constexpr, + BLOCK_C: tl.constexpr, + NUM_STAGES: tl.constexpr, + STEP: tl.constexpr, +): + """_gdn_conv_post_kernel's conv for one program: STEP-row tile loads pipelined NUM_STAGES deep.""" + w_row = w_ptr + cols.to(tl.int64) * 4 + w0 = tl.load(w_row).to(tl.float32) + w1 = tl.load(w_row + 1).to(tl.float32) + w2 = tl.load(w_row + 2).to(tl.float32) + w3 = tl.load(w_row + 3).to(tl.float32) + if HAS_BIAS: + bias = tl.load(bias_ptr + cols).to(tl.float32) + else: + bias = tl.zeros((BLOCK_C,), tl.float32) + t_end = tl.minimum(t0 + CHUNK, num_tokens) + + # Sequence of t0: the largest s in [0, num_seqs] with qsl[s] <= t0. + lo = num_seqs * 0 + hi = num_seqs + while lo < hi: + mid = (lo + hi + 1) // 2 + if tl.load(qsl_ptr + mid) <= t0: + lo = mid + else: + hi = mid - 1 + seq = lo + start = tl.load(qsl_ptr + tl.minimum(seq, num_seqs - 1)) + next_start, slot, hinit, conv_ok = _seq_state( + seq, qsl_ptr, cidx_ptr, hinit_ptr, num_seqs, pad_slot + ) + cs_row = cs_ptr + slot.to(tl.int64) * cs_b + cols.to(tl.int64) * cs_c + x_rows = x_ptr + cols + # Window: the raw inputs at t0 - 3, t0 - 2, t0 - 1 as the conv of row t0 sees them. + wa = _window_tap(x_rows, t0 - 3, start, stride_x, cs_row, cs_l, conv_ok, hinit, cols) + wb = _window_tap(x_rows, t0 - 2, start, stride_x, cs_row, cs_l, conv_ok, hinit, cols) + wc = _window_tap(x_rows, t0 - 1, start, stride_x, cs_row, cs_l, conv_ok, hinit, cols) + + for tb in tl.range(t0, t_end, STEP, num_stages=NUM_STAGES): + r = tb + tl.arange(0, STEP) + tile = tl.load( + x_ptr + r.to(tl.int64)[:, None] * stride_x + cols[None, :], + mask=(r < t_end)[:, None], + other=0.0, + ) + cur = _tile_rows(tile, BLOCK_C) + for u in tl.static_range(STEP): + t = tb + u + if t == next_start: + # A new sequence (or the padding past the last one) starts at t. + seq += 1 + while (seq < num_seqs) & ( + tl.load(qsl_ptr + seq + 1, mask=seq < num_seqs, other=0) <= t + ): + seq += 1 + next_start, slot, hinit, conv_ok = _seq_state( + seq, qsl_ptr, cidx_ptr, hinit_ptr, num_seqs, pad_slot + ) + cs_row = cs_ptr + slot.to(tl.int64) * cs_b + cols.to(tl.int64) * cs_c + take = (cols >= 0) & conv_ok & hinit + wa = tl.load(cs_row, mask=take, other=0.0).to(tl.float32) + wb = tl.load(cs_row + cs_l, mask=take, other=0.0).to(tl.float32) + wc = tl.load(cs_row + 2 * cs_l, mask=take, other=0.0).to(tl.float32) + x = cur[u] + xf = x.to(tl.float32) + acc = tl.fma(w0, wa, bias) + acc = tl.fma(w1, wb, acc) + acc = tl.fma(w2, wc, acc) + acc = tl.fma(w3, xf, acc) + if SILU: + acc = _silu(acc, BLOCK_C) + o = tl.where(conv_ok, acc.to(x.dtype), x) + if QK: + o = _l2_normalize(o, eps, BLOCK_C) + tl.store(out_ptrs + t.to(tl.int64) * out_row, o, mask=(cols >= 0) & (t < t_end)) + wa = wb + wb = wc + wc = xf + + +@triton.jit(do_not_specialize=["num_tokens", "num_seqs", "pad_slot"]) +def _gdn_conv_post_kernel( + x_ptr, + stride_x, + w_ptr, + bias_ptr, + cs_ptr, + cs_b, + cs_c, + cs_l, + qsl_ptr, + cidx_ptr, + hinit_ptr, + q_ptr, + k_ptr, + v_ptr, + num_tokens, + num_seqs, + pad_slot, + eps, + a_ptr, + b_ptr, + A_log_ptr, + dt_bias_ptr, + g_ptr, + beta_ptr, + alpha_ptr, + stride_a_tok, + stride_a_head, + stride_b_tok, + stride_b_head, + softplus_threshold, + NK_D: tl.constexpr, + NV_D: tl.constexpr, + HAS_BIAS: tl.constexpr, + SILU: tl.constexpr, + CHUNK: tl.constexpr, + BLOCK_C: tl.constexpr, + NUM_STAGES: tl.constexpr, + STEP: tl.constexpr, + GATE_T: tl.constexpr, + WITH_ALPHA: tl.constexpr, +): + """Conv1d (width 4) + SiLU of CHUNK tokens x BLOCK_C channels (all q / k or all v), sliding a window of each + channel's last 3 raw inputs; q / k heads are then L2-normalized, v programs also write their heads' gates. At a + sequence start the window is the slot's old conv state (has_initial_state) or zeros. Rows outside a sequence or + of a padded slot keep their raw input. Only reads conv states.""" + t0 = tl.program_id(0) * CHUNK + cols = tl.program_id(1) * BLOCK_C + tl.arange(0, BLOCK_C) + if tl.program_id(1) < 2 * NK_D // BLOCK_C: + _conv_post_chunk( + x_ptr, + stride_x, + w_ptr, + bias_ptr, + cs_ptr, + cs_b, + cs_c, + cs_l, + qsl_ptr, + cidx_ptr, + hinit_ptr, + tl.where(cols < NK_D, q_ptr + cols, k_ptr + (cols - NK_D)), + NK_D, + cols, + t0, + num_tokens, + num_seqs, + pad_slot, + eps, + HAS_BIAS, + SILU, + True, + CHUNK, + BLOCK_C, + NUM_STAGES, + STEP, + ) + else: + _conv_post_chunk( + x_ptr, + stride_x, + w_ptr, + bias_ptr, + cs_ptr, + cs_b, + cs_c, + cs_l, + qsl_ptr, + cidx_ptr, + hinit_ptr, + v_ptr + (cols - 2 * NK_D), + NV_D, + cols, + t0, + num_tokens, + num_seqs, + pad_slot, + eps, + HAS_BIAS, + SILU, + False, + CHUNK, + BLOCK_C, + NUM_STAGES, + STEP, + ) + _gates( + a_ptr, + b_ptr, + A_log_ptr, + dt_bias_ptr, + g_ptr, + beta_ptr, + alpha_ptr, + t0, + num_tokens, + (tl.program_id(1) * BLOCK_C - 2 * NK_D) // 128, + stride_a_tok, + stride_a_head, + stride_b_tok, + stride_b_head, + softplus_threshold, + NV_D // 128, + BLOCK_C // 128, + CHUNK, + GATE_T, + WITH_ALPHA, + ) + + +@triton.jit +def _gates( + a_ptr, + b_ptr, + A_log_ptr, + dt_bias_ptr, + g_ptr, + beta_ptr, + alpha_ptr, + t0, + num_tokens, + h0, + stride_a_tok, + stride_a_head, + stride_b_tok, + stride_b_head, + softplus_threshold, + NUM_V_HEADS: tl.constexpr, + HEADS: tl.constexpr, + CHUNK: tl.constexpr, + GATE_T: tl.constexpr, + WITH_ALPHA: tl.constexpr, +): + """g, beta FP32 of tokens [t0, t0 + CHUNK) x value heads [h0, h0 + HEADS) with _fused_gdn_post_conv_kernel's + expressions; with WITH_ALPHA also alpha = exp(g), FlashInfer's linear-space gate, as libdevice expf (bit-identical + to torch.exp; the stock kernel's tl.exp differs by up to a few tens of ulp).""" + t = t0 + tl.arange(0, GATE_T) + h = h0 + tl.arange(0, HEADS) + t64 = t.to(tl.int64) + m = ((t < num_tokens) & (t < t0 + CHUNK))[:, None] + a_values = tl.load( + a_ptr + t64[:, None] * stride_a_tok + h[None, :] * stride_a_head, mask=m, other=0.0 + ).to(tl.float32) + b_values = tl.load( + b_ptr + t64[:, None] * stride_b_tok + h[None, :] * stride_b_head, mask=m, other=0.0 + ).to(tl.float32) + A_log = tl.load(A_log_ptr + h).to(tl.float32) + dt_bias = tl.load(dt_bias_ptr + h).to(tl.float32) + gate_input = a_values + dt_bias[None, :] + softplus = tl.where( + gate_input <= softplus_threshold, tl.log(1.0 + tl.exp(gate_input)), gate_input + ) + g_values = -tl.exp(A_log)[None, :] * softplus + beta_values = tl.sigmoid(b_values) + off = t64[:, None] * NUM_V_HEADS + h[None, :] + tl.store(g_ptr + off, g_values, mask=m) + tl.store(beta_ptr + off, beta_values, mask=m) + if WITH_ALPHA: + tl.store(alpha_ptr + off, tldevice.exp(g_values), mask=m) + + +@triton.jit +def _state_value( + x_ptr, base, cols, cmask, start, end, hinit, w, stride_x_tok, stride_cs_l, KW: tl.constexpr +): + p = end - (KW - 1) + w + from_x = p >= start + xv = tl.load(x_ptr + p.to(tl.int64) * stride_x_tok + cols, mask=cmask & from_x, other=0.0) + sv = tl.load( + base + (p - start + (KW - 1)) * stride_cs_l, mask=cmask & (from_x == 0) & hinit, other=0.0 + ) + return tl.where(from_x, xv, sv) + + +@triton.jit +def _gdn_conv_state_update_kernel( + x_ptr, + cs_ptr, + qsl_ptr, + cidx_ptr, + hinit_ptr, + pad_slot_id, + conv_dim, + stride_x_tok, + stride_cs_b, + stride_cs_c, + stride_cs_l, + KW: tl.constexpr, + BLOCK_C: tl.constexpr, +): + """New conv state of each sequence = its last KW - 1 inputs (the old state shifted by the length, or zeros, + for short sequences), as causal_conv1d_fwd writes it back (empty sequences included). KW == 4.""" + s = tl.program_id(0) + slot = tl.load(cidx_ptr + s) + if slot != pad_slot_id: + start = tl.load(qsl_ptr + s) + end = tl.load(qsl_ptr + s + 1) + hinit = tl.load(hinit_ptr + s) != 0 + cols = tl.program_id(1) * BLOCK_C + tl.arange(0, BLOCK_C) + cmask = cols < conv_dim + base = cs_ptr + slot.to(tl.int64) * stride_cs_b + cols * stride_cs_c + v0 = _state_value( + x_ptr, base, cols, cmask, start, end, hinit, 0, stride_x_tok, stride_cs_l, KW + ) + v1 = _state_value( + x_ptr, base, cols, cmask, start, end, hinit, 1, stride_x_tok, stride_cs_l, KW + ) + v2 = _state_value( + x_ptr, base, cols, cmask, start, end, hinit, 2, stride_x_tok, stride_cs_l, KW + ) + tl.store(base, v0, mask=cmask) + tl.store(base + stride_cs_l, v1, mask=cmask) + tl.store(base + 2 * stride_cs_l, v2, mask=cmask) + + +def gdn_prefill_conv_post( + mixed_qkv: torch.Tensor, + conv_weight: torch.Tensor, + conv_bias: Optional[torch.Tensor], + conv_states: torch.Tensor, + query_start_loc: torch.Tensor, + cache_indices: torch.Tensor, + has_initial_state: torch.Tensor, + a: torch.Tensor, + b: torch.Tensor, + A_log: torch.Tensor, + dt_bias: torch.Tensor, + num_k_heads: int, + head_k_dim: int, + num_v_heads: int, + head_v_dim: int, + activation: str = "silu", + l2_norm_eps: float = 1e-6, + softplus_threshold: float = 20.0, + pad_slot_id: int = -1, + alpha_out: Optional[torch.Tensor] = None, + out: Optional[ + Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor] + ] = None, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """q, k (L2-normed), v [1, T, H, D] in mixed_qkv's dtype and g, beta [1, T, HV] FP32, with conv_states updated + in place; g, beta and the conv states equal extract_transpose_prefill_slice + causal_conv1d_fn + + fused_gdn_post_conv, q / k / v up to the SiLU form and the q / k L2 norms' FP32 summation order (module + docstring). mixed_qkv: [T, conv_dim] BF16 token-major (gdn_prefill_conv_eligible). + alpha_out: optional [1, T, HV] FP32 tensor that receives exp(g), bit-identical to torch.exp(g). + out: optional contiguous (q, k, v, g, beta) of the shapes / dtypes above that the kernel writes and that are + returned (e.g. views of a scratch shared by the layers of one iteration); same launches, same values.""" + if activation not in (None, "silu", "swish"): + raise ValueError(f"unsupported activation {activation!r}") + T, conv_dim = mixed_qkv.shape + if not ( + gdn_prefill_conv_supported( + head_k_dim, + head_v_dim, + conv_weight.reshape(conv_dim, -1).shape[1], + activation, + conv_dim, + num_k_heads, + ) + and conv_dim == (2 * num_k_heads + num_v_heads) * head_k_dim + and gdn_prefill_conv_eligible( + mixed_qkv, conv_weight, conv_states, query_start_loc, cache_indices, has_initial_state + ) + ): + raise ValueError("shapes / layouts not supported by gdn_prefill_conv_post") + num_seqs = query_start_loc.shape[0] - 1 + D = head_k_dim + dev = mixed_qkv.device + if out is None: + q = torch.empty((1, T, num_k_heads, D), dtype=mixed_qkv.dtype, device=dev) + k = torch.empty_like(q) + v = torch.empty((1, T, num_v_heads, D), dtype=mixed_qkv.dtype, device=dev) + g = torch.empty((1, T, num_v_heads), dtype=torch.float32, device=dev) + beta = torch.empty((1, T, num_v_heads), dtype=torch.float32, device=dev) + else: + q, k, v, g, beta = out + shapes = ( + ((1, T, num_k_heads, D),) * 2 + ((1, T, num_v_heads, D),) + ((1, T, num_v_heads),) * 2 + ) + dtypes = (mixed_qkv.dtype,) * 3 + (torch.float32,) * 2 + if any( + t.shape != shape or t.dtype != dtype or not t.is_contiguous() + for t, shape, dtype in zip(out, shapes, dtypes) + ): + raise ValueError( + "out must be contiguous (q, k, v, g, beta) of [1, T, Hk, D] x 2, [1, T, HV, D] in mixed_qkv's " + "dtype and [1, T, HV] FP32 x 2" + ) + if alpha_out is not None and ( + alpha_out.shape != (1, T, num_v_heads) + or alpha_out.dtype != torch.float32 + or not alpha_out.is_contiguous() + ): + raise ValueError("alpha_out must be a contiguous [1, T, num_v_heads] FP32 tensor") + if num_seqs == 0: + return q, k, v, g, beta + if T > 0: + _gdn_conv_post_kernel[(triton.cdiv(T, _CHUNK), conv_dim // _BLOCK_C)]( + mixed_qkv, + mixed_qkv.stride(0), + conv_weight, + conv_bias, + conv_states, + conv_states.stride(0), + conv_states.stride(1), + conv_states.stride(2), + query_start_loc, + cache_indices, + has_initial_state, + q, + k, + v, + T, + num_seqs, + pad_slot_id, + l2_norm_eps, + a, + b, + A_log, + dt_bias, + g, + beta, + alpha_out if alpha_out is not None else g, + a.stride(0), + a.stride(1), + b.stride(0), + b.stride(1), + softplus_threshold, + NK_D=num_k_heads * D, + NV_D=num_v_heads * D, + HAS_BIAS=conv_bias is not None, + SILU=activation is not None, + CHUNK=_CHUNK, + BLOCK_C=_BLOCK_C, + NUM_STAGES=_NUM_STAGES, + STEP=_STEP, + GATE_T=triton.next_power_of_2(_CHUNK), + WITH_ALPHA=alpha_out is not None, + num_warps=_NUM_WARPS, + ) + block_c = 1024 + _gdn_conv_state_update_kernel[(num_seqs, triton.cdiv(conv_dim, block_c))]( + mixed_qkv, + conv_states, + query_start_loc, + cache_indices, + has_initial_state, + pad_slot_id, + conv_dim, + mixed_qkv.stride(0), + conv_states.stride(0), + conv_states.stride(1), + conv_states.stride(2), + KW=4, + BLOCK_C=block_c, + num_warps=4, + ) + return q, k, v, g, beta + + +def gdn_prefill_conv_supported( + head_k_dim: int, + head_v_dim: int, + conv_kernel_size: int, + activation: Optional[str], + conv_dim: int, + num_k_heads: int, +) -> bool: + """Shapes the fused prefill conv handles: 128-wide heads, conv width 4, SiLU or none, q / k and v channels in + whole _BLOCK_C-channel programs.""" + return ( + head_k_dim == head_v_dim == 128 + and conv_kernel_size == 4 + and activation in (None, "silu", "swish") + and conv_dim % _BLOCK_C == 0 + and (2 * num_k_heads * head_k_dim) % _BLOCK_C == 0 + ) + + +def gdn_prefill_conv_eligible( + mixed_qkv: torch.Tensor, + conv_weight: torch.Tensor, + conv_states: torch.Tensor, + query_start_loc: torch.Tensor, + cache_indices: torch.Tensor, + has_initial_state: torch.Tensor, +) -> bool: + """Run-time layout / dtype conditions of gdn_prefill_conv_post (else the caller keeps the stock kernels).""" + return ( + mixed_qkv.dtype == torch.bfloat16 + and mixed_qkv.dim() == 2 + and mixed_qkv.stride(1) == 1 + and mixed_qkv.stride(0) % 8 == 0 + and mixed_qkv.data_ptr() % 16 == 0 + and conv_weight.dtype == torch.bfloat16 + and conv_weight.is_contiguous() + and conv_states.dtype == torch.bfloat16 + and conv_states.dim() == 3 + and conv_states.shape[2] == 3 + and conv_states.shape[1] == mixed_qkv.shape[1] + and query_start_loc.dtype == torch.int32 + and cache_indices.dtype == torch.int32 + and has_initial_state.dtype == torch.bool + ) diff --git a/tensorrt_llm/_torch/modules/mamba/layernorm_gated.py b/tensorrt_llm/_torch/modules/mamba/layernorm_gated.py index 00fdf5ef3241..98754aaf0f76 100644 --- a/tensorrt_llm/_torch/modules/mamba/layernorm_gated.py +++ b/tensorrt_llm/_torch/modules/mamba/layernorm_gated.py @@ -157,76 +157,48 @@ def _multirow_pdl(grid_size: int, device_index: int) -> bool: return allowed and grid_size < num_sms -@triton.heuristics({"OUTPUT_FP8": lambda args: args["FP8_SCALE"] is not None}) -@triton.heuristics({"SAVE_RSTD": lambda args: args["Rstd"] is not None}) @triton.jit -def _rms_norm_gated_fwd_multirow_kernel( - X, # pointer to the input - Y, # pointer to the output - W, # pointer to the weights - Z, # pointer to the gate branch - Rstd, # optional pointer to the 1/std - FP8_SCALE, # static scale for an optional FP8 output - stride_x_row, - stride_y_row, - stride_z_tok, - M, # number of rows in X - eps, - N: tl.constexpr, # row length; power of two, whole row per program - ROWS: tl.constexpr, # rows per program - HEADS_PER_TOK: tl.constexpr, - GATE_SIGMOID: tl.constexpr, - WEIGHT_IS_DELTA: tl.constexpr, - SAVE_RSTD: tl.constexpr, - OUTPUT_FP8: tl.constexpr, - LAUNCH_WITH_PDL: tl.constexpr, - EARLY_TRIGGER: tl.constexpr = False, - # Fast-path hints; the defaults take the general strided, masked path. - CONTIG: tl.constexpr = False, # X and Y rows dense (stride == N) - EVEN: tl.constexpr = False, # M % ROWS == 0: no row masking needed -): - """Gated rmsnorm(x), several short rows per program. - - Z is addressed token-major: row r reads z at - (r // HEADS_PER_TOK) * stride_z_tok + (r % HEADS_PER_TOK) * N. With - HEADS_PER_TOK == 1 and stride_z_tok == z's row stride this is a plain - [M, N] z; with HEADS_PER_TOK == heads it reads a [num_tokens, heads, N] - view whose (heads, N) block is contiguous per token, e.g. a column slice - of a wider projection. - - When CONTIG, x is loaded and y stored through flat [ROWS * N] offsets so - the whole program block is one contiguous span (widest possible global - accesses); EVEN additionally drops the bounds masks. - """ - r0 = tl.program_id(0) * ROWS +def _gated_rows_load(X, Z, r0, M, stride_x_row, stride_z_tok, N: tl.constexpr, + ROWS: tl.constexpr, HEADS_PER_TOK: tl.constexpr, + CONTIG: tl.constexpr, EVEN: tl.constexpr): + """Rows [r0, r0 + ROWS) of X and their gate rows of Z (see the kernel below).""" rows = r0 + tl.arange(0, ROWS) cols = tl.arange(0, N) - if EARLY_TRIGGER: - # Dependents read Y only after their own griddepcontrol.wait. - tl.extra.cuda.gdc_launch_dependents() - # The weight is a parameter (not produced in-step), so it is fetched before - # the PDL wait; X (the producer's output) and Z (an earlier in-step kernel's - # output) are read only after it. - w = tl.load(W + cols).to(tl.float32) - if WEIGHT_IS_DELTA: - w += 1.0 - if LAUNCH_WITH_PDL: - tl.extra.cuda.gdc_wait() if CONTIG: - base = tl.cast(r0, tl.int64) * N flat = tl.arange(0, ROWS * N) + x_ptr = X + tl.cast(r0, tl.int64) * N + flat if EVEN: - xr = tl.load(X + base + flat) + x = tl.load(x_ptr) else: - xr = tl.load(X + base + flat, mask=(r0 + flat // N) < M, other=0.0) - x = tl.reshape(xr, (ROWS, N)).to(tl.float32) + x = tl.load(x_ptr, mask=(r0 + flat // N) < M, other=0.0) + x = tl.reshape(x, (ROWS, N)) else: - x_off = rows[:, None].to(tl.int64) * stride_x_row + cols[None, :] + x_ptr = X + rows[:, None].to(tl.int64) * stride_x_row + cols[None, :] if EVEN: - x = tl.load(X + x_off).to(tl.float32) + x = tl.load(x_ptr) else: - x = tl.load(X + x_off, mask=rows[:, None] < M, - other=0.0).to(tl.float32) + x = tl.load(x_ptr, mask=rows[:, None] < M, other=0.0) + tok = rows // HEADS_PER_TOK + head = rows % HEADS_PER_TOK + z_ptr = Z + (tok[:, None].to(tl.int64) * stride_z_tok + head[:, None] * N + + cols[None, :]) + if EVEN: + z = tl.load(z_ptr) + else: + z = tl.load(z_ptr, mask=rows[:, None] < M, other=0.0) + return x, z + + +@triton.jit +def _gated_rows_store(X, Y, Rstd, FP8_SCALE, x, z, w, r0, M, eps, stride_y_row, + N: tl.constexpr, ROWS: tl.constexpr, + GATE_SIGMOID: tl.constexpr, SAVE_RSTD: tl.constexpr, + OUTPUT_FP8: tl.constexpr, CONTIG: tl.constexpr, + EVEN: tl.constexpr): + """Gated RMSNorm of one loaded tile, stored to Y (and Rstd).""" + rows = r0 + tl.arange(0, ROWS) + cols = tl.arange(0, N) + x = x.to(tl.float32) var = tl.sum(x * x, axis=1) / N rstd = 1.0 / tl.sqrt(var + eps) if SAVE_RSTD: @@ -235,14 +207,7 @@ def _rms_norm_gated_fwd_multirow_kernel( else: tl.store(Rstd + rows, rstd, mask=rows < M) y = x * rstd[:, None] * w[None, :] - tok = rows // HEADS_PER_TOK - head = rows % HEADS_PER_TOK - z_off = (tok[:, None].to(tl.int64) * stride_z_tok + head[:, None] * N + - cols[None, :]) - if EVEN: - z = tl.load(Z + z_off).to(tl.float32) - else: - z = tl.load(Z + z_off, mask=rows[:, None] < M, other=0.0).to(tl.float32) + z = z.to(tl.float32) gate = tl.sigmoid(z) if not GATE_SIGMOID: gate *= z @@ -254,24 +219,102 @@ def _rms_norm_gated_fwd_multirow_kernel( y = y.to(X.dtype.element_ty).to(tl.float32) y *= tldevice.rcp_rn(tl.load(FP8_SCALE).to(tl.float32)) if CONTIG: - yo = tl.reshape(y, (ROWS * N, )).to(Y.dtype.element_ty) + flat = tl.arange(0, ROWS * N) + y_ptr = Y + tl.cast(r0, tl.int64) * N + flat + y = tl.reshape(y, (ROWS * N, )).to(Y.dtype.element_ty) if EVEN: - tl.store(Y + base + flat, yo) + tl.store(y_ptr, y) else: - tl.store(Y + base + flat, yo, mask=(r0 + flat // N) < M) + tl.store(y_ptr, y, mask=(r0 + flat // N) < M) else: - y_off = rows[:, None].to(tl.int64) * stride_y_row + cols[None, :] + y_ptr = Y + rows[:, None].to(tl.int64) * stride_y_row + cols[None, :] if EVEN: - tl.store(Y + y_off, y.to(Y.dtype.element_ty)) + tl.store(y_ptr, y.to(Y.dtype.element_ty)) else: - tl.store(Y + y_off, - y.to(Y.dtype.element_ty), - mask=rows[:, None] < M) + tl.store(y_ptr, y.to(Y.dtype.element_ty), mask=rows[:, None] < M) + + +@triton.heuristics({"OUTPUT_FP8": lambda args: args["FP8_SCALE"] is not None}) +@triton.heuristics({"SAVE_RSTD": lambda args: args["Rstd"] is not None}) +@triton.jit +def _rms_norm_gated_fwd_multirow_kernel( + X, # pointer to the input + Y, # pointer to the output + W, # pointer to the weights + Z, # pointer to the gate branch + Rstd, # optional pointer to the 1/std + FP8_SCALE, # static scale for an optional FP8 output + stride_x_row, + stride_y_row, + stride_z_tok, + M, # number of rows in X + eps, + N: tl.constexpr, # row length; power of two, whole row per program + ROWS: tl.constexpr, # rows per tile + HEADS_PER_TOK: tl.constexpr, + GATE_SIGMOID: tl.constexpr, + WEIGHT_IS_DELTA: tl.constexpr, + SAVE_RSTD: tl.constexpr, + OUTPUT_FP8: tl.constexpr, + LAUNCH_WITH_PDL: tl.constexpr, + EARLY_TRIGGER: tl.constexpr = False, + # Fast-path hints; the defaults take the general strided, masked path. + CONTIG: tl.constexpr = False, # X and Y rows dense (stride == N) + EVEN: tl.constexpr = False, # M % (ROWS * GROUPS) == 0: no row masks + GROUPS: tl.constexpr = 1, +): + """Gated rmsnorm(x), several short rows per program. + + Z is addressed token-major: row r reads z at + (r // HEADS_PER_TOK) * stride_z_tok + (r % HEADS_PER_TOK) * N. With + HEADS_PER_TOK == 1 and stride_z_tok == z's row stride this is a plain + [M, N] z; with HEADS_PER_TOK == heads it reads a [num_tokens, heads, N] + view whose (heads, N) block is contiguous per token, e.g. a column slice + of a wider projection. A program runs GROUPS ROWS-row tiles, loading tile + g + 1 before it computes tile g; each row's arithmetic does not depend on + GROUPS. + + When CONTIG, x is loaded and y stored through flat [ROWS * N] offsets so + each tile is one contiguous span (widest possible global accesses); EVEN + additionally drops the bounds masks. + """ + base = tl.program_id(0) * (ROWS * GROUPS) + cols = tl.arange(0, N) + if EARLY_TRIGGER: + # Dependents read Y only after their own griddepcontrol.wait. + tl.extra.cuda.gdc_launch_dependents() + # The weight is a parameter (not produced in-step), so it is fetched before + # the PDL wait; X (the producer's output) and Z (an earlier in-step kernel's + # output) are read only after it. + w = tl.load(W + cols).to(tl.float32) + if WEIGHT_IS_DELTA: + w += 1.0 + if LAUNCH_WITH_PDL: + tl.extra.cuda.gdc_wait() + x_next, z_next = _gated_rows_load(X, Z, base, M, stride_x_row, stride_z_tok, + N, ROWS, HEADS_PER_TOK, CONTIG, EVEN) + for g in tl.static_range(GROUPS): + r0 = base + g * ROWS + x_cur = x_next + z_cur = z_next + if g + 1 < GROUPS: + x_next, z_next = _gated_rows_load(X, Z, r0 + ROWS, M, stride_x_row, + stride_z_tok, N, ROWS, + HEADS_PER_TOK, CONTIG, EVEN) + _gated_rows_store(X, Y, Rstd, FP8_SCALE, x_cur, z_cur, w, r0, M, eps, + stride_y_row, N, ROWS, GATE_SIGMOID, SAVE_RSTD, + OUTPUT_FP8, CONTIG, EVEN) if LAUNCH_WITH_PDL and not EARLY_TRIGGER: # Release only after both Rstd (when present) and Y have been stored. tl.extra.cuda.gdc_launch_dependents() +# Tiles per program of rms_norm_gated_token_major from _MULTIROW_GROUPS_MIN_ROWS +# rows (prefill-sized inputs). +_MULTIROW_GROUPS = 4 +_MULTIROW_GROUPS_MIN_ROWS = 1 << 16 + + def _multirow_gated_rmsnorm_eligible(N, ngroups, bias, z, norm_before_gate, is_rms_norm): return (is_rms_norm and norm_before_gate and z is not None and bias is None @@ -329,8 +372,9 @@ def rms_norm_gated_token_major( out = torch.empty_like(x, dtype=out_dtype) # rstd is not consumed on this path; Rstd=None skips both the scratch # allocation and the (measurably expensive) extra store in the kernel. - grid_size = triton.cdiv(M, _MULTIROW_ROWS) device_index = x.device.index + groups = _MULTIROW_GROUPS if M >= _MULTIROW_GROUPS_MIN_ROWS else 1 + grid_size = triton.cdiv(M, _MULTIROW_ROWS * groups) launch_with_pdl = _multirow_pdl(grid_size, device_index) with torch.cuda.device(device_index): _rms_norm_gated_fwd_multirow_kernel[(grid_size, )]( @@ -352,11 +396,12 @@ def rms_norm_gated_token_major( WEIGHT_IS_DELTA=False, LAUNCH_WITH_PDL=launch_with_pdl, CONTIG=(x.stride(0) == N and out.stride(0) == N), - EVEN=(M % _MULTIROW_ROWS == 0), + EVEN=(M % (_MULTIROW_ROWS * groups) == 0), num_warps=_MULTIROW_NUM_WARPS, # Dependents (out_proj) prefetch their weights; they read Y only # after their own griddepcontrol.wait. EARLY_TRIGGER=_pdl_device_policy(device_index)[0], + GROUPS=groups, launch_pdl=launch_with_pdl, ) return out diff --git a/tensorrt_llm/_torch/modules/mamba/recurrent_state_cache.py b/tensorrt_llm/_torch/modules/mamba/recurrent_state_cache.py index 8beb4e3183e3..559a6e4ff298 100644 --- a/tensorrt_llm/_torch/modules/mamba/recurrent_state_cache.py +++ b/tensorrt_llm/_torch/modules/mamba/recurrent_state_cache.py @@ -24,23 +24,25 @@ def _reset_recurrent_state_rows_kernel( BLOCK_SIZE: tl.constexpr, ): request_idx = tl.program_id(0) - offsets = tl.program_id(1) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) state_idx = tl.load(state_indices + request_idx).to(tl.int64) needs_reset = ~tl.load(has_initial_states + request_idx).to(tl.int1) valid_state = (state_idx >= 0) & (state_idx < NUM_CACHE_LINES) - recurrent_row_offset = state_idx * recurrent_state_stride.to(tl.int64) - tl.store( - recurrent_states + recurrent_row_offset + offsets, - 0.0, - mask=needs_reset & valid_state & (offsets < RECURRENT_STATE_SIZE), - ) - if RESET_CONV: - conv_row_offset = state_idx * conv_state_stride.to(tl.int64) + # Most context requests carry an initial state: their programs leave right away. + if needs_reset & valid_state: + offsets = tl.program_id(1) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + recurrent_row_offset = state_idx * recurrent_state_stride.to(tl.int64) tl.store( - conv_states + conv_row_offset + offsets, + recurrent_states + recurrent_row_offset + offsets, 0.0, - mask=needs_reset & valid_state & (offsets < CONV_STATE_SIZE), + mask=offsets < RECURRENT_STATE_SIZE, ) + if RESET_CONV: + conv_row_offset = state_idx * conv_state_stride.to(tl.int64) + tl.store( + conv_states + conv_row_offset + offsets, + 0.0, + mask=offsets < CONV_STATE_SIZE, + ) def reset_recurrent_state_rows( @@ -75,7 +77,7 @@ def reset_recurrent_state_rows( if conv_states is not None and conv_states.stride(0) < conv_state_size: raise ValueError("convolution state rows must not overlap") - block_size = 256 + block_size = 4096 grid = ( num_requests, triton.cdiv(max(recurrent_state_size, conv_state_size), block_size), diff --git a/tensorrt_llm/_torch/moe/fused_moe/MOE_DEVELOPER_GUIDE.md b/tensorrt_llm/_torch/moe/fused_moe/MOE_DEVELOPER_GUIDE.md index 844bbbaa01a9..9f2cbe684d43 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/MOE_DEVELOPER_GUIDE.md +++ b/tensorrt_llm/_torch/moe/fused_moe/MOE_DEVELOPER_GUIDE.md @@ -196,9 +196,15 @@ A staged routing override (e.g. the layer-wise benchmark's balanced replacement) `MoESortTables` is the decode-time hand-off to a backend's `run_moe` (the sorting kernel wrote the tables for the ids it produced). `PreroutedRouting` is the other hand-off — routing a *caller* computed for one `run_moe` of an impl that declares `supports_prerouted_routing` (the TRT-LLM-Gen decode front): eager, stricter (one chunk, no comm) and table-format-specific. They are not interchangeable; folding them into one hand-off (covering `PreroutedRouting`, `MoESortTables` and the `MoERoutingTables` hand-off proposed in #21438) is tracked as TRTLLM-17649, under the TRTLLM-14607 MoE refactor epic — for now a producer that owns the whole front builds `PreroutedRouting` and a backend-side sorting forward builds `sort_tables`.. +`EngineRouting` (a `PreroutedRouting` subtype) is the decode MoE engine's hand-off: with `candidates` (the router GEMM's per-128-expert top-k keys, `[num_tokens, num_experts / 128, top_k]` int32) the routing is not done yet. Only the decode MoE engine (`trtllm_gen.decode_moe`, `ENGINE`) consumes it: it routes the call itself and writes `tables`, `topk_ids` and `topk_weights` before it reads them, and the FP4 op raises for any other kernel; `decode_moe.engine_routes` is the condition under which the decode front builds one. Nothing may read those tensors before the op returns. + +`MoERunContext.lamport_fc2_out` is the hand-off to a caller whose all-reduce polls the un-finalized FC2 rows (the MNNVL MoE-output fold). It is passed only to one un-finalized chunk without communication of a backend that declares `takes_lamport_fc2_out` (`TrtllmTrtllmGenNvfp4Impl`). Such a `run_moe` may write its FC2 rows into the buffer and then returns that buffer as the rows (the `ENGINE` and `CUTE_FC2` decode kernels); otherwise it returns rows of its own and leaves the buffer untouched (`CUBIN`), and `decode_moe.rows_in_lamport` tells the two apart. `decode_moe.LamportFc2Buffer` owns the protocol: the buffer holds 0xFFFFFFFF wherever FC2 has not written, the kernels write each word of a real row exactly once with a value that is never 0xFFFFFFFF, and the all-reduce resets each word it reads. Because a custom-op output may not alias an input, the FP4 op returns an empty first output for rows it wrote into the buffer and `moe_op_backend` substitutes the buffer. + +`MoEDecodeOptions` (`impl_contract.py`) is how a model declares MoE decode kernels at construction, through `model_config.extra_attrs[MOE_DECODE_OPTIONS]`: decode-step tuning buckets and the decode kernels of the TRTLLM-Gen FP4 op (`fp4_block_scale_moe_decode_runner`, `decode_moe.select`: `ENGINE`, `CUTE_FC2`, `CUBIN`), the engine's early release rows, the CuTe DSL evict-first FC2 rows, and the TRTLLM-Gen BF16 decode MoE engine (`bf16_decode_engine`). The SMs the decode engine leaves to a shared expert are not an option: the model asks for them per forward through the hook below. The defaults are the stock paths, which every model that declares nothing keeps. + A model that orders work around the routing asks `ConfigurableMoE.routes_with_sort_tables(num_tokens)` instead of re-deriving these conditions. Likewise, a producer that can emit the routed experts' NVFP4 input (e.g. from a GEMM epilogue) asks `ConfigurableMoE.nvfp4_input_scale(num_tokens)`: the global scale of an `Fp4QuantizedTensor` input (linear scale factors) that the forward takes as is, or `None` when the forward needs an unquantized input (the backend declares no `MoEImplBase.prequantized_nvfp4_input_scale()`, or a comm strategy, EPLB, `apply_router_weight_on_input` or more than one chunk). `ConfigurableMoE.quantize_nvfp4_input(x)` quantizes as the backend would. -A model that runs other work on a side stream while the routed experts run (e.g. a shared expert) asks the backend, once per forwards's launch, to keep SMs free of its persistent grid: `backend.reserve_sms_for_concurrent_kernels(num_sms)` returns the SMs applied to that launch (default 0: declined). Ask for the shared work's count only while it runs beside the routed grid (multi-stream); an in-order launch hands 0 so the grid keeps every SM. The paired confinement is torch's SM carveout, which only GEMM launches issued through torch's cuBLAS (`F.linear`) honor — a CuTe DSL shared GEMM ignores it, and a model whose shared projections take those paths must not reserve SMs for them. `TrtllmCutedslFusedFc12Nvfp4Impl` applies the count to the fused FC12 kernel (`reserved_sms` of `trtllm::cute_dsl_nvfp4_fc12_fused_rubin`, alongside `cute_dsl_utils.sm_reserve()`). +A model that runs other work on a side stream while the routed experts run (e.g. a shared expert) asks the backend, once per forwards's launch, to keep SMs free of its persistent grid: `backend.reserve_sms_for_concurrent_kernels(num_sms)` returns the SMs applied to that launch (default 0: declined). Ask for the shared work's count only while it runs beside the routed grid (multi-stream); an in-order launch hands 0 so the grid keeps every SM. The paired confinement is torch's SM carveout, which only GEMM launches issued through torch's cuBLAS (`F.linear`) honor — a CuTe DSL shared GEMM ignores it, and a model whose shared projections take those paths must not reserve SMs for them. `TrtllmCutedslFusedFc12Nvfp4Impl` applies the count to the fused FC12 kernel (`reserved_sms` of `trtllm::cute_dsl_nvfp4_fc12_fused_rubin`, alongside `cute_dsl_utils.sm_reserve()`). The TRTLLM-Gen NVFP4 leaves apply it to the decode MoE engine's persistent grid (`decode_spare_sms` of `trtllm::fp4_block_scale_moe_decode_runner`, ceiling `decode_moe.ENGINE_SPARE_SMS`, only where the model declares the decode kernels); the engine and the CuTe FC2 also leave out `cute_dsl_utils.sm_reserve()`. `unfinalized_combine_fn` is a constructor argument (`create_moe(..., unfinalized_combine_fn=...)`) for a model that needs a per-`(token, expert)` transform applied to each expert output *before* the top-k sum. Once registered it runs on **every** `do_finalize=False` forward, with or without a comm strategy, so the forward's return type (dense tensor vs. unfinalized triple) depends only on static config. Under a comm strategy the scheduler runs it on the dispatched rows and the combine reduces already-finalized partials — equal to finalizing after the combine, because each term depends on one row alone and non-local slots contribute exact zeros. That reordering is only sound for a combine that is an unweighted row sum over a dense per-token tensor; `DeepEPLowLatency.combine` is not one (it consumes expert-major rows and applies the routing weights itself), which is what `Communication.supports_finalize_before_combine()` declares. `ConfigurableMoE.validate_backend` rejects at construction: a backend without `supports_unfinalized_output()`, a comm without `supports_finalize_before_combine()`, and `apply_router_weight_on_input`. With no hook registered, `do_finalize=False` plus a comm strategy stays a named runtime refusal instead of a crash inside the comm layer. diff --git a/tensorrt_llm/_torch/moe/fused_moe/configurable_moe.py b/tensorrt_llm/_torch/moe/fused_moe/configurable_moe.py index af814de66cc9..aed83acfdeb3 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/configurable_moe.py +++ b/tensorrt_llm/_torch/moe/fused_moe/configurable_moe.py @@ -804,6 +804,7 @@ def forward_impl( lora_params: Optional[Dict] = None, input_ready_event: Optional[torch.cuda.Event] = None, prerouted: Optional[PreroutedRouting] = None, + lamport_fc2_out: Optional[torch.Tensor] = None, **kwargs, ) -> torch.Tensor: """Forward entry point. @@ -824,6 +825,9 @@ def forward_impl( ``prerouted``: the tokens' routing, computed by the caller for a backend that declares ``supports_prerouted_routing`` (one chunk, no communication). + + ``lamport_fc2_out``: the un-finalized FC2 rows' buffer for a caller + whose MoE-output all-reduce polls them (``MoERunContext``). """ input_ids = kwargs.get("input_ids") routing_aux = kwargs.get("routing_aux") @@ -856,6 +860,7 @@ def forward_impl( routing_aux=routing_aux, input_ready_event=input_ready_event, prerouted=prerouted, + lamport_fc2_out=lamport_fc2_out, ) # DWDP: record compute and trigger next prefetch (per-layer, not per-chunk). diff --git a/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/base.py b/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/base.py index cee77145116c..0b64aa50a073 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/base.py +++ b/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/base.py @@ -26,6 +26,7 @@ from ...activation import DEFAULT_MOE_ACTIVATION, MoEActivation from ...cutlass.eligibility import BF16_ONLY, SmSupport from ...impl_base import MoEImplBase, apply_moe_impl_construction_state +from ...impl_contract import MoEDecodeOptions from ...quantization import MoEWeightLoadingMode from ...routing import BaseMoeRoutingMethod @@ -84,6 +85,10 @@ class CuteDslFusedMoEBase(MoEImplBase): #: replaces with per-partition shards, released after the split. _locality_domain_full_scale_params: tuple[str, ...] = () + #: Declared by the model (``MoEDecodeOptions.fc2_weights_evict_first_rows``): NVFP4 calls + #: of up to this many rows load the FC2 weights evict-first (0: none). + fc2_weights_evict_first_rows: int = 0 + def _has_moe_output_memset_aux_stream(self) -> bool: event_dict = getattr(self, "event_dict", None) aux_stream_dict = getattr(self, "aux_stream_dict", None) @@ -173,6 +178,9 @@ def __init__( self.use_fused_finalize = ( not model_config.moe_disable_finalize_fusion and model_config.lora_config is None ) + self.fc2_weights_evict_first_rows = MoEDecodeOptions.of( + model_config.extra_attrs + ).fc2_weights_evict_first_rows # Output-memset overlap is independent of MoE chunking, so ensure its # stream and events exist even if the parent creates no chunking event. diff --git a/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/nvfp4.py b/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/nvfp4.py index 1561dcb70d13..371ce90fbeae 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/nvfp4.py +++ b/tensorrt_llm/_torch/moe/fused_moe/cutedsl/grouped_gemm/nvfp4.py @@ -614,6 +614,12 @@ def run_moe_nvfp4_impl( finalize_inplace_kwargs["expert_capacity"] = ( deep_ep_expert_capacity if use_count_native_expert_metadata else 0 ) + finalize_inplace_kwargs["weights_evict_first"] = ( + token_selected_experts.size(0) <= self.fc2_weights_evict_first_rows + ) + finalize_inplace_kwargs["weights_evict_first_max_tokens"] = ( + self.fc2_weights_evict_first_rows + ) finalize_inplace_op(**finalize_inplace_kwargs) else: diff --git a/tensorrt_llm/_torch/moe/fused_moe/impl_blocks.py b/tensorrt_llm/_torch/moe/fused_moe/impl_blocks.py index 2f9be0026613..5cd980d34c0c 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/impl_blocks.py +++ b/tensorrt_llm/_torch/moe/fused_moe/impl_blocks.py @@ -63,6 +63,12 @@ class MoEExecutionContractMixin: # backend has to handle a short final partition to claim it. _supports_non_divisible_ep: bool = False + # An un-finalized ``run_moe`` handed ``MoERunContext.lamport_fc2_out`` may + # write its FC2 rows there and then returns that buffer as the rows; + # otherwise it returns its own rows and leaves the buffer untouched + # (``trtllm_gen.decode_moe.rows_in_lamport``). + takes_lamport_fc2_out: bool = False + def supports_moe_output_in_alltoall_workspace(self) -> bool: """Whether ``run_moe`` can write its output into the alltoall workspace. diff --git a/tensorrt_llm/_torch/moe/fused_moe/impl_contract.py b/tensorrt_llm/_torch/moe/fused_moe/impl_contract.py index 5567a8b72169..44c2b9e4040f 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/impl_contract.py +++ b/tensorrt_llm/_torch/moe/fused_moe/impl_contract.py @@ -67,6 +67,30 @@ class MoEStaticCapability: supports_deep_ep_direct_metadata: bool = False +#: ``ModelConfig.extra_attrs`` key of a model's MoEDecodeOptions. +MOE_DECODE_OPTIONS = "moe_decode_options" + + +@dataclass(frozen=True) +class MoEDecodeOptions: + """MoE decode kernels a model declares at construction (``extra_attrs[MOE_DECODE_OPTIONS]``); the defaults are the + stock paths every other model keeps.""" + + # trtllm-gen FP4 op: decode-step tuning buckets and decode kernels (trtllm_gen.decode_moe.select). + tuning: bool = False + # Rows from which the decode engine releases its dependents right after its own wait (0: never). + early_release_rows: int = 0 + # CuTe DSL NVFP4 calls of up to this many rows load the FC2 weights evict-first (0: none). + fc2_weights_evict_first_rows: int = 0 + # TRTLLM-Gen BF16: logits-routed un-finalized SwiGLU runs of up to 32 rows take the BF16 decode MoE engine. + bf16_decode_engine: bool = False + + @classmethod + def of(cls, extra_attrs: Dict) -> "MoEDecodeOptions": + """The options declared in a model config's ``extra_attrs``, else the defaults.""" + return extra_attrs.get(MOE_DECODE_OPTIONS, cls()) + + @dataclass(frozen=True) class MoEInputRequirement: """Caller-side inputs the scheduler must prepare; not a selection filter.""" @@ -704,7 +728,7 @@ class MoECommPlan: @dataclass(frozen=True) class PreroutedRouting: - """Routing a caller computed for one ``run_moe`` of an impl that declares + """Routing the caller computed for one ``run_moe`` of an impl that declares ``supports_prerouted_routing``: the routing tables of the kernels' tile (flat int32, layout of ``trtllm_gen.decode_front.prerouted_table_views``), the [tile, config] tactic they are built for, and the [num_tokens, top_k] @@ -717,6 +741,23 @@ class PreroutedRouting: topk_weights: torch.Tensor +@dataclass(frozen=True) +class EngineRouting(PreroutedRouting): + """Routing still to be done, by the decode MoE engine (``trtllm_gen.decode_moe`` + ``ENGINE``, under ``engine_routes``): ``candidates`` ([num_tokens, + num_experts / 128, top_k] int32, the router GEMM's per-tile top-k keys). + ``tables``, ``topk_ids`` and ``topk_weights`` are buffers the engine writes + before it reads them: only the ENGINE path consumes this hand-off (the FP4 + op raises for any other kernel), and nothing may read those buffers before + the op returns.""" + + candidates: Optional[torch.Tensor] = None + + def __post_init__(self) -> None: + if self.candidates is None: + raise ValueError("EngineRouting needs the router GEMM's candidates") + + @dataclass(frozen=True) class MoEReplicaPlan: """Per-forward physical replica layout produced by the EPLB layer. @@ -802,9 +843,15 @@ class MoERunContext: all_rank_num_tokens: Optional[List[int]] = None # produced by the comm strategy, one object per forward comm_plan: Optional[MoECommPlan] = None - # produced by a decode front end that routed the tokens itself; single - # chunk, no communication (see PreroutedRouting) + # produced by a decode front end: the routing it computed + # (PreroutedRouting), or, as an EngineRouting, left to the decode MoE + # engine, which writes it before it reads it; single chunk, no + # communication prerouted: Optional[PreroutedRouting] = None + # produced by a caller whose all-reduce polls the un-finalized FC2 rows + # (trtllm_gen.decode_moe.LamportFc2Buffer); one un-finalized chunk of a + # backend that declares ``takes_lamport_fc2_out`` + lamport_fc2_out: Optional[torch.Tensor] = None # produced by per-layer dynamic EPLB; None for standard EPLB and OFF. replica_plan: Optional[MoEReplicaPlan] = None # produced by routing when the impl's ``try_route_with_sort`` routed this diff --git a/tensorrt_llm/_torch/moe/fused_moe/interface.py b/tensorrt_llm/_torch/moe/fused_moe/interface.py index 8586f3583646..9d2fbdf21da5 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/interface.py +++ b/tensorrt_llm/_torch/moe/fused_moe/interface.py @@ -923,6 +923,10 @@ def forward( raise NotImplementedError( "the `trtllm::moe_custom_op` graph path cannot carry prerouted routing" ) + if kwargs.get("lamport_fc2_out") is not None: + raise NotImplementedError( + "the `trtllm::moe_custom_op` graph path cannot carry a Lamport FC2 output" + ) hidden_states = x.fp4_tensor if isinstance( x, Fp4QuantizedTensor) else x x_sf = x.scaling_factor if isinstance(x, diff --git a/tensorrt_llm/_torch/moe/fused_moe/moe_op_backend.py b/tensorrt_llm/_torch/moe/fused_moe/moe_op_backend.py index b27f381fcc7d..ae5875ce12c6 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/moe_op_backend.py +++ b/tensorrt_llm/_torch/moe/fused_moe/moe_op_backend.py @@ -36,7 +36,7 @@ from tensorrt_llm._torch.utils import ActType_TrtllmGen -from .impl_contract import PreroutedRouting +from .impl_contract import EngineRouting, PreroutedRouting # Global registry for MoE backends _MOE_OP_BACKEND_REGISTRY: Dict[str, Type["MoEOpBackend"]] = {} @@ -169,10 +169,17 @@ def run_fp4_block_scale_moe( use_dp: bool = False, prerouted: Optional[PreroutedRouting] = None, decode_tuning: bool = False, + decode_engine_state: Optional[torch.Tensor] = None, + lamport_fc2_out: Optional[torch.Tensor] = None, + decode_early_release_rows: int = 0, + decode_spare_sms: int = 0, ) -> List[torch.Tensor]: """Run FP4 block scale MoE computation. ``prerouted``: routing the caller computed (native op backend only). ``decode_tuning``: the native NVFP4 op - tunes for the model's decode steps (``FP4BlockScaleMoERunner``).""" + tunes for the model's decode steps and runs its decode kernels + (``FP4BlockScaleMoERunner``); ``decode_engine_state`` / + ``lamport_fc2_out`` / ``decode_early_release_rows`` / + ``decode_spare_sms``: see ``fp4_block_scale_moe_decode_runner``.""" raise NotImplementedError def run_bf16_moe( @@ -344,6 +351,10 @@ def run_fp4_block_scale_moe( use_dp=False, prerouted=None, decode_tuning=False, + decode_engine_state=None, + lamport_fc2_out=None, + decode_early_release_rows=0, + decode_spare_sms=0, ): # The native runners take the block scales as one flat linear-layout # tensor (``fp4BlockScaleMoe.cpp`` checks ``dim() == 1``); the @@ -418,8 +429,28 @@ def run_fp4_block_scale_moe( gemm1_weights_scale is not None and gemm1_weights_scale.shape[-1] == hidden_size // 16 ): - # nvfp4 - outputs = torch.ops.trtllm.fp4_block_scale_moe_runner( + # nvfp4; calls that take the decode kernels' buffers go to the op that declares their writes + decode_call = ( + decode_tuning + or decode_engine_state is not None + or lamport_fc2_out is not None + or isinstance(prerouted, EngineRouting) + ) + if decode_call: + fp4_op = torch.ops.trtllm.fp4_block_scale_moe_decode_runner + decode_kwargs = dict( + prerouted_candidates=( + prerouted.candidates if isinstance(prerouted, EngineRouting) else None + ), + decode_engine_state=decode_engine_state, + lamport_fc2_out=lamport_fc2_out, + decode_early_release_rows=decode_early_release_rows, + decode_spare_sms=decode_spare_sms, + ) + else: + fp4_op = torch.ops.trtllm.fp4_block_scale_moe_runner + decode_kwargs = {} + outputs = fp4_op( router_logits, routing_bias, hidden_states, @@ -459,8 +490,13 @@ def run_fp4_block_scale_moe( prerouted_weights=None if prerouted is None else prerouted.topk_weights, prerouted_tactic=None if prerouted is None else prerouted.tactic, decode_tuning=decode_tuning, + **decode_kwargs, ) if not do_finalize: + if lamport_fc2_out is not None and outputs[0].numel() == 0: + # The op's ABI for rows it wrote into the Lamport buffer + # (decode_moe.rows_in_lamport): an empty first output. + outputs = [lamport_fc2_out, *outputs[1:]] if prerouted is not None: # The op returns the FC2 rows; the top-k weights and the # expanded -> permuted index (head of the tables) are ours. diff --git a/tensorrt_llm/_torch/moe/fused_moe/moe_scheduler.py b/tensorrt_llm/_torch/moe/fused_moe/moe_scheduler.py index 8aa2cf14408a..2f3017cafa23 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/moe_scheduler.py +++ b/tensorrt_llm/_torch/moe/fused_moe/moe_scheduler.py @@ -132,6 +132,7 @@ def forward( routing_aux: Optional[torch.Tensor] = None, input_ready_event: Optional[torch.cuda.Event] = None, prerouted: Optional[PreroutedRouting] = None, + lamport_fc2_out: Optional[torch.Tensor] = None, ) -> torch.Tensor: ... @@ -176,10 +177,12 @@ def forward( routing_aux: Optional[torch.Tensor] = None, input_ready_event: Optional[torch.cuda.Event] = None, prerouted: Optional[PreroutedRouting] = None, + lamport_fc2_out: Optional[torch.Tensor] = None, ) -> torch.Tensor: """``input_ready_event``: ``x`` is written on another stream. The join is deferred to the first kernel that reads ``x`` so routing overlaps it. ``prerouted``: the routing of ``x`` (single chunk, no communication). + ``lamport_fc2_out``: see ``MoERunContext`` (single chunk). """ moe = self.moe @@ -244,6 +247,17 @@ def forward( # ========== Step 3: Execute MoE computation ========== if prerouted is not None and (num_chunks > 1 or moe.comm is not None or use_dp_padding): raise ValueError("prerouted routing needs one chunk without communication or padding") + if lamport_fc2_out is not None and ( + num_chunks > 1 + or moe.comm is not None + or use_dp_padding + or do_finalize + or not moe.backend.takes_lamport_fc2_out + ): + raise ValueError( + "a Lamport FC2 output takes one un-finalized chunk without communication or padding, " + "of a backend that writes it" + ) if num_chunks == 1: outputs = self._forward_single_chunk( x, @@ -257,6 +271,7 @@ def forward( routing_aux=routing_aux, input_ready_event=input_ready_event, prerouted=prerouted, + lamport_fc2_out=lamport_fc2_out, ) else: input_ready_event = _wait_input_ready(input_ready_event) @@ -409,6 +424,7 @@ def _forward_single_chunk( routing_aux: Optional[torch.Tensor] = None, input_ready_event: Optional[torch.cuda.Event] = None, prerouted: Optional[PreroutedRouting] = None, + lamport_fc2_out: Optional[torch.Tensor] = None, ) -> torch.Tensor: moe = self.moe is_first_call = moe.repeat_idx == 0 @@ -431,6 +447,7 @@ def _forward_single_chunk( routing_aux=routing_aux, input_ready_event=input_ready_event, prerouted=prerouted, + lamport_fc2_out=lamport_fc2_out, ) def _forward_chunk_impl( @@ -450,6 +467,7 @@ def _forward_chunk_impl( routing_aux: Optional[torch.Tensor] = None, input_ready_event: Optional[torch.cuda.Event] = None, prerouted: Optional[PreroutedRouting] = None, + lamport_fc2_out: Optional[torch.Tensor] = None, ) -> torch.Tensor: """Unified per-chunk execution flow for all external-comm backends. @@ -743,6 +761,7 @@ def _forward_chunk_impl( use_deep_ep_direct_metadata=use_deep_ep_direct_metadata, x_ready_event=x_ready_event, prerouted=prerouted, + lamport_fc2_out=lamport_fc2_out, sort_tables=sort_tables, ) final_hidden_states = moe.backend.run_moe( @@ -1126,6 +1145,7 @@ def _build_run_context( use_deep_ep_direct_metadata: bool = False, x_ready_event: Optional[torch.cuda.Event] = None, prerouted: Optional[PreroutedRouting] = None, + lamport_fc2_out: Optional[torch.Tensor] = None, sort_tables: Optional[MoESortTables] = None, ) -> MoERunContext: """The single ``run_moe`` argument set, identical for every backend. @@ -1153,6 +1173,7 @@ def _build_run_context( use_deep_ep_direct_metadata=use_deep_ep_direct_metadata, ), prerouted=prerouted, + lamport_fc2_out=lamport_fc2_out, sort_tables=sort_tables, ) @@ -1245,6 +1266,7 @@ def forward( routing_aux: Optional[torch.Tensor] = None, input_ready_event: Optional[torch.cuda.Event] = None, prerouted: Optional[PreroutedRouting] = None, + lamport_fc2_out: Optional[torch.Tensor] = None, ) -> torch.Tensor: """Sequential multi-chunk path for MegaMoE-style backends. @@ -1257,6 +1279,8 @@ def forward( del use_dp_padding # MegaMoE has no host-side cross-rank shape alignment. if prerouted is not None: raise ValueError("fused-comm MoE backends route in-kernel") + if lamport_fc2_out is not None: + raise ValueError("fused-comm MoE backends finalize in-kernel") _wait_input_ready(input_ready_event) # Fused-comm (MegaMoE) backends cannot carry LoRA adapters; routed-expert diff --git a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/base.py b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/base.py index 2e708a3e39e0..989075ac1f9a 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/base.py +++ b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/base.py @@ -46,6 +46,7 @@ MoEActivationSupport, ) from ..impl_base import MoEImplBase, apply_moe_impl_construction_state +from ..impl_contract import MoEDecodeOptions from ..impl_identity import MOE_IMPL_REGISTRY from ..interface import FORCE_SEPARATED_ROUTING, MoEWeightLoadingMode from ..moe_op_backend import MoEOpBackend, get_op_backend @@ -111,6 +112,9 @@ class TrtllmGenFusedMoEBase(MoEImplBase): capabilities = TRTLLM_GEN_CAPABILITIES input_requirement = TRTLLM_GEN_INPUT_REQUIREMENT + decode_tuning: bool = False + decode_early_release_rows: int = 0 + def __init_subclass__(cls, **kwargs: object) -> None: """Take the provider off the descriptor a leaf already publishes. @@ -211,9 +215,10 @@ def __init__( # Cached for autotune profile sizing (forward path passes # tune_max_num_tokens to the MoE op). self.max_num_tokens = model_config.max_num_tokens - # Declared by the model: the FP4 block-scale op tunes for its decode steps - # (FP4BlockScaleMoERunner.get_tuning_config). - self.decode_tuning = bool(model_config.extra_attrs.get("moe_decode_tuning", False)) + # Declared by the model (MoEDecodeOptions): the FP4 block-scale op's decode tuning and kernels. + decode = MoEDecodeOptions.of(model_config.extra_attrs) + self.decode_tuning = decode.tuning + self.decode_early_release_rows = decode.early_release_rows self.op_backend: MoEOpBackend = get_op_backend(self.provider) diff --git a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/decode_front.py b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/decode_front.py index ccf0ab4b945a..b7702e042711 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/decode_front.py +++ b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/decode_front.py @@ -23,7 +23,7 @@ hidden size (``router_front_supports``); other steps take the stock path. """ -from typing import Optional +from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Tuple, Union import torch import triton @@ -44,7 +44,12 @@ from ....modules.low_m_gemm import low_m_gemm_dispatcher from ....modules.low_m_mma_gemm import candidate_tactics from ....utils import Fp4QuantizedTensor -from ..impl_contract import PreroutedRouting +from ..impl_contract import EngineRouting, PreroutedRouting + +if TYPE_CHECKING: + from ....modules.expert_l2_prefetch import ExpertL2Prefetch + from ..configurable_moe import ConfigurableMoE + from .fp4_block_scale import TRTLLMGenFp4BlockScaleBase # Expert count and top-k the routing kernels are written for. KERNEL_NUM_EXPERTS = 512 @@ -53,9 +58,14 @@ ROUTER_MAX_TOKENS = 32 # Largest step of the one-launch front. FUSED_FRONT_MAX_TOKENS = 16 -# Largest step of the route front (route-only launch after the stock router GEMM): clusters of 8 up to 256 -# tokens, clusters of 16 (moe_route_front.ROUTE_CLUSTER_WIDE) above. +# Largest step of the route front (route-only launch after the router GEMM: the stock one, or the CuTe one below for +# the decode kernels' steps of ROUTER_MAX_TOKENS + 1 to ROUTER_GEMM_MAX_TOKENS rows): clusters of 8 up to 256 tokens, +# clusters of 16 (moe_route_front.ROUTE_CLUSTER_WIDE) above. ROUTE_FRONT_MAX_TOKENS = 1024 +# Router GEMM of the route front steps above ROUTER_MAX_TOKENS rows (DecodeFront's decode kernels): one tcgen05 launch +# whose split-K partials are summed inside the cluster in a fixed order (kernels/blackwell/moe_router_gemm.py), +# instead of the stock GEMM (cuBLAS + its split-K reduce). Not bitwise to it (BF16 rounding of some logits). +ROUTER_GEMM_MAX_TOKENS = 128 # Warps per program of the per-token route + tables kernel (one warp leaves the last program's table phase # serial). _ROUTE_WARPS = 4 @@ -64,15 +74,20 @@ MIN_KEY = tl.constexpr(-2147483648) -def route_front_steps(cuda_graph_batch_sizes, tokens_per_gen_step: int) -> frozenset: +def route_front_steps( + cuda_graph_batch_sizes: Iterable[int], + tokens_per_gen_step: int, + min_rows: int = ROUTER_MAX_TOKENS + 1, +) -> frozenset: """Token counts the route front takes: the CUDA-graph decode steps (``b`` draft and ``tokens_per_gen_step * b`` - target rows per graph batch size ``b``) above the router GEMM's range. Other counts keep the stock path, so - the front compiles no kernel for shapes an eager step happens to have.""" + target rows per graph batch size ``b``) from ``min_rows`` rows (default: above the router GEMM's range; a caller + may start right above the one-launch front's range, ``FUSED_FRONT_MAX_TOKENS + 1``). Other counts keep the stock + path, so the front compiles no kernel for shapes an eager step happens to have.""" return frozenset( m for b in cuda_graph_batch_sizes for m in (b, tokens_per_gen_step * b) - if ROUTER_MAX_TOKENS < m <= ROUTE_FRONT_MAX_TOKENS + if min_rows <= m <= ROUTE_FRONT_MAX_TOKENS ) @@ -743,8 +758,9 @@ def _route_front_compile( top_k: int, a_stride: int, use_pdl: bool, + lean: bool = False, ): - key = (m, k, n, num_local, tile, top_k, a_stride, use_pdl) + key = (m, k, n, num_local, tile, top_k, a_stride, use_pdl, lean) if key in _ROUTE_FRONT_COMPILED: return _ROUTE_FRONT_COMPILED[key] # None: the kernel does not take this shape if torch.cuda.is_current_stream_capturing(): @@ -756,26 +772,29 @@ def _route_front_compile( from ....kernels.blackwell.moe_route_front import ( ROUTE_CLUSTER, ROUTE_CLUSTER_WIDE, + ROUTE_THREADS, MoeRouteFrontKernel, ) wide = m > ROUTE_CLUSTER * 32 # above 256 tokens: clusters of 16 - try: - kernel = MoeRouteFrontKernel( - num_rows=m, - k_extent=k, - num_experts=n, - top_k=top_k, - num_local=num_local, - tile=tile, - a_stride=a_stride, - use_pdl=use_pdl, - cluster=ROUTE_CLUSTER_WIDE if wide else ROUTE_CLUSTER, - quant_clusters=3 if wide else 7, - ) - except ValueError: + lean = lean and not wide + config = dict( + num_rows=m, + k_extent=k, + num_experts=n, + top_k=top_k, + num_local=num_local, + tile=tile, + a_stride=a_stride, + cluster=ROUTE_CLUSTER_WIDE if wide else ROUTE_CLUSTER, + quant_clusters=3 if wide else 7, + threads=_route_front_threads(m, k, num_local) if lean else ROUTE_THREADS, + lean=lean, + ) + if not MoeRouteFrontKernel.supports(**config): _ROUTE_FRONT_COMPILED[key] = None return None + kernel = MoeRouteFrontKernel(use_pdl=use_pdl, **config) z = cutlass.Int64(0) stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream) fn = (cute.compile(kernel, z, z, z, z, z, z, z, z, cutlass.Int32(0), stream), kernel.ctas) @@ -783,23 +802,158 @@ def _route_front_compile( return fn +def _route_front_threads(m: int, k: int, num_local: int) -> int: + """Threads per CTA of the lean route front: the fewest of 256 / 512 / 1024 that keep one token per routing warp, + one thread per local expert and one quantization pass at 7 quantization clusters (else 1024). Fewer threads need + fewer registers, so the CTAs fit beside the decode step's other kernels.""" + tokens_per_cta = -(-m // 8) # the lean kernel's routing cluster of 8 CTAs, one token per warp + for threads in (256, 512, 1024): + if ( + 32 * tokens_per_cta <= threads + and num_local <= threads + and m * (k // 16) <= 7 * 8 * threads + ): + return threads + return 1024 + + +_ROUTER_GEMM_COMPILED = {} + + +def _router_gemm_compile( + m: int, k: int, n: int, a_stride: int, use_pdl: bool, route_top_k: int = 0 +) -> Optional[Callable]: + key = (m, k, n, a_stride, use_pdl, route_top_k) + if key in _ROUTER_GEMM_COMPILED: + return _ROUTER_GEMM_COMPILED[key] # None: the kernel does not take this shape + if torch.cuda.is_current_stream_capturing(): + return None # compile outside graph capture only (eager warmup precedes it) + import cuda.bindings.driver as cuda + import cutlass + import cutlass.cute as cute + + from ....kernels.blackwell.moe_router_gemm import ( + QUANT_ROWS_PER_TILE, + MoeRouterGemmKernel, + router_gemm_token_tile, + ) + from ....kernels.blackwell.utils import make_ptr + + # route_top_k: the epilogue the routing MoE engine reads, whose x quantization sets the token tile + token_tile = QUANT_ROWS_PER_TILE * (n // 128) if route_top_k else router_gemm_token_tile(m) + if token_tile is None: + _ROUTER_GEMM_COMPILED[key] = None + return None + shape = dict( + num_rows=m, + k_extent=k, + num_experts=n, + a_stride=a_stride, + token_tile=token_tile, + ) + if not MoeRouterGemmKernel.supports(**shape, route_top_k=route_top_k): + _ROUTER_GEMM_COMPILED[key] = None + return None + kernel = MoeRouterGemmKernel(use_pdl=use_pdl, route_top_k=route_top_k, **shape) + dev = torch.device("cuda") + x = torch.empty((m, a_stride), dtype=torch.bfloat16, device=dev) + w = torch.empty((n, k), dtype=torch.bfloat16, device=dev) + xp = make_ptr(cutlass.BFloat16, x.data_ptr(), cute.AddressSpace.gmem, assumed_align=16) + wp = make_ptr(cutlass.BFloat16, w.data_ptr(), cute.AddressSpace.gmem, assumed_align=16) + stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream) + epilogue = (cutlass.Int64(0),) * 4 if route_top_k else () + fn = cute.compile(kernel, xp, wp, cutlass.Int64(0), stream, *epilogue) + _ROUTER_GEMM_COMPILED[key] = fn + return fn + + +class RouteFrontRouterGemm: + """Launcher of the route front steps' router GEMM: logits [m, E] bf16 = x @ weight.T, or None (the caller + then runs the stock GEMM). + + ``engine_route``: the GEMM of the steps the decode MoE engine routes, which also returns each token's top + ``top_k`` keys per 128-expert tile (candidates [m, E / 128, top_k] int32) and the NVFP4 quantization of x with + ``global_scale`` (xq [m, H / 2] u8, linear xsf [m, H / 16] u8).""" + + engine_route: bool = False + + def __init__(self, engine_route: bool = False) -> None: + self.engine_route = engine_route + + def __call__( + self, + x: torch.Tensor, + weight: torch.Tensor, + global_scale: Optional[torch.Tensor] = None, + top_k: int = 0, + ) -> Union[None, torch.Tensor, Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]]: + m, k = x.shape + n = weight.shape[0] + if ( + not ROUTER_MAX_TOKENS < m <= ROUTER_GEMM_MAX_TOKENS + or x.dtype != torch.bfloat16 + or weight.dtype != torch.bfloat16 + or weight.shape[1] != k + or not weight.is_contiguous() + or x.stride(1) != 1 + or x.stride(0) % 8 + or x.data_ptr() % 16 + or weight.data_ptr() % 16 + ): + return None + route_top_k = top_k if self.engine_route else 0 + if self.engine_route and top_k < 1: + raise ValueError("an engine_route router GEMM takes the router's top_k") + fn = _router_gemm_compile(m, k, n, x.stride(0), get_env_enable_pdl(), route_top_k) + if fn is None: + return None + import cuda.bindings.driver as cuda + import cutlass + import cutlass.cute as cute + + from ....kernels.blackwell.utils import make_ptr + + out = torch.empty((m, n), dtype=torch.bfloat16, device=x.device) + args = ( + make_ptr(cutlass.BFloat16, x.data_ptr(), cute.AddressSpace.gmem, assumed_align=16), + make_ptr(cutlass.BFloat16, weight.data_ptr(), cute.AddressSpace.gmem, assumed_align=16), + cutlass.Int64(out.data_ptr()), + cuda.CUstream(torch.cuda.current_stream().cuda_stream), + ) + if not self.engine_route: + fn(*args) + return out + cand = torch.empty((m, n // 128, top_k), dtype=torch.int32, device=x.device) + xq = torch.empty((m, k // 2), dtype=torch.uint8, device=x.device) + xsf = torch.empty((m, k // 16), dtype=torch.uint8, device=x.device) + p64 = lambda t: cutlass.Int64(t.data_ptr()) # noqa: E731 + fn(*args, p64(cand), p64(global_scale), p64(xq), p64(xsf)) + return out, cand, xq, xsf + + class RouteFront: """Launcher of the route front: routing + pre-routed tables + NVFP4 x in one launch after the stock router - GEMM (no device state carried between launches).""" + GEMM (no device state carried between launches). ``lean``: up to 256 rows, the kernel's lean table build that + releases the MoE at the front's start (``MoeRouteFrontKernel``), bitwise to the default one.""" + + def __init__(self, lean: bool = False) -> None: + self.lean = lean - def compiled(self, x: torch.Tensor, n: int, tile: int, num_local: int, top_k: int): + def compiled( + self, x: torch.Tensor, n: int, tile: int, num_local: int, top_k: int + ) -> Optional[Tuple[Callable[..., None], Any]]: """The compiled launch for this call, or None when the kernel does not take it (checked before the router GEMM runs, so the caller can still take the stock path).""" m, k = x.shape if m > ROUTE_FRONT_MAX_TOKENS or x.stride(0) % 8 or x.data_ptr() % 16: return None return _route_front_compile( - m, k, n, num_local, tile, top_k, x.stride(0), get_env_enable_pdl() + m, k, n, num_local, tile, top_k, x.stride(0), get_env_enable_pdl(), self.lean ) def __call__( self, - fn, + fn: Tuple[Callable[..., None], Any], logits: torch.Tensor, x: torch.Tensor, global_scale: torch.Tensor, @@ -808,7 +962,7 @@ def __call__( local_start: int, num_local: int, top_k: int, - ): + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: """(xq [m, H/2] u8, xsf [m, H/16] u8, ids [m, K] int32, bf16 weights [m, K]) with the tables written into ``flat`` (prerouted_table_views layout for (m, top_k, num_local, tile)).""" import cuda.bindings.driver as cuda @@ -894,7 +1048,8 @@ class FrontRunner(TunableRunner): """The two ways a step of up to ``FUSED_FRONT_MAX_TOKENS`` tokens can produce the routed experts' inputs, timed whole by the AutoTuner (the experts after them are the same): tactic ``k_warps`` > 0 is the one-launch front with the router GEMM split over that many warps; tactic 0 (and the fallback -1) is the gate's own - projection (the low-M race's pick) followed by the route + tables launch. + projection (the low-M race's pick) followed by the route + tables launch. A ``fused_only`` front offers tactic + 0 only where no warp split takes the step. Inputs: [x [m, H] bf16, NVFP4 global scale]. ``tile_of(m)``: the MoE tactic's tile for m tokens, or None.""" @@ -916,7 +1071,14 @@ class FrontRunner(TunableRunner): ) def __init__( - self, front: "DecodeFront", gate, num_local: int, local_start: int, top_k: int, tile_of + self, + front: "DecodeFront", + gate, + num_local: int, + local_start: int, + top_k: int, + tile_of, + do_finalize: bool = True, ): self.front = front self.gate = gate @@ -924,9 +1086,17 @@ def __init__( self.local_start = local_start self.top_k = top_k self.tile_of = tile_of + self.do_finalize = do_finalize def unique_id(self): - return (tuple(self.gate.weight.shape), self.num_local, self.top_k) + # tile_of(m) is the MoE tactic of calls with this do_finalize, which the tactics offered depend on. + return ( + tuple(self.gate.weight.shape), + self.num_local, + self.top_k, + self.front.fused_only, + self.do_finalize, + ) def get_valid_tactics(self, inputs, profile, **kwargs): x = inputs[0] @@ -945,6 +1115,8 @@ def get_valid_tactics(self, inputs, profile, **kwargs): and FusedFront.supports(x, w, self.num_local, tile, self.top_k, t) } ) + if fused and self.front.fused_only: + return fused return [0, *fused] def forward(self, inputs, *, tactic=-1, do_preparation=False, **kwargs): @@ -978,33 +1150,87 @@ def forward(self, inputs, *, tactic=-1, do_preparation=False, **kwargs): class DecodeFront: """Per MoE layer decode front (module docstring). - ``route_steps``: token counts the route front takes after the stock router GEMM (``route_front_steps``); + ``route_steps``: token counts the route front takes after the router GEMM (``route_front_steps``); other counts up to ``ROUTER_MAX_TOKENS`` run the router GEMM in the front (power-of-two hidden sizes only, ``router_front_supports``), as one launch where the AutoTuner's race of the two (``FrontRunner``) picked it. + ``decode_kernels`` (declared by the model): the route front steps run the CuTe router GEMM above + ``ROUTER_MAX_TOKENS`` rows and the lean route front, and the steps the one-launch front takes run it + (``fused_only``: the race picks among its warp splits only). + ``engine_route`` (declared by the model): an un-finalized route front call whose rows the routing engine and + its router GEMM epilogue take (``decode_moe.engine_routes``, ``RouteFrontRouterGemm``) runs the router GEMM with + each token's per-tile candidates and NVFP4 x in its epilogue, and the engine routes + (``EngineRouting.candidates``). """ - def __init__(self, route_steps: frozenset): + fused_only: bool = False + engine_router: Optional[RouteFrontRouterGemm] = None + + def __init__( + self, + route_steps: frozenset, + decode_kernels: bool = False, + engine_route: bool = False, + ) -> None: self.route_steps = route_steps + self.fused_only = decode_kernels self.route = RouteTables() self.router_gemm = RouterGemm() self.fused = FusedFront() - self.route_front = RouteFront() - # Per token count: the MoE op's tactic, and per (token count, tile) the table buffer. A buffer first made - # during CUDA-graph capture comes from the graph's pool and stays with the layer. + self.route_front = RouteFront(lean=decode_kernels) + self.route_front_router = RouteFrontRouterGemm() if decode_kernels else None + if engine_route: + self.engine_router = RouteFrontRouterGemm(engine_route=True) + # Per (token count, do_finalize): the MoE op's tactic; per (token count, tile): the table buffer. A buffer + # first made during CUDA-graph capture comes from the graph's pool and stays with the layer. self._tactics = {} self._tables = {} - # Per token count: the FrontRunner tactic (k_warps of the one-launch front, 0 for the two launches). + # Per (token count, do_finalize): the FrontRunner tactic (k_warps of the one-launch front, 0 for the two + # launches). self._front_tactics = {} - - def _moe_tactic(self, backend, m: int) -> Optional[list]: - tactic = self._tactics.get(m) + # (ExpertL2Prefetch, layer index): un-finalized calls record their experts for the next step's prefetch. + self._expert_prefetch = None + # Per token count: whether an un-finalized call routes in the decode MoE engine (decode_moe.engine_routes), + # once the backend's engine state exists (everything else it reads is fixed per layer). + self._engine_route_rows = {} + + def set_expert_prefetch(self, prefetch: "ExpertL2Prefetch", layer_idx: int) -> None: + self._expert_prefetch = (prefetch, layer_idx) + + def _moe_tactic( + self, backend: "TRTLLMGenFp4BlockScaleBase", m: int, do_finalize: bool + ) -> Optional[list]: + """The MoE op's tuned tactic for a call of ``m`` rows and ``do_finalize`` (part of its tuning key).""" + tactic = self._tactics.get((m, do_finalize)) if tactic is None: - tactic = backend.decode_tactic(m) + tactic = backend.decode_tactic(m, do_finalize) if tactic is not None: - self._tactics[m] = tactic + self._tactics[(m, do_finalize)] = tactic return tactic - def _table_buffer(self, m: int, top_k: int, num_local: int, tile: int, device) -> torch.Tensor: + def _engine_routes( + self, + backend: "TRTLLMGenFp4BlockScaleBase", + m: int, + top_k: int, + num_experts: int, + moe_kwargs: Dict[str, Any], + ) -> bool: + """Whether this call routes in the decode MoE engine: declared, un-finalized, on a backend whose call of + ``m`` rows takes the routing engine (the router GEMM may still decline the rows, then the route front runs).""" + if self.engine_router is None or moe_kwargs.get("do_finalize", True): + return False + routes = self._engine_route_rows.get(m) + if routes is None: + from .decode_moe import engine_routes + + routes = engine_routes(backend, m, top_k, num_experts) + if backend.decode_engine_state is not None: + self._engine_route_rows[m] = routes + return routes + + def _table_buffer( + self, m: int, top_k: int, num_local: int, tile: int, device: torch.device + ) -> torch.Tensor: flat = self._tables.get((m, tile)) if flat is None: flat = torch.empty( @@ -1015,7 +1241,9 @@ def _table_buffer(self, m: int, top_k: int, num_local: int, tile: int, device) - self._tables[(m, tile)] = flat return flat - def _front_runner(self, gate, moe) -> FrontRunner: + def _front_runner( + self, gate: torch.nn.Module, moe: "ConfigurableMoE", do_finalize: bool + ) -> FrontRunner: backend = moe.backend return FrontRunner( self, @@ -1023,37 +1251,59 @@ def _front_runner(self, gate, moe) -> FrontRunner: backend.expert_size_per_partition, backend.slot_start, moe.routing_method.experts_per_token, - lambda m: (t[0] if (t := self._moe_tactic(backend, m)) is not None else None), + lambda m: ( + t[0] if (t := self._moe_tactic(backend, m, do_finalize)) is not None else None + ), + do_finalize, ) - def _front_tactic(self, gate, moe, x: torch.Tensor, gs: torch.Tensor) -> int: - """The raced FrontRunner tactic for x's token count (0 until the race has run).""" + def _front_tactic( + self, + gate: torch.nn.Module, + moe: "ConfigurableMoE", + x: torch.Tensor, + gs: torch.Tensor, + do_finalize: bool, + ) -> int: + """The raced FrontRunner tactic for x's token count and ``do_finalize`` (0 until the race has run).""" m = x.shape[0] - tactic = self._front_tactics.get(m) + tactic = self._front_tactics.get((m, do_finalize)) if tactic is None: _, tactic = AutoTuner.get().choose_one( - FrontRunner.OP, [self._front_runner(gate, moe)], FrontRunner.TUNING_CONFIG, [x, gs] + FrontRunner.OP, + [self._front_runner(gate, moe, do_finalize)], + FrontRunner.TUNING_CONFIG, + [x, gs], ) if tactic == -1: return 0 - self._front_tactics[m] = tactic + self._front_tactics[(m, do_finalize)] = tactic return tactic - def _tune(self, gate, moe, x: torch.Tensor, **moe_kwargs): + def _tune( + self, gate: torch.nn.Module, moe: "ConfigurableMoE", x: torch.Tensor, **moe_kwargs: Any + ) -> Union[torch.Tensor, List[torch.Tensor]]: """Autotuning step: the stock router GEMM and MoE (which tune their own races), then, once the router race covers the front's token counts, the race of the two fronts. Returns the stock output.""" out = moe(x, gate(x), output_dtype=x.dtype, **moe_kwargs) dispatcher = low_m_gemm_dispatcher(gate) - if dispatcher is not None and x.shape[0] <= ROUTER_MAX_TOKENS: + # The one-launch front runs the router GEMM in it: power-of-two hidden sizes only. + if ( + dispatcher is not None + and x.shape[0] <= ROUTER_MAX_TOKENS + and router_front_supports(x.shape[1]) + ): AutoTuner.get().choose_one( FrontRunner.OP, - [self._front_runner(gate, moe)], + [self._front_runner(gate, moe, moe_kwargs.get("do_finalize", True))], FrontRunner.TUNING_CONFIG, [x[:FUSED_FRONT_MAX_TOKENS], moe.backend.fc31_input_scale], ) return out - def __call__(self, gate, moe, x: torch.Tensor, **moe_kwargs): + def __call__( + self, gate: torch.nn.Module, moe: "ConfigurableMoE", x: torch.Tensor, **moe_kwargs: Any + ) -> Union[None, torch.Tensor, List[torch.Tensor]]: """Routed-expert output of ``moe`` for ``x`` through the decode front, or None when it does not apply (the caller then runs the stock path). @@ -1077,7 +1327,8 @@ def __call__(self, gate, moe, x: torch.Tensor, **moe_kwargs): if AutoTuner.get().is_tuning_mode: return self._tune(gate, moe, x, **moe_kwargs) backend = moe.backend - tactic = self._moe_tactic(backend, m) + do_finalize = moe_kwargs.get("do_finalize", True) + tactic = self._moe_tactic(backend, m, do_finalize) if tactic is None: return None tile = tactic[0] @@ -1085,19 +1336,33 @@ def __call__(self, gate, moe, x: torch.Tensor, **moe_kwargs): local_start, num_local = backend.slot_start, backend.expert_size_per_partition flat = self._table_buffer(m, top_k, num_local, tile, x.device) gs = backend.fc31_input_scale + candidates = None if route_front: - fn = self.route_front.compiled(x, gate.weight.shape[0], tile, num_local, top_k) - if fn is None: - return None - logits = gate(x) - xq, xsf, ids, wts = self.route_front( - fn, logits, x, gs, flat, tile, local_start, num_local, top_k - ) + routed = None + if self._engine_routes(backend, m, top_k, gate.weight.shape[0], moe_kwargs): + routed = self.engine_router(x, gate.weight, gs, top_k) + if routed is not None: + # the MoE engine writes ids, weights and tables from the candidates + logits, candidates, xq, xsf = routed + ids = torch.empty((m, top_k), dtype=torch.int32, device=x.device) + wts = torch.empty((m, top_k), dtype=torch.bfloat16, device=x.device) + else: + fn = self.route_front.compiled(x, gate.weight.shape[0], tile, num_local, top_k) + if fn is None: + return None + logits = None + if self.route_front_router is not None: + logits = self.route_front_router(x, gate.weight) + if logits is None: + logits = gate(x) + xq, xsf, ids, wts = self.route_front( + fn, logits, x, gs, flat, tile, local_start, num_local, top_k + ) else: dispatcher = low_m_gemm_dispatcher(gate) fused = None k_warps = ( - self._front_tactic(gate, moe, x, gs) + self._front_tactic(gate, moe, x, gs, do_finalize) if dispatcher is not None and m <= FUSED_FRONT_MAX_TOKENS else 0 ) @@ -1117,13 +1382,22 @@ def __call__(self, gate, moe, x: torch.Tensor, **moe_kwargs): logits, xq, xsf = self.router_gemm(x, gate.weight, gs) ids, wts, *_ = self.route(logits, top_k, local_start, num_local, tile, flat=flat) x_in = Fp4QuantizedTensor(xq, xsf, is_sf_swizzled=False) - return moe( + out = moe( x_in, logits, output_dtype=x.dtype, - prerouted=PreroutedRouting(flat, tactic, ids, wts), + prerouted=( + PreroutedRouting(flat, tactic, ids, wts) + if candidates is None + else EngineRouting(flat, tactic, ids, wts, candidates) + ), **moe_kwargs, ) + if self._expert_prefetch is not None and not do_finalize: + prefetch, layer_idx = self._expert_prefetch + _, _, batch, limit, nct, _ = prerouted_table_views(flat, m, top_k, num_local, tile) + prefetch.record(layer_idx, batch, limit, nct, tile, num_local, flat, rows=m) + return out __all__ = [ @@ -1132,6 +1406,7 @@ def __call__(self, gate, moe, x: torch.Tensor, **moe_kwargs): "KERNEL_NUM_EXPERTS", "KERNEL_TOP_K", "ROUTE_FRONT_MAX_TOKENS", + "ROUTER_GEMM_MAX_TOKENS", "ROUTER_MAX_TOKENS", "front_eligible", "nvfp4_quant_rows", diff --git a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/decode_moe.py b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/decode_moe.py new file mode 100644 index 000000000000..09c16bb7c821 --- /dev/null +++ b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/decode_moe.py @@ -0,0 +1,474 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Decode kernels of the trtllm-gen NVFP4 MoE op (``FP4BlockScaleMoERunner``), where the model declares them +(``MoEDecodeOptions.tuning``). :func:`select` picks an un-finalized call's kernels (:class:`DecodeKernel`); each +produces the runner's gemm2 rows bit for bit and returns its ``do_finalize=False`` outputs: + +* ``ENGINE``: a pre-routed SwiGLU call, FC1 -> SwiGLU -> NVFP4 -> FC2 in one persistent launch (``moe_nvfp4_engine``); + given the router GEMM's per-tile candidates it also routes the call (:func:`engine_routes`). +* ``CUTE_FC2``: up to :data:`MAX_TOKENS` tokens whose FC2 cubin ``moe_lowm_fc2`` reproduces: the runner's FC1, then + FC2 on ``moe_lowm_fc2`` (two smaller CTAs per SM). +* ``CUBIN``: the runner's own FC1 and FC2 (also where it runs its fine-grained-sync pair, which has no FC1-only + entry: ``TLLM_USE_FINE_GRAINED_SYNC`` with such a cubin for the shape). + +Lamport FC2 (:class:`LamportFc2Buffer`): ``ENGINE`` / ``CUTE_FC2`` store nothing before their PDL wait, release their +dependents only after it and write each word of a real row once (``cvt.rn.satfinite.bf16x2.f32``, never 0xFFFFFFFF), +so the MoE-output all-reduce can poll their rows instead of waiting for FC2. +""" + +import enum +from types import SimpleNamespace +from typing import TYPE_CHECKING, Dict, List, Mapping, Optional, Sequence, Tuple + +import torch + +from tensorrt_llm._torch.utils import ActType_TrtllmGen + +from .decode_front import max_num_tiles +from .kernel_inputs import get_data_or_none, to_trtllm_gen_act_type + +if TYPE_CHECKING: + from ....custom_ops.trtllm_gen_custom_ops import FP4BlockScaleMoEInputs + from .fp4_block_scale import TRTLLMGenFp4BlockScaleBase + +#: Most tokens of a CuTe FC2 call (the kernel walks the runner's tile tables and has no token bound of its own). +MAX_TOKENS = 128 +#: The runner's token tile whose FC2 cubins the CuTe FC2 reproduces. +TILE_N = 8 +#: Most SMs ``ENGINE``'s persistent grid leaves free for work another stream runs beside it +#: (``TRTLLMGenFp4BlockScaleBase.sm_reserve_ceiling``): a shared expert's down-projection CTAs cannot share an SM with +#: an engine CTA. Measured on GB300 with Qwen3.5-397B-A17B NVFP4 (hidden 4096, top-10) MTP decode steps at the GEN +#: reference layouts; other GPUs and expert shapes are not measured. +ENGINE_SPARE_SMS = 8 +#: Fewest rows of a call whose segments take MMA N 64 (fewer rows take N 32): the crossover measured on GB300 with the +#: same Qwen3.5-397B-A17B NVFP4 decode steps. +N64_MIN_ROWS = 225 + +#: The FC2 cubin options ``moe_lowm_fc2`` reproduces bit for bit (``get_gemm2_kernel_options`` of the C++ runner): +#: E2m1 x E2m1 -> FP32 -> BF16 in tiles of 128 x TILE_N with M128 N8 K64 MMAs over the whole K in order (one CTA per +#: tile, no split-K). The tile K, stage count, unrolling and tile scheduler only change when those MMAs issue. +_CUTE_FC2_OPTIONS = { + "dtypeA": "E2m1", + "dtypeB": "E2m1", + "dtypeAcc": "Fp32", + "dtypeC": "Bfloat16", + "tileM": "128", + "tileN": str(TILE_N), + "mmaM": "128", + "mmaN": str(TILE_N), + "mmaK": "64", + "clusterDimX": "1", + "clusterDimY": "1", + "clusterDimZ": "1", + "numSlicesForSplitK": "1", +} + + +def cute_fc2_reproduces(gemm2_kernel_options: Mapping[str, str]) -> bool: + """Whether ``moe_lowm_fc2`` reproduces the FC2 cubin of these options (the runner's + ``get_gemm2_kernel_options(tile, config)``) bit for bit.""" + return all(gemm2_kernel_options.get(key) == value for key, value in _CUTE_FC2_OPTIONS.items()) + + +class DecodeKernel(enum.Enum): + CUBIN = 0 + CUTE_FC2 = 1 + ENGINE = 2 + + +#: (act type, tile, config) -> whether ``moe_lowm_fc2`` reproduces that tactic's FC2 cubin. The C++ runners are +#: shared per act type (``FP4BlockScaleMoERunner.get_runner``), so the key names the cubin. +_FC2_REPRODUCED: Dict[Tuple[int, int, int], bool] = {} + + +def _cute_fc2_fits( + kernel_runner: torch.ScriptObject, + act_type: int, + tactic: List[int], + args: "FP4BlockScaleMoEInputs", + top_k: int, + intermediate_size: int, +) -> bool: + if len(tactic) != 2 or tactic[0] != TILE_N or tactic[1] < 0: + return False + x, w2, w2_sf = args.hidden_states, args.gemm2_weights, args.gemm2_weights_scale + if x.shape[0] > MAX_TOKENS or w2.dim() != 3 or w2_sf.dim() != 3: + return False + if w2.shape[2] * 2 != intermediate_size: + return False + key = (int(act_type), int(tactic[0]), int(tactic[1])) + reproduced = _FC2_REPRODUCED.get(key) + if reproduced is None: + reproduced = _FC2_REPRODUCED[key] = cute_fc2_reproduces( + kernel_runner.get_gemm2_kernel_options(key[1], key[2]) + ) + # The CuTe FC2 stands in for the tuned tactic's FC2; the runner runs its fine-grained-sync pair instead (which + # has no FC1-only entry) only where TLLM_USE_FINE_GRAINED_SYNC is set and such a cubin exists for this shape. + return reproduced and not kernel_runner.uses_fine_grained_sync( + key[1], top_k, 2 * x.shape[1], intermediate_size, w2.shape[0], x.shape[0] + ) + + +def _engine_fits(args: "FP4BlockScaleMoEInputs", act_type: int, top_k: int) -> bool: + """The engine's operands and shapes, with the K tile :func:`tile_k_for` picks for this call dividing both GEMMs' + K and the call's (expert, row chunk) segments within the engine's segment table.""" + if act_type != ActType_TrtllmGen.SwiGlu or args.hidden_states_scale is None: + return False + if any( + t is not None + for t in (args.gemm1_bias, args.gemm1_alpha, args.gemm1_beta, args.gemm1_clamp_limit) + ): + return False + if any( + t is None + for t in ( + args.output1_scale_scalar, + args.output1_scale_gate_scalar, + args.output2_scale_scalar, + ) + ): + return False + from tensorrt_llm._torch.kernels.blackwell.moe_nvfp4_engine import MAX_LOCAL_EXPERTS, SEG_CAP + + w13, w2, x = args.gemm1_weights, args.gemm2_weights, args.hidden_states + if w13.dim() != 3 or w2.dim() != 3 or w13.shape[0] > MAX_LOCAL_EXPERTS or x.dim() != 2: + return False + hidden, inter = w2.shape[1], w13.shape[1] // 2 + if w2.shape[2] * 2 != inter or w13.shape[2] * 2 != hidden or x.shape[1] * 2 != hidden: + return False + n_max = n_max_for(x.shape[0]) + if w13.shape[0] + -(-x.shape[0] * top_k // n_max) > SEG_CAP: + return False + tile_k = tile_k_for(n_max, hidden, inter) + return hidden % tile_k == 0 and inter % tile_k == 0 + + +def takes_engine( + args: "FP4BlockScaleMoEInputs", + act_type: int, + *, + top_k: int, + do_finalize: bool, + output: Optional[torch.Tensor], + prerouted: bool, + engine_state: Optional[torch.Tensor], +) -> bool: + """Whether :func:`select` picks ``ENGINE`` for this call (arguments as there).""" + return ( + not do_finalize + and output is None + and args.gemm2_bias is None + and prerouted + and engine_state is not None + and _engine_fits(args, act_type, top_k) + ) + + +def engine_routes( + backend: "TRTLLMGenFp4BlockScaleBase", num_rows: int, top_k: int, num_experts: int +) -> bool: + """Whether ``backend``'s (``TRTLLMGenFp4BlockScaleBase``) un-finalized pre-routed call of ``num_rows`` NVFP4 + tokens over ``num_experts`` experts runs ``ENGINE`` with the routing in the engine (``moe_nvfp4_engine``'s + ``route_top_k`` / ``route_lists``): :func:`takes_engine` on the operands its ``run_moe`` passes, within the + routing's bounds: ``moe_nvfp4_engine.route_error`` on ``top_k`` keys of ``num_experts / 128`` lists, and the + router GEMM's ``route_top_k`` epilogue that writes them.""" + from tensorrt_llm._torch.kernels.blackwell.moe_nvfp4_engine import ROUTE_MAX_ROWS, route_error + from tensorrt_llm._torch.kernels.blackwell.moe_router_gemm import ( + QUANT_ROWS_PER_TILE, + MoeRouterGemmKernel, + ) + + if not backend.decode_tuning or not 0 < num_rows <= ROUTE_MAX_ROWS: + return False + if num_experts % 128 or route_error(top_k, num_experts // 128) is not None: + return False + act_type = to_trtllm_gen_act_type(backend.activation_type) + if act_type != ActType_TrtllmGen.SwiGlu: + return False + packed_hidden = backend.w3_w1_weight.shape[-1] + if not MoeRouterGemmKernel.supports( + num_rows=num_rows, + k_extent=2 * packed_hidden, + num_experts=num_experts, + a_stride=2 * packed_hidden, + token_tile=QUANT_ROWS_PER_TILE * (num_experts // 128), + route_top_k=top_k, + ): + return False + args = SimpleNamespace( + hidden_states=torch.empty((num_rows, packed_hidden), device="meta"), + hidden_states_scale=torch.empty((num_rows * packed_hidden // 8,), device="meta"), + gemm1_weights=backend.w3_w1_weight, + gemm1_bias=backend.w3_w1_bias if backend.bias else None, + gemm1_alpha=backend.act_alpha, + gemm1_beta=backend.act_beta, + gemm1_clamp_limit=backend.act_clamp, + gemm2_weights=backend.w2_weight, + gemm2_bias=backend.w2_bias if backend.bias else None, + output1_scale_scalar=get_data_or_none(backend, "fc31_scale_c"), + output1_scale_gate_scalar=get_data_or_none(backend, "fc31_alpha"), + output2_scale_scalar=get_data_or_none(backend, "fc2_alpha"), + ) + return takes_engine( + args, + act_type, + top_k=top_k, + do_finalize=False, + output=None, + prerouted=True, + engine_state=backend.decode_engine_state, + ) + + +def select( + kernel_runner: torch.ScriptObject, + act_type: int, + tactic: List[int], + args: "FP4BlockScaleMoEInputs", + *, + top_k: int, + do_finalize: bool, + output: Optional[torch.Tensor], + intermediate_size: int, + prerouted: bool, + engine_state: Optional[torch.Tensor], +) -> DecodeKernel: + """The kernels of one op call where the model declares its decode kernels (``FP4BlockScaleMoERunner``; + host-side checks only). ``engine_state``: the calling backend's engine state + (``moe_persistent_engine.new_state``), or None.""" + if takes_engine( + args, + act_type, + top_k=top_k, + do_finalize=do_finalize, + output=output, + prerouted=prerouted, + engine_state=engine_state, + ): + return DecodeKernel.ENGINE + if do_finalize or output is not None or args.gemm2_bias is not None: + return DecodeKernel.CUBIN + if _cute_fc2_fits(kernel_runner, act_type, tactic, args, top_k, intermediate_size): + return DecodeKernel.CUTE_FC2 + return DecodeKernel.CUBIN + + +def n_max_for(num_rows: int) -> int: + """MMA N = rows per segment. Each ring stage reserves N x 128 B of activation room, so a smaller N leaves more + stages for the weight stream; an expert with more rows than N splits into segments whose weights are read again, + mostly from L2.""" + from tensorrt_llm._torch.kernels.blackwell.moe_nvfp4_engine import N_MAX + + if num_rows <= N_MAX[0]: # every expert's rows fit one segment + return N_MAX[0] + if num_rows < N64_MIN_ROWS: + return N_MAX[1] + return N_MAX[2] + + +def tile_k_for(n_max: int, hidden: int, inter: int) -> int: + """K per ring stage: 512 halves the barrier round trips per byte while N <= 32 still leaves 4 stages and 512 + divides both GEMMs' K; else 256 (at N 64, 512 would leave 3 stages).""" + return 512 if n_max <= 32 and hidden % 512 == 0 and inter % 512 == 0 else 256 + + +def run_engine( + args: "FP4BlockScaleMoEInputs", + tables: List[torch.Tensor], + tile: int, + top_k: int, + num_local: int, + state: torch.Tensor, + lamport_out: Optional[torch.Tensor], + release_after_wait: bool, + spare_sms: int = 0, + candidates: Optional[torch.Tensor] = None, + topk_ids: Optional[torch.Tensor] = None, + topk_weights: Optional[torch.Tensor] = None, + local_start: int = 0, +) -> List[torch.Tensor]: + """``ENGINE`` on the pre-routed ``tables`` (``prerouted_table_views`` for ``tile``); returns [gemm2 rows], as the + runner's pre-routed un-finalized call. ``release_after_wait``: the engine's PDL release point (its dependency + wait, else once its FC2 tickets are spent), the caller's choice for the kernel that follows. + ``spare_sms``: SMs the persistent grid leaves free for work another stream runs beside it (the backend's + ``reserve_sms_for_concurrent_kernels``; at most :data:`ENGINE_SPARE_SMS`). + ``candidates`` (``PreroutedRouting.candidates``): the engine routes the call for the local experts from + ``local_start`` and writes ``tables``, ``topk_ids`` and ``topk_weights`` itself (:func:`engine_routes`).""" + from tensorrt_llm._torch.kernels.blackwell.moe_nvfp4_engine import moe_nvfp4_engine + + x = args.hidden_states + m = x.shape[0] + e2p, p2t, batch, limit, nct, npad = tables + cap = max_num_tiles(m, top_k, num_local, tile) * tile + w13, w2 = args.gemm1_weights, args.gemm2_weights + hidden, inter = w2.shape[1], w13.shape[1] // 2 + dev = x.device + h = torch.empty((cap, inter // 2), dtype=torch.uint8, device=dev) + hsf = torch.empty((cap * inter // 16,), dtype=torch.uint8, device=dev) + if lamport_out is not None: + out = _lamport_out_view(lamport_out, cap, hidden) + else: + out = torch.empty((cap, hidden), dtype=torch.bfloat16, device=dev) + n_max = n_max_for(m) + moe_nvfp4_engine( + x.view(torch.uint8), + args.hidden_states_scale.view(torch.uint8).reshape(m, -1), + p2t, + batch, + limit, + nct, + w13.view(torch.uint8), + args.gemm1_weights_scale.view(torch.uint8), + w2.view(torch.uint8), + args.gemm2_weights_scale.view(torch.uint8), + args.output1_scale_scalar, + args.output1_scale_gate_scalar, + args.output2_scale_scalar, + h, + hsf, + out, + state, + tile=tile, + n_max=n_max, + tile_k=tile_k_for(n_max, hidden, inter), + release_after_wait=release_after_wait, + spare_sms=spare_sms, + candidates=candidates, + topk_ids=topk_ids, + topk_weights=topk_weights, + e2p=e2p, + num_padded=npad, + local_start=local_start, + ) + return [out] + + +#: Positions of ``gemm2_bias``, ``do_finalize`` and ``output`` in the runner's ``run_moe`` / ``run_moe_prerouted`` +#: arguments (``FP4BlockScaleMoeRunner::run`` / ``runPrerouted`` in fp4BlockScaleMoe.cpp), which its FC1-only entries +#: (``runFc1`` / ``runPreroutedFc1``) do not take. +GEMM2_BIAS_ARG, DO_FINALIZE_ARG, OUTPUT_ARG = 12, 25, 29 + + +def fc1_only_args(run_args: Sequence[object]) -> Tuple[object, ...]: + """The runner's ``run_moe`` / ``run_moe_prerouted`` arguments as its FC1-only entries take them: without + ``gemm2_bias``, ``do_finalize`` and ``output``, which must be None, False and None.""" + run_args = tuple(run_args) + if ( + run_args[GEMM2_BIAS_ARG] is not None + or run_args[DO_FINALIZE_ARG] + or run_args[OUTPUT_ARG] is not None + ): + raise ValueError("an FC1-only call is un-finalized, without FC2 bias or output tensor") + return ( + run_args[:GEMM2_BIAS_ARG] + + run_args[GEMM2_BIAS_ARG + 1 : DO_FINALIZE_ARG] + + run_args[DO_FINALIZE_ARG + 1 : OUTPUT_ARG] + + run_args[OUTPUT_ARG + 1 :] + ) + + +def run_cute_fc2( + fc1_outputs: List[torch.Tensor], + args: "FP4BlockScaleMoEInputs", + lamport_out: Optional[torch.Tensor], +) -> List[torch.Tensor]: + """``CUTE_FC2`` on the FC1-only runner's outputs; returns the runner's ``do_finalize=False`` triple.""" + from tensorrt_llm._torch.kernels.blackwell.moe_lowm_fc2 import moe_lowm_fc2 + + ( + gemm1_output, + gemm1_output_scale, + gemm2_output, + expert_weights, + expanded_idx_to_permuted_idx, + cta_batch, + cta_limit, + num_ctas, + ) = fc1_outputs + out = gemm2_output + if lamport_out is not None: + out = _lamport_out_view(lamport_out, gemm2_output.shape[0], gemm2_output.shape[1]) + moe_lowm_fc2( + gemm1_output.view(torch.uint8), + gemm1_output_scale.view(torch.uint8), + args.gemm2_weights.view(torch.uint8), + args.gemm2_weights_scale.view(torch.uint8), + args.output2_scale_scalar, + cta_batch, + cta_limit, + num_ctas.view(-1), + out, + ) + return [out, expert_weights, expanded_idx_to_permuted_idx] + + +def rows_in_lamport(rows: torch.Tensor, lamport_out: Optional[torch.Tensor]) -> bool: + """Whether an un-finalized call's FC2 ``rows`` are the Lamport buffer ``lamport_out`` (``ENGINE`` / ``CUTE_FC2`` + wrote them there); a ``CUBIN`` call returns rows of its own and leaves the buffer untouched.""" + return lamport_out is not None and rows.data_ptr() == lamport_out.data_ptr() + + +def _lamport_out_view(lamport_out: torch.Tensor, rows: int, hidden: int) -> torch.Tensor: + """The first ``rows`` rows of the Lamport FC2 buffer, the FC2 output of a call of that many rows.""" + if lamport_out.shape[0] < rows or lamport_out.shape[1] != hidden: + raise RuntimeError( + f"Lamport FC2 buffer {tuple(lamport_out.shape)} cannot hold {rows} x {hidden}" + ) + return lamport_out[:rows] + + +def lamport_buffer_rows( + runner: torch.ScriptObject, + max_rows: int, + hidden: int, + inter: int, + top_k: int, + local_experts: int, +) -> int: + """Rows of the largest Lamport call of up to ``max_rows`` tokens: at the largest tile the FP4 MoE ``runner`` + (``torch.classes.trtllm.FP4BlockScaleMoERunner``) offers for ``max_rows`` tokens (the tile-padded row count grows + with tokens and tile, and so does the tile offered), or the CuTe FC2's MAX_TOKENS tokens at TILE_N.""" + tile = max( + int(t[0]) for t in runner.get_valid_configs(top_k, hidden, inter, local_experts, max_rows) + ) + return max( + MAX_TOKENS * top_k + local_experts * (TILE_N - 1), + max_num_tiles(max_rows, top_k, local_experts, tile) * tile, + ) + + +class LamportFc2Buffer: + """The FC2 output buffer of the Lamport calls (up to ``max_rows`` tokens) of a model's MoE layers, which run one + at a time and share it. + + It holds 0xFFFFFFFF wherever FC2 has not written: the MoE-output all-reduce's fold polls each word of the rows it + reads (``MoEAllReduceParams.fc2_lamport``) instead of waiting for FC2, then writes the word back. Allocated at the + first call, before CUDA-graph capture, and never reallocated, so graphs captured later keep a valid address.""" + + max_rows = 0 + _buf: Optional[torch.Tensor] = None + + def __init__(self, max_rows: int) -> None: + self.max_rows = max_rows + self._buf: Optional[torch.Tensor] = None + + def get( + self, hidden: int, inter: int, top_k: int, local_experts: int, device: torch.device + ) -> torch.Tensor: + """The buffer [>= lamport_buffer_rows(...), hidden] bf16 for the FP4 MoE layers of these shapes.""" + buf = self._buf + if buf is None: + if torch.cuda.is_current_stream_capturing(): + raise RuntimeError("allocate the Lamport FC2 buffer before CUDA graph capture") + + runner = torch.classes.trtllm.FP4BlockScaleMoERunner(int(ActType_TrtllmGen.SwiGlu)) + rows = lamport_buffer_rows(runner, self.max_rows, hidden, inter, top_k, local_experts) + buf = torch.full((rows, hidden), -1, dtype=torch.int16, device=device).view( + torch.bfloat16 + ) + self._buf = buf + if buf.shape[1] != hidden: + raise RuntimeError( + f"Lamport FC2 buffer {tuple(buf.shape)} cannot hold {hidden} columns" + ) + return buf diff --git a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/decode_moe_bf16.py b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/decode_moe_bf16.py new file mode 100644 index 000000000000..f2e5ec23d0b9 --- /dev/null +++ b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/decode_moe_bf16.py @@ -0,0 +1,101 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Decode MoE engine on the BF16 trtllm-gen path (declared by ``MoEDecodeOptions.bf16_decode_engine``): an +un-finalized logits-routed SwiGLU run of up to ``M_MAX`` rows takes one launch (``moe_bf16_engine.py``) +instead of ``bf16_moe_runner``'s routing + two GEMMs and returns its ``do_finalize=False`` outputs: per (token, k) a +gemm2 row and the BF16 top-k weight, through the engine's own expanded -> permuted index (rows packed). +""" + +from typing import TYPE_CHECKING + +import torch + +from tensorrt_llm._torch.kernels.blackwell.moe_bf16_engine import ( + M_MAX, + moe_bf16_engine, + supports_local_experts, + supports_routing, +) +from tensorrt_llm._torch.utils import ActivationType + +from ..quantization import TRTLLM_GEN_WEIGHT_LAYOUT_BLOCK_MAJOR_K +from ..routing import RoutingMethodType + +if TYPE_CHECKING: + from .kernel_inputs import KernelInputs + from .trtllm_bf16 import TrtllmTrtllmGenBf16Impl + + +def applies(impl: "TrtllmTrtllmGenBf16Impl", k: "KernelInputs") -> bool: + """Whether this run fits the engine (host-side checks only).""" + if k.do_finalize or k.router_logits is None or k.routing_bias is not None: + return False + if impl.activation_type != ActivationType.Swiglu or impl.bias: + return False + if impl.act_alpha is not None or impl.act_beta is not None or impl.act_clamp is not None: + return False + if impl.routing_method.routing_method_type != RoutingMethodType.Renormalize: + return False + if not supports_routing(impl.num_slots, k.top_k) or not supports_local_experts( + impl.num_slots, impl.expert_size_per_partition + ): + return False + qm = impl.quant_method + if not qm.use_shuffled_weight or qm.weight_layout != TRTLLM_GEN_WEIGHT_LAYOUT_BLOCK_MAJOR_K: + return False + x, lg = k.x, k.router_logits + if not isinstance(x, torch.Tensor) or x.dtype != torch.bfloat16 or x.dim() != 2: + return False + m = x.shape[0] + # The kernel reads x rows with 16-byte cp.async and logits rows with 16-byte vector loads. + if not 1 <= m <= M_MAX or x.stride(1) != 1 or (x.stride(0) * 2) % 16 or x.data_ptr() % 16: + return False + if ( + lg.dtype != torch.bfloat16 + or tuple(lg.shape) != (m, impl.num_slots) + or not lg.is_contiguous() + or lg.data_ptr() % 16 + ): + return False + w13, w2 = impl.w3_w1_weight, impl.w2_weight + if w13.dtype != torch.bfloat16 or w2.dtype != torch.bfloat16 or w13.dim() != 4 or w2.dim() != 4: + return False + e, hb, two_i, kb = w13.shape + hidden, inter = hb * kb, two_i // 2 + if ( + kb != 64 + or e != impl.expert_size_per_partition + or tuple(w2.shape) != (e, inter // 64, hidden, 64) + or x.shape[1] != hidden + ): + return False + return hidden % 128 == 0 and inter % 128 == 0 + + +def run( + impl: "TrtllmTrtllmGenBf16Impl", k: "KernelInputs", state: torch.Tensor +) -> list[torch.Tensor]: + x = k.x + m = x.shape[0] + top_k = k.top_k + hidden, inter = impl.w2_weight.shape[2], impl.w3_w1_weight.shape[2] // 2 + dev = x.device + h = torch.empty((m * top_k, inter), dtype=torch.bfloat16, device=dev) + out = torch.empty((m * top_k, hidden), dtype=torch.bfloat16, device=dev) + wts = torch.empty((m, top_k), dtype=torch.bfloat16, device=dev) + e2p = torch.empty((m, top_k), dtype=torch.int32, device=dev) + moe_bf16_engine( + x, + k.router_logits, + impl.w3_w1_weight, + impl.w2_weight, + h, + out, + wts, + e2p, + state, + top_k=top_k, + local_start=impl.slot_start, + ) + # bf16_moe_runner's un-finalized ABI: gemm2 rows, top-k weights [m, top_k], expanded -> permuted index [m, top_k] + return [out, wts, e2p] diff --git a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/fp4_block_scale.py b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/fp4_block_scale.py index 9f9f3b8ca0fa..850891dbb4e5 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/fp4_block_scale.py +++ b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/fp4_block_scale.py @@ -68,15 +68,24 @@ class TRTLLMGenFp4BlockScaleBase(TrtllmGenFusedMoEBase): #: pre-routed entry point). supports_prerouted_routing: bool = False + #: The decode MoE engine's call state where the model declares its decode kernels (``decode_tuning``), + #: created with the weights (``cache_derived_state``). + decode_engine_state: torch.Tensor | None = None + + #: SMs the decode MoE engine's persistent grid leaves free on the next ``run_moe`` calls + #: (``reserve_sms_for_concurrent_kernels``). + _concurrent_sm_reserve: int = 0 + def _intermediate_size_padded(self) -> int: act_type = to_trtllm_gen_act_type(self.activation_type) factor = 1 if act_type in [ActType_TrtllmGen.Relu2, ActType_TrtllmGen.Silu] else 2 return self.w3_w1_weight.shape[-2] // factor - def decode_tactic(self, num_tokens: int) -> list[int] | None: - """The [tile, config] ``run_moe`` runs for ``num_tokens`` tokens with router logits (the tuned - choice of the FP4 MoE op), or None when the shape is not tuned. A caller that routes the tokens - itself builds the tables for this tactic's tile.""" + def decode_tactic(self, num_tokens: int, do_finalize: bool) -> list[int] | None: + """The [tile, config] ``run_moe`` runs for ``num_tokens`` tokens with router logits and + ``do_finalize`` (the tuned choice of the FP4 MoE op, whose decode-tuning key carries + ``do_finalize``), or None when the shape is not tuned. A caller that routes the tokens itself + builds the tables for this tactic's tile.""" from ....custom_ops.trtllm_gen_custom_ops import FP4BlockScaleMoERunner rp = extract_routing_params(self.routing_method) @@ -90,7 +99,7 @@ def decode_tactic(self, num_tokens: int) -> list[int] | None: self.expert_size_per_partition, rp.routed_scaling_factor, self.routing_method.routing_method_type, - True, + do_finalize, to_trtllm_gen_act_type(self.activation_type), tune_max_num_tokens=self.max_num_tokens, use_dp=self.use_dp, @@ -167,7 +176,7 @@ def _check_configs(self) -> None: ) def cache_derived_state(self) -> None: - """Refill the SiTu soft-caps after meta-device materialization. + """Create the decode engine's call state; refill the SiTu soft-caps after meta-device materialization. The model loader calls this on every module once storage is bound, because materialization wipes anything that is not a checkpoint tensor, @@ -177,6 +186,10 @@ def cache_derived_state(self) -> None: meta at that point, so a snapshot would carry no values. """ super().cache_derived_state() + if self.decode_tuning and self.decode_engine_state is None: + from tensorrt_llm._torch.kernels.blackwell.moe_persistent_engine import new_state + + self.decode_engine_state = new_state(self.w3_w1_weight.device) if not self.is_situ_activation: return params = materialize_activation_params( @@ -189,6 +202,24 @@ def cache_derived_state(self) -> None: self.act_alpha.data.copy_(params.alpha) self.act_beta.data.copy_(params.beta) + def sm_reserve_ceiling(self) -> int: + """Where the model declares the decode kernels (``decode_tuning``) of a pre-routed native call, the decode MoE + engine (``decode_moe.ENGINE``) sizes a persistent grid it can shrink by up to + ``decode_moe.ENGINE_SPARE_SMS`` SMs; 0 otherwise (the cubins' grids are fixed).""" + if not (self.decode_tuning and self.supports_prerouted_routing): + return 0 + from .decode_moe import ENGINE_SPARE_SMS + + return ENGINE_SPARE_SMS + + def reserve_sms_for_concurrent_kernels(self, num_sms: int) -> int: + """The decode MoE engine launches its persistent grid ``num_sms`` SMs short (at most + ``sm_reserve_ceiling()``) until the next call; other kernels of the op keep their grids.""" + if num_sms < 0: + raise ValueError(f"num_sms must be non-negative, got {num_sms}") + self._concurrent_sm_reserve = min(num_sms, self.sm_reserve_ceiling()) + return self._concurrent_sm_reserve + def run_moe( self, ctx: MoERunContext, @@ -200,6 +231,8 @@ def run_moe( prerouted = ctx.prerouted if prerouted is not None and not self.supports_prerouted_routing: raise ValueError(f"{type(self).__name__} does not take prerouted routing") + if ctx.lamport_fc2_out is not None and not self.takes_lamport_fc2_out: + raise ValueError(f"{type(self).__name__} does not take a Lamport FC2 output") act_type = to_trtllm_gen_act_type(self.activation_type) intermediate_size_per_partition_padded = self._intermediate_size_padded() @@ -251,6 +284,10 @@ def run_moe( use_dp=self.use_dp, prerouted=prerouted, decode_tuning=self.decode_tuning, + decode_engine_state=self.decode_engine_state, + lamport_fc2_out=ctx.lamport_fc2_out, + decode_early_release_rows=self.decode_early_release_rows, + decode_spare_sms=self._concurrent_sm_reserve, ) if not k.do_finalize: diff --git a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/trtllm_bf16.py b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/trtllm_bf16.py index 5ce4f1adecdc..57ee8703af08 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/trtllm_bf16.py +++ b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/trtllm_bf16.py @@ -18,6 +18,7 @@ import torch +from tensorrt_llm._torch.model_config import ModelConfig from tensorrt_llm._torch.moe.expert_statistic import ExpertStatistic from tensorrt_llm._torch.route_capture import get_active_route_capture from tensorrt_llm._torch.utils import ActivationType @@ -25,6 +26,7 @@ from tensorrt_llm.tools.layer_wise_benchmarks.calibrator import Mode as CalibratorMode from ..impl_contract import ( + MoEDecodeOptions, MoEDeployment, MoEEligibility, MoEProblem, @@ -51,7 +53,9 @@ class TrtllmTrtllmGenBf16Impl(TrtllmGenFusedMoEBase): BF16 activations times BF16 weights on the ``Bmm_Bfloat16_Bfloat16Bfloat16`` cubins, through ``trtllm::bf16_moe_runner``. The weights are stored in the - shuffled BlockMajorK layout ``BF16TRTLLMGenFusedMoEMethod`` produces. + shuffled BlockMajorK layout ``BF16TRTLLMGenFusedMoEMethod`` produces. A + model that declares ``MoEDecodeOptions.bf16_decode_engine`` also runs its + small un-finalized logits-routed calls on the BF16 decode MoE engine. """ descriptor = trtllm_gen_descriptor( @@ -60,6 +64,14 @@ class TrtllmTrtllmGenBf16Impl(TrtllmGenFusedMoEBase): "TRTLLM-Gen batched-GEMM cubins, BF16 activations and weights, SM100 family.", ) + #: Declared by the model (``MoEDecodeOptions.bf16_decode_engine``), for every BF16 MoE layer it builds: + #: un-finalized logits-routed SwiGLU runs of up to 32 rows take the one-launch BF16 decode MoE engine + #: (decode_moe_bf16.py) instead of ``bf16_moe_runner``. + uses_decode_engine: bool = False + #: The BF16 decode MoE engine's call state, created with the weights (``cache_derived_state``) where + #: ``uses_decode_engine`` holds. + _decode_engine_state: torch.Tensor | None = None + #: The gemm1 epilogues the BF16 cubins ship: gated SwiGLU and non-gated #: Relu2. Read from both sides here: the eligibility gate below and #: ``_check_configs``. @@ -75,6 +87,11 @@ class TrtllmTrtllmGenBf16Impl(TrtllmGenFusedMoEBase): _MAX_ROUTING_EXPERTS = 2048 _MAX_ROUTING_TOP_K = 32 + def __init__(self, *, model_config: ModelConfig = ModelConfig(), **kwargs: object) -> None: + super().__init__(model_config=model_config, **kwargs) + decode = MoEDecodeOptions.of(model_config.extra_attrs) + self.uses_decode_engine = decode.bf16_decode_engine + @classmethod def can_implement(cls, p: MoEProblem, d: MoEDeployment) -> MoEEligibility: return check_trtllm_gen_leaf( @@ -107,6 +124,15 @@ def supports_unfinalized_output(self) -> bool: """``bf16_moe_runner`` honors ``do_finalize=False`` and returns the triple.""" return True + def cache_derived_state(self) -> None: + """Also create the BF16 decode MoE engine's call state once storage is bound (before any CUDA-graph + capture).""" + super().cache_derived_state() + if self.uses_decode_engine and self._decode_engine_state is None: + from tensorrt_llm._torch.kernels.blackwell.moe_persistent_engine import new_state + + self._decode_engine_state = new_state(self.w3_w1_weight.device) + def _check_configs(self) -> None: """The unquantized kernels take no activation constants at all. @@ -187,6 +213,12 @@ def run_moe( del workspace # TRTLLMGen kernels allocate their own intermediates. k = prepare_kernel_inputs(self, ctx) + if self._decode_engine_state is not None: + from . import decode_moe_bf16 + + if decode_moe_bf16.applies(self, k): + return self._unfinalized(decode_moe_bf16.run(self, k, self._decode_engine_state)) + result = self.op_backend.run_bf16_moe( router_logits=k.router_logits, routing_bias=k.routing_bias, diff --git a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/trtllm_nvfp4.py b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/trtllm_nvfp4.py index 077ebcf3ac5a..4b93302c051e 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/trtllm_nvfp4.py +++ b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/trtllm_nvfp4.py @@ -37,6 +37,9 @@ class TrtllmTrtllmGenNvfp4Impl(TRTLLMGenNvfp4Base): #: The native op's pre-routed entry point (``run_moe_prerouted``). supports_prerouted_routing = True + #: The native op's ``lamport_fc2_out``. + takes_lamport_fc2_out = True + @classmethod def can_implement(cls, p: MoEProblem, d: MoEDeployment) -> MoEEligibility: return check_trtllm_gen_leaf(cls, p, d) diff --git a/tensorrt_llm/_torch/moe/kernels/blackwell/blockscaled_contiguous_grouped_gemm_finalize_fusion.py b/tensorrt_llm/_torch/moe/kernels/blackwell/blockscaled_contiguous_grouped_gemm_finalize_fusion.py index 88b088e34d67..63cc01c68e43 100644 --- a/tensorrt_llm/_torch/moe/kernels/blackwell/blockscaled_contiguous_grouped_gemm_finalize_fusion.py +++ b/tensorrt_llm/_torch/moe/kernels/blackwell/blockscaled_contiguous_grouped_gemm_finalize_fusion.py @@ -35,7 +35,9 @@ import cutlass.utils as utils import cutlass.utils.blackwell_helpers as sm100_utils import cutlass.utils.blockscaled_layout as blockscaled_utils +from cutlass._mlir.dialects import llvm from cutlass.cute.nvgpu import cpasync, tcgen05 +from cutlass.cutlass_dsl import T, dsl_user_op from tensorrt_llm._torch.kernels.blackwell.utils import ( TRTLLM_ENABLE_PDL, @@ -155,6 +157,24 @@ """ +@dsl_user_op +def _l2_evict_first_policy(*, loc=None, ip=None) -> cutlass.Int64: + """An L2 evict_first cache policy (fraction 1.0) for TMA loads.""" + return cutlass.Int64( + llvm.inline_asm( + T.i64(), + [], + "createpolicy.fractional.L2::evict_first.b64 $0, 1.0;", + "=l", + has_side_effects=True, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + class Sm100BlockScaledContiguousGroupedGemmFinalizeFusionKernel: """This class implements batched matrix multiplication (C = A x SFA x B x SFB) with support for various data types and architectural features specific to Blackwell GPUs with persistent tile scheduling and warp specialization. @@ -206,6 +226,7 @@ def __init__( raster_along_m: bool = False, use_expert_counts: bool = False, num_local_experts: int = 0, + weights_evict_first: bool = False, ): """Initializes the configuration for a Blackwell blockscaled dense GEMM kernel. @@ -223,9 +244,13 @@ def __init__( :type cluster_shape_mn: Tuple[int, int] :param raster_along_m: Boolean, True to use raster along M. :type raster_along_m: bool + :param weights_evict_first: Boolean, True to load B / SFB (the expert weights) with an L2 evict_first policy, + so that weights each tile reads once do not evict A and the output rows the epilogue adds into. + :type weights_evict_first: bool """ self.sf_vec_size = sf_vec_size + self.weights_evict_first = weights_evict_first self.acc_dtype = cutlass.Float32 self.use_2cta_instrs = mma_tiler_mn[0] == 256 self.cluster_shape_mn = cluster_shape_mn @@ -1445,12 +1470,17 @@ def kernel( ) tBgB_slice = tBgB_0[(None, mma_tile_coord_mnl[1], None, expert_idx)] tBgSFB_slice = tBgSFB_0[(None, slice_n, None, expert_idx)] + # cute.copy treats cache_policy=None as no policy. + b_policy = None + if cutlass.const_expr(self.weights_evict_first): + b_policy = _l2_evict_first_policy() cute.copy( tma_atoms_b[0], tBgB_slice[(None, ab_producer_state.count)], tBsB_pipe, tma_bar_ptr=tma_bar, mcast_mask=b_full_mcast_mask, + cache_policy=b_policy, ) cute.copy( tma_atoms_sfb[0], @@ -1458,6 +1488,7 @@ def kernel( tBsSFB_pipe, tma_bar_ptr=tma_bar, mcast_mask=sfb_full_mcast_mask, + cache_policy=b_policy, ) # Peek (try_wait) AB buffer empty for k_tile = prefetch_k_tile_cnt + k_tile + 1 diff --git a/tensorrt_llm/_torch/pyexecutor/_util.py b/tensorrt_llm/_torch/pyexecutor/_util.py index 83927d7e51a3..d249a09afc74 100644 --- a/tensorrt_llm/_torch/pyexecutor/_util.py +++ b/tensorrt_llm/_torch/pyexecutor/_util.py @@ -98,6 +98,9 @@ if TYPE_CHECKING: from tensorrt_llm._torch.models.modeling_dflash import DFlashForCausalLM + from .kv_cache.remote_donor import RemoteMemDonor + from .resource_manager import BaseResourceManager + GB = 1 << 30 _DEFAULT_INDEX_MAPPER_RESERVED_SLOTS = 1 _CONFIDENCE_INDEX_MAPPER_RESERVED_SLOTS = 2 @@ -1021,6 +1024,13 @@ class KvCacheCreator: _joint_kv_cache_reuse = False _gen_preemption_headroom: int = 0 + # This rank's donation (remote_cache_config.donor), started before the + # estimation so that clients do not wait out the warmup; the final target + # manager takes it over. + _remote_donor: Optional["RemoteMemDonor"] = None + # The donation handed to the final target manager (close_remote_donor). + _handed_remote_donor: Optional["RemoteMemDonor"] = None + def __init__( self, *, @@ -1092,6 +1102,7 @@ def __init__( "ranks only in the chunked-context path. Set " "enable_chunked_prefill=True on a GPU that supports it " "for MLA.") + self._reject_unused_v2_only_fields(mapping, llm_args) self._disable_overlap_scheduler = llm_args.disable_overlap_scheduler self._draft_config = draft_config self._skip_est = skip_est @@ -1103,6 +1114,37 @@ def __init__( # reads it directly instead of re-deriving it from pool layout. None until reserved (or w == 0). self._fp8_ctx_mla_kv_len_cap = None + def _reject_unused_v2_only_fields(self, mapping: Mapping, + llm_args: TorchLlmArgs) -> None: + """Raise for KV cache fields the resolved manager or executor loop would ignore.""" + kv_cache_config = self._kv_cache_config + used_fields = { + "remote_cache_config": + kv_cache_config.remote_cache_config is not None, + "defer_generation_only_release": + kv_cache_config.defer_generation_only_release, + } + for field, is_set in used_fields.items(): + if is_set and not self._is_kv_cache_manager_v2: + raise ValueError( + f"kv_cache_config.{field} requires KVCacheManagerV2, but " + f"{self._kv_cache_manager_cls.__name__} was selected. Set " + "kv_cache_config.use_kv_cache_manager_v2=True and disable " + "features that fall back to V1.") + # TorchLlmArgs rejects the same at parse time; this sees the resolved values. + if kv_cache_config.defer_generation_only_release and ( + llm_args.disable_overlap_scheduler or mapping.pp_size > 1): + raise ValueError( + "kv_cache_config.defer_generation_only_release is used only " + "by the overlap scheduler loop, which needs " + "disable_overlap_scheduler=False and pipeline parallel size 1.") + if kv_cache_config.defer_generation_only_release and not self._is_disagg: + logger.warning( + "kv_cache_config.defer_generation_only_release has no effect " + "without a cache transceiver: only the generation-only " + "requests of a disaggregated generation server are released " + "late.") + def _get_model_kv_cache_manager_cls( self, kv_cache_config_override: Optional[KvCacheConfig] = None, @@ -2207,6 +2249,7 @@ def _create_kv_cache_manager( estimating_kv_cache: bool = False, kv_cache_config_override: Optional[KvCacheConfig] = None, cold_page_codec_provider: Optional[object] = None, + remote_donor: Optional["RemoteMemDonor"] = None, ) -> KVCacheManager: mapping = self._mapping assert self._model_engine.model.model_config.is_generation, "Only construct KV cache for generation models." @@ -2273,6 +2316,7 @@ def _create_kv_cache_manager( joint_kv_cache_reuse=self._joint_kv_cache_reuse, layer_specs=unified_layer_specs, shared_draft_block_width=shared_draft_block_width, + remote_donor=remote_donor, ) if not self._skip_est: @@ -2873,10 +2917,12 @@ def _create_one_model_draft_kv_cache_manager( estimating_kv_cache: bool = False, kv_cache_config_override: Optional[KvCacheConfig] = None, cold_page_codec_provider: Optional[object] = None, + remote_donor: Optional["RemoteMemDonor"] = None, ) -> Optional[KVCacheManager]: """ Create a KV cache manager for draft model layers in one-model mode - when target and draft have different KV cache layouts. + when target and draft have different KV cache layouts. `remote_donor` + is the target's donation, which the draft waits for but does not own. """ num_draft_layers = self._get_num_draft_layers() spec_dec_layer_mask = self._get_one_model_draft_layer_mask() @@ -2965,6 +3011,7 @@ def _create_one_model_draft_kv_cache_manager( disable_overlap_scheduler=self._disable_overlap_scheduler, cold_page_codec_provider=cold_page_codec_provider, joint_kv_cache_reuse=self._joint_kv_cache_reuse, + remote_donor=remote_donor, ) def _get_target_and_draft_cache_costs( @@ -3462,7 +3509,9 @@ def _split_kv_cache_budget_for_cross( "KV cache pool.") self_kv_cache_config = base_kv_cache_config.model_copy() - cross_kv_cache_config = base_kv_cache_config.model_copy() + # The self-attention manager owns the rank's remote level and donation. + cross_kv_cache_config = base_kv_cache_config.model_copy( + update={"remote_cache_config": None}) split_any_budget = False free_fraction = base_kv_cache_config.free_gpu_memory_fraction @@ -3616,7 +3665,9 @@ def _drop_explicit_offload_tier_budgets( Host sizing then falls to the V2 auto host tier policy, which matches the tier to the manager's own device quota; V1 builds no secondary pool. The disk tier is V2 only and has no auto policy, so dropping its budget - leaves the tier out. + leaves the tier out; so does dropping the remote cache config: the + donation is placed before the probe (_start_remote_donation), the claim waits + for the final build. """ if kv_cache_config is None: return kv_cache_config @@ -3625,6 +3676,8 @@ def _drop_explicit_offload_tier_budgets( for attr in cls._OFFLOAD_TIER_BUDGET_ATTRS if getattr(kv_cache_config, attr) } + if kv_cache_config.remote_cache_config is not None: + dropped["remote_cache_config"] = None if not dropped: return kv_cache_config return kv_cache_config.model_copy(update=dropped) @@ -3687,6 +3740,8 @@ def build_managers(self, self_kv_cache_config) cross_kv_cache_config = self._drop_explicit_offload_tier_budgets( cross_kv_cache_config) + if not self._skip_est: + self._start_remote_donation() # Split combined KV cache budgets before creating managers. draft_kv_cache_config = None @@ -3720,11 +3775,34 @@ def build_managers(self, compression_manager if compression_manager is not None and compression_manager.provides_cold_page_codec else None) + # The early donation goes to the final target, which owns it; a separate draft only waits for it. + early_donor = None if estimating_kv_cache else self._remote_donor kv_cache_manager = self._create_kv_cache_manager( estimating_kv_cache, kv_cache_config_override=self_kv_cache_config, cold_page_codec_provider=cold_page_codec_provider, + remote_donor=early_donor, ) + if not estimating_kv_cache: + # The manager owns it now, or the donation it started itself when the estimation was skipped; kept only + # to mark it should startup fail after this. The draft waits for either and does not charge it again. + if early_donor is None: + early_donor = getattr(kv_cache_manager, "remote_donor", None) + self._handed_remote_donor, self._remote_donor = early_donor, None + try: + draft_kv_cache_manager, cross_kv_cache_manager = ( + self._build_secondary_managers( + has_separate_one_model_draft, original_max_seq_len, + estimating_kv_cache, self_kv_cache_config, + draft_kv_cache_config, cross_kv_cache_config, + cold_page_codec_provider, early_donor)) + except BaseException as error: + # Nothing holds the target manager yet: withdraw its donation with the failure marker, then shut it down. + if not estimating_kv_cache: + self.close_remote_donor(error) + if kv_cache_manager is not None: + kv_cache_manager.shutdown() + raise # Carry the fp8 context-MLA workspace admission cap (computed in configure_kv_cache_capacity) onto # the real KV manager so the scheduler reads it directly instead of re-deriving from pool layout. @@ -3733,6 +3811,27 @@ def build_managers(self, if not estimating_kv_cache and kv_cache_manager is not None: kv_cache_manager.fp8_ctx_mla_kv_len_cap = self._fp8_ctx_mla_kv_len_cap + resources[ResourceManagerType.KV_CACHE_MANAGER] = kv_cache_manager + resources[ + ResourceManagerType.DRAFT_KV_CACHE_MANAGER] = draft_kv_cache_manager + resources[ + ResourceManagerType.CROSS_KV_CACHE_MANAGER] = cross_kv_cache_manager + if (compression_manager is not None + and compression_manager.uses_iteration_lifecycle): + resources[ResourceManagerType.KV_CACHE_COMPRESSION_MANAGER] = ( + compression_manager) + + def _build_secondary_managers( + self, has_separate_one_model_draft: bool, original_max_seq_len: int, + estimating_kv_cache: bool, self_kv_cache_config: KvCacheConfig, + draft_kv_cache_config: Optional[KvCacheConfig], + cross_kv_cache_config: Optional[KvCacheConfig], + cold_page_codec_provider: Optional[object], + early_donor: Optional["RemoteMemDonor"] + ) -> tuple[Optional["BaseResourceManager"], + Optional["BaseResourceManager"]]: + """The one-model draft and encoder-decoder cross managers built beside the target; the draft waits for + `early_donor`, the target's donation, before measuring host memory.""" draft_kv_cache_manager = None draft_build_kv_cache_config = (draft_kv_cache_config if draft_kv_cache_config is not None else @@ -3744,24 +3843,42 @@ def build_managers(self, original_max_seq_len, estimating_kv_cache, kv_cache_config_override=draft_build_kv_cache_config, - cold_page_codec_provider=cold_page_codec_provider) + cold_page_codec_provider=cold_page_codec_provider, + remote_donor=early_donor) # Encoder-decoder cross-attention pool cross_kv_cache_manager = None if cross_kv_cache_config is not None: + if early_donor is not None: + # Without the estimation, the target started its donation in the background. The cross manager + # does not own it (it gets no remote config) but sizes its automatic host tier from free host + # memory, so measure with the donation placed. + early_donor.wait_started() cross_kv_cache_manager = self._create_cross_kv_cache_manager( cross_kv_cache_config, estimating_kv_cache, original_max_seq_len) + return draft_kv_cache_manager, cross_kv_cache_manager - resources[ResourceManagerType.KV_CACHE_MANAGER] = kv_cache_manager - resources[ - ResourceManagerType.DRAFT_KV_CACHE_MANAGER] = draft_kv_cache_manager - resources[ - ResourceManagerType.CROSS_KV_CACHE_MANAGER] = cross_kv_cache_manager - if (compression_manager is not None - and compression_manager.uses_iteration_lifecycle): - resources[ResourceManagerType.KV_CACHE_COMPRESSION_MANAGER] = ( - compression_manager) + def _start_remote_donation(self) -> None: + """Start this rank's donation for the final target manager, once, and wait until it is placed or failed.""" + remote_config = self._kv_cache_config.remote_cache_config + if (remote_config is None or remote_config.donor is None + or self._remote_donor is not None): + return + from .kv_cache.remote_donor import start_donation + self._remote_donor = start_donation(remote_config, + torch.cuda.current_device()) + # Placed before the estimation probe and its warmup take host memory, which would leave the donation short. + self._remote_donor.wait_started() + + def close_remote_donor(self, error: Optional[BaseException] = None) -> None: + """Withdraw a donation that no manager took over, leaving its failure marker when `error` is given. With `error`, + a donation already handed to the final target manager is withdrawn and marked too; its later close is a no-op.""" + donor, self._remote_donor = self._remote_donor, None + if donor is None and error is not None: + donor, self._handed_remote_donor = self._handed_remote_donor, None + if donor is not None: + donor.close(error) def teardown_managers(self, resources: Dict) -> None: """Clean up KV caches for model, draft model, and cross pool.""" @@ -3890,6 +4007,7 @@ def _create_kv_cache_manager( max_cuda_graph_batch_size: Optional[int] = None, layer_specs: Optional[Sequence[KVCacheLayerSpec]] = None, shared_draft_block_width: Optional[int] = None, + remote_donor: Optional["RemoteMemDonor"] = None, gen_preemption_headroom: int = 0) -> KVCacheManager: """ Returns: @@ -4051,6 +4169,7 @@ def _create_kv_cache_manager( manager_extra_kwargs["layer_specs"] = layer_specs manager_extra_kwargs[ "shared_draft_block_width"] = shared_draft_block_width + manager_extra_kwargs["remote_donor"] = remote_donor # Vocab size also enables multimodal event decoding and its per-block # digest scan. Leave it unset for text-only engines. Without an engine # (e.g. separate one-model draft caches), preserve config resolution: @@ -4936,6 +5055,11 @@ def create_py_executor_resources( context_starvation_iterations=scheduler_config. context_starvation_iterations if scheduler_config is not None else None, + # Ranks that schedule the same requests in lock step cannot recover + # a remote cache level failure that only some of them saw. + recover_lost_kv_per_rank=not ( + mapping.has_pp() or mapping.has_cp() or + (mapping.has_tp() and mapping.tp_group_shares_requests)), ) elif (scheduler_config is not None and scheduler_config.use_python_scheduler): @@ -5162,6 +5286,8 @@ def create_py_executor_instance( enable_kv_pool_rebalance, kv_pool_rebalance_check_interval=llm_args.kv_cache_config. kv_pool_rebalance_config.check_interval, + defer_generation_only_release=llm_args.kv_cache_config. + defer_generation_only_release, enable_adp_dummy_fixes=should_enable_adp_dummy_fixes(mapping), enable_scheduler_aware_adp_dummy=should_enable_scheduler_aware_adp_dummy( getattr(config, "model_type", None), mapping, diff --git a/tensorrt_llm/_torch/pyexecutor/engine/model_setup.py b/tensorrt_llm/_torch/pyexecutor/engine/model_setup.py index f19fd8ea363f..e577f588d24e 100644 --- a/tensorrt_llm/_torch/pyexecutor/engine/model_setup.py +++ b/tensorrt_llm/_torch/pyexecutor/engine/model_setup.py @@ -344,7 +344,7 @@ def compile_model( model, prefill_only = apply_torch_compile( model, backend, llm_args=llm_args, fullgraph=torch_compile_fullgraph ) - torch._dynamo.config.cache_size_limit = 16 + torch._dynamo.config.cache_size_limit = DYNAMO_RECOMPILE_LIMIT else: set_torch_compiling(False) if window_scopes_enabled: @@ -369,6 +369,9 @@ def compile_model( _DEEP_GEMM_PDL_CONFIGURED = False +# Dynamo recompile limit of a compiled model; PyExecutor applies it again on its +# worker thread, since torch keeps each Dynamo config value per thread. +DYNAMO_RECOMPILE_LIMIT = 16 def _configure_deep_gemm_pdl() -> None: diff --git a/tensorrt_llm/_torch/pyexecutor/engine/runners/decoder/graphs.py b/tensorrt_llm/_torch/pyexecutor/engine/runners/decoder/graphs.py index cc5f251b6b46..a8fc417fee52 100644 --- a/tensorrt_llm/_torch/pyexecutor/engine/runners/decoder/graphs.py +++ b/tensorrt_llm/_torch/pyexecutor/engine/runners/decoder/graphs.py @@ -231,6 +231,8 @@ def __init__( # Promoted context rows carry no per-sequence extra model inputs. self._context_promotion_supported = context_promotion_supported self._force_lora_graph_for_capture: bool | None = None + # Whether a warmup batch already ran an in-forward Mamba snapshot split (its Triton copy kernels compiled). + self._inforward_split_warmed = False def forward_discarded_warmup( self, @@ -361,6 +363,62 @@ def warmup_and_capture(self, resource_manager: ResourceManager) -> None: # serving timeouts. The warmup-only pass above keeps the warmup ones. with moe_comm_serving_timeouts(): self.run_cuda_graph_warmup(resource_manager) + self._warm_inforward_split(resource_manager) + + def _plans_inforward_splits(self, resource_manager: ResourceManager) -> bool: + """Whether the KV cache manager plans in-forward Mamba snapshot splits of context chunks.""" + kv_cache_manager = resource_manager.get_resource_manager( + ResourceManagerType.KV_CACHE_MANAGER + ) + return ( + isinstance(kv_cache_manager, KVCacheManagerV2) + and kv_cache_manager.inforward_snapshot_rows > 0 + ) + + def _warm_inforward_split(self, resource_manager: ResourceManager) -> None: + """Run one eager context request with an in-forward Mamba snapshot split, so that the split's kernels + (gdn_inforward_split.py) compile before serving where no break-graph capture ran one (prefill CUDA graphs + disabled, or no bucket with graphable breaks). Their compiled variants depend only on the model's strides + and the persistent split-index buffer, so one batch covers every later split.""" + if ( + self._inforward_split_warmed + or self.mapping.has_cp_helix() + or is_decode_only(self.sparse_attention_config) + or not self._plans_inforward_splits(resource_manager) + ): + return + kv_cache_manager = resource_manager.get_resource_manager( + ResourceManagerType.KV_CACHE_MANAGER + ) + # Room for the longest tail after the shortest main part (Mamba2Metadata._warmup_inforward_split_plan). + num_tokens = ( + kv_cache_manager.inforward_snapshot_min_main + + kv_cache_manager.inforward_snapshot_max_tail + ) + if num_tokens > self._config.max_num_tokens: + return + logger.info(f"Running in-forward Mamba snapshot split warmup ({num_tokens} tokens)") + with ( + self.no_cuda_graph(), + resolve_mamba_metadata_cls(self.model).inforward_split_for_warmup(), + ): + warmup_request = self._dummy_requests.create_warmup_request( + resource_manager, num_tokens, 0, num_context_requests=1 + ) + with self._dummy_requests.release_batch_context( + warmup_request, resource_manager + ) as batch: + self._agreement.assert_all_tp_ranks_have_warmup_batch(batch, num_tokens) + if batch is None: + return + self.forward_discarded_warmup( + batch, + resource_manager, + enable_spec_decode=self._config.is_spec_decode, + runtime_draft_len=get_static_draft_len(self._config.spec_config), + ) + torch.cuda.synchronize() + self._inforward_split_warmed = True def _prepare_capture_batch( self, @@ -977,15 +1035,11 @@ def _capture_break_graphs( eager_on_graph) on warmup batches of each _BREAK_GRAPH_NUM_CONTEXTS request count, with and without in-forward Mamba snapshot splits when the cache manager plans them.""" - kv_cache_manager = resource_manager.get_resource_manager( - ResourceManagerType.KV_CACHE_MANAGER - ) variants = [contextlib.nullcontext] - if ( - isinstance(kv_cache_manager, KVCacheManagerV2) - and kv_cache_manager.inforward_snapshot_rows > 0 - ): - variants.append(resolve_mamba_metadata_cls(self.model).inforward_split_for_warmup) + split_variant = None + if self._plans_inforward_splits(resource_manager): + split_variant = resolve_mamba_metadata_cls(self.model).inforward_split_for_warmup + variants.append(split_variant) for num_contexts in _BREAK_GRAPH_NUM_CONTEXTS: for variant in variants: warmup_request = self._dummy_requests.create_warmup_request( @@ -1007,6 +1061,8 @@ def _capture_break_graphs( ), self._warmup_inputs, ) + if variant is split_variant: + self._inforward_split_warmed = True def _capture_prefill_cuda_graphs(self, resource_manager: ResourceManager) -> None: """Warm up and capture prefill CUDA graphs, timing each phase separately. diff --git a/tensorrt_llm/_torch/pyexecutor/engine/runners/decoder/inputs.py b/tensorrt_llm/_torch/pyexecutor/engine/runners/decoder/inputs.py index 3af0201f9417..7233bce80fef 100644 --- a/tensorrt_llm/_torch/pyexecutor/engine/runners/decoder/inputs.py +++ b/tensorrt_llm/_torch/pyexecutor/engine/runners/decoder/inputs.py @@ -863,6 +863,9 @@ def attach_cuda_graph_runners( and self._steady_gen_cache_supported and not self.mapping.has_cp_helix() ): + stage_rng = False + if self.runtime_hooks.pack_spec_rng_uploads: + stage_rng = True self._steady_mtp = SteadyMtpPrepare( max_batch_size=self._config.max_batch_size, max_num_tokens=self._config.max_num_tokens, @@ -871,6 +874,7 @@ def attach_cuda_graph_runners( ), use_mrope=self._config.use_mrope, has_static_inputs=cuda_graph_runner is not None and cuda_graph_runner.enabled, + stage_rng=stage_rng, ) def _can_use_steady_mtp_fast_prepare( @@ -928,8 +932,32 @@ def _apply_steady_mtp_fast_prepare( requests = scheduled_requests.generation_requests num_requests = len(requests) num_tokens = num_requests * record.tokens_per_step + rng_state = None + rng_rows = steady_mtp.rng_rows() + sampling_populated = False + if rng_rows is not None and scheduled_requests.num_context_requests == 0: + # Populate the sampling parameters before staging, so that the staging kernel writes this step's + # Philox state from the host's values instead of four uploads on the stream after it. + rng_state = spec_metadata.populate_sampling_params_for_one_model( + scheduled_requests.all_requests(), defer_rng_rows=rng_rows + ) + sampling_populated = True num_cached_tokens_per_seq, kv_lens, static_inputs_staged = steady_mtp.stage( - requests, new_tensors_device, self._buffers, attn_metadata + requests, + new_tensors_device, + self._buffers, + attn_metadata, + rng_state=rng_state, + rng_buffers=( + ( + spec_metadata.request_seeds, + spec_metadata.request_offsets, + spec_metadata.seeds, + spec_metadata.offsets, + ) + if rng_state is not None + else None + ), ) attn_metadata.beam_width = 1 @@ -959,7 +987,8 @@ def _apply_steady_mtp_fast_prepare( spec_metadata.gather_ids = self._buffers.gather_ids_cuda[:num_tokens] # The positions are written on the device only. spec_metadata.host_position_ids = None - spec_metadata.populate_sampling_params_for_one_model(scheduled_requests.all_requests()) + if not sampling_populated: + spec_metadata.populate_sampling_params_for_one_model(scheduled_requests.all_requests()) spec_metadata.prepare() inputs = self.model_inputs(attn_metadata, resource_manager, virtual_num_tokens, []) diff --git a/tensorrt_llm/_torch/pyexecutor/engine/runners/decoder/metadata.py b/tensorrt_llm/_torch/pyexecutor/engine/runners/decoder/metadata.py index debf2cf273f9..36073372040b 100644 --- a/tensorrt_llm/_torch/pyexecutor/engine/runners/decoder/metadata.py +++ b/tensorrt_llm/_torch/pyexecutor/engine/runners/decoder/metadata.py @@ -157,7 +157,10 @@ def setup_speculative( self.spec_metadata.skip_greedy_rng_upload = self.runtime_hooks.skip_greedy_rng_upload self.spec_metadata.pack_rng_uploads = self.runtime_hooks.pack_spec_rng_uploads if self.runtime_hooks.pack_spec_rng_uploads: - logger.info("[M3 host] sampled-step Philox uploads staged into the step-input pack") + logger.info( + "Sampled-step Philox uploads: written by the steady MTP stager on its steps, " + "else staged into the step-input pack when one is open" + ) if self.runtime_hooks.spec_small_h2d: logger.info( "[M3 host] spec step small uploads off the boundary (accepted counts packed, static slot ids)" diff --git a/tensorrt_llm/_torch/pyexecutor/kv_cache/host_memory.py b/tensorrt_llm/_torch/pyexecutor/kv_cache/host_memory.py new file mode 100644 index 000000000000..24231d711f2d --- /dev/null +++ b/tensorrt_llm/_torch/pyexecutor/kv_cache/host_memory.py @@ -0,0 +1,327 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Host memory placement for KV cache donations (``remote_donor.py``): fault-in, NUMA binding and topology, and the +chunk placement of a fabric donation over the host's NUMA nodes. + +A fabric chunk the driver refuses is retried; with reclaim-and-compact passes on +(``RemoteFabricTransportConfig.compact_host_memory``), the node is then compacted for it under a per-node flock that +donors on one host take in turn. Without them, what fits is published and the job prolog is left to compact. +""" + +import contextlib +import ctypes +import errno +import fcntl +import mmap +import os +import time +from collections.abc import Callable, Iterator +from types import ModuleType +from typing import TYPE_CHECKING, Optional + +from tensorrt_llm._torch.mmap_utils import madvise_range +from tensorrt_llm.logger import logger + +if TYPE_CHECKING: + from cuda.bindings.driver import CUdevice + +_GIB = 1 << 30 + + +def _log(message: str) -> None: + logger.info(f"KVCM2 remote donor: {message}") + + +# Linux values (asm-generic, so x86_64 and aarch64 alike); Python's mmap module lacks some of them before 3.13. +MADV_HUGEPAGE = 14 +_POPULATE_SLICE = 64 << 20 + + +def populate(region: mmap.mmap, address: int, nbytes: int) -> None: + """Make every page of `region` (at `address`) resident: huge pages where the kernel has them (MADV_HUGEPAGE is set + first), 4 KiB pages elsewhere. MADV_POPULATE_WRITE does it in the kernel without holding the GIL; a kernel without + it gets the region zeroed slice by slice. Any other madvise error (ENOMEM, EHWPOISON) raises.""" + try: + madvise_range(address, nbytes, "populate_write") + return + except OSError as error: + if error.errno not in (errno.EINVAL, errno.ENOSYS): + raise + zeros = bytes(_POPULATE_SLICE) + view = memoryview(region) + try: + for offset in range(0, nbytes, _POPULATE_SLICE): + end = min(offset + _POPULATE_SLICE, nbytes) + view[offset:end] = zeros[: end - offset] + finally: + view.release() + + +def bind_to_numa_node(address: int, nbytes: int, node: int) -> bool: + """Bind [address, address + nbytes) to NUMA node `node` with libnuma, before it is touched.""" + try: + libnuma = ctypes.CDLL("libnuma.so.1") + except OSError: + return False + if libnuma.numa_available() < 0: + return False + libnuma.numa_tonode_memory.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int] + libnuma.numa_tonode_memory.restype = None + libnuma.numa_tonode_memory( + ctypes.c_void_p(address), ctypes.c_size_t(nbytes), ctypes.c_int(node) + ) + return True + + +# Seconds a refused fabric chunk is retried with backoff before a pass: the driver refuses transiently while reclaiming. +_REFUSAL_RETRY_S = 2.0 +# A reclaim-and-compact pass (compact_node) covers the donation still missing, at least this share of the node reserve +# and at most _MAX_PASS_CHUNKS chunks, and leaves this share of the reserve free above the reserve and the chunk. +_PASS_RESERVE_SHARE = 1 / 3 +_MAX_PASS_CHUNKS = 64 +# Pass bounds: per node, and per refused chunk; past the first bound only while each pass adds a chunk's worth of +# >= 2 MiB blocks. +_MAX_PASSES_PER_NODE = 64 +_MAX_PASSES_PER_REFUSAL = 3 +_MAX_PASSES_PER_REFUSAL_PROGRESSING = 16 + + +def node_meminfo(node: int) -> dict: + """GiB per field of /sys/devices/system/node/node/meminfo; empty if unreadable.""" + out = {} + try: + with open(f"/sys/devices/system/node/node{node}/meminfo") as f: + for line in f: + parts = line.split() # "Node 0 MemFree: 123 kB" + if len(parts) >= 4 and parts[3].isdigit(): + out[parts[2].rstrip(":")] = int(parts[3]) * 1024 / _GIB + except OSError: + return {} + return out + + +def _numa_nodes() -> list: + try: + names = os.listdir("/sys/devices/system/node") + except OSError: + return [] + return sorted(int(n[4:]) for n in names if n.startswith("node") and n[4:].isdigit()) + + +def _reclaimable_gib(info: dict) -> float: + """Clean file pages the kernel can drop, which cuMemCreate's host allocations reclaim (shmem sits on the + anonymous LRU, outside these counts).""" + return max( + 0.0, + info.get("Active(file)", 0.0) + info.get("Inactive(file)", 0.0) - info.get("Dirty", 0.0), + ) + + +def host_numa_nodes() -> list: + """The NUMA nodes that have memory (GPU memory partitions show up as nodes with MemTotal 0).""" + return [n for n in _numa_nodes() if node_meminfo(n).get("MemTotal", 0.0) > 0] + + +def contiguous_free_gib( + node: int, min_bytes: int = 2 << 20, text: Optional[str] = None, page: Optional[int] = None +) -> float: + """GiB of free memory on NUMA node `node` held in blocks of at least `min_bytes` (/proc/buddyinfo: free blocks of + each order, per zone); -1 when unreadable. A refusal while this is near zero points at fragmentation.""" + try: + if text is None: + with open("/proc/buddyinfo") as f: + text = f.read() + page = page or os.sysconf("SC_PAGE_SIZE") + except (OSError, ValueError): + return -1.0 + total = 0 + for line in text.splitlines(): + parts = line.replace(",", " ").split() # "Node 0, zone Normal n0 n1 ..." + if len(parts) < 5 or parts[0] != "Node" or not parts[1].isdigit() or int(parts[1]) != node: + continue + for order, count in enumerate(parts[4:]): + if count.isdigit() and (page << order) >= min_bytes: + total += int(count) * (page << order) + return total / _GIB + + +def host_numa_node_of(drv: ModuleType, device: "CUdevice") -> int: + """The host NUMA node closest to CUDA device `device`; the first node with memory if the driver reports none.""" + err, node = drv.cuDeviceGetAttribute( + drv.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_HOST_NUMA_ID, device + ) + if err == drv.CUresult.CUDA_SUCCESS and node >= 0: + return node + nodes = host_numa_nodes() + return nodes[0] if nodes else 0 + + +def compact_node(node: int, gib: float) -> None: + """Reclaim and compact memory on NUMA node `node`: fault in `gib` GiB of node-bound anonymous memory with huge + pages (direct reclaim and compaction), then unmap it, leaving about that much free in 2 MiB blocks. Raises when + libnuma cannot bind the region, since unbound it would land anywhere.""" + nbytes = int(gib * _GIB) // (2 << 20) * (2 << 20) + region = mmap.mmap(-1, nbytes, flags=mmap.MAP_PRIVATE | mmap.MAP_ANONYMOUS) + try: + anchor = ctypes.c_char.from_buffer(region) + address = ctypes.addressof(anchor) + del anchor # the buffer export must end before close() + if not bind_to_numa_node(address, nbytes, node): + raise RuntimeError("libnuma is unavailable, so the region cannot be bound to the node") + try: + region.madvise(MADV_HUGEPAGE) + except OSError: + pass + populate(region, address, nbytes) + finally: + region.close() + + +@contextlib.contextmanager +def node_compaction_lock(directory: str, host: str, node: int) -> Iterator[bool]: + """Hold the exclusive flock of NUMA node `node` of `host` in `directory`; yields False, holding nothing, when the + file system refuses it (no pass may then run on the node).""" + path = os.path.join(directory, f"compact.{host}.node{node}.lock") + try: + fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600) + except OSError as error: + _log(f"cannot open {path} ({error}); no reclaim-and-compact pass on node {node}") + yield False + return + try: + try: + fcntl.flock(fd, fcntl.LOCK_EX) + except OSError as error: + _log(f"cannot lock {path} ({error}); no reclaim-and-compact pass on node {node}") + yield False + return + yield True + finally: + os.close(fd) # drops the lock + + +def place_chunks( + n_chunks: int, + nodes: list, + create: Callable[[int], Optional[object]], + *, + chunk_gib: float, + reserve_gib: float, + node_lock: Callable[[int], contextlib.AbstractContextManager[bool]], + compact_passes: bool = True, + meminfo: Optional[Callable[[int], dict]] = None, + compact: Optional[Callable[[int, float], None]] = None, + contiguous: Optional[Callable[[int], float]] = None, + sleep: Callable[[float], None] = time.sleep, + clock: Callable[[], float] = time.monotonic, +) -> tuple[list, dict[int, int]]: + """Place up to `n_chunks` chunks over `nodes`, the preferred node first; `create(node)` returns a handle, or None + when the driver refuses. A node takes chunks while it keeps `reserve_gib`; a refused chunk is retried, then, with + `compact_passes`, compacted for under `node_lock(node)` (see the constants), which donors sharing the node take + in turn; a node that still refuses is left, and swept once more when no node takes the chunk. Returns (handles, + {node: placed}).""" + meminfo = meminfo or node_meminfo + compact = compact or compact_node + contiguous = contiguous or contiguous_free_gib + handles = [] + placement = {n: 0 for n in nodes} + passes = {n: 0 for n in nodes} + pass_failed = set() + min_pass_gib = margin_gib = reserve_gib * _PASS_RESERVE_SHARE + max_pass_gib = _MAX_PASS_CHUNKS * chunk_gib + + def room(node: int) -> float: + info = meminfo(node) + return info.get("MemFree", 0.0) + _reclaimable_gib(info) if info else float("inf") + + def recover(node: int) -> Optional[object]: + delay, deadline = 0.05, clock() + _REFUSAL_RETRY_S + while clock() < deadline: + sleep(delay) + delay = min(2 * delay, 0.5) + handle = create(node) + if handle is not None: + return handle + if not compact_passes: + return None + tries = 0 + while ( + tries < _MAX_PASSES_PER_REFUSAL_PROGRESSING + and passes[node] < _MAX_PASSES_PER_NODE + and node not in pass_failed + ): + tries += 1 + with node_lock(node) as locked: + if not locked: + pass_failed.add(node) + return None + # Sized from the node's memory once the lock is held: another donor may have used it meanwhile. + missing = (n_chunks - len(handles)) * chunk_gib + size = min( + max(min_pass_gib, missing), + max_pass_gib, + room(node) - reserve_gib - chunk_gib - margin_gib, + ) + if size < chunk_gib: + return None + before = contiguous(node) + try: + compact(node, size) + except Exception as error: # noqa: BLE001 - no pass is possible here; the chunk moves on + _log(f"reclaim-and-compact pass on node {node} failed: {error!r}") + pass_failed.add(node) + return None + passes[node] += 1 + gained = contiguous(node) - before + handle = create(node) + if handle is not None: + return handle + if tries >= _MAX_PASSES_PER_REFUSAL and gained < chunk_gib: + return None # the passes stopped bringing contiguous memory + return None + + exhausted = set() + swept = False + while len(handles) < n_chunks: + handle = None + for node in nodes: + if node in exhausted or room(node) - chunk_gib < reserve_gib: + continue # refused for good, or the node keeps its reserve for the serving process + handle = create(node) + if handle is None: + handle = recover(node) + if handle is None: + exhausted.add(node) + if handle is not None: + placement[node] += 1 + break + if handle is None: + if swept: + break + # A node given up on can recover after the donor left it (compaction and other donors' frees go on). + swept = True + revived = { + n + for n in exhausted + if contiguous(n) >= chunk_gib and room(n) - chunk_gib >= reserve_gib + } + if not revived: + break + exhausted -= revived + continue + handles.append(handle) + if any(passes.values()): + _log(f"reclaim-and-compact passes per NUMA node: {passes}") + return handles, placement diff --git a/tensorrt_llm/_torch/pyexecutor/kv_cache/kv_cache_manager_v2.py b/tensorrt_llm/_torch/pyexecutor/kv_cache/kv_cache_manager_v2.py index 3ab8bce41031..5d4742fd7256 100644 --- a/tensorrt_llm/_torch/pyexecutor/kv_cache/kv_cache_manager_v2.py +++ b/tensorrt_llm/_torch/pyexecutor/kv_cache/kv_cache_manager_v2.py @@ -12,6 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +import functools import math import os import sys @@ -21,6 +22,7 @@ from functools import cached_property from typing import ( TYPE_CHECKING, + Any, Callable, Dict, Iterable, @@ -30,7 +32,9 @@ Optional, Sequence, Tuple, + TypeVar, Union, + cast, ) import numpy as np @@ -61,7 +65,12 @@ copy_batch_block_offsets_to_device, gather_base_page_rows, ) -from tensorrt_llm.llmapi.llm_args import KvCacheConfig, KVEventsConfig, SparseKvCacheOffloadConfig +from tensorrt_llm.llmapi.llm_args import ( + KvCacheConfig, + KVEventsConfig, + RemoteCacheConfig, + SparseKvCacheOffloadConfig, +) from tensorrt_llm.logger import logger from tensorrt_llm.mapping import Mapping from tensorrt_llm.math_utils import ceil_div, pad_up @@ -95,6 +104,10 @@ PlannedDropHandle, PoolGroupPeakBlockStats, PoolRebalanceConfig, + RemoteCacheTierConfig, + RemoteMemError, + RemoteTransferConfig, + RemoteTransport, ReusePolicy, ReuseScope, SsmLayerConfig, @@ -157,6 +170,8 @@ from tensorrt_llm._torch.attention.backends.interface import AttentionMetadata from tensorrt_llm.llmapi.llm_args import DecodingBaseConfig + from .remote_donor import RemoteMemDonor + KV_CACHE_ITERATION_STATS_DELTA_FIELDS = _KV_CACHE_ITERATION_STATS_DELTA_FIELDS KV_CACHE_ITERATION_STATS_REUSE_FIELDS = ( @@ -182,6 +197,7 @@ CacheTier.GPU_MEM: "gpu", CacheTier.HOST_MEM: "host", CacheTier.DISK: "disk", + CacheTier.REMOTE: "remote", } # The guard page is a permanent sequence that must never collide with any other @@ -2010,8 +2026,42 @@ def copy_block_offsets_to( ) +_InitT = TypeVar("_InitT", bound=Callable[..., None]) + + +def _withdraws_remote_donation_on_error(init: _InitT) -> _InitT: + """Wrap ``__init__`` so a construction that raises undoes what it set up (``_abandon_construction``). + + Every subclass's ``__init__`` is wrapped too (``KVCacheManagerV2.__init_subclass__``), so that its own finalization + after ``super().__init__()`` is guarded; the outermost wrapper does the cleanup, and ``shutdown()`` inside it leaves + the donation to that cleanup. + """ + + @functools.wraps(init) + def wrapper(self: "KVCacheManagerV2", *args: Any, **kwargs: Any) -> None: + if self.__dict__.get("_guarding_construction", False): + init(self, *args, **kwargs) + return + self._guarding_construction = True + try: + init(self, *args, **kwargs) + except BaseException as error: + self._abandon_construction(error) + raise + finally: + self._guarding_construction = False + + return cast(_InitT, wrapper) + + class KVCacheManagerV2(BaseResourceManager): gen_preemption_headroom: int = 0 + # Host memory this rank donates to remote cache levels (remote_cache_config.donor); closed by shutdown(). + _remote_donor: Optional["RemoteMemDonor"] = None + # The remote config of a donation this manager owns, started or not; a failure leaves its marker. + _planned_donation: Optional[RemoteCacheConfig] = None + # True while a __init__ wrapped by _withdraws_remote_donation_on_error runs. + _guarding_construction: bool = False # Filled lazily by _cold_pool_group_membership(); the grouping is fixed after construction. # Declared on the class so it is present even when an instance is built without running __init__. _cold_pool_group_membership_cache: Optional[tuple[tuple[int, frozenset[int]], ...]] = None @@ -2027,6 +2077,10 @@ class KVCacheManagerV2(BaseResourceManager): inforward_snapshot_rows: int = 0 # Block width of a drafter whose layers share this manager, else 0. _shared_draft_block_width: int = 0 + # Deferred KvCache closes of finished generation-only requests (enable_deferred_close); + # __init__ gives each instance its own queue. + _defer_close_enabled: bool = False + _deferred_closes: "deque[tuple[int, _KVCache]] | tuple[()]" = () # Local layer id -> storage of the draft-owned layers a subclass appends # after the layers it describes itself (MambaHybridCacheManagerV2). # Empty when ``layer_specs`` describes every layer. @@ -2096,8 +2150,12 @@ def _kv_alloc_extra_tokens(self) -> int: # built without running __init__. _sparse_kv_offload: Optional[SparseKvCacheOffloadConfig] = None # Host history pages admitted requests hold through their last token; None - # unless offload runs with no cache level below the hot one. + # unless offload runs with no host or disk level below the hot one. _host_history_reservations: Optional[HostHistoryReservations] = None + # Whether the configured tiers have a level below the GPU, and whether all of them are remote levels, which retire + # at run time when a transfer or their donor fails (see can_evict). + _can_evict: bool = False + _only_remote_below_gpu: bool = False # Host history pages the smallest rank's pool has for requests once dummy # requests are set aside, the most one request can be given; None when no # rank offloads sparse history. @@ -2124,6 +2182,13 @@ def _kv_alloc_extra_tokens(self) -> int: # device quota; None until offload sizing first asks for it. _offload_sizing_config: Optional[KVCacheManagerConfigPy] = None + def __init_subclass__(cls, **kwargs: Any) -> None: + super().__init_subclass__(**kwargs) + init = cls.__dict__.get("__init__") + if init is not None: + cls.__init__ = _withdraws_remote_donation_on_error(init) + + @_withdraws_remote_donation_on_error def __init__( self, kv_cache_config: KvCacheConfig, @@ -2161,9 +2226,17 @@ def __init__( layer_specs: Optional[Sequence[KVCacheLayerSpec]] = None, sparse_kv_offload_config: Optional[SparseKvCacheOffloadConfig] = None, shared_draft_block_width: Optional[int] = None, + remote_donor: Optional["RemoteMemDonor"] = None, gen_preemption_headroom: int = 0, **kwargs, ) -> None: + # A donation started before this manager (remote_donor.start_donation) is owned from here and closed by + # shutdown(). A draft manager gets the target's donation only to wait for it before measuring host memory. + remote_config = kv_cache_config.remote_cache_config + if not is_draft: + self._remote_donor = remote_donor + if remote_config is not None and remote_config.donor is not None: + self._planned_donation = remote_config self.mapping = mapping self.gen_preemption_headroom = gen_preemption_headroom self.dtype = dtype @@ -2392,6 +2465,13 @@ def __init__( "on every CP rank. Set " "kv_cache_config.disk_cache_size=0." ) + if remote_config is not None and remote_config.level is not None: + raise ValueError( + "KVCacheManagerV2 does not support a remote cache level " + "with aggregated helix context parallelism, for the same " + "reason as a disk tier. Unset " + "kv_cache_config.remote_cache_config.level." + ) if kv_connector_manager is not None: raise ValueError( "KVCacheManagerV2 does not support a KV cache " @@ -2773,6 +2853,8 @@ def append_to_kv_heads_per_layer( logger.info(f"KV cache manager v2 device quota set to {quota / (1 << 30)}GiB") cache_tiers: List[CacheTierConfig] = [GpuCacheTierConfig(quota=int(quota))] + # A remote-tier failure on one rank, raised once every rank has agreed on the init status. + remote_init_error: Optional[Exception] = None # A capacity-only connector registers nothing for migration to # invalidate, so it keeps the tier the scheduler spills to. The # rejection of non-GPU tiers in `PyExecutor` exempts it to match. @@ -2816,12 +2898,33 @@ def append_to_kv_heads_per_layer( # co-located ranks each reserving a device-quota-sized block can # OOM the host (observed on GB300 NVL72 with 4 ranks/node and # ~170GiB device quota each on a 975GiB node). + remote_config = kv_cache_config.remote_cache_config + donation_started = remote_donor is not None + if donation_started: + # The co-located ranks started their donations as early as this one: measure with them resident. + remote_donor.wait_started() local_ranks, mem_available, memlock_limit = get_host_memory_limits(mapping) # Every rank on the node also pins its host-backed sparse pools and # its sparse Batch's staging copy. offload_pinned_bytes = self._host_history_budget + self._sparse_batch_staging_bytes mem_available = max(0.0, mem_available - local_ranks * offload_pinned_bytes) memlock_limit = max(0.0, memlock_limit - offload_pinned_bytes) + if ( + remote_config is not None + and remote_config.donor is not None + and not donation_started + ): + # Every co-located rank donates this much more, faulted in after this sizing. + donated = local_ranks * remote_config.donor.size + if donated >= mem_available: + remote_init_error = ValueError( + f"remote_cache_config.donor.size x {local_ranks} rank(s) leaves none of the " + f"{mem_available / (1 << 30):.2f}GiB available host memory to the automatic " + "host tier; set kv_cache_config.host_cache_size." + ) + self._report_unstarted_donation(remote_init_error) + else: + mem_available -= donated host_quota = _compute_auto_host_tier_quota( quota, local_ranks, @@ -2883,6 +2986,12 @@ def append_to_kv_heads_per_layer( logger.info( f"KV cache manager v2 disk cache quota set to {disk_cache_size / (1 << 30):.2f}GiB at {disk_cache_path}" ) + if kv_cache_config.remote_cache_config is not None and remote_init_error is None: + try: + self._add_remote_level(kv_cache_config.remote_cache_config, cache_tiers) + except Exception as error: + remote_init_error = error + self._report_unstarted_donation(error) if self._sparse_kv_offload is not None: self._warn_if_lower_tiers_cannot_take_history(cache_tiers) @@ -2946,8 +3055,13 @@ def create_cold_page_codec(cache_config: object) -> Optional[object]: ) # Aggregated helix CP ranks need a common verdict even without a host # tier: a rank that fails to allocate would otherwise leave its peers - # waiting in the first collective. - sync_init_status = has_host_cache_tier or (self._has_cp_helix and not is_disagg) + # waiting in the first collective. So do ranks with a remote tier, + # whose donation and claims can fail on one rank. + sync_init_status = ( + has_host_cache_tier + or kv_cache_config.remote_cache_config is not None + or (self._has_cp_helix and not is_disagg) + ) if not sync_init_status: candidate = self._allocate_cache_pools( config, @@ -2956,24 +3070,28 @@ def create_cold_page_codec(cache_config: object) -> Optional[object]: max_gpu_total_bytes=kv_cache_config.max_gpu_total_bytes, ) else: - init_error: Optional[Exception] = None + init_error: Optional[Exception] = remote_init_error local_init_status = _KVCacheManagerInitStatus.OK - try: - candidate = self._allocate_cache_pools( - config, - event_manager=event_sink, - cold_page_codec=create_cold_page_codec(config), - max_gpu_total_bytes=kv_cache_config.max_gpu_total_bytes, - ) - except Exception as error: - init_error = error.with_traceback(None) + if init_error is not None: local_init_status = _KVCacheManagerInitStatus.ABORT + else: + try: + candidate = self._allocate_cache_pools( + config, + event_manager=event_sink, + cold_page_codec=create_cold_page_codec(config), + max_gpu_total_bytes=kv_cache_config.max_gpu_total_bytes, + ) + except Exception as error: + init_error = error.with_traceback(None) + local_init_status = _KVCacheManagerInitStatus.ABORT init_status = _sync_kv_cache_manager_init_status(local_init_status, mapping) if init_status == _KVCacheManagerInitStatus.ABORT: if candidate is not None: candidate.shutdown() + # The construction guard withdraws the donation and leaves its failure marker. if init_error is not None: raise init_error raise RuntimeError("KV cache manager initialization failed on another rank") @@ -2989,11 +3107,21 @@ def create_cold_page_codec(cache_config: object) -> Optional[object]: ) self.kv_cache_manager_py_config = config self.impl = candidate - self.can_evict = len(config.cache_tiers) > 1 - if self._sparse_kv_offload is not None and not self.can_evict: + if self._remote_donor is not None: + # This rank's claims are done: place the donation now (a no-op once placed, as after the estimation), so + # it does not fault in and register beside warmup, CUDA-graph capture and the first serving steps. + self._remote_donor.wait_started() + self._can_evict = len(config.cache_tiers) > 1 + self._only_remote_below_gpu = self._can_evict and all( + isinstance(tier, RemoteCacheTierConfig) for tier in config.cache_tiers[1:] + ) + if self._sparse_kv_offload is not None and ( + not self._can_evict or self._only_remote_below_gpu + ): logger.warning( "Sparse KV cache offload runs without a host or disk cache tier: suspending a " - "request cannot free its KV cache pages, and a decode-only worker cannot " + "request cannot free its KV cache pages (a remote level stops taking them once " + "its donor fails), and a decode-only worker cannot " "recompute them, so scheduling can stall once the device KV cache is full. " "Admission therefore reserves each request's offloaded history through its last " "token, which admits fewer requests. Set kv_cache_config.host_cache_size to give " @@ -3134,6 +3262,10 @@ def create_cold_page_codec(cache_config: object) -> Optional[object]: index_mapper_capacity, max_beam_width, self.max_copy_beam_width ) self._early_freed_index_requests: set[int] = set() + # Finished generation-only requests whose KvCache.close() (a host-side + # page release) waits for flush_deferred_closes, oldest first. + self._defer_close_enabled = False + self._deferred_closes: deque[tuple[int, _KVCache]] = deque() # Requests whose pages a connector is still reading from, so the # release half of `preempt_request` has to wait. self._pending_preemption: Dict[int, LlmRequest] = {} @@ -6598,8 +6730,37 @@ def resume_request(self, req: LlmRequest) -> bool: @property def has_cache_tier_below_gpu(self) -> bool: - """True when a suspended page has somewhere to be evicted to.""" - return len(self.impl.cache_tier_list) > 1 + """True when a suspended page has somewhere to be evicted to; a failed remote level takes no more pages.""" + if len(self.impl.cache_tier_list) <= 1: + return False + return self._has_durable_tier_below_gpu or not self.impl.any_remote_level_failed + + @property + def _has_durable_tier_below_gpu(self) -> bool: + """True when a level below the GPU cannot retire at run time, as a remote level does when its donor dies.""" + return any(tier != CacheTier.REMOTE for tier in self.impl.cache_tier_list[1:]) + + @property + def can_evict(self) -> bool: + """True when the configured tiers have a level below the GPU that has not failed.""" + return self._can_evict and not ( + self._only_remote_below_gpu and self.impl.any_remote_level_failed + ) + + @property + def remote_donor(self) -> Optional["RemoteMemDonor"]: + """This rank's donation (remote_cache_config.donor) while this manager owns it, else None.""" + return self._remote_donor + + @property + def has_remote_cache_level(self) -> bool: + """True when this manager has a remote cache level (remote_cache_config.level).""" + return CacheTier.REMOTE in self.impl.cache_tier_list + + @property + def any_remote_level_failed(self) -> bool: + """Whether any remote cache level of this manager failed on this rank (a transfer or its donor did).""" + return self.impl.any_remote_level_failed def has_pending_preemption(self) -> bool: """True while a deferred preemption is still waiting on a connector.""" @@ -7975,8 +8136,9 @@ def _setup_sparse_kv_offload( # decode, and the scheduler suspends one under pressure, demoting its # history. Without one, suspension frees nothing and a decode-only worker # cannot recompute, so admission reserves each request's history through - # its last token instead. - if not self.has_cache_tier_below_gpu: + # its last token instead. A remote level alone counts as none: it retires + # when its donor dies, and admitted requests could then exhaust the slots. + if not self._has_durable_tier_below_gpu: self._host_history_reservations = HostHistoryReservations(capacity_blocks) if not self.is_estimating_kv_cache: if self._host_tier_follows_history: @@ -8604,6 +8766,151 @@ def _remove_kv_cache(self, request_id: int) -> None: else: self.index_mapper.remove_sequence(request_id) + def _add_remote_level(self, remote_config: RemoteCacheConfig, cache_tiers: list) -> None: + """Start this rank's donation, unless it was started before, and append the remote cache level to + `cache_tiers`. + + Both happen once per rank, in the target manager; a draft manager only counts the + donation in its automatic host tier.""" + if self.is_draft: + return + from .remote_donor import ( + check_remote_capacity, + ensure_rendezvous_directory, + nixl_ucx_backend_params, + resolve_rendezvous_directory, + resolve_ucx_devices, + start_donation, + ) + + remote_dir = resolve_rendezvous_directory(remote_config.directory) + ensure_rendezvous_directory(remote_dir) + transport = remote_config.transport + nixl = transport.kind == "nixl" + agent_backend_params = ( + nixl_ucx_backend_params(resolve_ucx_devices(transport.ucx_devices)) if nixl else {} + ) + if remote_config.donor is not None and self._remote_donor is None: + # This rank's memory joins the pool before its own cache exists: clients wait for donors. + self._remote_donor = start_donation(remote_config, torch.cuda.current_device()) + level = remote_config.level + if level is not None: + if level.expected is not None: + check_remote_capacity( + remote_dir, + level.expected.num_donors, + level.expected.claim_size, + transport=transport.kind, + timeout_s=level.donor_wait_timeout_s, + log=logger.info, + ) + # The remote level goes below the host tier. + cache_tiers.append( + RemoteCacheTierConfig( + quota=level.size, + path=remote_dir, + wait_timeout_ms=math.ceil(level.donor_wait_timeout_s * 1000), + expected_donors=level.expected.num_donors if level.expected is not None else 0, + pool_ratio=list(level.pool_ratio or []), + # How pages move is declared apart from the memory. + transfer=RemoteTransferConfig( + transport=RemoteTransport[transport.kind.upper()], + # Fabric copies run on the stream and are not timed: the binding's default. + timeout_ms=math.ceil(transport.transfer_timeout_s * 1000) + if nixl + else RemoteTransferConfig().timeout_ms, + backend_params=agent_backend_params, + ), + ) + ) + logger.info( + f"KV cache manager v2 remote cache quota set to " + f"{level.size / (1 << 30):.2f}GiB via {remote_dir} ({transport.kind})" + ) + + def _report_unstarted_donation(self, error: BaseException) -> None: + """Leave the failure marker of this rank's planned donation now if it never started, before the init-status + collective: peers waiting in check_remote_capacity for this donor then stop at once, instead of after + donor_wait_timeout_s with no word of this error. A started donation reports through its donor.""" + if self._remote_donor is None: + self._close_remote_donor(error) + + def _abandon_construction(self, error: BaseException) -> None: + """Undo a construction that raised `error`: withdraw the donation with it, whose failure marker tells the + peers counting on this donor to stop waiting, and shut the runtime down, which returns this rank's remote + chunk claims now rather than at garbage collection. The caches construction opened (the guard page's) close + first: the runtime's shutdown refuses while one is open.""" + self._close_remote_donor(error) + impl = self.__dict__.get("impl") + if impl is not None: + for kv_cache in list(self.__dict__.get("kv_cache_map", {}).values()): + try: + kv_cache.close() + except Exception as close_error: # noqa: BLE001 - `error` is the one to report + logger.warning( + f"KV cache manager v2: closing a cache after a failed construction failed: {close_error!r}" + ) + try: + impl.shutdown() # a no-op when it is shut down already + except Exception as shutdown_error: # noqa: BLE001 - `error` is the one to report + logger.warning( + f"KV cache manager v2: shutting down after a failed construction failed: {shutdown_error!r}" + ) + + def _close_remote_donor(self, error: Optional[BaseException] = None) -> None: + """Withdraw this rank's donation: clients still holding its chunks fail their next transfer. With `error`, leave + the donation's failure marker too, also for a donation that never started, so that peers stop waiting for it.""" + donor, self._remote_donor = self._remote_donor, None + planned, self._planned_donation = self._planned_donation, None + if donor is not None: + donor.close(error) + elif error is not None and planned is not None: + from .remote_donor import publish_donation_failure + + publish_donation_failure(planned, error) + + def enable_deferred_close(self, enabled: bool) -> None: + """Turn the deferred close of finished generation-only requests on or off + (the overlap executor's switch). Turning it off runs any closes still pending.""" + if not enabled: + self.flush_deferred_closes() + self._defer_close_enabled = bool(enabled) and not self.is_draft + + def _defer_remove_kv_cache(self, request_id: int) -> bool: + """`_remove_kv_cache` except for the close, which `flush_deferred_closes` runs later. + + The index slot is released now (detached first, so the close never writes a reused row); + the pages are not. Returns False when there is nothing to defer.""" + kv_cache = self.kv_cache_map.get(request_id) + if kv_cache is None: + return False + if request_id not in self._early_freed_index_requests: + self.release_index_slot(request_id) + # Nothing of the id is left to free, so a new request with the same id takes the normal path. + self._early_freed_index_requests.discard(request_id) + self.kv_cache_map.pop(request_id, None) + kv_cache.discard_pending_stats() + self._deferred_closes.append((request_id, kv_cache)) + return True + + def flush_deferred_closes(self) -> bool: + """Close the KvCaches `_defer_remove_kv_cache` left open, oldest first. + + Returns whether any was pending. A close that raises leaves the later ones queued; its own + request is forgotten all the same. + """ + if not self._deferred_closes: + return False + while self._deferred_closes: + request_id, kv_cache = self._deferred_closes.popleft() + try: + if self._sharing is not None: + self._sharing._on_free(request_id, kv_cache) + kv_cache.close() + finally: + self.impl.clear_stats_excluded(request_id) + return True + def free_resources(self, request: LlmRequest, pin_on_release: bool = False): # A request awaiting preemption can still be cancelled or fail while # its saves drain, and a dead entry here would block every later @@ -8640,6 +8947,18 @@ def free_resources(self, request: LlmRequest, pin_on_release: bool = False): self._disagg_receive_ready.pop(request.py_request_id, None) self._on_allocation_stream.discard(request.py_request_id) self._allocation_ready.pop(request.py_request_id, None) + # Dummies reuse request ids, so their closes stay immediate. + if ( + self._defer_close_enabled + and request.is_generation_only_request + and not pin_on_release + and not request.is_dummy + # Host history reservations back admission; keep their release with the close. + and self._host_history_reservations is None + and request.py_request_id not in _RESERVED_REQUEST_IDS + and self._defer_remove_kv_cache(request.py_request_id) + ): + return if self._host_history_reservations is not None: self._host_history_reservations.release(request.py_request_id) self._remove_kv_cache(request.py_request_id) @@ -8959,6 +9278,24 @@ def check_invalid_values_in_kv_cache(self, fill_with_zero: bool = False) -> bool return bool(has_invalid_values) def shutdown(self): + try: + self._shutdown_caches() + finally: + # A construction that shuts down on an error withdraws the donation with that error itself + # (_abandon_construction), so that its failure marker tells peers to stop waiting. + if not self._guarding_construction: + self._close_remote_donor() + # Shut the streaming event manager down last so removals emitted during + # cache / impl teardown (via the radix tree's own event-manager + # reference) are still flushed before the publisher stops. Do not null + # event_manager: get_latest_events/flush snapshot it and operate safely + # on a closed manager, so there is no teardown-time None race. + if isinstance(self.event_manager, StreamingKVCacheEventManager): + self.event_manager.shutdown() + + def _shutdown_caches(self) -> None: + # impl.shutdown() raises while any cache is open, deferred ones included. + self.enable_deferred_close(False) # Before the caches close: a lender waiting on a lease has to be told to stop while # the caches it lent against are still alive. if self._sharing is not None: @@ -8982,13 +9319,6 @@ def shutdown(self): # After the runtime's shutdown, which raises while any cache is open, in the map or not; # a poisoned runtime returns at once, and a close then does nothing. self._sharing._on_caches_closed() - # Shut the streaming event manager down last so removals emitted during - # cache / impl teardown (via the radix tree's own event-manager - # reference) are still flushed before the publisher stops. Do not null - # event_manager: get_latest_events/flush snapshot it and operate safely - # on a closed manager, so there is no teardown-time None race. - if isinstance(self.event_manager, StreamingKVCacheEventManager): - self.event_manager.shutdown() def get_max_resource_count(self) -> int: # TODO: implement this @@ -9847,7 +10177,7 @@ def probe_first_new_block_key(self, req: LlmRequest) -> bytes | None: return self.impl.probe_first_new_block_key(scope, tokens) def prefetch_for_context_tokens(self, requests: list) -> bool: - """Prefetch radix-tree blocks from disk→host for upcoming context requests. + """Prefetch radix-tree blocks from a cold level (disk or remote) to the host for upcoming context requests. Returns True if all prefetches succeeded, False if any failed. """ @@ -9862,9 +10192,15 @@ def prefetch_for_context_tokens(self, requests: list) -> bool: # Use the same salt derivation as _create_kv_cache so the transient # cache hits the same radix-tree blocks. reuse_salt = self._derive_reuse_salt(req.cache_salt) - prefetched = self.impl.prefetch_reuse( - ReuseScope(lora_id=req.lora_task_id, salt=reuse_salt), tokens, CACHE_LEVEL1 - ) + try: + prefetched = self.impl.prefetch_reuse( + ReuseScope(lora_id=req.lora_task_id, salt=reuse_salt), tokens, CACHE_LEVEL1 + ) + except RemoteMemError as error: + # A failed remote level has retired; its pages drop from the tree, so the request recomputes them. + logger.warning(f"prefetch for request {req.py_request_id} failed: {error}") + success = False + continue if not prefetched: logger.warning("prefetch failed for request %s", req.py_request_id) success = False @@ -9875,6 +10211,8 @@ def reset_reuse_state( *, on_cleared: Optional[Callable[[], None]] = None, ): + # A deferred close commits its pages for reuse, which must not outlive the clear. + self.flush_deferred_closes() try: self.impl.clear_reusable_blocks() if on_cleared is not None: diff --git a/tensorrt_llm/_torch/pyexecutor/kv_cache/remote_donor.py b/tensorrt_llm/_torch/pyexecutor/kv_cache/remote_donor.py new file mode 100644 index 000000000000..8d7c5280fbe0 --- /dev/null +++ b/tensorrt_llm/_torch/pyexecutor/kv_cache/remote_donor.py @@ -0,0 +1,995 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Donate host memory to the remote cache levels of KV cache manager v2. + +A donor publishes host memory in a rendezvous directory on a shared file system; a remote cache level +(``KvCacheConfig.remote_cache_config``; C++ ``storage/remoteMem.h``, which also describes the directory layout) claims +whole chunks of it with O_EXCL claim files and moves cold pages itself, so the donor does no work after publishing. + +``RemoteMemDonor`` declares the donation (size, chunks, the files, the failure marker, start and close) and does not +pick how it is reached: its ``DonorTransport``, chosen apart (``make_donor``, ``RemoteCacheConfig.transport.kind``), +allocates and registers the memory: + +* ``AgentDonorTransport``: anonymous memory registered with the donor's own transfer agent through the + ``BaseTransferAgent`` interface (a NIXL agent); ``donor..desc`` holds the agent's ``AgentDesc``. +* ``FabricDonorTransport``: Grace DRAM allocated with cuMemCreate (``CU_MEM_LOCATION_TYPE_HOST_NUMA``), one + allocation per chunk because an imported fabric allocation maps only whole; ``donor..fabric`` holds one + 64-byte handle per chunk. Chunks fill the GPU's host NUMA node first, then the other nodes; a donation that only + partly fits is published with ``short_bytes``. Placement, and the optional reclaim-and-compact passes, are + ``host_memory``'s. + +A donor that cannot start, or whose owner fails, leaves ``donor..failed``, which clients ignore and capacity +checks count. In a serving process ``start_donation`` starts the donation (``remote_cache_config.donor``) +before the KV cache estimation, or, where no estimation runs (``TRTLLM_SKIP_KV_CACHE_ESTIMATION``, helix CP on KV +cache manager v2, encoder-decoder models), when the target ``KVCacheManagerV2`` is built; that manager owns it. + +Trust model: the directory is private to the job's user (``ensure_rendezvous_directory``) and every file in it is +0600, since donor files hold NIXL memory registration keys and fabric handles; use one directory per job. +""" + +import contextlib +import ctypes +import mmap +import os +import re +import socket +import stat +import threading +import time +import uuid +import weakref +from collections.abc import Callable, Iterator +from types import ModuleType +from typing import TYPE_CHECKING, Any, Optional + +from tensorrt_llm.llmapi.llm_args import REMOTE_CACHE_CHUNK_BYTES, REMOTE_CACHE_DONOR_RESERVE_BYTES +from tensorrt_llm.logger import logger + +from .host_memory import ( + MADV_HUGEPAGE, + bind_to_numa_node, + host_numa_node_of, + host_numa_nodes, + node_compaction_lock, + place_chunks, + populate, +) + +if TYPE_CHECKING: + from cuda.bindings.driver import CUmemAllocationProp, CUmemGenericAllocationHandle + + from tensorrt_llm.llmapi.llm_args import RemoteCacheConfig + from tensorrt_llm.tensorrt_llm_transfer_agent_binding import ( + BaseTransferAgent, + NixlTransferAgent, + ) + + +def _nvml_gpu_index(device: int) -> int: + """NVML's index (nvidia-smi's numbering) of CUDA device `device`, found by its PCI bus id.""" + import pynvml + from cuda.bindings import driver as drv + + _cuda_check(drv.cuInit(0)) + bus_id = _cuda_check(drv.cuDeviceGetPCIBusId(32, _cuda_check(drv.cuDeviceGet(device)))) + if isinstance(bus_id, bytes): + bus_id = bus_id.decode() + pynvml.nvmlInit() + try: + return pynvml.nvmlDeviceGetIndex( + pynvml.nvmlDeviceGetHandleByPciBusId(bus_id.rstrip("\x00")) + ) + finally: + pynvml.nvmlShutdown() + + +def _physical_gpu_index(device: Optional[int]) -> int: + """The physical index of CUDA device `device` (default: the current one): a plain index in CUDA_VISIBLE_DEVICES + directly, any other entry (a UUID or MIG id) through the device's PCI bus id.""" + if device is None: + import torch + + device = torch.cuda.current_device() + visible = [ + v.strip() for v in os.environ.get("CUDA_VISIBLE_DEVICES", "").split(",") if v.strip() + ] + if not visible: + return device + if device >= len(visible): + raise ValueError( + f"cannot map CUDA device {device} to a GPU index through " + f"CUDA_VISIBLE_DEVICES={os.environ.get('CUDA_VISIBLE_DEVICES')}" + ) + if visible[device].isdigit(): + return int(visible[device]) + return _nvml_gpu_index(device) + + +def resolve_ucx_devices(devices: Optional[str], device: Optional[int] = None) -> Optional[str]: + """Replace ``{GPU}`` in `devices` with this rank's physical GPU index (CUDA device `device`, default the current + one, through CUDA_VISIBLE_DEVICES), so that "rdma_vf_rail{GPU}:1" gives each rank the rail next to its GPU.""" + if not devices or "{" not in devices: + return devices + resolved = devices.replace("{GPU}", str(_physical_gpu_index(device))) + if "{" in resolved or "}" in resolved: + raise ValueError(f"UCX devices {devices!r}: unknown token (known: {{GPU}})") + return resolved + + +def nixl_ucx_backend_params(devices: Optional[str]) -> dict: + """The NIXL UCX backend parameters that restrict an agent to `devices` (UCX_NET_DEVICES form, e.g. + "mlx5_0:1,mlx5_1:1", ``{GPU}`` already resolved); empty for None. + + NIXL's UCX backend reads only ``device_list``: device names split on ", ", each given port 1 (``ucx_devices``, the + key its plugin lists, is never read). A device on another port cannot be expressed and raises.""" + if not devices: + return {} + names = [] + for entry in devices.split(","): + name, _, port = entry.strip().partition(":") + if not name or port not in ("", "1"): + raise ValueError( + f"UCX devices {devices!r}: {entry.strip()!r} is not '' or ':1' (NIXL's UCX " + "backend uses port 1 of each device)" + ) + names.append(name) + return {"device_list": ", ".join(names)} + + +def _log(message: str) -> None: + logger.info(f"KVCM2 remote donor: {message}") + + +_ENV_REFERENCE = re.compile(r"\$(?:\{[A-Za-z_][A-Za-z0-9_]*\}|[A-Za-z_][A-Za-z0-9_]*)") + + +def resolve_rendezvous_directory(configured: str) -> str: + """``remote_cache_config.directory`` with ``~`` and environment variables expanded and trailing separators + stripped (a path ending in one follows a symlink). A variable left unset raises: the path would otherwise be one + literal directory shared by every run without it, whose leftover donor files would count as live donors.""" + directory = os.path.expandvars(os.path.expanduser(configured)) + unset = sorted({m.group(0) for m in _ENV_REFERENCE.finditer(directory)}) + if unset: + raise ValueError( + f"remote_cache_config.directory {configured!r} names unset environment variable(s) {', '.join(unset)}" + ) + return directory.rstrip(os.sep) or os.sep + + +def ensure_rendezvous_directory(directory: str) -> None: + """Create `directory` and its missing parents as 0700, or accept an existing one only if it is a directory (not a + symlink to one) that this user owns and nobody else can write. Clients pin the directory they checked (C++ + ``RemoteMemClient``).""" + directory = directory.rstrip(os.sep) or os.sep + missing = [] + parent = directory + while parent and not os.path.lexists(parent): + missing.append(parent) + parent = os.path.dirname(parent) + for path in reversed(missing): + with contextlib.suppress(FileExistsError): # another rank made it first + os.mkdir(path, 0o700) + st = os.lstat(directory) + if not stat.S_ISDIR(st.st_mode): + raise PermissionError( + f"KVCM2 remote rendezvous directory {directory} must be a directory, not a symlink or another file" + ) + if st.st_uid != os.geteuid() or st.st_mode & 0o022: + raise PermissionError( + f"KVCM2 remote rendezvous directory {directory} must be owned by uid {os.geteuid()} and not writable by " + f"group or others (owner uid {st.st_uid}, mode {st.st_mode & 0o777:o})" + ) + + +def _write_atomically(path: str, data: bytes) -> None: + # A fresh name, created exclusively and never through a symlink: a planted file or link is not written through. + tmp = f"{path}.tmp.{os.getpid()}.{uuid.uuid4().hex}" + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC + fd = os.open(tmp, flags, 0o600) + try: + with os.fdopen(fd, "wb") as f: + f.write(data) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(tmp) + raise + + +class _DonorFiles: + """The rendezvous files a donor published, shared with its finalizer. Once withdrawn, nothing more is published: + at exit the finalizer may run while a background start is still publishing (daemon threads keep running).""" + + def __init__(self) -> None: + self.lock = threading.Lock() + self.paths: list[str] = [] + self.withdrawn = False + + def withdraw(self, failed: Optional[tuple[str, bytes]] = None) -> None: + """Unlink the published files and refuse later ones; with `failed` (path, text), leave that marker too.""" + with self.lock: + self.withdrawn = True + for path in reversed(self.paths): + with contextlib.suppress(OSError): + os.unlink(path) + self.paths.clear() + if failed is not None: + with contextlib.suppress(OSError): + _write_atomically(*failed) + + +def _withdraw_unowned( + files: _DonorFiles, failed_path: str, marker: bytes, transport: "DonorTransport" +) -> None: + """Finalizer of a donor nobody closed: withdraw its files, leave the failure marker and free its memory. + + It holds the transport, not the donor: e.g. a fabric donation's pinned chunks and retained primary context + otherwise stay until the process exits, though the donor is gone (a failed startup in a process that lives on). + """ + files.withdraw((failed_path, marker)) + transport.release_unowned() + + +# Linux values (asm-generic, so x86_64 and aarch64 alike); Python's mmap module lacks some of them before 3.13. +_MAP_NORESERVE = 0x4000 + + +def _cuda_check(result: object) -> Any: + """Unwrap a cuda.bindings driver call's (CUresult, value...) tuple, raising on an error.""" + from cuda.bindings import driver as drv + + err = result[0] if isinstance(result, tuple) else result + if err != drv.CUresult.CUDA_SUCCESS: + name = drv.cuGetErrorName(err)[1] + raise RuntimeError(name.decode() if isinstance(name, bytes) else str(name)) + if isinstance(result, tuple): + return result[1] if len(result) == 2 else result[1:] + return None + + +_GIB = 1 << 30 + + +def _meta_fields(path: str) -> dict: + fields = {"segments": []} + with open(path) as f: + for line in f: + key, _, value = line.strip().partition(" ") + if key == "segment": + fields["segments"].append([int(x) for x in value.split()]) + elif key: + fields[key] = value + return fields + + +def scan_donors( + directory: str, malformed: Optional[list[str]] = None +) -> tuple[list[dict], list[dict]]: + """The donors of a rendezvous directory that have reported: (published, failed). A published donor offers the + whole chunks of its segments; a failed one left donor..failed (RemoteMemDonor.publish_failure). Files that + name no transport count as neither; their names are appended to `malformed`.""" + published, failed = [], [] + try: + files = sorted(os.listdir(directory)) + except FileNotFoundError: + return published, failed + for file in files: + if not file.startswith("donor."): + continue + name = file[len("donor.") :].rsplit(".", 1)[0] + try: + if file.endswith(".ready"): + fields = _meta_fields(os.path.join(directory, f"donor.{name}.meta")) + if "transport" not in fields: + # Malformed: every donor names its transport, as clients require. + if malformed is not None: + malformed.append(f"donor.{name}.meta") + continue + chunk = int(fields.get("chunk_bytes", 0)) + offered = sum(b - b % chunk for _, b in fields["segments"]) if chunk else 0 + published.append( + { + "name": name, + "host": fields.get("host", "?"), + "transport": fields["transport"], + "offered_bytes": offered, + "short_bytes": int(fields.get("short_bytes", 0)), + "numa_chunks": fields.get("numa_chunks", ""), + } + ) + elif file.endswith(".failed"): + fields = _meta_fields(os.path.join(directory, file)) + if "transport" not in fields: + if malformed is not None: + malformed.append(file) + continue + failed.append( + { + "name": name, + "host": fields.get("host", "?"), + "transport": fields["transport"], + "planned_bytes": int(fields.get("planned_bytes", 0)), + "error": fields.get("error", "?"), + } + ) + except (OSError, ValueError): + continue # a file being replaced; the next scan sees it + return published, failed + + +def check_remote_capacity( + directory: str, + num_donors: int, + need_bytes: int, + *, + timeout_s: float, + transport: Optional[str] = None, + poll_s: float = 2.0, + log: Optional[Callable[[str], None]] = None, +) -> dict: + """Wait until `num_donors` donors have published or failed (at most `timeout_s`), or until they offer + `need_bytes`, then raise if the offer falls short, naming the failed and short donors. A job whose donors cannot + cover its clients thus stops when the last donor reports instead of after the clients' claim wait. + + With `transport`, only donors of that transport count, as the clients skip the others.""" + log = log or _log + need = need_bytes + expected = num_donors + deadline = time.monotonic() + timeout_s + warned: set[str] = set() + while True: + malformed: list[str] = [] + published, failed = scan_donors(directory, malformed) + for file in malformed: + if file not in warned: + warned.add(file) + logger.warning( + f"KVCM2 remote donor file {file} in {directory} is malformed; it is not counted" + ) + if transport is not None: + published = [p for p in published if p["transport"] == transport] + failed = [f for f in failed if f["transport"] == transport] + offered = sum(p["offered_bytes"] for p in published) + reported = len(published) + len(failed) + if offered >= need or reported >= expected or time.monotonic() >= deadline: + break + time.sleep(poll_s) + summary = ( + f"{len(published)} of {expected} planned donors published {offered / _GIB:.0f} GiB, {len(failed)} failed, " + f"{max(0, expected - reported)} not reported; the plan's clients claim {need / _GIB:.0f} GiB" + + (f"; malformed (not counted): {', '.join(malformed)}" if malformed else "") + ) + if offered < need: + notes = [f"{f['name']} ({f['host']}) failed: {f['error']}" for f in failed] + notes += [ + f"{p['name']} ({p['host']}) is {p['short_bytes'] / _GIB:.0f} GiB short" + + (f" (chunks per NUMA node {p['numa_chunks']})" if p["numa_chunks"] else "") + for p in published + if p["short_bytes"] + ] + raise RuntimeError( + f"KVCM2 remote level capacity check failed in {directory}: {summary}" + + (f". {'; '.join(notes)}" if notes else "") + + ". Raise remote_cache_config.donor.size or the number of donating ranks (level.expected.num_donors), " + "lower level.size (level.expected.claim_size), or for the fabric transport lower " + "transport.donor_reserve_size." + ) + log(f"KVCM2 remote level capacity check passed in {directory}: {summary}") + return {"published": published, "failed": failed, "offered_bytes": offered, "need_bytes": need} + + +class DonorTransport: + """How a donation is made reachable: allocates the memory its transfers need, registers it and hands the donor + what clients read (``RemoteMemDonor._publish``); frees it again. Chosen apart from the donation itself + (``make_donor``).""" + + # The transport's name, as written to the donor's files. + kind: str = "" + + @classmethod + def options_from(cls, remote_config: "RemoteCacheConfig") -> dict: + """The constructor options of this transport that ``remote_config`` sets.""" + return {} + + def start(self, donor: "RemoteMemDonor") -> None: + """Allocate and register `donor`'s memory, then publish it (``donor._publish``).""" + raise NotImplementedError + + def release_unowned(self) -> None: + """Free what ``start`` made, without the donor (also the finalizer of a donor nobody closed); teardown keeps + going past errors.""" + + +@contextlib.contextmanager +def _donor_thread_cuda(device: Optional[int]) -> Iterator[None]: + """CUDA state of the thread that starts or releases a donation, for the duration of that step. + + Relaxed stream-capture mode: the start may run in the background while the serving thread captures a CUDA graph + in global mode, and a capture-unsafe CUDA call here (e.g. host-memory registration) would invalidate that capture. + `device`'s primary context current: CUDA calls the transport makes land on the donor's GPU, not on device 0. + """ + from cuda.bindings import driver as drv + + _cuda_check(drv.cuInit(0)) + capture_mode = _cuda_check( + drv.cuThreadExchangeStreamCaptureMode( + drv.CUstreamCaptureMode.CU_STREAM_CAPTURE_MODE_RELAXED + ) + ) + cu_device = context = None + try: + if device is not None: + cu_device = _cuda_check(drv.cuDeviceGet(device)) + context = _cuda_check(drv.cuDevicePrimaryCtxRetain(cu_device)) + _cuda_check(drv.cuCtxPushCurrent(context)) + yield + finally: + steps = [lambda: drv.cuThreadExchangeStreamCaptureMode(capture_mode)] + if context is not None: + steps = [drv.cuCtxPopCurrent, lambda: drv.cuDevicePrimaryCtxRelease(cu_device), *steps] + for step in steps: + try: + _cuda_check(step()) + except RuntimeError as error: + _log(f"leaving the donor thread's CUDA state failed: {error}") + + +@contextlib.contextmanager +def _donor_release_cuda(device: Optional[int], name: str) -> Iterator[None]: + """``_donor_thread_cuda`` for a release, which keeps going without it: e.g. a failed start's cleanup on the donor + thread, which may run while the serving thread captures a CUDA graph in global mode, or a finalizer at exit.""" + with contextlib.ExitStack() as stack: + try: + stack.enter_context(_donor_thread_cuda(device)) + except (ImportError, RuntimeError) as error: + _log(f"{name}: releasing without the donor thread's CUDA state: {error}") + yield + + +class RemoteMemDonor: + """One donation: the host memory a rank gives remote cache levels, published by ``start()`` in the rendezvous + directory and withdrawn by ``close()``. + + The donation declares the memory (size, chunks, placement, rendezvous files, failure marker, lifecycle); its + ``transport`` (``AgentDonorTransport`` or ``FabricDonorTransport``) allocates and registers it. A donor collected + or left at exit without ``close()`` withdraws its files and leaves the failure marker.""" + + transport: Optional[DonorTransport] = None + directory: str = "" + nbytes: int = 0 + chunk_bytes: int = REMOTE_CACHE_CHUNK_BYTES + numa_node: Optional[int] = None + device: Optional[int] = None + name: str = "" + host: str = "" + _files: Optional[_DonorFiles] = None # files written, withdrawn by close() or the finalizer + # start_in_background()'s thread, joined by close(). + _start_thread: Optional[threading.Thread] = None + # Serializes close(): a failed background start closes on its own thread. + _close_lock: Optional[threading.Lock] = None + # Withdraws the files of a donor nobody closed; close() detaches it. + _finalizer: Optional[weakref.finalize] = None + + def __init__( + self, + directory: str, + nbytes: int, + transport: DonorTransport, + *, + chunk_bytes: int = REMOTE_CACHE_CHUNK_BYTES, + name: Optional[str] = None, + numa_node: Optional[int] = None, + device: Optional[int] = None, + ) -> None: + if nbytes < chunk_bytes: + raise ValueError(f"donation size {nbytes} is below one chunk ({chunk_bytes})") + self.transport = transport + self.directory = directory + # Whole chunks only: a client never sees a partial chunk. + self.nbytes = nbytes - nbytes % chunk_bytes + self.chunk_bytes = chunk_bytes + self.numa_node = numa_node + self.device = device + host = socket.gethostname().split(".")[0] + # Unique per donor, also within one process: clients never take claims from a withdrawn name again. + self.name = name or f"kvcm2-donor-{host}-{os.getpid()}-{uuid.uuid4().hex[:12]}" + self.host = host + self._files = _DonorFiles() + self._start_thread = None + self._close_lock = threading.Lock() + self._finalizer = None + + def _path(self, suffix: str) -> str: + return os.path.join(self.directory, f"donor.{self.name}.{suffix}") + + def _publish( + self, extra_files: list[tuple[str, bytes]], meta_lines: list[str], timing: str + ) -> None: + meta = "\n".join( + [ + "version 1", + f"name {self.name}", + f"host {self.host}", + f"pid {os.getpid()}", + f"chunk_bytes {self.chunk_bytes}", + f"transport {self.transport.kind}", + *meta_lines, + "", + ] + ).encode() + with self._files.lock: + if self._files.withdrawn: + raise RuntimeError(f"{self.name} was withdrawn before it published") + for suffix, data in [*extra_files, ("meta", meta), ("ready", b"")]: + _write_atomically(self._path(suffix), data) + self._files.paths.append(self._path(suffix)) + _log( + f"{self.name} donates {self.nbytes / (1 << 30):.2f} GiB in {self.nbytes // self.chunk_bytes} chunk(s) " + f"of {self.chunk_bytes / (1 << 30):.2f} GiB via {self.directory} ({timing})" + ) + + def _failure_text(self, error: BaseException) -> bytes: + return "\n".join( + [ + "version 1", + f"name {self.name}", + f"host {self.host}", + f"pid {os.getpid()}", + f"transport {self.transport.kind}", + f"planned_bytes {self.nbytes}", + f"error {error!r}".replace("\n", " "), + "", + ] + ).encode() + + def publish_failure(self, error: BaseException) -> None: + """Leave donor..failed (planned bytes and the error) so capacity checks count this donor as reported + instead of waiting for it. Clients ignore the file: they list only .ready donors.""" + try: + ensure_rendezvous_directory(self.directory) + _write_atomically(self._path("failed"), self._failure_text(error)) + except OSError as write_error: + _log(f"{self.name}: cannot write its failure marker: {write_error}") + + def start(self) -> None: + if self._finalizer is None: + self._finalizer = weakref.finalize( + self, + _withdraw_unowned, + self._files, + self._path("failed"), + self._failure_text(RuntimeError("the donor's owner exited without closing it")), + self.transport, + ) + self.transport.start(self) + + def start_or_report(self) -> None: + """``start()``; on failure, release what was made and leave the failure marker (``publish_failure``).""" + try: + self.start() + except Exception as error: # noqa: BLE001 - a failed donor only removes capacity + logger.warning(f"KVCM2 remote donor: {self.name} failed to start: {error!r}") + self.close(error) + + def start_in_background(self) -> None: + """``start_or_report()`` on a thread, so the caller does not wait for the memory to be faulted in and + registered; clients wait for the ``.ready`` file.""" + self._start_thread = threading.Thread( + target=self.start_or_report, name="kvcm2-remote-donor", daemon=True + ) + self._start_thread.start() + + def wait_started(self) -> None: + """Wait for a background start to publish or fail.""" + thread = self._start_thread + if thread is not None and thread is not threading.current_thread(): + thread.join() + + def close(self, error: Optional[BaseException] = None) -> None: + """Wait for a background start, then withdraw the files and the transport's memory; with `error`, leave the + failure marker too. Clients still holding chunks fail their next transfer instead of reading stale bytes. + + A failed background start closes on its own thread; ``_start_thread`` stays set until that close ends, so + ``wait_started()`` returns only once the failed donation is released and marked.""" + thread = self._start_thread + on_start_thread = thread is threading.current_thread() + if thread is not None and not on_start_thread: + thread.join() + with self._close_lock: + if self._finalizer is not None: + self._finalizer.detach() + self._withdraw() + if error is not None: + self.publish_failure(error) + if not on_start_thread: + self._start_thread = None + + def _withdraw(self) -> None: + self._files.withdraw() + self.transport.release_unowned() + + +def _make_nixl_agent(name: str, backend_params: dict) -> "NixlTransferAgent": + """A NIXL transfer agent (the C++ binding's ``NixlTransferAgent``, a ``BaseTransferAgent``) named `name`.""" + from tensorrt_llm.tensorrt_llm_transfer_agent_binding import BaseAgentConfig, NixlTransferAgent + + config = BaseAgentConfig() + config.name = name + config.use_prog_thread = True + config.multi_thread = False + config.use_listen_thread = False + # This agent's own UCX devices; the process-wide UCX_NET_DEVICES stays as the serving process needs it. + if backend_params: + config.backend_params = backend_params + return NixlTransferAgent(config) + + +class AgentDonorTransport(DonorTransport): + """Anonymous memory registered with the donor's own transfer agent, through the ``BaseTransferAgent`` interface + only (``make_agent``, default a NIXL agent); ``donor..desc`` holds the agent's ``AgentDesc``. + ``ucx_devices`` (``{GPU}`` resolved at start) selects the agent's UCX devices.""" + + kind = "nixl" + ucx_devices: Optional[str] = None + _map: Optional[mmap.mmap] = None + _address: int = 0 + _nbytes: int = 0 # the registered donation + _name: str = "" # the donor's, for logs + _agent = None + _registered: bool = False + # The donor's CUDA device, current while the agent is made or released. + _device: Optional[int] = None + + def __init__( + self, + *, + ucx_devices: Optional[str] = None, + make_agent: Callable[[str, dict], "BaseTransferAgent"] = _make_nixl_agent, + ) -> None: + self.ucx_devices = ucx_devices + self._make_agent = make_agent + self._map = None + self._address = 0 + self._nbytes = 0 + self._name = "" + self._agent = None + self._registered = False + self._device = None + + @classmethod + def options_from(cls, remote_config: "RemoteCacheConfig") -> dict: + return {"ucx_devices": remote_config.transport.ucx_devices} + + def start(self, donor: "RemoteMemDonor") -> None: + from tensorrt_llm.tensorrt_llm_transfer_agent_binding import ( + MemoryDesc, + MemoryDescs, + MemoryType, + ) + + ensure_rendezvous_directory(donor.directory) + backend_params = nixl_ucx_backend_params( + resolve_ucx_devices(self.ucx_devices, donor.device) + ) + self._name = donor.name + self._nbytes = donor.nbytes + self._device = donor.device + t0 = time.monotonic() + flags = mmap.MAP_PRIVATE | mmap.MAP_ANONYMOUS | _MAP_NORESERVE + self._map = mmap.mmap(-1, donor.nbytes, flags=flags) + self._address = ctypes.addressof(ctypes.c_char.from_buffer(self._map)) + try: + self._map.madvise(MADV_HUGEPAGE) + except OSError: + pass + if donor.numa_node is not None and not bind_to_numa_node( + self._address, donor.nbytes, donor.numa_node + ): + _log(f"libnuma unavailable; {donor.name} relies on first touch for NUMA placement") + # Fault every page in now: registration does not pin memory where the NIC pages on demand, and a resident + # donation fails here rather than mid-run and never makes a remote write wait on a page fault. + populate(self._map, self._address, donor.nbytes) + t1 = time.monotonic() + + # NIXL/UCX may make CUDA calls while creating the agent and registering host memory. + with _donor_thread_cuda(donor.device): + self._agent = self._make_agent(donor.name, backend_params) + self._agent.register_memory( + MemoryDescs(MemoryType.DRAM, [MemoryDesc(self._address, donor.nbytes, 0)]) + ) + self._registered = True + t2 = time.monotonic() + desc = self._agent.get_local_agent_desc().serialize() + donor._publish( + [("desc", desc)], + [f"segment {self._address} {donor.nbytes}"], + f"map + populate {t1 - t0:.1f} s, register {t2 - t1:.1f} s", + ) + + def release_unowned(self) -> None: + # Clients still holding chunks fail their next transfer at the NIC. Deregistering and dropping the agent run in + # the start's CUDA state (_donor_thread_cuda), like registering: NIXL/UCX may make CUDA calls there too. + if self._agent is not None: + with _donor_release_cuda(self._device, self._name): + if self._registered: + from tensorrt_llm.tensorrt_llm_transfer_agent_binding import ( + MemoryDesc, + MemoryDescs, + MemoryType, + ) + + try: + self._agent.deregister_memory( + MemoryDescs( + MemoryType.DRAM, [MemoryDesc(self._address, self._nbytes, 0)] + ) + ) + except Exception as error: # noqa: BLE001 - teardown keeps going + _log(f"{self._name}: deregistering failed: {error}") + self._registered = False + self._agent = None + if self._map is not None: + try: + self._map.close() + except BufferError: + pass + self._map = None + + +class FabricDonorTransport(DonorTransport): + """Grace DRAM allocated with cuMemCreate (``CU_MEM_LOCATION_TYPE_HOST_NUMA``), one allocation per chunk because an + imported fabric allocation maps only whole, published as one 64-byte CUDA fabric handle per chunk in + ``donor..fabric``. Chunks fill the donor's NUMA node (default: the node of its CUDA device) first, then the + other nodes, leaving ``reserve_bytes`` free per node; a donation that only partly fits is published with + ``short_bytes``. With ``compact_host_memory`` a refused chunk gets reclaim-and-compact passes on its node first + (``host_memory.place_chunks``). Clients map the chunks and copy on their own streams, so no transfer agent is + involved.""" + + kind = "fabric" + name: str = "" # the donor's, for logs + chunk_bytes: int = REMOTE_CACHE_CHUNK_BYTES + reserve_bytes: int = REMOTE_CACHE_DONOR_RESERVE_BYTES + compact_host_memory: bool = False + _fabric: Optional[list] = None # the cuMemCreate handles, one per chunk + # The CUDA device ordinal whose primary context the donation retains while it lives (None: not started). + _device: Optional[int] = None + + def __init__( + self, + *, + reserve_bytes: int = REMOTE_CACHE_DONOR_RESERVE_BYTES, + compact_host_memory: bool = False, + ) -> None: + self.reserve_bytes = reserve_bytes + self.compact_host_memory = compact_host_memory + self._fabric = [] + self._device = None + + @classmethod + def options_from(cls, remote_config: "RemoteCacheConfig") -> dict: + return { + "reserve_bytes": remote_config.transport.donor_reserve_size, + "compact_host_memory": remote_config.transport.compact_host_memory, + } + + def _release_fabric(self) -> None: + from cuda.bindings import driver as drv + + for handle in self._fabric: + try: + _cuda_check(drv.cuMemRelease(handle)) + except Exception as error: # noqa: BLE001 - teardown keeps going + _log(f"{self.name}: releasing a fabric chunk failed: {error}") + self._fabric = [] + + @staticmethod + def _fabric_prop(drv: ModuleType, node: int) -> "CUmemAllocationProp": + prop = drv.CUmemAllocationProp() + prop.type = drv.CUmemAllocationType.CU_MEM_ALLOCATION_TYPE_PINNED + prop.location.type = drv.CUmemLocationType.CU_MEM_LOCATION_TYPE_HOST_NUMA + prop.location.id = node + prop.requestedHandleTypes = drv.CUmemAllocationHandleType.CU_MEM_HANDLE_TYPE_FABRIC + return prop + + def _try_create( + self, drv: ModuleType, prop: "CUmemAllocationProp" + ) -> Optional["CUmemGenericAllocationHandle"]: + """One chunk, or None when the node is out of memory (any other error raises).""" + try: + return _cuda_check(drv.cuMemCreate(self.chunk_bytes, prop, 0)) + except RuntimeError as error: + if "OUT_OF_MEMORY" in str(error): + return None + raise + + def start(self, donor: "RemoteMemDonor") -> None: + """Allocate the donation one chunk at a time, placed by place_chunks, and publish their fabric handles in chunk + order. What fits is published with short_bytes; a donor that fits nothing raises.""" + from cuda.bindings import driver as drv + + self.name = donor.name + self.chunk_bytes = donor.chunk_bytes + ensure_rendezvous_directory(donor.directory) + handles = [] + planned = donor.nbytes + chunk_gib = self.chunk_bytes / _GIB + reserve_gib = self.reserve_bytes / _GIB + ordinal = 0 if donor.device is None else donor.device + # cuMemCreate and the export may run while the serving thread captures a CUDA graph in global mode. + with _donor_thread_cuda(ordinal): + device = _cuda_check(drv.cuDeviceGet(ordinal)) + # Held for the donation's life; release_unowned releases it after the chunks. + _cuda_check(drv.cuDevicePrimaryCtxRetain(device)) + self._device = ordinal + try: + numa = ( + donor.numa_node + if donor.numa_node is not None + else host_numa_node_of(drv, device) + ) + nodes = [numa] + [n for n in host_numa_nodes() if n != numa] + props = {n: self._fabric_prop(drv, n) for n in nodes} + gran = _cuda_check( + drv.cuMemGetAllocationGranularity( + props[numa], + drv.CUmemAllocationGranularity_flags.CU_MEM_ALLOC_GRANULARITY_MINIMUM, + ) + ) + if self.chunk_bytes % gran: + raise ValueError( + f"chunk size {self.chunk_bytes} is not a multiple of the fabric allocation granularity {gran}" + ) + + def create(node: int) -> Optional["CUmemGenericAllocationHandle"]: + handle = self._try_create(drv, props[node]) + if handle is not None: + # Released by the except below if anything fails later. + self._fabric.append(handle) + return handle + + t0 = time.monotonic() + placed, per_node = place_chunks( + planned // self.chunk_bytes, + nodes, + create, + chunk_gib=chunk_gib, + reserve_gib=reserve_gib, + node_lock=lambda node: node_compaction_lock(donor.directory, donor.host, node), + compact_passes=self.compact_host_memory, + ) + for handle in placed: + exported = _cuda_check( + drv.cuMemExportToShareableHandle( + handle, drv.CUmemAllocationHandleType.CU_MEM_HANDLE_TYPE_FABRIC, 0 + ) + ) + handles.append(bytes(exported.data)) + # The C++ client reads 64-byte CUmemFabricHandles back to back. + if len(handles[-1]) != 64: + raise RuntimeError(f"fabric handle of {len(handles[-1])} B, expected 64") + t1 = time.monotonic() + if not handles: + raise RuntimeError( + f"no NUMA node can hold a {chunk_gib:.2f} GiB fabric chunk and keep its " + f"{reserve_gib:.0f} GiB reserve" + ) + except BaseException: + # Nothing is published: release what was made. + self._release_fabric() + raise + donor.nbytes = len(handles) * self.chunk_bytes + short = planned - donor.nbytes + placement = ",".join(f"{n}:{c}" for n, c in per_node.items() if c) + meta = [ + f"numa {numa}", + f"numa_chunks {placement}", + f"segment 0 {donor.nbytes}", + ] + if short: + meta.append(f"short_bytes {short}") + _log( + f"{self.name}: only {donor.nbytes / _GIB:.0f} of {planned / _GIB:.0f} GiB fit as fabric memory " + f"(reserve {reserve_gib:.0f} GiB per node)" + ) + donor._publish( + [("fabric", b"".join(handles))], + meta, + f"fabric memory, chunks per NUMA node {placement}, {len(handles)} allocation(s) created in " + f"{t1 - t0:.1f} s", + ) + + def release_unowned(self) -> None: + if self._device is not None: + from cuda.bindings import driver as drv + + # In the start's CUDA state: a failed start releases on the donor thread, possibly during a capture. + with _donor_release_cuda(self._device, self.name): + self._release_fabric() + try: + _cuda_check( + drv.cuDevicePrimaryCtxRelease(_cuda_check(drv.cuDeviceGet(self._device))) + ) + except Exception as error: # noqa: BLE001 - teardown keeps going + _log(f"{self.name}: releasing the primary context failed: {error}") + self._device = None + self._fabric = [] + + +# The donor transport of each RemoteCacheConfig.transport.kind. +DONOR_TRANSPORTS = {"nixl": AgentDonorTransport, "fabric": FabricDonorTransport} +TRANSPORTS = tuple(DONOR_TRANSPORTS) + + +def make_donor( + directory: str, + nbytes: int, + transport: str = "nixl", + *, + chunk_bytes: int = REMOTE_CACHE_CHUNK_BYTES, + name: Optional[str] = None, + numa_node: Optional[int] = None, + device: Optional[int] = None, + **transport_options: object, +) -> RemoteMemDonor: + """A donation of `nbytes` in `directory`, made reachable by `transport` (one of ``TRANSPORTS``) built with + `transport_options` (``ucx_devices`` for NIXL, ``reserve_bytes`` and ``compact_host_memory`` for fabric).""" + if transport not in DONOR_TRANSPORTS: + raise ValueError(f"transport {transport!r} is not one of {TRANSPORTS}") + return RemoteMemDonor( + directory, + nbytes, + DONOR_TRANSPORTS[transport](**transport_options), + chunk_bytes=chunk_bytes, + name=name, + numa_node=numa_node, + device=device, + ) + + +def _donor_for(remote_config: "RemoteCacheConfig", device: Optional[int]) -> RemoteMemDonor: + return make_donor( + resolve_rendezvous_directory(remote_config.directory), + remote_config.donor.size, + remote_config.transport.kind, + device=device, + **DONOR_TRANSPORTS[remote_config.transport.kind].options_from(remote_config), + ) + + +def start_donation(remote_config: "RemoteCacheConfig", device: int) -> RemoteMemDonor: + """Start donating ``remote_config.donor.size`` bytes of host memory near CUDA device `device`, in the background. + Every start error, ``{GPU}`` resolution included, surfaces as the donor's failure marker.""" + donor = _donor_for(remote_config, device) + directory = donor.directory + donor.start_in_background() + size = remote_config.donor.size + donated = size - size % REMOTE_CACHE_CHUNK_BYTES # as RemoteMemDonor rounds it + if donated != size: + logger.warning( + f"remote_cache_config.donor.size {size} is not a whole number of " + f"{REMOTE_CACHE_CHUNK_BYTES}-byte chunks; {donated} bytes are donated" + ) + logger.info( + f"KV cache manager v2 donates {donated / _GIB:.2f}GiB of host memory " + f"to remote cache levels via {directory} ({remote_config.transport.kind})" + ) + return donor + + +def publish_donation_failure(remote_config: "RemoteCacheConfig", error: BaseException) -> None: + """Leave the failure marker of a donation this rank planned but never started, so peers stop waiting for it.""" + _donor_for(remote_config, None).publish_failure(error) diff --git a/tensorrt_llm/_torch/pyexecutor/model_engine.py b/tensorrt_llm/_torch/pyexecutor/model_engine.py index 039767a00775..28e15a99802f 100644 --- a/tensorrt_llm/_torch/pyexecutor/model_engine.py +++ b/tensorrt_llm/_torch/pyexecutor/model_engine.py @@ -621,6 +621,11 @@ def _initialize_decoder_runner( **runner_kwargs, ) + @property + def uses_torch_compile(self) -> bool: + """Whether the model forward runs under torch.compile.""" + return self._torch_compile_backend is not None + @property def attn_metadata(self) -> AttentionMetadata | None: if isinstance(self._runner, DecoderRunner): diff --git a/tensorrt_llm/_torch/pyexecutor/model_loader.py b/tensorrt_llm/_torch/pyexecutor/model_loader.py index f7c054210ab6..7a2def50c17a 100644 --- a/tensorrt_llm/_torch/pyexecutor/model_loader.py +++ b/tensorrt_llm/_torch/pyexecutor/model_loader.py @@ -939,6 +939,28 @@ def _checkpoint_io_policy_metadata( } +def captured_cuda_graph_batch_sizes( + llm_args: TorchLlmArgs, max_num_tokens: int, + spec_config: Optional[DecodingBaseConfig]) -> Tuple[int, ...]: + """The decode CUDA-graph batch sizes the engine captures + (``engine.cuda_graph.plan_cuda_graphs``): the configured ones within + max_batch_size and max_num_tokens // tokens per request; () without + CUDA graphs. Sizes above them never run, so buffers sized by the largest + graph batch (``ModelConfig.cuda_graph_batch_sizes``) stop there.""" + config = llm_args.cuda_graph_config + if config is None or not config.batch_sizes: + return () + from .engine.cuda_graph import filter_cuda_graph_batch_sizes + max_batch_size = (llm_args.max_batch_size if llm_args.max_batch_size + is not None else max(config.batch_sizes)) + tokens_per_request = (spec_config.tokens_per_gen_step + if spec_config is not None else 1) + return tuple( + filter_cuda_graph_batch_sizes(list(config.batch_sizes), max_batch_size, + max_num_tokens, tokens_per_request, + config.enable_padding)) + + class ModelLoader: """ Handles the loading, configuration, and weight initialization of a PyTorch model. @@ -2348,9 +2370,8 @@ def _load_and_validate_config( mnnvl_allreduce_fp8_payload=self.llm_args. mnnvl_allreduce_fp8_payload, replicate_embedding=self.llm_args.replicate_embedding, - cuda_graph_batch_sizes=tuple( - self.llm_args.cuda_graph_config.batch_sizes or - ()) if self.llm_args.cuda_graph_config else (), + cuda_graph_batch_sizes=captured_cuda_graph_batch_sizes( + self.llm_args, self.max_num_tokens, self.spec_config), mm_encoder_only=self.llm_args.mm_encoder_only, disable_mm_encoder=self.llm_args.disable_mm_encoder, attn_backend=self.llm_args.attn_backend, diff --git a/tensorrt_llm/_torch/pyexecutor/perf_metrics_manager.py b/tensorrt_llm/_torch/pyexecutor/perf_metrics_manager.py index d129095b0045..e70523921304 100644 --- a/tensorrt_llm/_torch/pyexecutor/perf_metrics_manager.py +++ b/tensorrt_llm/_torch/pyexecutor/perf_metrics_manager.py @@ -26,10 +26,19 @@ class PerfMetricsManager: Args: enabled: Whether performance metrics collection is turned on (mirrors ``LlmArgs.return_perf_metrics``). + timing_side_stream: Record the timing events on a side stream that waits + for the current stream (``RuntimeHooks.perf_metrics_timing_side_stream``). """ - def __init__(self, enabled: bool): + _timing_stream: Optional[torch.cuda.Stream] = None + # Marks the current stream's position for the side stream to wait on; reused every record. + _fork_event: Optional[torch.cuda.Event] = None + + def __init__(self, enabled: bool, timing_side_stream: bool = False): self.enabled = enabled + if enabled and timing_side_stream: + self._timing_stream = torch.cuda.Stream() + self._fork_event = torch.cuda.Event() self._perf_events = None self._perf_event_idx = 0 self._forward_event_pool = [] @@ -99,7 +108,7 @@ def record_perf_events( # --- Pre-execution: record start --- if start_event is not None: - start_event.record() + self._record(start_event) if self.enabled: timing.start_time = get_steady_clock_now_in_seconds() @@ -107,10 +116,19 @@ def record_perf_events( # --- Post-execution: record end --- if end_event is not None: - end_event.record() + self._record(end_event) if self.enabled: timing.end_time = get_steady_clock_now_in_seconds() + def _record(self, event: torch.cuda.Event) -> None: + """Record ``event`` after the current stream's work, on the side stream when there is one.""" + if self._timing_stream is None or torch.cuda.is_current_stream_capturing(): + event.record() + return + self._fork_event.record() + self._timing_stream.wait_event(self._fork_event) + event.record(self._timing_stream) + # ------------------------------------------------------------------ # Saving / computing timing data # ------------------------------------------------------------------ @@ -119,16 +137,22 @@ def get_timestamp(self) -> Optional[float]: """Return a CPU timestamp if metrics are enabled, else ``None``.""" return get_steady_clock_now_in_seconds() if self.enabled else None - @staticmethod def try_compute_gpu_elapsed_time_ms( + self, start_event: Optional[torch.cuda.Event], end_event: Optional[torch.cuda.Event], ) -> Optional[float]: - """Return CUDA-event elapsed time if ready, without synchronizing.""" + """Return CUDA-event elapsed time if ready. + + Events on the current stream are not waited for. An event on the timing side stream is + ordered after nothing the caller synchronized with, so it is waited for. + """ if start_event is None or end_event is None: return None try: - if not end_event.query(): + if self._timing_stream is not None: + end_event.synchronize() + elif not end_event.query(): return None return float(start_event.elapsed_time(end_event)) except RuntimeError as e: diff --git a/tensorrt_llm/_torch/pyexecutor/py_executor.py b/tensorrt_llm/_torch/pyexecutor/py_executor.py index 3ffa4c901f60..14c9eba39a5e 100644 --- a/tensorrt_llm/_torch/pyexecutor/py_executor.py +++ b/tensorrt_llm/_torch/pyexecutor/py_executor.py @@ -91,6 +91,7 @@ from .cuda_graph_runner import ADPShapeAgreement from .disagg_adapter import PyExecutorEffects, PyExecutorRequestRegistry from .dwdp import DwdpManager +from .engine.model_setup import DYNAMO_RECOMPILE_LIMIT from .error_classification import ErrorBudget from .executor_request_queue import (PREFIX_LOAD_COMPLETION_REQUEST_ID, ExecutorRequestQueue, @@ -695,6 +696,8 @@ class _ExecutorExecutionConfig: enable_kv_pool_rebalance: bool # cache_transceiver_config.max_tokens_in_buffer was set by the user. transfer_budget_is_explicit: bool = False + # kv_cache_config.defer_generation_only_release. + defer_generation_only_release: bool = False class PyExecutor: @@ -707,6 +710,16 @@ class PyExecutor: # The model's executor events (RuntimeHooks.executor_events); read once at # construction. _executor_events: Optional[ExecutorEvents] = None + # Whether the waiting queue's wait cap needs rank 0's clock on every rank. + _waiting_queue_needs_clock = False + # Whether the ADP rank-state allgather carries rank 0's pending-request + # count for the busy-path fetch; set at construction. + _fetch_hint_enabled = False + # Whether the overlap loop defers the KV cache close of finished + # generation-only requests (kv_cache_config.defer_generation_only_release). + _defer_generation_only_release = False + # Whether the model forward runs under torch.compile; read once at construction. + _uses_torch_compile = False # Whether the KV cache manager is a KVCacheManagerV2; set at construction. _is_kv_manager_v2 = False # Shutdown publication is leader-only, while join/finalize runs on every rank. @@ -762,6 +775,7 @@ def __init__( enable_non_overlap_adp_forward_intent: bool = False, gen_preemption: Optional[GenPreemptionConfig] = None, transfer_budget_is_explicit: bool = False, + defer_generation_only_release: bool = False, ) -> None: if kv_pool_rebalance_check_interval <= 0: raise ValueError( @@ -839,6 +853,7 @@ def __init__( self._profile_manager = PyExecutorProfileManager(self) self.model_engine = model_engine + self._uses_torch_compile = model_engine.uses_torch_compile hooks = runtime_hooks_of(model_engine.model) self._execution_stream_loop_armed = hooks.loop_on_execution_stream self._executor_events = hooks.executor_events @@ -866,6 +881,7 @@ def __init__( hang_detection_timeout=hang_detection_timeout, enable_kv_pool_rebalance=enable_kv_pool_rebalance, transfer_budget_is_explicit=transfer_budget_is_explicit, + defer_generation_only_release=defer_generation_only_release, ) self._resources_released = False self._closed = False @@ -1020,8 +1036,12 @@ def _initialize_execution(self, resources: PyExecutorResources) -> None: self._late_compile_detect = False if model_hooks.mxfp8_pinned_tactics or model_hooks.late_compile_detect: self._late_compile_detect = _arm_runtime_opt_ins(model_hooks) + timing_side_stream = False + if model_hooks.perf_metrics_timing_side_stream: + timing_side_stream = True self.perf_manager = PerfMetricsManager( - enabled=getattr(self.llm_args, 'return_perf_metrics', False)) + enabled=self.llm_args.return_perf_metrics, + timing_side_stream=timing_side_stream) self.attention_dp_enable_balance = ( self.llm_args.attention_dp_config is not None and self.llm_args.attention_dp_config.enable_balance) @@ -1122,6 +1142,9 @@ def _initialize_execution(self, resources: PyExecutorResources) -> None: ResourceManagerType.DRAFT_KV_CACHE_MANAGER) self._is_kv_manager_v2 = isinstance(self.kv_cache_manager, KVCacheManagerV2) + self._defer_generation_only_release = ( + self._is_kv_manager_v2 + and self._execution_config.defer_generation_only_release) # The KV cache manager takes Mamba snapshots inside the forward and # finishes them on the execution stream right after it (_forward_step). self._finish_inforward_snapshots = ( @@ -1454,6 +1477,13 @@ def on_detected(): torch.cuda.Event) self._gen_admission = GenAdmissionConfig.from_env() + waiting_queue_max_wait_s = None + if waiting_queue_policy == WaitingQueuePolicy.PRIORITY: + waiting_queue_max_wait_s = ( + self.llm_args.scheduler_config.waiting_queue_max_wait_s) + # The wait cap ages requests by rank 0's arrival stamps on rank 0's + # clock, so that every rank pops the same order. + self._waiting_queue_needs_clock = waiting_queue_max_wait_s is not None # request fetcher initialization self._set_global_steady_clock_offset() @@ -1462,7 +1492,8 @@ def on_detected(): max_batch_size=max_batch_size, enable_iter_perf_stats=self.enable_iter_perf_stats, batch_wait_timeout_ms=self.batch_wait_timeout_ms, - stamp_admission_times=self._gen_admission.enabled, + stamp_admission_times=self._gen_admission.enabled + or self._waiting_queue_needs_clock, ) # When overlap scheduler is enabled then when starting to handle a new prompt, # _sample_async is called twice before the first call to update_requests: @@ -1487,7 +1518,8 @@ def on_detected(): self.request_broadcaster = RequestBroadcaster( self.dist, self.hang_detector, - sync_clock=self._gen_admission.needs_clock) + sync_clock=self._gen_admission.needs_clock + or self._waiting_queue_needs_clock) # With attention DP, the per-iteration rank-state allgather can carry # rank 0's pending-request count, letting the busy-path fetch skip the # request-count probe broadcast (one host collective per iteration) or @@ -1498,11 +1530,13 @@ def on_detected(): # rank 0's clock, so it must not be skipped. self._fetch_hint_enabled = (self.enable_attention_dp and self.dist.tp_size == self.dist.world_size - and not self._gen_admission.needs_clock) + and not self.request_broadcaster.sync_clock) # Waiting queue for requests that have been fetched but not yet scheduled self.waiting_queue: WaitingQueue = create_waiting_queue( - waiting_queue_policy, gen_admission=self._gen_admission) + waiting_queue_policy, + gen_admission=self._gen_admission, + max_wait_s=waiting_queue_max_wait_s) self._first_token_timer = None if self.dist.rank == 0 and isinstance(self.waiting_queue, GenAdmissionWaitingQueue): @@ -1959,7 +1993,8 @@ def _reject_non_gpu_cache_tiers(kv_cache_manager) -> None: "another tier have their GPU slot reassigned, which would " "invalidate the addresses registered with the connector. Set " "KvCacheConfig.host_cache_size=0 and " - "KvCacheConfig.disk_cache_size=0 to run GPU-only.") + "KvCacheConfig.disk_cache_size=0, and leave " + "remote_cache_config.level unset, to run GPU-only.") def _release_transfer(self, request: LlmRequest) -> None: """Release one transfer claim held by the KV connector or transceiver. @@ -2028,10 +2063,20 @@ def _flush_iter_stats_synced(self): # Performance metrics methods are in PerfMetricsManager (self.perf_manager) + def _apply_dynamo_recompile_limit(self) -> None: + """Apply the compiled model's Dynamo recompile limit on this thread. + + torch keeps each Dynamo config value per thread, so the limit set + while the engine was built does not reach the worker thread. + """ + if self._uses_torch_compile: + torch._dynamo.config.cache_size_limit = DYNAMO_RECOMPILE_LIMIT + def _event_loop_wrapper(self) -> None: crashed = False self._event_loop_completed = False try: + self._apply_dynamo_recompile_limit() # Skip line profiler during warmup/memory estimation phase to avoid # saving incomplete results that would be overwritten anyway enable_profiler = bool(os.environ.get( @@ -3789,9 +3834,14 @@ def _process_iter_stats( self._pending_num_completed_requests = 0 # Snapshot per-loop profiler timings plus the batch-matched GPU - # forward time. The FPM GPU value is read from CUDA events without - # synchronizing here; the normal sampler/update path has already - # established the required completion point for processed batches. + # forward time. Events on the current stream are only queried (not + # complete -> no value); every caller runs after _update_requests, + # whose sampler synchronize (TorchSampler) follows this forward on that + # stream. With the timing side stream (perf_metrics_timing_side_stream) + # try_compute_gpu_elapsed_time_ms synchronizes on the end event, which + # that stream records once this batch's forward has finished: the host + # can wait for that point (already passed after a sampler synchronize), + # never for later work. host_step_time_ms = self._latest_host_step_time_ms prev_device_step_time_ms = self._latest_prev_device_step_time_ms gpu_forward_time_ms = self.perf_manager.try_compute_gpu_elapsed_time_ms( @@ -7452,6 +7502,9 @@ def _rebalance_kv_pools_now(self) -> None: underneath whatever holds them. """ mgr = self.kv_cache_manager + if self._defer_generation_only_release: + # adjust() moves pages; a deferred close must not hold any. + mgr.flush_deferred_closes() paused: List[LlmRequest] = [] for req in self.active_requests: @@ -7705,6 +7758,12 @@ def _executor_loop_overlap(self) -> None: CUASSERT(cudart.cudaSetDevice(self.device_id)) if self._executor_events is not None: self._executor_events.before_overlap_loop() + # A finished generation-only request's KV cache close (a host-side page + # release) runs after the next forward is queued instead of before the + # next batch's preparation. + defer_kv_close = self._defer_generation_only_release + if defer_kv_close: + self.kv_cache_manager.enable_deferred_close(True) with self._overlap_loop_stream_scope(), self._profiler() as profile_step, \ self.hang_detector: iter_start_time = time.time() @@ -7769,6 +7828,9 @@ def _executor_loop_overlap(self) -> None: self._pause_recompute_paused_requests(scheduled_batch) self._finalize_adp_dummy_allocation(False) self._flush_pending_transfer_responses() + if defer_kv_close: + # The flush after the forward is skipped this round. + self.kv_cache_manager.flush_deferred_closes() continue if (self._mm_encoder_item_scheduling_enabled @@ -7905,6 +7967,10 @@ def _executor_loop_overlap(self) -> None: self._maybe_prefetch_next_iter_mm_encoders( scheduled_batch) + if defer_kv_close: + # Closes left by the previous iteration's terminations. + self.kv_cache_manager.flush_deferred_closes() + if self.previous_batch is not None and should_process_previous_batch: self._update_requests(self.previous_batch.sample_state) # Turning off speculative decoding when Acceptance Rate is low. @@ -8013,6 +8079,11 @@ def _executor_loop_overlap(self) -> None: else: self._enqueue_responses([]) + if defer_kv_close and not self.active_requests: + # Idle: no next forward to overlap with, so close now and + # let the KV cache events below publish it. + self.kv_cache_manager.flush_deferred_closes() + # KV-cache event flushing performs an attention-DP allgather. # Keep it outside the rank-divergent previous-batch branch so # every rank enters the collective in the same order. @@ -8070,6 +8141,11 @@ def _executor_loop_overlap(self) -> None: if not self.enable_attention_dp: self._kv_connector_terminate_requests() + if defer_kv_close and not self.active_requests: + # Requests terminated since the flush above: do not hold + # their pages while the next fetch may block. + self.kv_cache_manager.flush_deferred_closes() + if not can_queue: self.disagg.pace_idle() @@ -8658,6 +8734,8 @@ def _fetch_and_enqueue_requests( self.request_broadcaster.rank0_aux) else: waiting_queue.set_now(time.monotonic()) + elif self._waiting_queue_needs_clock: + waiting_queue.set_now(self.request_broadcaster.rank0_now) # Validate and filter requests new_requests = self._handle_special_queue_items(new_requests) @@ -8814,15 +8892,21 @@ def _pop_from_waiting_queue( max_new_requests, self.max_num_active_requests, kv_balance=kv_balance) + mm_admission = getattr(self, "_mm_encoder_item_scheduling_enabled", + False) new_requests = get_from_waiting_queue( waiting_queue, max_new_requests, enable_attention_dp=False, - max_num_active_requests=self.max_num_active_requests) - if (not new_requests or not getattr( - self, "_mm_encoder_item_scheduling_enabled", False)): + max_num_active_requests=self.max_num_active_requests, + mark_admitted=not mm_admission) + if not mm_admission: return new_requests, {} - return self._apply_mm_encoder_admission(waiting_queue, new_requests), {} + # Deferred requests go back with their arrival order, so only the rest are admitted. + admitted = (self._apply_mm_encoder_admission( + waiting_queue, new_requests) if new_requests else []) + waiting_queue.mark_admitted(admitted) + return admitted, {} @nvtx_range("_fetch_new_requests") def _fetch_new_requests( @@ -9615,6 +9699,12 @@ def _schedule(self): ] scheduler_output = self.scheduler.schedule_request( scheduling_requests, self.inflight_req_ids) + # Requests whose KV pages a failed remote cache level took with it, unable to recompute them here; a + # wrapping scheduler (e.g. MultimodalScheduler) forwards them from the scheduler it wraps. + for request, error_msg in self.scheduler.take_lost_kv_requests(): + self._handle_errors(error_msg, + requests=[request], + charge_budget=False) scheduled_encoder_requests = self._encoder_requests_in_arrival_order( scheduler_output.encoder_requests) diff --git a/tensorrt_llm/_torch/pyexecutor/py_executor_creator.py b/tensorrt_llm/_torch/pyexecutor/py_executor_creator.py index cfa7fee3617b..a44e8d7d712c 100644 --- a/tensorrt_llm/_torch/pyexecutor/py_executor_creator.py +++ b/tensorrt_llm/_torch/pyexecutor/py_executor_creator.py @@ -1395,56 +1395,65 @@ def allocation_scope(current_stage: ExecutorMemoryType): model_engine.set_warmup_purpose( "memory_profiling" if estimating_kv_cache else "final_executor") - with allocation_scope( - ExecutorMemoryType.INIT_EXTRA_RESOURCES - if estimating_kv_cache else ExecutorMemoryType.EXTRA_RESOURCES): - # Reclaim unreachable allocations before warmup. - gc.collect() - py_executor = create_py_executor_instance( - dist=dist, - resources=resources, - mapping=mapping, - llm_args=llm_args, - ctx_chunk_config=_branch_snapshot_ctx_chunk_config( - ctx_chunk_config, - resources.get(ResourceManagerType.KV_CACHE_MANAGER), - tokens_per_block, scheduler_config.context_chunking_policy), - model_engine=model_engine, - start_worker=False, - sampler=sampler, - drafter=drafter, - guided_decoder=guided_decoder, - capturable_guided_decoder=capturable_guided_decoder, - lora_config=lora_config, - garbage_collection_gen0_threshold=garbage_collection_gen0_threshold, - kv_connector_manager=kv_connector_manager - if not estimating_kv_cache else None, - resource_governor_queue=resource_governor_queue, - max_seq_len=net_max_seq_len, - max_batch_size=max_batch_size, - max_beam_width=max_beam_width, - max_num_tokens=max_num_tokens, - peft_cache_config=peft_cache_config, - scheduler_config=scheduler_config, - cache_transceiver_config=cache_transceiver_config, - transfer_budget_is_explicit=transfer_budget_is_explicit, - virtual_memory_pools=vm_pools if not estimating_kv_cache else None, - execution_stream=execution_stream, - # Without the KV-cache estimation the executor serves from its - # construction: it gets the DWDP manager or the standalone dense - # DWDP manager now, primes it and exits it at shutdown. With the - # estimation only the serving phase gets it (rebind_resources - # below), since release_resources() exits the managers the - # executor holds. - dwdp_manager=dwdp_manager if not estimating_kv_cache else None, - dense_dwdp_manager=dense_dwdp_manager - if not estimating_kv_cache else None, - max_num_sequences=max_num_seq_slots, - ) + try: + with allocation_scope( + ExecutorMemoryType.INIT_EXTRA_RESOURCES + if estimating_kv_cache else ExecutorMemoryType.EXTRA_RESOURCES): + # Reclaim unreachable allocations before warmup. + gc.collect() + py_executor = create_py_executor_instance( + dist=dist, + resources=resources, + mapping=mapping, + llm_args=llm_args, + ctx_chunk_config=_branch_snapshot_ctx_chunk_config( + ctx_chunk_config, + resources.get(ResourceManagerType.KV_CACHE_MANAGER), + tokens_per_block, scheduler_config.context_chunking_policy), + model_engine=model_engine, + start_worker=False, + sampler=sampler, + drafter=drafter, + guided_decoder=guided_decoder, + capturable_guided_decoder=capturable_guided_decoder, + lora_config=lora_config, + garbage_collection_gen0_threshold= + garbage_collection_gen0_threshold, + kv_connector_manager=kv_connector_manager + if not estimating_kv_cache else None, + resource_governor_queue=resource_governor_queue, + max_seq_len=net_max_seq_len, + max_batch_size=max_batch_size, + max_beam_width=max_beam_width, + max_num_tokens=max_num_tokens, + peft_cache_config=peft_cache_config, + scheduler_config=scheduler_config, + cache_transceiver_config=cache_transceiver_config, + transfer_budget_is_explicit=transfer_budget_is_explicit, + virtual_memory_pools=vm_pools + if not estimating_kv_cache else None, + execution_stream=execution_stream, + # Without the KV-cache estimation the executor serves from its + # construction: it gets the DWDP manager or the standalone dense + # DWDP manager now, primes it and exits it at shutdown. With the + # estimation only the serving phase gets it (rebind_resources + # below), since release_resources() exits the managers the + # executor holds. + dwdp_manager=dwdp_manager if not estimating_kv_cache else None, + dense_dwdp_manager=dense_dwdp_manager + if not estimating_kv_cache else None, + max_num_sequences=max_num_seq_slots, + ) - # Originally, peft_cache_config might be mutated inside - # create_py_executor_instance. Restore it here. - peft_cache_config = py_executor.peft_cache_config + # Originally, peft_cache_config might be mutated inside + # create_py_executor_instance. Restore it here. + peft_cache_config = py_executor.peft_cache_config + except BaseException as error: + # A failed warmup or capture leaves the donation with no owner that + # would withdraw it before exit. + if kv_cache_creator is not None: + kv_cache_creator.close_remote_donor(error) + raise if estimating_kv_cache: try: @@ -1501,7 +1510,9 @@ def allocation_scope(current_stage: ExecutorMemoryType): max_num_sequences=max_num_seq_slots, ) py_executor.rebind_resources(execution_resources) - except BaseException: + except BaseException as error: + # Also past the final build, whose target manager's shutdown would withdraw the donation unmarked. + kv_cache_creator.close_remote_donor(error) py_executor.shutdown() raise diff --git a/tensorrt_llm/_torch/pyexecutor/request_utils.py b/tensorrt_llm/_torch/pyexecutor/request_utils.py index 5c98f67092d2..70ad71b9ab6d 100644 --- a/tensorrt_llm/_torch/pyexecutor/request_utils.py +++ b/tensorrt_llm/_torch/pyexecutor/request_utils.py @@ -97,6 +97,7 @@ def get_from_waiting_queue( enable_attention_dp: bool, max_num_active_requests: int, all_ranks_num_active_requests: Optional[list[int]] = None, + mark_admitted: bool = True, ) -> list["RequestQueueItem"]: """Get requests from the waiting queue. @@ -106,6 +107,8 @@ def get_from_waiting_queue( enable_attention_dp: Whether to enable attention DP scheduling. max_num_active_requests: Maximum number of active requests per rank. all_ranks_num_active_requests: Number of active requests for each rank. + mark_admitted: Report the returned requests to ``WaitingQueue.mark_admitted``; + False when the caller may still put some of them back. Returns: List of requests that can be processed. @@ -146,7 +149,8 @@ def get_from_waiting_queue( # Put the pending requests back to the waiting queue # All ranks should have the same waiting queue waiting_queue.prepend_requests(pending_requests) - waiting_queue.mark_admitted(items) + if mark_admitted: + waiting_queue.mark_admitted(items) return items @@ -340,8 +344,9 @@ def __init__( self.hang_detector = hang_detector self.send_requests_handler = None # sync_clock: rank 0's time.monotonic() and ``aux`` (>= 0) ride along - # with the request count, read on every rank as ``rank0_now`` and - # ``rank0_aux``. Must be the same on all ranks: it changes the length. + # with the request count (or in the single-round header), read on + # every rank as ``rank0_now`` and ``rank0_aux``. Must be the same on + # all ranks: it changes the length. self.sync_clock = sync_clock self.rank0_now: Optional[float] = None self.aux: Optional[float] = None @@ -396,13 +401,12 @@ def _single_round(self, prefer_cpu: bool) -> bool: Rank-consistent: ``prefer_cpu`` is so by the caller's contract, the rest is static topology / transport state shared by every rank. The - PP route keeps its probe + send/recv chain, the idle path - (``prefer_cpu``) keeps the CPU-transport probe as its wake mechanism, - and ``sync_clock`` keeps the probe that carries rank 0's clock. + PP route keeps its probe + send/recv chain and the idle path + (``prefer_cpu``) keeps the CPU-transport probe as its wake mechanism. + ``sync_clock`` rides in the envelope (``_broadcast_single_round``). """ return ( not prefer_cpu - and not self.sync_clock and self.dist.world_size > 1 and not self.dist.has_pp and bool(getattr(self.dist, "supports_single_round_broadcast", False)) @@ -421,12 +425,31 @@ def _broadcast_single_round( one call ahead of the slowest peer, no further); non-root ranks wait here for rank 0 exactly as they did in the probe. The hang-detector pause covers both the non-root wait and the root's bounded fence. + + With ``sync_clock`` rank 0's clock and aux ride in a fixed-size header + next to the size word (``broadcast_or_none_with_header``), so the + collective counts stay one (empty) and two (requests). """ payloads = None - if self.dist.rank == 0 and new_requests: + is_root = self.dist.rank == 0 + if is_root and new_requests: payloads = new_requests - with self.hang_detector.pause(): - received = self.dist.broadcast_or_none(payloads, root=0) + if self.sync_clock: + # Same microsecond encoding as the probe (_broadcast_request_count), so the clock never steps back + # when consecutive iterations take different routes. + header = [0, -1] + if is_root: + aux_us = int(self.aux * 1e6) if self.aux is not None else -1 + header = [int(time.monotonic() * 1e6), aux_us] + with self.hang_detector.pause(): + (now_us, aux_us), received = self.dist.broadcast_or_none_with_header( + payloads, header, root=0 + ) + self.rank0_now = now_us / 1e6 + self.rank0_aux = None if aux_us < 0 else aux_us / 1e6 + else: + with self.hang_detector.pause(): + received = self.dist.broadcast_or_none(payloads, root=0) if received is None: return [] if self.dist.rank == 0: diff --git a/tensorrt_llm/_torch/pyexecutor/runtime_hooks.py b/tensorrt_llm/_torch/pyexecutor/runtime_hooks.py index 613a8d8f9353..af9ea94f979e 100644 --- a/tensorrt_llm/_torch/pyexecutor/runtime_hooks.py +++ b/tensorrt_llm/_torch/pyexecutor/runtime_hooks.py @@ -237,8 +237,8 @@ class RuntimeHooks: # one-model speculative batches (the argmax path never reads them). skip_greedy_rng_upload: bool = False # Stage the one-model speculative sampler's per-step Philox seed and offset - # uploads into the step-input pack (pack_step_inputs), so they ride its one - # upload instead of each being a copy the next graph waits for. + # uploads into the step-input pack (pack_step_inputs), or into the steady MTP + # stager's slab on the steps it prepares, instead of four separate copies. pack_spec_rng_uploads: bool = False # The one-model speculative step's small per-step uploads: the accepted-draft # counts join the step-input pack, and the spec sampler keeps its slot ids in @@ -253,6 +253,9 @@ class RuntimeHooks: # stream that waits for the current stream, instead of an end and a start event back to back on the # current stream (the same instant, with no GPU work between them). The reported step times are unchanged. iteration_timing_one_event: bool = False + # Record the per-request perf-metrics timing events (return_perf_metrics) on a side stream that waits for + # the current stream, so a timing record does not cost the current stream. The elapsed times are unchanged. + perf_metrics_timing_side_stream: bool = False # MiniMax-M3 MSA metadata preparation. msa: MsaRuntimePolicy = MsaRuntimePolicy() diff --git a/tensorrt_llm/_torch/pyexecutor/scheduler/__init__.py b/tensorrt_llm/_torch/pyexecutor/scheduler/__init__.py index ef2927d24713..dbda57414f7c 100644 --- a/tensorrt_llm/_torch/pyexecutor/scheduler/__init__.py +++ b/tensorrt_llm/_torch/pyexecutor/scheduler/__init__.py @@ -43,6 +43,7 @@ # Re-export from waiting_queue.py from .waiting_queue import ( + AgingPriorityWaitingQueue, FCFSWaitingQueue, PriorityWaitingQueue, WaitingQueue, @@ -73,6 +74,7 @@ "KVCacheAwareADPRouter", "RankState", # Waiting queues + "AgingPriorityWaitingQueue", "FCFSWaitingQueue", "PriorityWaitingQueue", "WaitingQueue", diff --git a/tensorrt_llm/_torch/pyexecutor/scheduler/adp_router.py b/tensorrt_llm/_torch/pyexecutor/scheduler/adp_router.py index 78ee32a96e85..d40101be6080 100644 --- a/tensorrt_llm/_torch/pyexecutor/scheduler/adp_router.py +++ b/tensorrt_llm/_torch/pyexecutor/scheduler/adp_router.py @@ -40,13 +40,14 @@ import random from abc import ABC, abstractmethod from collections import OrderedDict, namedtuple -from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple +from types import MappingProxyType +from typing import TYPE_CHECKING, Dict, List, Mapping, Optional, Set, Tuple from tensorrt_llm.bindings.executor import RequestType from tensorrt_llm.logger import logger from ..llm_request import LlmRequestState -from ..request_utils import get_from_waiting_queue +from ..request_utils import can_process_attention_dp_request, get_from_waiting_queue from .rank_state import RankIterStatsPayload, RankState if TYPE_CHECKING: @@ -275,6 +276,7 @@ def create( max_sessions=attention_dp_config.kv_cache_routing_max_sessions, fair_share_multiplier=attention_dp_config.kv_cache_routing_fair_share_multiplier, new_conv_placement=attention_dp_config.kv_cache_routing_new_conv_placement, + home_wait_rounds=attention_dp_config.kv_cache_routing_home_wait_rounds, ) if ( @@ -1148,6 +1150,19 @@ class ConversationAwareADPRouter(ADPRouter): # Default LRU cap on the conversation->rank map (entries are ~tens of # bytes each). Bounds memory on long-running servers as conversations churn. DEFAULT_MAX_SESSIONS = 1 << 16 + # Rounds a returning conversation may wait for its home rank (kv_cache_routing_home_wait_rounds). + _home_wait_rounds: Optional[int] = None + # Home-wait state; __init__ gives each instance its own (see there). + _home_wait_age: Dict[int, int] | Mapping[int, int] = MappingProxyType({}) + # Request id -> home ranks of requests the last pop_requests round held for an earlier admission group: an + # unplanned request may not take them in route_requests either. + _route_avoid: Dict[int, frozenset] | Mapping[int, frozenset] = MappingProxyType({}) + # The first window one home-wait round peeks; it doubles while no request in it stopped the round. + HOME_WAIT_WINDOW = 256 + # Requests one home-wait round may hold for their home rank before it stops: bounds the round's work by this plus + # its admission budget, however deep the queue of held requests. Unbound requests without room are set aside + # uncounted, as by the base pop. + HOME_WAIT_MAX_PASSED = 256 def __init__( self, @@ -1156,9 +1171,15 @@ def __init__( max_sessions: int = DEFAULT_MAX_SESSIONS, fair_share_multiplier: float = 2.0, new_conv_placement: str = "round_robin", + home_wait_rounds: Optional[int] = None, ): super().__init__(dist, has_seq_slot_headroom=has_seq_slot_headroom) self._conv_to_rank: "OrderedDict[str, int]" = OrderedDict() + # Home-wait admission (see pop_requests); None: overflow at once. + self._home_wait_rounds = home_wait_rounds + # Request id -> rounds it was held for its home rank while another rank had room, for the requests in the + # last round's window. + self._home_wait_age = {} # Uncached-prefill estimate for the V2 scheduler's long-prefill # demotion: within a conversation the prompt only grows and the rank # that served the previous turn caches its prompt, so on that rank @@ -1245,6 +1266,163 @@ def _publish_uncached_estimate( while len(self._conv_last_prompt) > self._max_sessions: self._conv_last_prompt.popitem(last=False) + def pop_requests( + self, + waiting_queue: "WaitingQueue", + all_rank_states: list[RankState], + max_new_requests: int, + max_num_active_requests: int, + kv_balance: bool = True, + ) -> Tuple[List["RequestQueueItem"], Dict[int, int]]: + """Pop the requests to admit and, under home-wait, plan their home ranks (request id -> rank). + + Home-wait admits a returning conversation only to its home rank until it was held ``home_wait_rounds`` + rounds while another rank had a free slot; then it is admitted unplanned and overflows in ``route_requests``. + Other requests are admitted as without home-wait. Later requests of a held request's admission group + may pass it; a later group may too, except into its home rank, so that each rank still admits in group + (priority) order. Held requests stay in order. A round holds at most ``HOME_WAIT_MAX_PASSED`` requests. + A request no single rank can take (1 + children > ``max_num_active_requests``) is never held, and with + ``kv_balance`` False (warmup, benchmark fill phase) the base FIFO pop runs. + """ + self._route_avoid = {} + if ( + self._home_wait_rounds is None + or not kv_balance + or max_new_requests <= 0 + or len(all_rank_states) <= 1 + ): + return super().pop_requests( + waiting_queue, + all_rank_states, + max_new_requests, + max_num_active_requests, + kv_balance=kv_balance, + ) + tp_size = len(all_rank_states) + num_active = [0] * tp_size + for state in all_rank_states: + num_active[state.rank] = state.num_active_requests + ages = self._home_wait_age + budget = max_new_requests + chosen_idx: List[int] = [] + placement: Dict[int, int] = {} + # Admission group of the request last examined, and the home ranks of the requests held in it. + group = None + held_homes: set = set() + # Home ranks of requests held in earlier groups, and what unplanned admissions must avoid in route_requests. + blocked: set = set() + avoid: Dict[int, frozenset] = {} + passed = 0 + window: List["RequestQueueItem"] = [] + size = self.HOME_WAIT_WINDOW + idx = 0 + while True: + # Look further only while every request so far was held or admitted and a rank has room. + window = waiting_queue.peek_requests(size) + groups = waiting_queue.admission_groups(window) + stopped = False + while idx < len(window): + item = window[idx] + if groups[idx] != group: + # A group finishes before the next one on each rank (WaitingQueue.admission_groups): a rank a + # held request waits for takes no planned request of a later group. + group = groups[idx] + if held_homes: + for rank in held_homes: + num_active[rank] = max(num_active[rank], max_num_active_requests) + blocked |= held_homes + held_homes.clear() + if all(n >= max_num_active_requests for n in num_active): + stopped = True + break + need = 1 + (len(item.child_req_ids) if item.child_req_ids else 0) + if need > budget or passed >= self.HOME_WAIT_MAX_PASSED: + stopped = True + break + conv_id = self._conversation_id(item) + home = None if conv_id is None else self._conv_to_rank.get(conv_id) + if home is None: + # Not bound: admitted as without home-wait (an explicit strict rank needs room; without it, set + # aside as by the base pop). + if can_process_attention_dp_request(item, num_active, max_num_active_requests): + budget -= need + chosen_idx.append(idx) + if blocked: + avoid[item.id] = frozenset(blocked) + elif num_active[home] + need <= max_num_active_requests: + num_active[home] += need + budget -= need + placement[item.id] = home + chosen_idx.append(idx) + else: + # Room as route_requests overflows a request: one slot on another rank, whatever its children. + other_room = any( + num_active[r] < max_num_active_requests for r in range(tp_size) if r != home + ) + # A request that no rank can take whole (1 + children over the per-rank cap) is never planned: + # its home would never have room, so it is admitted unplanned at once, as without home-wait. + if need > max_num_active_requests or ( + other_room and ages.get(item.id, 0) >= self._home_wait_rounds + ): + budget -= need + chosen_idx.append(idx) + if blocked: + avoid[item.id] = frozenset(blocked) + else: + if other_room: + ages[item.id] = ages.get(item.id, 0) + 1 + held_homes.add(home) + passed += 1 + idx += 1 + if stopped or len(window) < size or budget <= 0: + break + if all(n >= max_num_active_requests for n in num_active): + break + size *= 2 + # Keep the ages of requests still in the window; a request admitted, cancelled or pushed out of the window + # loses its age. + chosen_ids = {window[i].id for i in chosen_idx} + self._home_wait_age = { + item.id: ages[item.id] + for item in window + if item.id in ages and item.id not in chosen_ids + } + if not chosen_idx: + return [], {} + self._route_avoid = avoid + chosen = [window[i] for i in chosen_idx] + popped = [waiting_queue.pop_request() for _ in range(chosen_idx[-1] + 1)] + waiting_queue.prepend_requests(item for item in popped if item.id not in chosen_ids) + waiting_queue.mark_admitted(chosen) + return chosen, placement + + def _pick_rank(self, num_active: List[int], token_load: List[int], soft_cap: int) -> int: + """``new_conv_placement`` over all ranks, preferring ranks under ``soft_cap``. + + ``token_load`` is read only by ``least_tokens``. + """ + tp_size = len(num_active) + preferred = [r for r in range(tp_size) if num_active[r] < soft_cap] + cands = preferred or list(range(tp_size)) + if self._new_conv_placement == "least_tokens": + rank = min( + cands, + key=lambda r: ( + token_load[r], + num_active[r], + (r - self._round_robin_cursor) % tp_size, + ), + ) + self._round_robin_cursor = (rank + 1) % tp_size + return rank + if self._new_conv_placement == "round_robin": + for _ in range(tp_size): + r = self._round_robin_cursor % tp_size + self._round_robin_cursor = (self._round_robin_cursor + 1) % tp_size + if r in preferred: + return r + return min(cands, key=lambda r: (num_active[r], r)) + def _assign_new_conversation_explicit_dp_ranks( self, requests: List["RequestQueueItem"], @@ -1272,6 +1450,7 @@ def _assign_new_conversation_explicit_dp_ranks( if ( target_dp_rank is not None and all_ranks_num_active_requests[target_dp_rank] < max_num_active_requests + and target_dp_rank not in self._route_avoid.get(req_item.id, ()) ): all_ranks_num_active_requests[target_dp_rank] += 1 self._publish_uncached_estimate(req_item, target_dp_rank, None) @@ -1289,20 +1468,31 @@ def route_requests( max_num_active_requests: int, placement: Optional[Dict[int, int]] = None, ) -> Tuple[Dict[int, List[RequestQueueItem]], int]: - # placement is unused: this router's pop_requests plans no ranks. tp_size = len(all_rank_states) all_ranks_new_requests: Dict[int, List[RequestQueueItem]] = { s.rank: [] for s in all_rank_states } all_ranks_num_active_requests = [s.num_active_requests for s in all_rank_states] + # 0) Requests pop_requests planned (home-wait admission) go to their conversation's home rank. + unplanned = [] + for req_item in new_requests: + rank = None if placement is None else placement.get(req_item.id) + if rank is None: + unplanned.append(req_item) + continue + self._record_target_rank(self._conversation_id(req_item), rank) # LRU touch + self._publish_uncached_estimate(req_item, rank, rank) + all_ranks_new_requests[rank].append(req_item) + all_ranks_num_active_requests[rank] += 1 + def get_relax_value(req_item): scheduling_params = getattr(req_item.request, "py_scheduling_params", None) if scheduling_params is None: return True return scheduling_params.attention_dp_relax - sorted_requests = sorted(new_requests, key=get_relax_value) + sorted_requests = sorted(unplanned, key=get_relax_value) # 1) Honour an explicit attention_dp_rank for a new conversation and # record that placement. Existing conversations keep their binding. @@ -1335,40 +1525,12 @@ def get_relax_value(req_item): hard_cap=max_num_active_requests, ) - def _least_loaded(soft_cap: int) -> int: - """Lowest-active rank under soft_cap (deterministic), else global min.""" - cands = [r for r in range(tp_size) if all_ranks_num_active_requests[r] < soft_cap] - if not cands: - cands = list(range(tp_size)) - return min(cands, key=lambda r: (all_ranks_num_active_requests[r], r)) - - def _next_rr(soft_cap: int) -> int: - """Round-robin to the next rank under soft_cap; advance the cursor.""" - for _ in range(tp_size): - r = self._round_robin_cursor % tp_size - self._round_robin_cursor = (self._round_robin_cursor + 1) % tp_size - if all_ranks_num_active_requests[r] < soft_cap: - return r - return _least_loaded(soft_cap) - - def _least_active_tokens(soft_cap: int) -> int: - """Shared active prompt load plus this call's admissions.""" - cands = [r for r in range(tp_size) if all_ranks_num_active_requests[r] < soft_cap] - rank = min( - cands or range(tp_size), - key=lambda r: ( - token_load[r], - all_ranks_num_active_requests[r], - (r - self._round_robin_cursor) % tp_size, - ), - ) - self._round_robin_cursor = (rank + 1) % tp_size - return rank - for req_item in remaining_unscheduled: conv_id = self._conversation_id(req_item) rank = None home_rank = None if conv_id is None else self._conv_to_rank.get(conv_id) + # Ranks held for a request of an earlier admission group count as full (pop_requests). + avoid = self._route_avoid.get(req_item.id, ()) if conv_id is not None and conv_id in self._conv_to_rank: target_rank = self._conv_to_rank[conv_id] @@ -1377,7 +1539,10 @@ def _least_active_tokens(soft_cap: int) -> int: # soft fair-share `expected`. Stickiness wins over balance so a # conversation's KV prefix stays resident on one rank instead of # migrating when the rank gets moderately busy. - if all_ranks_num_active_requests[target_rank] < max_num_active_requests: + if ( + all_ranks_num_active_requests[target_rank] < max_num_active_requests + and target_rank not in avoid + ): rank = target_rank self._record_target_rank(conv_id, target_rank) # LRU touch # else: target saturated this batch -> fall through to overflow @@ -1387,12 +1552,13 @@ def _least_active_tokens(soft_cap: int) -> int: # First turn of a new conversation, sticky-overflow, or no # conversation_id -> spread under the soft cap using the # configured count- or token-based placement strategy. - if self._new_conv_placement == "least_tokens": - rank = _least_active_tokens(expected_num_active_requests) - elif self._new_conv_placement == "least_queued": - rank = _least_loaded(expected_num_active_requests) - else: - rank = _next_rr(expected_num_active_requests) + counts = all_ranks_num_active_requests + if avoid: + counts = [ + max(n, max_num_active_requests) if r in avoid else n + for r, n in enumerate(counts) + ] + rank = self._pick_rank(counts, token_load, expected_num_active_requests) if conv_id is not None and conv_id not in self._conv_to_rank: # Bind this new conversation to its first-turn rank. self._record_target_rank(conv_id, rank) diff --git a/tensorrt_llm/_torch/pyexecutor/scheduler/scheduler.py b/tensorrt_llm/_torch/pyexecutor/scheduler/scheduler.py index e64b3135a314..3083c0907a79 100644 --- a/tensorrt_llm/_torch/pyexecutor/scheduler/scheduler.py +++ b/tensorrt_llm/_torch/pyexecutor/scheduler/scheduler.py @@ -377,6 +377,15 @@ def release_context_admission(self, request: LlmRequest) -> None: to release; the default is a no-op. """ + def take_lost_kv_requests(self) -> list[tuple[LlmRequest, str]]: + """Requests whose KV pages a failed remote cache level took, which the + executor must fail, with their error messages. + + Only the KV cache manager V2 scheduler loses pages this way; the + default has none. + """ + return [] + def set_disagg_transfer_admission_controller(self, controller) -> None: """Register the executor's disaggregated KV-transfer window (DisaggTransferAdmissionController), when it bounds admission. @@ -750,6 +759,9 @@ def scheduling_state_range(self) -> tuple[LlmRequestState, LlmRequestState]: def set_disagg_transfer_admission_controller(self, controller) -> None: self.scheduler.set_disagg_transfer_admission_controller(controller) + def take_lost_kv_requests(self) -> list[tuple[LlmRequest, str]]: + return self.scheduler.take_lost_kv_requests() + def set_retiring_gen_receives_probe(self, probe: Callable[[], bool]) -> None: """Forward the local retirement probe to the wrapped scheduler. diff --git a/tensorrt_llm/_torch/pyexecutor/scheduler/scheduler_v2.py b/tensorrt_llm/_torch/pyexecutor/scheduler/scheduler_v2.py index 3799a967c389..7d75d2443996 100644 --- a/tensorrt_llm/_torch/pyexecutor/scheduler/scheduler_v2.py +++ b/tensorrt_llm/_torch/pyexecutor/scheduler/scheduler_v2.py @@ -24,6 +24,7 @@ ContextSchedulingPolicy, ) from tensorrt_llm.logger import logger +from tensorrt_llm.runtime.kv_cache_manager_v2 import RemoteMemError from ...disaggregation import diagnostics as disagg_diagnostics from ..llm_request import ( @@ -171,6 +172,15 @@ class KVCacheV2Scheduler(RequestScheduler): assignment into one unified loop. """ + # The RemoteMemError a resume raised because the request's KV pages were on a remote cache level that failed: set + # by _try_allocate_generation and by the context and disagg generation-init admissions, consumed by + # _on_lost_kv_cache. + _lost_kv_error: Optional[RemoteMemError] = None + # (request, error message) of requests that lost KV pages and cannot recompute them; take_lost_kv_requests. + _lost_kv_requests: tuple = () + # Managers whose remote cache level failing stops this rank (recover_lost_kv_per_rank=False); empty otherwise. + _lockstep_remote_managers: tuple = () + def __init__( self, max_batch_size: int, @@ -188,7 +198,11 @@ def __init__( enable_recompute_pause: bool = True, context_scheduling_policy: ContextSchedulingPolicy = ContextSchedulingPolicy.FCFS, context_starvation_iterations: Optional[int] = None, + recover_lost_kv_per_rank: bool = True, ) -> None: + """``recover_lost_kv_per_rank`` False is for ranks that schedule in lock step (TP without attention DP, CP, + PP): a failed remote cache level then raises RemoteMemError out of ``schedule_request`` instead of re-matching, + recomputing or failing the affected requests on this rank alone, which would desynchronize the group.""" self.remote_tail_phase: RemoteTailPhase | None = None self._remote_tail_context_ids: frozenset[int] = frozenset() self._remote_tail_generation_ids: frozenset[int] = frozenset() @@ -213,6 +227,13 @@ def __init__( self.cross_kv_cache_manager = cross_kv_cache_manager self.enable_prefix_aware_scheduling = enable_prefix_aware_scheduling self.enable_recompute_pause = enable_recompute_pause + self.recover_lost_kv_per_rank = recover_lost_kv_per_rank + if not recover_lost_kv_per_rank: + self._lockstep_remote_managers = tuple( + manager + for manager in (kv_cache_manager, draft_kv_cache_manager, cross_kv_cache_manager) + if manager is not None and manager.has_remote_cache_level + ) # Every input to the prefix-aware skip is fixed for this scheduler's # lifetime: the knob is a constructor argument, and both manager # attributes are assigned once in ``KVCacheManagerV2.__init__``. Resolve @@ -427,6 +448,9 @@ def schedule_request( ) -> SchedulerOutput: self._sched_iter += 1 self._reuse_probes.clear() + # A level that failed since the last pass (e.g. in an eviction WRITE during prepare_resources) has already + # dropped pages from this rank's reuse tree only. + self._raise_if_lockstep_remote_level_failed() active_requests = drop_decoder_context_requests_waiting_for_encoder_output(active_requests) # Main scheduling loop ( @@ -438,6 +462,8 @@ def schedule_request( disagg_candidates, has_chunking, ) = self._schedule_loop(active_requests, inflight_request_ids) + # One that failed in this pass, e.g. in an eviction WRITE that the C++ retried past it, before the batch runs. + self._raise_if_lockstep_remote_level_failed() # Sort by LoRA task ID scheduled_encoder.sort(key=_get_lora_task_id) @@ -919,9 +945,14 @@ def preempt_for_pages(req: LlmRequest) -> bool: scheduled_encoder.append(req) budget.commit(req, tokens, peft_pages) else: - action, tokens, chunking_flag = self._try_schedule_context( - req, budget, preempt_for_pages, token_cap - ) + try: + action, tokens, chunking_flag = self._try_schedule_context( + req, budget, preempt_for_pages, token_cap + ) + except RemoteMemError as error: + # Raised by its cache's resume, before anything was taken for it. + self._lost_kv_error = error + action = self._on_lost_kv_cache(req, inflight_request_ids, recompute_paused) if action is ScheduleAction.STOP: ctx_stopped = True break @@ -1317,7 +1348,13 @@ def _try_schedule_disagg_gen_init( # under disagg keep their layers in that manager (MTP/Eagle fold them # in; DFlash uses explicit draft layer specs). A separate draft manager # gets no transfer and no paired-reuse path here. - prepared = self.kv_cache_manager.prepare_disagg_gen_init(req) + try: + prepared = self.kv_cache_manager.prepare_disagg_gen_init(req) + except RemoteMemError as error: + # Its prefix match resumed pages a failed remote cache level took with it: drop the match, and the next + # pass matches again without them. + self._lost_kv_error = error + return self._on_lost_kv_cache(req, set(), []), 0 if not prepared: if disagg_diagnostics.DISAGG_TRANSFER_DIAGNOSTICS_ENABLED: disagg_diagnostics.emit_kv_admission_result( @@ -2117,25 +2154,40 @@ def _try_schedule_generation( elif scheduled_beam_width != beam_width: return ScheduleAction.SKIP, 0, scheduled_beam_width, req_it_end + self._lost_kv_error = None success = self._try_allocate_generation(req) + if self._lost_kv_error is not None: + lost = self._on_lost_kv_cache(req, inflight_request_ids, recompute_paused) + return lost, 0, scheduled_beam_width, req_it_end + + if not success and self.kv_cache_manager.flush_deferred_closes(): + # Finished requests whose close is deferred + # (kv_cache_config.defer_generation_only_release) still hold pages. + # Closing them now is never earlier than the immediate close they + # replace, and costs no running request a suspend or a recompute. + success = self._try_allocate_generation(req) + if self._lost_kv_error is not None: + lost = self._on_lost_kv_cache(req, inflight_request_ids, recompute_paused) + return lost, 0, scheduled_beam_width, req_it_end + + if not success and self.has_cp_helix and not self.enable_recompute_pause: + # Without recompute pause (e.g. a disaggregated generation server, + # which cannot replay a prefill) and with the deferred closes above + # flushed, no page is left to free. Suspending to a lower tier is + # validated only under aggregated helix, so fail instead of + # stalling. + raise RuntimeError( + f"[V2Scheduler] KV allocation failed for helix request " + f"{req.py_request_id}; recompute pause is disabled " + f"(e.g. on a disaggregated generation server, which " + f"cannot replay the prefill), so the scheduler cannot " + f"preempt a request. Increase " + f"kv_cache_config.max_gpu_total_bytes (rank-local bytes) " + f"or max_tokens (GLOBAL tokens across CP ranks, not " + f"per-rank), or reduce concurrency." + ) if not success: - if self.has_cp_helix: - if not self.enable_recompute_pause: - # Without recompute pause (e.g. a disaggregated generation - # server, which cannot replay a prefill) there is no way to - # free pages, and suspending to a lower tier is validated - # only under aggregated helix, so fail instead of stalling. - raise RuntimeError( - f"[V2Scheduler] KV allocation failed for helix request " - f"{req.py_request_id}; recompute pause is disabled " - f"(e.g. on a disaggregated generation server, which " - f"cannot replay the prefill), so the scheduler cannot " - f"preempt a request. Increase " - f"kv_cache_config.max_gpu_total_bytes (rank-local bytes) " - f"or max_tokens (GLOBAL tokens across CP ranks, not " - f"per-rank), or reduce concurrency." - ) # Under helix without a tier below GPU, a suspended request's pages # have nowhere to go, so recompute-pause is the only way to make # room. @@ -2144,7 +2196,7 @@ def _try_schedule_generation( req, requests_list, req_it, req_it_end, evicted, inflight_request_ids ) - if not success: + if not success and self._lost_kv_error is None: req_it_end, success = self._try_recompute_pause_for_gen( req, requests_list, @@ -2156,6 +2208,11 @@ def _try_schedule_generation( inflight_request_ids, ) + if self._lost_kv_error is not None: + # Lost only once a victim made room for its resume; the ladders stopped there. + lost = self._on_lost_kv_cache(req, inflight_request_ids, recompute_paused) + return lost, 0, scheduled_beam_width, req_it_end + if success: return ScheduleAction.SCHEDULED, req_tokens, scheduled_beam_width, req_it_end @@ -2196,7 +2253,12 @@ def _try_allocate_generation(self, req: LlmRequest) -> bool: here, but its mirror still has to be admitted under this rollback: see ``_admit_unpaired_draft``. """ - if not self.kv_cache_manager.try_allocate_generation(req): + try: + if not self.kv_cache_manager.try_allocate_generation(req): + return False + except RemoteMemError as error: + # Its resume read pages a failed remote cache level took with it: no room brings them back. + self._lost_kv_error = error return False draft_manager = self._joint_draft_manager @@ -2209,6 +2271,67 @@ def _try_allocate_generation(self, req: LlmRequest) -> bool: self.kv_cache_manager.revert_allocate_generation(req) return False + def _on_lost_kv_cache( + self, req: LlmRequest, inflight_request_ids: set[int], recompute_paused: RequestList + ) -> ScheduleAction: + """Handle *req* after its cache's resume raised ``_lost_kv_error``: pages it needs were on a remote cache + level that failed, which the manager retires and unlinks from the reuse tree. + + A request that computed nothing yet matches its prompt again next pass. A started one re-prefills through + recompute pause where this executor can, and is failed (``take_lost_kv_requests``) where it cannot. + + Without ``recover_lost_kv_per_rank`` the error is re-raised: lock-step peers did not see it. + """ + error, self._lost_kv_error = self._lost_kv_error, None + if not self.recover_lost_kv_per_rank: + raise RemoteMemError( + f"Request {req.py_request_id} lost KV pages to a failed remote cache level on this rank, whose " + f"TP/CP/PP peers schedule in lock step and did not see the failure; stopping the executor" + ) from error + if not self._is_started_request(req): + logger.warning( + f"[V2Scheduler] Request {req.py_request_id} matched KV pages on a failed remote cache level; " + f"matching it again: {error}" + ) + self.release_context_admission(req) + elif self.enable_recompute_pause and self._is_recompute_pause_candidate( + req, inflight_request_ids + ): + logger.warning( + f"[V2Scheduler] Request {req.py_request_id} lost KV pages to a failed remote cache level; " + f"recomputing it: {error}" + ) + self._preempt_or_defer(req, recompute_paused) + else: + logger.error( + f"[V2Scheduler] Request {req.py_request_id} lost KV pages to a failed remote cache level and " + f"cannot recompute them here; failing it: {error}" + ) + self._clear_request_runtime_state(req) + if all(lost is not req for lost, _ in self._lost_kv_requests): + message = f"KV cache pages lost with a failed remote cache level: {error}" + self._lost_kv_requests = (*self._lost_kv_requests, (req, message)) + return ScheduleAction.SKIP + + def _raise_if_lockstep_remote_level_failed(self) -> None: + """Stop a lock-step rank once any of its remote cache levels failed. + + The failure is rank-local (a donor this rank's chunks sat on, or this rank's transfer timeout), and the level's + pages leave only this rank's reuse tree, so the group's matches, admissions and collectives would diverge. + """ + for manager in self._lockstep_remote_managers: + if manager.any_remote_level_failed: + raise RemoteMemError( + "A remote KV cache level failed on this rank. Its TP/CP/PP peers schedule in lock step and cannot " + "drop the same pages or requests, so the executor stops instead of diverging from them." + ) + + def take_lost_kv_requests(self) -> list[tuple[LlmRequest, str]]: + """Requests the last passes could neither schedule nor recompute after a remote cache level failed, with their + error messages; the executor fails them.""" + lost, self._lost_kv_requests = self._lost_kv_requests, () + return list(lost) + # ---- Eviction ---- @staticmethod @@ -2638,6 +2761,8 @@ def _try_evict_for_gen( if self._try_allocate_generation(req): return req_it_end, True + if self._lost_kv_error is not None: + break # no victim brings its pages back return req_it_end, False @@ -2717,6 +2842,8 @@ def _try_recompute_pause_for_gen( # secondary-tier capacity just released to ordinary-suspend another # active victim. success = self._try_allocate_generation(req) + if self._lost_kv_error is not None: + return req_it_end, False if not success and self.kv_cache_manager.can_evict: req_it_end, success = self._try_evict_for_gen( req, requests_list, req_it, req_it_end, evicted, inflight_request_ids diff --git a/tensorrt_llm/_torch/pyexecutor/scheduler/waiting_queue.py b/tensorrt_llm/_torch/pyexecutor/scheduler/waiting_queue.py index f38b74cfce0f..099222e52252 100644 --- a/tensorrt_llm/_torch/pyexecutor/scheduler/waiting_queue.py +++ b/tensorrt_llm/_torch/pyexecutor/scheduler/waiting_queue.py @@ -15,9 +15,11 @@ import heapq import itertools +import math from abc import ABC, abstractmethod from collections import deque -from collections.abc import Iterable, Iterator +from collections.abc import Callable, Iterable, Iterator +from typing import Optional from tensorrt_llm.executor.request import DEFAULT_REQUEST_PRIORITY from tensorrt_llm.llmapi.llm_args import WaitingQueuePolicy @@ -118,10 +120,12 @@ class FCFSWaitingQueue(deque, WaitingQueue): @staticmethod def _warn_if_priority_set(request: RequestQueueItem) -> None: if request.request is not None and request.request.priority != DEFAULT_REQUEST_PRIORITY: - logger.warning( + # Once per process: with output_length_prediction every request has one. + logger.warning_once( "A request has a non-default priority but the FCFS waiting " "queue is in use; the priority value will be ignored. " - "Use WaitingQueuePolicy.PRIORITY to enable priority scheduling." + "Use WaitingQueuePolicy.PRIORITY to enable priority scheduling.", + key="fcfs_waiting_queue_ignores_priority", ) def add_request(self, request: RequestQueueItem) -> None: @@ -195,7 +199,7 @@ class PriorityWaitingQueue(WaitingQueue): Complexity: - add_request / add_requests: O(log n) - pop_request / peek_request: O(log n) / O(1) - - peek_requests(k): O(n log k), without copying or sorting the heap + - peek_requests(k): O(k log k), without copying or sorting the heap - remove_by_ids: O(n) rebuild + O(n) heapify - __iter__: O(n log n) over a sorted copy (priority order) """ @@ -247,8 +251,21 @@ def peek_request(self) -> RequestQueueItem: return self._heap[0][2] def peek_requests(self, k: int) -> list[RequestQueueItem]: - """Return up to ``k`` requests in priority order without removing them.""" - return [e[2] for e in heapq.nsmallest(max(k, 0), self._heap)] + """Return up to ``k`` requests in priority order without removing them. + + Best-first over the heap's tree: an entry's children are its only successors, so the walk reads O(k) entries + and the whole heap is never scanned. + """ + heap = self._heap + frontier = [(heap[0], 0)] if heap and k > 0 else [] + result = [] + while frontier and len(result) < k: + entry, index = heapq.heappop(frontier) + result.append(entry[2]) + for child in (2 * index + 1, 2 * index + 2): + if child < len(heap): + heapq.heappush(frontier, (heap[child], child)) + return result def admission_groups(self, requests: list[RequestQueueItem]) -> list[int]: """One group per priority.""" @@ -301,19 +318,229 @@ def __iter__(self) -> Iterator[RequestQueueItem]: return (e[2] for e in sorted(self._heap)) +def _heap_smallest(heap: list, k: int, keep: Callable[[tuple], bool]) -> list: + """Up to ``k`` smallest entries of ``heap`` that ``keep`` accepts, in order. + + Walks the heap best-first, visiting O(k + skipped) entries instead of the whole heap. + """ + out = [] + frontier = [(heap[0], 0)] if heap and k > 0 else [] + while frontier and len(out) < k: + entry, idx = heapq.heappop(frontier) + if keep(entry): + out.append(entry) + for child in (2 * idx + 1, 2 * idx + 2): + if child < len(heap): + heapq.heappush(frontier, (heap[child], child)) + return out + + +class AgingPriorityWaitingQueue(WaitingQueue): + """``PriorityWaitingQueue`` with a wait cap. + + Serves the highest ``request.priority`` first; ties go in arrival order. A request + that has waited ``max_wait_s`` since it reached the server (``admit_orig_arrival`` in + disaggregated serving, else ``admit_arrival``) goes ahead of every request that has + not, oldest first. + + Every rank pops the same order: the keys are the broadcast request's priority, the + arrival order and rank 0's arrival stamps against rank 0's clock (``set_now``). A + request put back keeps its arrival sequence. + + Waiting requests sit in a ``(-priority, seq)`` heap and an ``(arrival, seq)`` heap; + ``set_now`` moves the newly aged ones into an aged ``(arrival, seq)`` heap that is + served first. Entries an aged or popped request leaves behind in the first two heaps + are skipped when reached. + """ + + def __init__(self, max_wait_s: float) -> None: + if not (math.isfinite(max_wait_s) and max_wait_s > 0.0): + raise ValueError(f"max_wait_s={max_wait_s!r} must be a positive number") + self.max_wait_s = max_wait_s + self._now: Optional[float] = None + # Arrival sequence -> queued request. + self._items: dict[int, RequestQueueItem] = {} + # Arrival sequences of the queued requests in _aged_heap. + self._aged: set[int] = set() + self._priority_heap: list[tuple[float, int]] = [] + self._arrival_heap: list[tuple[float, int]] = [] + self._aged_heap: list[tuple[float, int]] = [] + # Arrival sequences with an entry in _arrival_heap. A pop from _priority_heap leaves the + # arrival entry in place, so a request put back reuses it rather than adding another. + self._in_arrival_heap: set[int] = set() + self._counter = itertools.count() + # For a request put back that was never added. + self._prepend_counter = itertools.count(-1, -1) + # Request id -> arrival sequence, while queued or popped and not yet admitted. + self._seq: dict[int, int] = {} + + def set_now(self, now: Optional[float]) -> None: + """Rank 0's clock, set once per iteration before the pops; None keeps the last value.""" + if now is None: + return + self._now = now + heap = self._arrival_heap + while heap and now - heap[0][0] >= self.max_wait_s: + arrival, seq = heapq.heappop(heap) + self._in_arrival_heap.discard(seq) + if self._waiting((arrival, seq)): + self._aged.add(seq) + heapq.heappush(self._aged_heap, (arrival, seq)) + + @staticmethod + def _arrival_of(item: RequestQueueItem) -> Optional[float]: + if item.admit_orig_arrival is not None: + return item.admit_orig_arrival + return item.admit_arrival + + @staticmethod + def _priority_of(item: RequestQueueItem) -> float: + if item.request is not None: + return item.request.priority + return DEFAULT_REQUEST_PRIORITY + + def _waiting(self, entry: tuple) -> bool: + """Whether a heap entry ``(key, seq)`` is a queued request that has not aged.""" + seq = entry[1] + return seq in self._items and seq not in self._aged + + def _push(self, item: RequestQueueItem, seq: int) -> None: + self._items[seq] = item + self._seq[item.id] = seq + arrival = self._arrival_of(item) + if arrival is not None and self._now is not None and self._now - arrival >= self.max_wait_s: + self._aged.add(seq) + heapq.heappush(self._aged_heap, (arrival, seq)) + return + heapq.heappush(self._priority_heap, (-self._priority_of(item), seq)) + if arrival is not None and seq not in self._in_arrival_heap: + self._in_arrival_heap.add(seq) + heapq.heappush(self._arrival_heap, (arrival, seq)) + if len(self._priority_heap) + len(self._arrival_heap) > 4 * len(self._items) + 64: + self._compact() + + def _compact(self) -> None: + """Drop the entries of requests that aged or left the queue.""" + self._priority_heap = [e for e in self._priority_heap if self._waiting(e)] + self._arrival_heap = [e for e in self._arrival_heap if self._waiting(e)] + self._in_arrival_heap = {seq for _, seq in self._arrival_heap} + self._aged_heap = [e for e in self._aged_heap if e[1] in self._items] + for heap in (self._priority_heap, self._arrival_heap, self._aged_heap): + heapq.heapify(heap) + + def _priority_head(self) -> tuple[float, int]: + heap = self._priority_heap + while not self._waiting(heap[0]): + heapq.heappop(heap) + return heap[0] + + def add_request(self, request: RequestQueueItem) -> None: + self._push(request, next(self._counter)) + + def add_requests(self, requests: Iterable[RequestQueueItem]) -> None: + for request in requests: + self.add_request(request) + + def pop_request(self) -> RequestQueueItem: + if not self._items: + raise IndexError("pop from an empty queue") + # Unreachable from the executor: requests enter the queue only in + # _fetch_and_enqueue_requests, after set_now(rank0_now) on every rank, and the + # broadcaster's sync_clock (on with this queue) sets rank0_now on each broadcast. + if self._now is None: + raise RuntimeError("AgingPriorityWaitingQueue needs set_now() before the first pop") + if self._aged_heap: + _, seq = heapq.heappop(self._aged_heap) + self._aged.discard(seq) + else: + _, seq = self._priority_head() + heapq.heappop(self._priority_heap) + return self._items.pop(seq) + + def peek_request(self) -> RequestQueueItem: + if not self._items: + raise IndexError("peek from an empty queue") + if self._aged_heap: + return self._items[self._aged_heap[0][1]] + return self._items[self._priority_head()[1]] + + def peek_requests(self, k: int) -> list[RequestQueueItem]: + """Up to ``k`` requests in pop order, O(k log k) plus skipped entries.""" + aged = _heap_smallest(self._aged_heap, k, lambda entry: True) + rest = _heap_smallest(self._priority_heap, k - len(aged), self._waiting) + return [self._items[entry[1]] for entry in aged + rest] + + def admission_groups(self, requests: list[RequestQueueItem]) -> list[int]: + """One group per aged request, in pop order, then one per priority (as ``PriorityWaitingQueue``).""" + groups = [] + group = -1 + num_aged = 0 + for i, request in enumerate(requests): + if num_aged == i and self._seq.get(request.id) in self._aged: + num_aged += 1 + group += 1 + elif i == num_aged or self._priority_of(request) != self._priority_of(requests[i - 1]): + group += 1 + groups.append(group) + return groups + + def prepend_request(self, request: RequestQueueItem) -> None: + seq = self._seq.get(request.id) + self._push(request, seq if seq is not None else next(self._prepend_counter)) + + def prepend_requests(self, requests: Iterable[RequestQueueItem]) -> None: + # Reversed, so that among requests without an arrival sequence the first gets the lowest one. + for request in reversed(list(requests)): + self.prepend_request(request) + + def mark_admitted(self, requests: Iterable[RequestQueueItem]) -> None: + for request in requests: + self._seq.pop(request.id, None) + + def remove_by_ids(self, request_ids: set[int]) -> None: + self._items = {s: item for s, item in self._items.items() if item.id not in request_ids} + self._aged &= self._items.keys() + for request_id in request_ids: + self._seq.pop(request_id, None) + self._compact() + + def __bool__(self) -> bool: + return len(self._items) > 0 + + def __len__(self) -> int: + return len(self._items) + + def __iter__(self) -> Iterator[RequestQueueItem]: + """Requests in pop order, over a snapshot taken at call time (O(n log n)).""" + aged = sorted(self._aged_heap) + rest = sorted(e for e in self._priority_heap if self._waiting(e)) + return iter([self._items[entry[1]] for entry in aged + rest]) + + def create_waiting_queue( policy: WaitingQueuePolicy = WaitingQueuePolicy.FCFS, gen_admission=None, + max_wait_s: Optional[float] = None, ) -> WaitingQueue: """Create a waiting queue based on the specified policy. Args: policy: The scheduling policy to use. gen_admission: Optional ``GenAdmissionConfig``; overrides ``policy`` when enabled. + max_wait_s: The wait cap of ``WaitingQueuePolicy.PRIORITY``; None: no cap. Returns: A WaitingQueue instance. """ + if max_wait_s is not None: + if policy != WaitingQueuePolicy.PRIORITY: + raise ValueError(f"max_wait_s needs waiting_queue_policy=priority, not {policy}") + if gen_admission is not None and gen_admission.enabled: + raise ValueError( + f"waiting_queue_max_wait_s cannot be combined with GEN admission by original " + f"arrival ({gen_admission.describe()})" + ) + return AgingPriorityWaitingQueue(max_wait_s) if gen_admission is not None and gen_admission.enabled: from .gen_admission_queue import GenAdmissionWaitingQueue diff --git a/tensorrt_llm/_torch/pyexecutor/steady_spec_prepare.py b/tensorrt_llm/_torch/pyexecutor/steady_spec_prepare.py index e54aaf57bfca..dc551bf12d6d 100644 --- a/tensorrt_llm/_torch/pyexecutor/steady_spec_prepare.py +++ b/tensorrt_llm/_torch/pyexecutor/steady_spec_prepare.py @@ -13,6 +13,12 @@ a later step matches when it runs the recorded requests on the recorded slots and metadata. Any other step (batch or slot change, context rows, dummies, multimodal, LoRA, guided decoding, beams, attention DP, helix CP, warmup) takes the full pass, which records again when it qualifies. + +With ``stage_rng`` (``RuntimeHooks.pack_spec_rng_uploads``) and zero-copy slabs the same kernel also writes the +step's Philox state for sampling (``SpecMetadata.request_seeds`` / ``request_offsets`` / ``seeds`` / +``offsets``) from a second pinned ring, instead of four host-to-device copies on the critical stream. The host +computes the same values and advances the same offset windows (``SpecMetadata._populate_request_rng_state``); only +the delivery changes. """ import types @@ -47,6 +53,7 @@ "nd_slot_stride", "mrope_axis_stride", "static_pos_axis_stride", + "rng_span", "B", ] _STAGE_PTR_ARGS = [ @@ -66,6 +73,11 @@ "kv_lens_out", "static_ids", "static_pos", + "rng_slab", + "req_seeds_out", + "req_offsets_out", + "seeds_out", + "offsets_out", ] @@ -100,12 +112,19 @@ def _steady_stage_kernel( static_ids, # graph static input ids (HAS_STATIC) static_pos, # graph static positions, [3, 1, M] (mrope) or [1, M] static_pos_axis_stride, + rng_slab, # int64 [2 * B] (HAS_RNG): each request's Philox seed, then its offset-window base + req_seeds_out, # int64 [B] SpecMetadata.request_seeds (HAS_RNG) + req_offsets_out, # int64 [B] SpecMetadata.request_offsets (HAS_RNG) + seeds_out, # int64 [B * T] SpecMetadata.seeds, one per logits row (HAS_RNG) + offsets_out, # int64 [B * T] SpecMetadata.offsets (HAS_RNG) + rng_span, # Philox offsets between a request's consecutive rows (_RNG_SLOT_SPAN) B, T: tl.constexpr, D: tl.constexpr, HAS_MROPE: tl.constexpr, HAS_KV: tl.constexpr, HAS_STATIC: tl.constexpr, + HAS_RNG: tl.constexpr, BLOCK: tl.constexpr, ): i = tl.arange(0, BLOCK) @@ -140,6 +159,15 @@ def _steady_stage_kernel( tl.store(prev_kv_offsets + i, lens_r - T, mask=req) if HAS_KV: tl.store(kv_lens_out + i, tl.load(slab + B + B * T + i, mask=req, other=0), mask=req) + if HAS_RNG: + # The layout SpecMetadata._populate_request_rng_state uploads: request_* per request, and per logits + # row (request r = i // T, row j = i % T) the request's seed and offset_r + j * rng_span. + tl.store(req_seeds_out + i, tl.load(rng_slab + i, mask=req, other=0), mask=req) + tl.store(req_offsets_out + i, tl.load(rng_slab + B + i, mask=req, other=0), mask=req) + row_seed = tl.load(rng_slab + r, mask=tok, other=0) + row_off = tl.load(rng_slab + B + r, mask=tok, other=0) + tl.store(seeds_out + i, row_seed, mask=tok) + tl.store(offsets_out + i, row_off + j.to(tl.int64) * rng_span, mask=tok) # draft rows: request i // D, draft i % D drf = i < B * D slot_d = tl.load(slab + i // D, mask=drf, other=0) @@ -166,6 +194,9 @@ def stage_steady_inputs( static_input_ids: torch.Tensor | None = None, static_position_ids: torch.Tensor | None = None, block: int | None = None, + rng_slab: torch.Tensor | None = None, + rng_buffers: tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor] | None = None, + rng_span: int = 0, ) -> None: """One launch of the steady staging kernel. @@ -185,6 +216,11 @@ def stage_steady_inputs( static_input_ids, static_position_ids: The CUDA graph's static inputs, when staged here. block: The BLOCK of the launch when it covers the batch (one variant for all batch sizes), else the batch's own power of two. + rng_slab: int64 [2 * b]: each request's Philox seed, then its offset-window base (a pinned + host tensor read through its device mapping), or None to leave the Philox state alone. + rng_buffers: ``SpecMetadata``'s (request_seeds, request_offsets, seeds, offsets), written + when ``rng_slab`` is given. + rng_span: Philox offsets between consecutive rows of a request (``_RNG_SLOT_SPAN``). """ d = t - 1 n = b * t @@ -194,6 +230,12 @@ def stage_steady_inputs( new_tokens = new_tensors_device.new_tokens next_drafts = new_tensors_device.next_draft_tokens has_mrope = mrope_positions is not None + has_rng = rng_slab is not None + if has_rng: + req_seeds_out, req_offsets_out, seeds_out, offsets_out = rng_buffers + else: + # Untouched without HAS_RNG; one dtype for every launch keeps a single variant. + rng_slab = req_seeds_out = req_offsets_out = seeds_out = offsets_out = gather_ids _steady_stage_kernel[(1,)]( slab, new_tokens, @@ -216,12 +258,19 @@ def stage_steady_inputs( static_input_ids if static_input_ids is not None else gather_ids, static_position_ids if static_position_ids is not None else gather_ids, static_position_ids.stride(0) if (static_position_ids is not None and has_mrope) else 0, + rng_slab, + req_seeds_out, + req_offsets_out, + seeds_out, + offsets_out, + rng_span, b, T=t, D=d, HAS_MROPE=has_mrope, HAS_KV=kv_lens_cuda is not None, HAS_STATIC=static_input_ids is not None, + HAS_RNG=has_rng, BLOCK=block, ) @@ -261,8 +310,15 @@ class SteadyMtpPrepare: use_mrope: Whether the model reads the [3, 1, N] mrope positions. has_static_inputs: Whether decode steps replay CUDA graphs (to compile the kernel variant that also writes their static inputs). + stage_rng: Whether the staging kernel also writes the step's Philox state. """ + # With stage_rng: Philox offsets between a request's consecutive rows, and the pinned ring of the step's Philox + # state (fenced by the slab events); 0 / empty otherwise. + rng_span: int = 0 + host_rng_slabs: tuple[torch.Tensor, ...] = () + host_rng_views: tuple[np.ndarray, ...] = () + def __init__( self, *, @@ -271,6 +327,7 @@ def __init__( max_tokens_per_step: int, use_mrope: bool, has_static_inputs: bool, + stage_rng: bool = False, ) -> None: self.record: SteadyMtpRecord | None = None self.use_mrope = use_mrope @@ -291,6 +348,17 @@ def __init__( else torch.zeros(self.slab_capacity, dtype=torch.int32, device="cuda") ) self.ring_pos = 0 + # With stage_rng the step's Philox state rides in a second pinned ring (int64, fenced by the same + # events). Zero-copy only: the device-copy fallback has no mirror for this ring. + if stage_rng and self.zero_copy and max_tokens_per_step >= 2: + from ..speculative.interface import _RNG_SLOT_SPAN + + self.rng_span = int(_RNG_SLOT_SPAN) + self.host_rng_slabs = tuple( + torch.zeros(2 * max_requests, dtype=torch.int64, pin_memory=self.zero_copy) + for _ in range(_RING) + ) + self.host_rng_views = tuple(slab.numpy() for slab in self.host_rng_slabs) # One staging-kernel BLOCK for every batch size of this engine, and its variant compiled now. self.block: int | None = None if max_tokens_per_step >= 2: @@ -299,37 +367,57 @@ def __init__( def _warm_stage_kernel(self, t: int, has_static_inputs: bool) -> None: """Compile the staging kernel variant the steady steps launch (same constexprs, unspecialized ints and - alignments) with a B = 0 launch, which reads and writes nothing.""" + alignments) with a B = 0 launch, which reads and writes nothing; with the Philox ring, that variant + too.""" if torch.cuda.is_current_stream_capturing(): return dummy = torch.zeros(1, dtype=torch.int32, device="cuda") - stage_steady_inputs( - dummy, - 0, - t, - types.SimpleNamespace( - new_tokens=dummy.view(1, 1, 1), - next_draft_tokens=dummy.view(1, 1), - new_tokens_lens=dummy, - ), - input_ids=dummy, - draft_tokens=dummy, - prev_batch_idx=dummy, - prev_pos_idx=dummy, - prev_pos_offsets=dummy, - prev_kv_offsets=dummy, - positions=dummy, - mrope_positions=dummy.view(1, 1, 1) if self.use_mrope else None, - gather_ids=dummy, - kv_lens_cuda=dummy, - static_input_ids=dummy if has_static_inputs else None, - static_position_ids=( - (dummy.view(1, 1, 1) if self.use_mrope else dummy.view(1, 1)) - if has_static_inputs - else None - ), - block=self.block, - ) + variants = [{}] + if self.rng_span: + dummy64 = torch.zeros(1, dtype=torch.int64, device="cuda") + variants.append( + dict( + rng_slab=dummy64, + rng_buffers=(dummy64, dummy64, dummy64, dummy64), + rng_span=self.rng_span, + ) + ) + for rng_kwargs in variants: + stage_steady_inputs( + dummy, + 0, + t, + types.SimpleNamespace( + new_tokens=dummy.view(1, 1, 1), + next_draft_tokens=dummy.view(1, 1), + new_tokens_lens=dummy, + ), + input_ids=dummy, + draft_tokens=dummy, + prev_batch_idx=dummy, + prev_pos_idx=dummy, + prev_pos_offsets=dummy, + prev_kv_offsets=dummy, + positions=dummy, + mrope_positions=dummy.view(1, 1, 1) if self.use_mrope else None, + gather_ids=dummy, + kv_lens_cuda=dummy, + static_input_ids=dummy if has_static_inputs else None, + static_position_ids=( + (dummy.view(1, 1, 1) if self.use_mrope else dummy.view(1, 1)) + if has_static_inputs + else None + ), + block=self.block, + **rng_kwargs, + ) + + def rng_rows(self) -> int | None: + """Logits rows per request when this stager writes the step's Philox state (``stage_rng``), + else None. The caller hands it to ``SpecMetadata`` before populating the sampling parameters.""" + if not self.rng_span or self.record is None: + return None + return self.record.tokens_per_step def invalidate(self) -> None: """Drop the record (every full pass does, before it may record again).""" @@ -450,6 +538,8 @@ def stage( new_tensors_device: Any, buffers: Any, attn_metadata: AttentionMetadata, + rng_state: tuple[list[int], list[int]] | None = None, + rng_buffers: tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor] | None = None, ) -> tuple[list[int], list[int], int]: """Write this step's device inputs (one slab write, one kernel launch). @@ -458,6 +548,10 @@ def stage( new_tensors_device: The previous step's device sampler tensors. buffers: The preparer's DecoderInputBuffers. attn_metadata: The recorded attention metadata. + rng_state: What ``SpecMetadata.populate_sampling_params_for_one_model`` returns (each request's Philox + seed and offset-window base, in batch order), or None. Written only when this stager has the Philox + ring. + rng_buffers: ``SpecMetadata``'s (request_seeds, request_offsets, seeds, offsets). Returns: The cached-token counts (``KVCacheParams.num_cached_tokens_per_seq``), the KV lengths @@ -488,6 +582,16 @@ def stage( else: self.device_slab[:used].copy_(self.host_slabs[k][:used], non_blocking=True) slab = self.device_slab + rng_kwargs = {} + if rng_state is not None and self.rng_span: + seeds, offsets = rng_state + assert len(seeds) == b and len(offsets) == b and rng_buffers is not None + rng_view = self.host_rng_views[k] + rng_view[:b] = seeds + rng_view[b : 2 * b] = offsets + rng_kwargs = dict( + rng_slab=self.host_rng_slabs[k], rng_buffers=rng_buffers, rng_span=self.rng_span + ) stage_steady_inputs( slab, @@ -507,8 +611,10 @@ def stage( static_input_ids=rec.static_ids, static_position_ids=rec.static_pos, block=self.block, + **rng_kwargs, ) - # The host slot may be rewritten once its reader (the copy, or the kernel itself) has run. + # The host slots (and the Philox slot) may be rewritten once their reader (the copy, or the kernel + # itself) has run. event = self.slab_events[k] if event is None: event = self.slab_events[k] = torch.cuda.Event() diff --git a/tensorrt_llm/_torch/speculative/eagle3.py b/tensorrt_llm/_torch/speculative/eagle3.py index bf32e922334f..28bdb03a26a6 100644 --- a/tensorrt_llm/_torch/speculative/eagle3.py +++ b/tensorrt_llm/_torch/speculative/eagle3.py @@ -19,6 +19,7 @@ from ..attention.backends.flashinfer import FlashInferAttentionMetadata from ..attention.backends.sparse.params import MTPIndexShareMetadata from ..model_config import ModelConfig +from ..modules.multi_stream_utils import do_multi_stream from ..pyexecutor.kv_cache.mamba_cache_manager import MambaHybridCacheManager from ..pyexecutor.llm_request import LlmRequest from ..pyexecutor.resource_manager import BaseResourceManager, SlotManager @@ -27,6 +28,8 @@ from .interface import (INVALID_PROMPT_LOOKAHEAD_TOKEN, DraftRowPick, SpecMetadata, SpecWorkerBase, supports_sharded_target_sampling) +from .kept_rows import (DraftKeptRows, generation_only_on_every_rank, + kept_row_ids) from .mtp import _select_mtp_position_ids from .sa_enhancer import SADraftEnhancer from .spec_tree_manager import SpecTreeManager @@ -458,6 +461,12 @@ class Eagle3OneModelWorker(SpecWorkerBase): ``eagle3_dynamic_tree.py``. """ + # Declared by the MTP draft model (set_draft_model): pass 0 takes the kept + # rows; the recurrent-state promotion runs beside the draft loop. + _draft_takes_kept_rows: bool = False + _promotion_stream: Optional[torch.cuda.Stream] = None + _promotion_done: Optional[torch.cuda.Event] = None + def __init__(self, spec_config: "EagleDecodingConfig", mapping: Optional[Mapping] = None, @@ -474,6 +483,11 @@ def __init__(self, # model_config is required for MTP Eagle TP / ADP / Mamba support; the # Eagle3 path can leave it as None. self.model_config = model_config + self.fused_sample_accept = (model_config is not None + and model_config.extra_attrs.get( + "spec_fused_sample_accept", False) + and key_exchange is not None + and key_exchange.fast_gumbel) # Mode flag: True = MTP Eagle one-model, False = Eagle3 one-model. self.is_mtp_eagle = spec_config.spec_dec_mode.is_mtp_eagle_one_model() @@ -517,6 +531,13 @@ def set_draft_model(self, draft_model) -> None: self._draft_folds_kv_lens_increment = ( self.is_mtp_eagle and isinstance(draft_model, MTPForCausalLM) and draft_model.folds_kv_lens_increment) + self._draft_takes_kept_rows = (self.is_mtp_eagle and isinstance( + draft_model, MTPForCausalLM) and draft_model.takes_kept_rows) + if (self.is_mtp_eagle and isinstance(draft_model, MTPForCausalLM) + and draft_model.promotes_target_state_beside + and not self._uses_external_shared_target_kv): + self._promotion_stream = torch.cuda.Stream() + self._promotion_done = torch.cuda.Event() def _step0_draft_layer_picks_rows(self, draft_model: nn.Module, use_epilogue: bool) -> bool: @@ -651,75 +672,92 @@ def _forward_impl(self, if self._is_mamba_hybrid_cache is None: self._is_mamba_hybrid_cache = isinstance( attn_metadata.kv_cache_manager, MambaHybridCacheManager) - if num_gens > 0 and self._is_mamba_hybrid_cache: + promoting = num_gens > 0 and self._is_mamba_hybrid_cache + # Beside the draft loop (multi-stream steps), which reads no target + # recurrent state; its inputs are not written before the join. + beside = (promoting and self._promotion_stream is not None + and do_multi_stream()) + if beside: + self._promotion_stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(self._promotion_stream): + attn_metadata.kv_cache_manager.update_mamba_states( + attn_metadata=attn_metadata, + num_accepted_tokens=num_accepted_tokens, + state_indices=attn_metadata.mamba_metadata.state_indices) + self._promotion_done.record() + elif promoting: attn_metadata.kv_cache_manager.update_mamba_states( attn_metadata=attn_metadata, num_accepted_tokens=num_accepted_tokens, state_indices=attn_metadata.mamba_metadata.state_indices) - sa_manager = getattr(spec_metadata.spec_resource_manager, 'sa_manager', - None) - if self.sa_enhancer is not None and sa_manager is not None: - self.sa_enhancer.extend_and_prepare( - sa_manager=sa_manager, - request_ids=spec_metadata.request_ids, - accepted_tokens=accepted_tokens, - num_accepted_tokens=num_accepted_tokens, - num_gens=num_gens, - num_contexts=num_contexts, - max_draft_len=runtime_draft_len, - ) + try: + sa_manager = getattr(spec_metadata.spec_resource_manager, + 'sa_manager', None) + if self.sa_enhancer is not None and sa_manager is not None: + self.sa_enhancer.extend_and_prepare( + sa_manager=sa_manager, + request_ids=spec_metadata.request_ids, + accepted_tokens=accepted_tokens, + num_accepted_tokens=num_accepted_tokens, + num_gens=num_gens, + num_contexts=num_contexts, + max_draft_len=runtime_draft_len, + ) - if self._uses_external_shared_target_kv: - next_new_tokens = None - next_draft_tokens = ( - self._forward_external_shared_target_kv_draft_loop( + if self._uses_external_shared_target_kv: + next_new_tokens = None + next_draft_tokens = ( + self._forward_external_shared_target_kv_draft_loop( + position_ids=position_ids, + hidden_states=hidden_states, + attn_metadata=attn_metadata, + spec_metadata=spec_metadata, + draft_model=draft_model, + accepted_tokens=accepted_tokens, + num_accepted_tokens=num_accepted_tokens, + num_contexts=num_contexts, + batch_size=batch_size, + )) + else: + # The step-0 sequence lengths, before the draft loop rewrites them. + pre_draft_seq_lens = attn_metadata._seq_lens_cuda + # Save the old attn_metadata and spec_metadata + self._prepare_attn_metadata_for_spec_dec(attn_metadata) + + # Prepare inputs for the 1st draft model forward + position_ids = position_ids.squeeze(0) + inputs = self.prepare_1st_drafter_inputs( + input_ids=input_ids, position_ids=position_ids, hidden_states=hidden_states, + accepted_tokens=accepted_tokens, attn_metadata=attn_metadata, spec_metadata=spec_metadata, - draft_model=draft_model, - accepted_tokens=accepted_tokens, - num_accepted_tokens=num_accepted_tokens, - num_contexts=num_contexts, - batch_size=batch_size, - )) - else: - # The step-0 sequence lengths, before the draft loop rewrites them. - pre_draft_seq_lens = attn_metadata._seq_lens_cuda - # Save the old attn_metadata and spec_metadata - self._prepare_attn_metadata_for_spec_dec(attn_metadata) - - # Prepare inputs for the 1st draft model forward - position_ids = position_ids.squeeze(0) - inputs = self.prepare_1st_drafter_inputs( - input_ids=input_ids, - position_ids=position_ids, - hidden_states=hidden_states, - accepted_tokens=accepted_tokens, - attn_metadata=attn_metadata, - spec_metadata=spec_metadata, - draft_model=draft_model) - - # Predict draft tokens. ``original_all_rank_num_tokens`` is saved here - # so the post-loop restore (below) can put attn_metadata back into a - # state the target model expects. - original_all_rank_num_tokens = attn_metadata.all_rank_num_tokens - - # Get the draft KV cache manager if using separate layouts - draft_kv_cache_manager = self.get_draft_kv_cache_manager( - resource_manager) - - next_draft_tokens, next_new_tokens = self._forward_draft_loop( - inputs, attn_metadata, spec_metadata, draft_model, - draft_kv_cache_manager, num_contexts, num_gens, batch_size, - num_accepted_tokens, original_all_rank_num_tokens, - resource_manager, accepted_tokens, pre_draft_seq_lens) - # restore attn_metadata to support cuda graph - self._restore_attn_metadata_from_spec_dec(attn_metadata) - # restore all_rank_num_tokens for attention DP - if original_all_rank_num_tokens is not None: - attn_metadata.all_rank_num_tokens = original_all_rank_num_tokens + draft_model=draft_model) + + # Predict draft tokens. ``original_all_rank_num_tokens`` is saved here + # so the post-loop restore (below) can put attn_metadata back into a + # state the target model expects. + original_all_rank_num_tokens = attn_metadata.all_rank_num_tokens + + # Get the draft KV cache manager if using separate layouts + draft_kv_cache_manager = self.get_draft_kv_cache_manager( + resource_manager) + + next_draft_tokens, next_new_tokens = self._forward_draft_loop( + inputs, attn_metadata, spec_metadata, draft_model, + draft_kv_cache_manager, num_contexts, num_gens, batch_size, + num_accepted_tokens, original_all_rank_num_tokens, + resource_manager, accepted_tokens, pre_draft_seq_lens) + # restore attn_metadata to support cuda graph + self._restore_attn_metadata_from_spec_dec(attn_metadata) + # restore all_rank_num_tokens for attention DP + if original_all_rank_num_tokens is not None: + attn_metadata.all_rank_num_tokens = original_all_rank_num_tokens + finally: + if beside: + torch.cuda.current_stream().wait_event(self._promotion_done) # prepare next new tokens to support overlap scheduler; the draft loop # may have built them already as a view of its token buffer. @@ -850,6 +888,32 @@ def _forward_draft_loop(self, inputs, attn_metadata, spec_metadata, num_accepted_tokens, original_all_rank_num_tokens, accepted_tokens, pre_draft_seq_lens) + @staticmethod + def _draft_kept_rows(spec_metadata: SpecMetadata, + step0_seq_lens: torch.Tensor, + num_accepted_tokens: torch.Tensor, num_contexts: int, + num_gens: int, runtime_draft_len: int, + num_ctx_tokens: int, + use_epilogue: bool) -> Optional[DraftKeptRows]: + """Pass 0's kept rows when the step is generation-only on every rank. + + Pass 0 then computes past attention only the rows the draft loop keeps + (under attention DP, its MoE on every rank's kept-row count); with TP + attention and the step-0 epilogue they come back compact. + """ + kept_counts = spec_metadata.all_rank_num_seqs + if not generation_only_on_every_rank(num_contexts, kept_counts, + spec_metadata.all_rank_num_gens): + return None + return DraftKeptRows(kept_row_ids(step0_seq_lens, + spec_metadata.batch_indices_cuda, + num_accepted_tokens, num_contexts, + num_gens, runtime_draft_len, + num_ctx_tokens), + kept_counts, + compact=kept_counts is None and use_epilogue + and not spec_metadata.is_layer_capture(0)) + def _forward_linear_draft_loop(self, inputs, attn_metadata, @@ -953,8 +1017,23 @@ def _forward_linear_draft_loop(self, # passes ``all_rank_num_tokens`` as a kwarg so the draft model # handles save/restore internally (Eagle3DraftModel.forward # uses try/finally); attn_metadata is left untouched here. - hidden_states, hidden_states_to_save = self._run_draft_forward( - draft_model, inputs, spec_metadata, i) + # A kept-rows draft layer (MTP declares it) selects its own + # step-0 rows; it never also takes pick_rows. + kept_rows = None + if (i == 0 and self._draft_takes_kept_rows and pick_rows is None + and self.guided_decoder is None): + kept_rows = self._draft_kept_rows( + spec_metadata, step0_seq_lens, num_accepted_tokens, + num_contexts, num_gens, runtime_draft_len, + attn_metadata.num_ctx_tokens, use_epilogue) + if kept_rows is not None: + inputs["kept_rows"] = kept_rows + try: + hidden_states, hidden_states_to_save = self._run_draft_forward( + draft_model, inputs, spec_metadata, i) + finally: + inputs.pop("kept_rows", None) + compact = kept_rows is not None and kept_rows.compact # Compute gather_ids: on the first draft step each generation # request may have accepted multiple tokens, so we index into @@ -979,7 +1058,8 @@ def _forward_linear_draft_loop(self, accepted_tokens=accepted_tokens if token_buffer is not None else None, last_out=token_buffer[0] if - token_buffer is not None else None) + token_buffer is not None else None, + hidden_compact=compact) if step0 is None: token_buffer = None # needs the epilogue's row 0 if i == 0 and step0 is not None: @@ -1000,6 +1080,8 @@ def _forward_linear_draft_loop(self, # step and the draft input on the next. if i == 0 and step0 is not None: request_hidden_states = step0.hidden + elif compact: + request_hidden_states = hidden_states elif self.is_mtp_eagle: request_hidden_states = hidden_states[output_rows] else: @@ -1136,15 +1218,22 @@ def _forward_linear_draft_loop(self, mapping_lm_head_tp = getattr( draft_model.mtp_layers[0].shared_head, "mapping_lm_head_tp", None) + # Fast paths: the sampler writes the tokens straight into + # the step's token buffer row. + token_row = (token_buffer[i + 1] if + (self.spec_decode_fast_paths + and token_buffer is not None + and not use_lm_head_tp_in_adp) else None) new_draft_token = self.sample_draft_tokens( logits, spec_metadata, batch_size, draft_step=i, - mapping_lm_head_tp=mapping_lm_head_tp) + mapping_lm_head_tp=mapping_lm_head_tp, + out=token_row) if use_lm_head_tp_in_adp: new_draft_token = new_draft_token[:token_count] - if token_buffer is not None: + if token_buffer is not None and token_row is None: token_buffer[i + 1].copy_(new_draft_token) next_draft_tokens.append(new_draft_token) @@ -1465,8 +1554,12 @@ def prepare_1st_drafter_inputs( input_ids_gen = accepted_tokens[ num_contexts:, :spec_metadata.runtime_draft_len + 1].flatten() - # get draft inputs - input_ids = torch.concat([input_ids_ctx, input_ids_gen], dim=0) + # get draft inputs; on the fast paths a generation-only batch reads the + # accepted tokens in place (the loop never writes them). + if self.spec_decode_fast_paths and input_ids_ctx.numel() == 0: + input_ids = input_ids_gen + else: + input_ids = torch.concat([input_ids_ctx, input_ids_gen], dim=0) return { "input_ids": input_ids, diff --git a/tensorrt_llm/_torch/speculative/fused_accept.py b/tensorrt_llm/_torch/speculative/fused_accept.py index 96f4c888d30d..18f7583470bd 100644 --- a/tensorrt_llm/_torch/speculative/fused_accept.py +++ b/tensorrt_llm/_torch/speculative/fused_accept.py @@ -34,12 +34,14 @@ import triton import triton.language as tl +from ..distributed.ll_exchange import TPKeyExchange, argmax_exchange_finish, fast_gumbel_key +from ..modules.fla.op import gdc_wait_with_memory_clobber + MAX_DRAFT_LEN = 31 # columns of the accept tile (k + 1 <= 32) -# The counts change every step: keep them out of the cache key. -@triton.jit(do_not_specialize=["num_contexts", "num_gens"]) -def _strict_accept_kernel( +@triton.jit +def _strict_accept_rows( target_ptr, # [num_contexts + num_gens * (K + 1)] sampled target tokens (any int dtype) draft_ptr, # [num_gens, K] draft tokens of the previous step accepted_ptr, # [batch, accepted_stride] int32 out @@ -60,6 +62,7 @@ def _strict_accept_kernel( BLOCK_B: tl.constexpr, BLOCK_K: tl.constexpr, ): + """The acceptance of every request, in one program.""" # ---- context requests: column 0 = their sampled token, one accepted token ---- ctx = tl.arange(0, BLOCK_B) for c0 in range(0, num_contexts, BLOCK_B): @@ -111,6 +114,285 @@ def _strict_accept_kernel( tl.store(counter_ptr, counter) +# The counts change every step: keep them out of the cache key. +@triton.jit(do_not_specialize=["num_contexts", "num_gens"]) +def _strict_accept_kernel( + target_ptr, + draft_ptr, + accepted_ptr, + num_accepted_ptr, + pool_ptr, + counter_ptr, + num_contexts, + num_gens, + accepted_stride, + frac, + K: tl.constexpr, + FORCE: tl.constexpr, + BASE_TOTAL: tl.constexpr, + MAX_TOTAL: tl.constexpr, + COUNTER_STRIDE: tl.constexpr, + SLOT_STRIDE: tl.constexpr, + POOL_MASK: tl.constexpr, + BLOCK_B: tl.constexpr, + BLOCK_K: tl.constexpr, +): + _strict_accept_rows( + target_ptr, + draft_ptr, + accepted_ptr, + num_accepted_ptr, + pool_ptr, + counter_ptr, + num_contexts, + num_gens, + accepted_stride, + frac, + K, + FORCE, + BASE_TOTAL, + MAX_TOTAL, + COUNTER_STRIDE, + SLOT_STRIDE, + POOL_MASK, + BLOCK_B, + BLOCK_K, + ) + + +@triton.jit( + do_not_specialize=[ + "m", + "v_shard", + "stride_m", + "rank", + "vocab_offset", + "vocab_full", + "greedy_threshold", + "num_contexts", + "num_gens", + "accepted_stride", + "frac", + "split", + ] +) +def _sample_accept_kernel( + logits_ptr, + stride_m, + v_shard, + tok_out_ptr, + scratch_ptr, + ticket_ptr, + state_ptr, + peers_ptr, + temp_ptr, + seed_ptr, + m, + rank, + vocab_offset, + vocab_full, + greedy_threshold, + draft_ptr, + accepted_ptr, + num_accepted_ptr, + pool_ptr, + counter_ptr, + num_contexts, + num_gens, + accepted_stride, + frac, + split, + BLOCK_V: tl.constexpr, + NRANKS: tl.constexpr, + WORDS: tl.constexpr, + BLOCK_M: tl.constexpr, + WAIT: tl.constexpr, + K: tl.constexpr, + FORCE: tl.constexpr, + BASE_TOTAL: tl.constexpr, + MAX_TOTAL: tl.constexpr, + COUNTER_STRIDE: tl.constexpr, + SLOT_STRIDE: tl.constexpr, + POOL_MASK: tl.constexpr, + BLOCK_B: tl.constexpr, + BLOCK_K: tl.constexpr, +): + """The four-draws Gumbel sample of the TP key exchange (``argmax_logits``) drawn from seed + 1; the + program that takes the last ticket stores seed + 1 after the exchange and runs the strict acceptance on + the tokens it wrote. Every program reads the seed before it takes its ticket. ``split`` (programs per row, + ``ll_exchange._fast_gumbel_split``) follows the row count, so it is a runtime argument: one compiled kernel serves + every split.""" + pv = tl.load(peers_ptr + tl.arange(0, NRANKS)) # host-written table: ahead of the wait + if WAIT: + gdc_wait_with_memory_clobber() + pid = tl.program_id(0) + row = pid // split + key = fast_gumbel_key( + logits_ptr, + stride_m, + v_shard, + temp_ptr, + seed_ptr, + row, + pid % split, + vocab_offset, + vocab_full, + greedy_threshold, + split, + BLOCK_V, + 1, + ) + last = argmax_exchange_finish( + key, + row, + m, + tok_out_ptr, + tok_out_ptr, + scratch_ptr, + ticket_ptr, + state_ptr, + pv, + rank, + split, + NRANKS, + WORDS, + BLOCK_M, + False, + True, + ) + if last: + tl.store(seed_ptr, tl.load(seed_ptr) + 1) + tl.debug_barrier() # the exchange's token stores are visible to every thread of this program + _strict_accept_rows( + tok_out_ptr, + draft_ptr, + accepted_ptr, + num_accepted_ptr, + pool_ptr, + counter_ptr, + num_contexts, + num_gens, + accepted_stride, + frac, + K, + FORCE, + BASE_TOTAL, + MAX_TOTAL, + COUNTER_STRIDE, + SLOT_STRIDE, + POOL_MASK, + BLOCK_B, + BLOCK_K, + ) + + +def _force_mode(force: Optional[tuple], k: int, num_accepted: torch.Tensor) -> tuple: + """(mode, base_total, max_total, frac, pool, counter, counter_stride, slot_stride, pool_mask) of + ``_strict_accept_rows`` for ``force`` (None: natural acceptance).""" + if force is None: + return 0, 1, k + 1, 0.0, num_accepted, num_accepted, 1, 1, 1 + base_total, max_total, frac, pool, counter, c_stride, s_stride, pool_size = force + mode = 2 if (frac > 0.0 and base_total < max_total) else 1 + if pool is None: + pool = counter = num_accepted # unused in mode 1 + return mode, base_total, max_total, frac, pool, counter, c_stride, s_stride, pool_size - 1 + + +def sample_and_strict_accept( + exchange: TPKeyExchange, + logits: torch.Tensor, + vocab_offset: int, + temperature: torch.Tensor, + seed: torch.Tensor, + greedy_threshold: float, + draft_tokens: torch.Tensor, + num_contexts: int, + batch_size: int, + force: Optional[tuple] = None, + channel: int = 1, +) -> Optional[tuple]: + """``seed += 1``, ``exchange.argmax_logits(logits, ..., seed=seed)`` (four-draws Gumbel) and + ``fused_strict_accept`` of its tokens in one launch, with the same outputs: ``(accepted_tokens, + num_accepted_tokens)``, or None where the shapes do not fit (the caller keeps the three launches). + ``exchange``: a ``TPKeyExchange`` with ``fast_gumbel``; ``logits`` [M, V_shard] this rank's shard.""" + k = draft_tokens.shape[-1] + num_gens = batch_size - num_contexts + m = logits.shape[0] if logits.dim() == 2 else 0 + v_shard = logits.shape[-1] + if ( + not exchange.fast_gumbel + or logits.dim() != 2 + or logits.stride(-1) != 1 + or v_shard % 4 + or vocab_offset % 4 + or not 1 <= m <= exchange.MAX_ROWS + or k + 1 > MAX_DRAFT_LEN + 1 + or num_gens < 0 + or m != num_contexts + num_gens * (k + 1) + or temperature.numel() != m + or seed.dtype != torch.int64 + or seed.numel() != 1 + ): + return None + (grid, split, block_v, scratch, ticket, state, peers, rank, nranks, words, block_m, pdl) = ( + exchange.fast_gumbel_launch(m, v_shard, channel) + ) + device = logits.device + tokens = torch.empty(m, dtype=torch.int32, device=device) + accepted = torch.empty((batch_size, k + 1), dtype=torch.int32, device=device) + num_accepted = torch.empty((batch_size,), dtype=torch.int32, device=device) + mode, base_total, max_total, frac, pool, counter, c_stride, s_stride, pool_mask = _force_mode( + force, k, num_accepted + ) + _sample_accept_kernel[(grid,)]( + logits, + logits.stride(0), + v_shard, + tokens, + scratch, + ticket, + state, + peers, + temperature.reshape(-1), + seed, + m, + rank, + vocab_offset, + v_shard * nranks, + float(greedy_threshold), + draft_tokens.contiguous() if num_gens > 0 else num_accepted, + accepted, + num_accepted, + pool, + counter, + num_contexts, + num_gens, + accepted.stride(0), + float(frac), + split=split, + BLOCK_V=block_v, + NRANKS=nranks, + WORDS=words, + BLOCK_M=block_m, + WAIT=pdl, + K=k, + FORCE=mode, + BASE_TOTAL=int(base_total), + MAX_TOTAL=int(max_total), + COUNTER_STRIDE=int(c_stride), + SLOT_STRIDE=int(s_stride), + POOL_MASK=int(pool_mask), + # The acceptance tile follows the batch (16 / 32 / 64 rows; it loops over row blocks above 64): one compile + # per tile size, the first time an eager step lands in it. Not one 64-row tile for every batch: the tile + # sizes this one-launch kernel's registers, so its captured decode steps keep their smaller variants. + BLOCK_B=max(16, min(64, triton.next_power_of_2(max(num_gens, num_contexts, 1)))), + BLOCK_K=max(8, triton.next_power_of_2(k + 1)), + num_warps=4, + launch_pdl=pdl, + ) + return accepted, num_accepted + + def fused_strict_accept( target_tokens: torch.Tensor, draft_tokens: torch.Tensor, @@ -129,16 +411,9 @@ def fused_strict_accept( device = target_tokens.device accepted = torch.empty((batch_size, k + 1), dtype=torch.int32, device=device) num_accepted = torch.empty((batch_size,), dtype=torch.int32, device=device) - if force is None: - mode, base_total, max_total, frac = 0, 1, k + 1, 0.0 - pool = counter = num_accepted # unused - c_stride = s_stride = pool_mask = 1 - else: - base_total, max_total, frac, pool, counter, c_stride, s_stride, pool_size = force - mode = 2 if (frac > 0.0 and base_total < max_total) else 1 - if pool is None: - pool = counter = num_accepted # unused in mode 1 - pool_mask = pool_size - 1 + mode, base_total, max_total, frac, pool, counter, c_stride, s_stride, pool_mask = _force_mode( + force, k, num_accepted + ) draft = draft_tokens.contiguous() if num_gens > 0 else num_accepted # One tile for every batch: the kernel loops over row blocks. block_b = 64 @@ -194,6 +469,7 @@ def _step0_epilogue_kernel( BLOCK_C: tl.constexpr, BLOCK_H: tl.constexpr, LAST: tl.constexpr, + COPY_HID: tl.constexpr, ): """One program per request ``i`` (every write is to row ``i`` only; ``seq_lens_ptr`` is never written).""" i = tl.program_id(0) @@ -213,10 +489,11 @@ def _step0_epilogue_kernel( ) dkv = tl.where(is_ctx, 1, acc - K) tl.store(ids_out_ptr + i, gid) - h = tl.arange(0, BLOCK_H) - hm = h < H - v = tl.load(hid_ptr + gid * hid_stride + h, mask=hm) - tl.store(hid_out_ptr + i.to(tl.int64) * H + h, v, mask=hm) + if COPY_HID: + h = tl.arange(0, BLOCK_H) + hm = h < H + v = tl.load(hid_ptr + gid * hid_stride + h, mask=hm) + tl.store(hid_out_ptr + i.to(tl.int64) * H + h, v, mask=hm) for r in tl.static_range(R): p = tl.load(pos_ptr + r * pos_row_stride + gid) for j in tl.static_range(1, K): @@ -262,11 +539,13 @@ def step0_epilogue( num_ctx_tokens: int, accepted_tokens: Optional[torch.Tensor] = None, last_out: Optional[torch.Tensor] = None, + hidden_compact: bool = False, ) -> Optional[Step0Epilogue]: """``seq_lens`` must not alias ``seq_lens_out`` (read the pre-draft-loop copy). With ``accepted_tokens`` ``[b, >= draft_len + 1]`` and ``last_out`` (contiguous ``[b]``), also ``last_out[i] = - accepted_tokens[i, num_accepted[i] - 1]``. Returns None when the shapes are not supported (caller keeps the - stock path).""" + accepted_tokens[i, num_accepted[i] - 1]``. ``hidden_compact``: ``hidden_states`` already holds each request's + row (the draft layer computed only those, speculative/kept_rows.py) and is the step's hidden rows as it is. + Returns None when the shapes are not supported (caller keeps the stock path).""" if ( seq_lens.data_ptr() == seq_lens_out.data_ptr() or hidden_states.dim() != 2 @@ -275,6 +554,7 @@ def step0_epilogue( or batch_size < 1 or batch_size > 1024 or draft_len < 1 + or (hidden_compact and hidden_states.shape[0] != batch_size) ): return None pos2 = position_ids.reshape(-1, position_ids.shape[-1]) @@ -284,7 +564,11 @@ def step0_epilogue( h = hidden_states.shape[1] dev = hidden_states.device ids = torch.empty((batch_size,), dtype=torch.int64, device=dev) - hid = torch.empty((batch_size, h), dtype=hidden_states.dtype, device=dev) + hid = ( + hidden_states + if hidden_compact + else torch.empty((batch_size, h), dtype=hidden_states.dtype, device=dev) + ) pos_all = torch.empty( (max(draft_len - 1, 1), rows, batch_size), dtype=position_ids.dtype, device=dev ) @@ -320,6 +604,7 @@ def step0_epilogue( BLOCK_C=64, BLOCK_H=triton.next_power_of_2(h), LAST=last, + COPY_HID=not hidden_compact, num_warps=4, ) return Step0Epilogue(ids, hid, pos_all, tuple(position_ids.shape[:-1])) @@ -328,6 +613,7 @@ def step0_epilogue( __all__ = [ "MAX_DRAFT_LEN", "fused_strict_accept", + "sample_and_strict_accept", "step0_epilogue", "Step0Epilogue", ] diff --git a/tensorrt_llm/_torch/speculative/interface.py b/tensorrt_llm/_torch/speculative/interface.py index 6b441aa5311a..b39ab5524b4b 100644 --- a/tensorrt_llm/_torch/speculative/interface.py +++ b/tensorrt_llm/_torch/speculative/interface.py @@ -51,7 +51,8 @@ from ..pyexecutor.sampler.ops import flashinfer as flashinfer_sampling from ..pyexecutor.sampler.ops.vanilla import greedy_search_sampling_batch from ..pyexecutor.sampler.watermark import WatermarkSpecState -from .fused_accept import MAX_DRAFT_LEN, fused_strict_accept +from .fused_accept import (MAX_DRAFT_LEN, fused_strict_accept, + sample_and_strict_accept) from .greedy_argmax import greedy_argmax from .spec_tail_kernels import strict_accept from .vocab_parallel import VocabParallelHead, VocabShardedLogits @@ -970,9 +971,11 @@ def _take_rng_window_offsets(self, requests: list["LlmRequest"], return offsets def _populate_request_rng_state( - self, requests: list["LlmRequest"], - per_request_normalized: list[tuple[float, int, float, float, - int]]) -> None: + self, + requests: list["LlmRequest"], + per_request_normalized: list[tuple[float, int, float, float, int]], + defer_rows: Optional[int] = None + ) -> Optional[tuple[list[int], list[int]]]: """Fill the Philox seed/offset buffers for this batch. A request's seed is fixed for its lifetime, so the offset is what has @@ -1005,14 +1008,7 @@ def _populate_request_rng_state( request_offsets = self._take_rng_window_offsets( requests, [seed is not None for seed in user_seeds]) num_tokens_per_request = [n for *_, n in per_request_normalized] - - flat_seeds: list[int] = [] - flat_offsets: list[int] = [] - for seed, offset, num_tokens in zip(request_seeds, request_offsets, - num_tokens_per_request): - flat_seeds.extend(seed for _ in range(num_tokens)) - flat_offsets.extend(offset + row * _RNG_SLOT_SPAN - for row in range(num_tokens)) + total_rows = sum(num_tokens_per_request) # A batch wider than the buffers would silently truncate the copies # below, so assert rather than grow: CUDA graph batch sizes are already @@ -1030,11 +1026,11 @@ def _populate_request_rng_state( self.request_offsets = torch.zeros(self.max_num_requests, dtype=torch.int64, device='cuda') - if self.seeds is None or self.seeds.numel() < len(flat_seeds): + if self.seeds is None or self.seeds.numel() < total_rows: # Match the per-token buffers' capacity so a later batch with more # rows does not reallocate mid-stream. capacity = max( - len(flat_seeds), + total_rows, self.temperatures.numel() if self.temperatures is not None else 0) self.seeds = torch.zeros(capacity, dtype=torch.int64, device='cuda') @@ -1059,7 +1055,21 @@ def _upload(dst: torch.Tensor, values: list[int]) -> None: # still uploads: a target head the worker cannot shard (vocab padding) # samples it on the stock path, which reads them. if self.is_all_greedy_sample: - return + return None + if (defer_rows is not None and num_tokens_per_request + and all(n == defer_rows for n in num_tokens_per_request)): + # The steady MTP stager writes the four buffers from these values in + # its one kernel: request_* as given, and row j of request r as + # (seed_r, offset_r + j * _RNG_SLOT_SPAN), the expansion below. + return request_seeds, request_offsets + + flat_seeds: list[int] = [] + flat_offsets: list[int] = [] + for seed, offset, num_tokens in zip(request_seeds, request_offsets, + num_tokens_per_request): + flat_seeds.extend(seed for _ in range(num_tokens)) + flat_offsets.extend(offset + row * _RNG_SLOT_SPAN + for row in range(num_tokens)) _upload(self.request_seeds, request_seeds) _upload(self.request_offsets, request_offsets) _upload(self.seeds, flat_seeds) @@ -1618,16 +1628,30 @@ def update_is_all_greedy_sample(self, requests: list["LlmRequest"]) -> None: self._scan_one_model_sampling(requests) def populate_sampling_params_for_one_model( - self, requests: list["LlmRequest"]) -> None: + self, + requests: list["LlmRequest"], + defer_rng_rows: Optional[int] = None + ) -> Optional[tuple[list[int], list[int]]]: """ Set up topp/topk/temperatures for 1-model sampler. Scans sampling configs to set skip_*/is_all_greedy_sample flags. When any request needs sampling, also builds per-token/per-request lists and copies them to GPU buffers; all-greedy batches skip this entirely. + + Args: + requests: The batch's requests. + defer_rng_rows: The logits rows per request of a caller that writes + the Philox buffers itself (the steady MTP stager). When every + request has that many rows, their values are returned instead + of uploaded. + + Returns: + The deferred Philox state, (request_seeds, request_offsets) in batch + order, or None when the buffers were uploaded or not needed. """ if not self.spec_dec_mode.use_one_engine(): - return + return None # Allocate the rejection buffers before copying py_seq_slot values into # batch_slot_ids below; this runs earlier than prepare() in the @@ -1685,7 +1709,8 @@ def populate_sampling_params_for_one_model( dtype=torch.float32, device='cuda') - self._populate_request_rng_state(requests, per_request_normalized) + deferred_rng_state = self._populate_request_rng_state( + requests, per_request_normalized, defer_rng_rows) # Always-populate the per-request slot id table when rejection sampling # is configured: it's tiny (max_num_requests longs) and needed at @@ -1711,7 +1736,7 @@ def populate_sampling_params_for_one_model( # is also bypassed for all-greedy), so the per-token buffers are never # read. Skip the heavier H->D copies. if self.is_all_greedy_sample: - return + return deferred_rng_state # Phase 2: build per-token / per-request lists and copy to GPU. # @@ -1724,7 +1749,7 @@ def populate_sampling_params_for_one_model( fill_min_p = self.advanced_sampling_mode.is_fused if not (need_update_sampler_param or need_update_expanded_sampler_param): - return + return deferred_rng_state if need_update_sampler_param: request_temperatures: list[float] = [] @@ -1798,6 +1823,7 @@ def populate_sampling_params_for_one_model( self.min_ps[:len(min_ps)].copy_(torch.tensor( min_ps, dtype=torch.float32, pin_memory=prefer_pinned()), non_blocking=True) + return deferred_rng_state def _sampling_params_buffers_need_update( self, per_request_normalized: list[tuple[float, int, float, float, int]] @@ -1950,6 +1976,11 @@ class SpecWorkerBase(nn.Module, ABC): Provides common functionality for sampling and token handling. """ + # Declared by the model: a temperature verify step on the key exchange's + # four-draws Gumbel noise bumps the seed, samples and accepts in one launch + # (fused_accept.sample_and_strict_accept; same outputs). + fused_sample_accept: bool = False + def __init__(self, use_separate_draft_kv_cache: bool = False, key_exchange=None): @@ -2379,6 +2410,41 @@ def _fused_force_params(self, runtime_draft_len: int, spec_metadata, _FORCE_ACCEPT_RNG_COUNTER_STRIDE, _FORCE_ACCEPT_RNG_SLOT_STRIDE, _FORCE_ACCEPT_RNG_POOL_SIZE) + def _sample_and_accept_in_one_launch( + self, logits: torch.Tensor, draft_tokens: torch.Tensor, + num_contexts: int, batch_size: int, + spec_metadata: "SpecMetadata") -> Optional[tuple]: + """The sharded temperature sample (``_sample_sharded_temperature``) + and the strict acceptance below as one launch, or None where the + launches below run: another sampling mode, a ragged verify, the eager + warmup of a forced run, a shape the launch does not take, watermarking.""" + if (spec_metadata is None or spec_metadata.is_ragged_verify + or _watermark_active(spec_metadata) + or not isinstance(logits, torch.Tensor) + or spec_metadata.is_all_greedy_sample + or not spec_metadata.sharded_target_logits + or self.key_exchange is None or self._gumbel_seed is None + or draft_tokens.shape[-1] > MAX_DRAFT_LEN): + return None + force = self._fused_force_params(draft_tokens.shape[-1], spec_metadata, + logits.device) + if force is None and self.force_num_accepted_tokens != 0.0: + return None + from ..pyexecutor.sampler.ops.vanilla import \ + GREEDY_TEMPERATURE_THRESHOLD + return sample_and_strict_accept( + self.key_exchange, + logits, + self.mapping.tp_rank * logits.shape[-1], + spec_metadata.temperatures[:logits.shape[0]], + self._gumbel_seed, + GREEDY_TEMPERATURE_THRESHOLD, + draft_tokens, + num_contexts, + batch_size, + force, + channel=1) + def _sample_and_accept_draft_tokens_base( self, logits: torch.Tensor, @@ -2414,6 +2480,12 @@ def _sample_and_accept_draft_tokens_base( if isinstance(logits, torch.Tensor) and logits.dim() == 1: logits = logits.unsqueeze(0) + if self.fused_sample_accept: + fused = self._sample_and_accept_in_one_launch( + logits, draft_tokens, num_contexts, batch_size, spec_metadata) + if fused is not None: + return fused + # Sample tokens using per-request sampling parameters if _watermark_active(spec_metadata): target_tokens, watermark_plans = self._sample_tokens_and_watermark_plans( @@ -3303,7 +3375,8 @@ def _get_draft_tokens_from_gathered(self, gathered): def greedy_sample_draft_with_tp_gather(self, logits: torch.Tensor, spec_metadata=None, - mapping_lm_head_tp=None): + mapping_lm_head_tp=None, + tokens_out=None): """Greedy draft-token sampling with a TP all-gather of the argmax. When the draft LM head is vocab-sharded under plain tensor parallelism, @@ -3314,6 +3387,13 @@ def greedy_sample_draft_with_tp_gather(self, gathered full-vocab draft head. Returns tokens in draft-vocab space (the caller applies d2t). Expects 2D ``[num_tokens, vocab_shard]`` logits. + ``tokens_out`` (int32 ``[num_tokens]``, optional, not with + ``mapping_lm_head_tp``): the tokens are written there and it is + returned (the one-launch LL exchange writes it directly). Overrides + take the same parameters (``sample_draft_tokens`` passes + ``tokens_out`` by keyword, only when it has one) and return + ``tokens_out`` when given; see ``_tokens_into``. + Under ADP + LM-head TP (``mapping_lm_head_tp`` given) the logits are the LM-head-TP group's row-stacked batch (``tp_size`` segments of ``max_num_requests`` padded rows, all-gathered along dim 0 by the MTP @@ -3348,25 +3428,38 @@ def greedy_sample_draft_with_tp_gather(self, return exchange.argmax_logits(logits, mapping.tp_rank * logits.shape[-1], + tokens_out=tokens_out, channel=0) local_max, local_argmax = torch.max(logits, dim=-1) return exchange.argmax_tokens(local_max, local_argmax, mapping.tp_rank * logits.shape[-1], + tokens_out=tokens_out, channel=0) from ..distributed.ops import allgather combined = self._get_local_max_and_combined(logits) gathered = allgather(combined, mapping, dim=-1) - return self._get_draft_tokens_from_gathered(gathered) + return self._tokens_into( + self._get_draft_tokens_from_gathered(gathered), tokens_out) # No cross-rank gather for plain attention-DP: each rank owns its own # requests with replicated full-vocab logits, so a per-rank argmax is # the correct proposal and a gather would desync the ranks (see # _draft_logits_are_sharded). Plain argmax; caller applies d2t. - return greedy_argmax(logits, - torch.int32, - small_rows=spec_metadata is not None - and spec_metadata.is_cuda_graph) + return self._tokens_into( + greedy_argmax(logits, + torch.int32, + small_rows=spec_metadata is not None + and spec_metadata.is_cuda_graph), tokens_out) + + @staticmethod + def _tokens_into(tokens: torch.Tensor, + tokens_out: Optional[torch.Tensor]) -> torch.Tensor: + """``tokens``, or ``tokens_out`` holding them when given.""" + if tokens_out is None: + return tokens + tokens_out.copy_(tokens) + return tokens_out def _watermark_draft_step(self, spec_metadata: "SpecMetadata", batch_size: int, draft_step: int, @@ -3518,7 +3611,8 @@ def sample_draft_tokens(self, *, num_contexts=0, draft_step=None, - mapping_lm_head_tp=None): + mapping_lm_head_tp=None, + out=None): """Unified draft-token production entry for all one-model workers. Branches by logits rank: 3D ``[num_gens, K, vocab]`` is the block form @@ -3534,6 +3628,10 @@ def sample_draft_tokens(self, down to the gen segment. The step form receives full-batch logits (context requests draft from target hidden states already available), so no slicing is needed. + + ``out`` (int32 ``[num_tokens]``, optional, step form): the tokens are + written there and ``out`` is returned; the greedy sampler writes it + directly when there is no d2t map or LM-head TP gather. """ is_block = logits.dim() == 3 @@ -3547,6 +3645,7 @@ def sample_draft_tokens(self, # matches sglang/vLLM, which draft with argmax/top-k by default and apply # sampling params only on the target/acceptance side. advanced = spec_metadata.wants_advanced_draft_sampling + tokens_out = None # All samplers below return tokens in draft-vocab space; d2t is applied # once after the branch. @@ -3554,9 +3653,24 @@ def sample_draft_tokens(self, # greedy_sample_draft_with_tp_gather expects 2D [tokens, vocab]; # flatten the block form and restore its shape (step form is 2D). batch_shape = logits.shape[:-1] - tokens = self.greedy_sample_draft_with_tp_gather( - logits.reshape(-1, logits.shape[-1]), spec_metadata, - mapping_lm_head_tp) + if (out is not None and not is_block and self._d2t is None + and mapping_lm_head_tp is None and out.dtype == torch.int32 + and out.is_contiguous() and out.numel() == logits.shape[0]): + tokens_out = out + flat_logits = logits.reshape(-1, logits.shape[-1]) + if tokens_out is None: + tokens = self.greedy_sample_draft_with_tp_gather( + flat_logits, spec_metadata, mapping_lm_head_tp) + else: + tokens = self.greedy_sample_draft_with_tp_gather( + flat_logits, + spec_metadata, + mapping_lm_head_tp, + tokens_out=tokens_out) + # The contract is that the sampler returns tokens_out; hold + # an override that returned its own tensor to it. + if tokens is not tokens_out: + tokens = self._tokens_into(tokens.reshape(-1), tokens_out) if mapping_lm_head_tp is None: tokens = tokens.reshape(batch_shape) # else: ADP+LM-head-TP (2D step form only) -- the sampler returned @@ -3582,7 +3696,11 @@ def sample_draft_tokens(self, if self._d2t is not None: tokens = self._d2t[tokens] + tokens - return tokens.type(torch.int32) + tokens = tokens.type(torch.int32) + if out is not None and tokens_out is None: + out.copy_(tokens) + return out + return tokens def _execute_guided_decoder_if_present(self, logits): """Execute the guided decoder on the target logits, if configured. diff --git a/tensorrt_llm/_torch/speculative/kept_rows.py b/tensorrt_llm/_torch/speculative/kept_rows.py new file mode 100644 index 000000000000..71fded9c9c24 --- /dev/null +++ b/tensorrt_llm/_torch/speculative/kept_rows.py @@ -0,0 +1,150 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""The rows an MTP-Eagle draft loop keeps from its first pass, known before that pass. + +Pass 0 runs the draft layer over every row of the step (a context request's chunk, a generation request's 1 + k +verified tokens); the loop then keeps one row per request for the LM head and the next pass: a context request's last +row, a generation request's last accepted row. The other rows matter only through the K / V their attention appends. +A draft layer handed :class:`DraftKeptRows` runs attention on every row as before and its MLP (and what follows it) +on the kept rows only. +""" + +from typing import List, NamedTuple, Optional, Tuple + +import torch +import triton +import triton.language as tl + + +class DraftKeptRows(NamedTuple): + """``ids``: int64 [b], the row each request keeps (the loop's step-0 gather ids). ``all_rank_counts``: under + attention DP, every rank's kept-row count (the MoE's collectives take them); None with TP attention. + ``compact``: the layer returns only the kept rows, in ``ids`` order, instead of scattering them back.""" + + ids: torch.Tensor + all_rank_counts: Optional[List[int]] + compact: bool + + +def generation_only_on_every_rank( + num_contexts: int, + all_rank_num_seqs: Optional[List[int]], + all_rank_num_gens: Optional[List[int]], +) -> bool: + """Whether pass 0 may take kept rows: every rank's MoE collectives then run on every rank's kept-row count, so + under attention DP (per-rank counts given) no rank may hold a context request; else this rank's batch decides.""" + if all_rank_num_seqs is None: + return num_contexts == 0 + return all_rank_num_gens is not None and list(all_rank_num_gens) == list(all_rank_num_seqs) + + +# Batch counts are not specialized: an eager step at a new batch size reuses the kernel compiled for its BLOCK (one +# compile per power of two of the batch, from 16; one tile holds the whole batch for the cumsum). +@triton.jit(do_not_specialize=["num_contexts", "num_gens", "num_ctx_tokens"]) +def _kept_row_ids_kernel( + seq_lens_ptr, + batch_idx_ptr, + num_accepted_ptr, + out_ptr, + num_contexts, + num_gens, + num_ctx_tokens, + K1: tl.constexpr, + BLOCK: tl.constexpr, +): + i = tl.arange(0, BLOCK) + is_ctx = i < num_contexts + g = i - num_contexts + is_gen = (i >= num_contexts) & (g < num_gens) + lens = tl.load(seq_lens_ptr + i, mask=is_ctx, other=0).to(tl.int64) + last_ctx = tl.cumsum(lens, axis=0) - 1 + bi = tl.load(batch_idx_ptr + g, mask=is_gen, other=0).to(tl.int64) + acc = tl.load(num_accepted_ptr + i, mask=is_gen, other=0).to(tl.int64) + ids = tl.where(is_ctx, last_ctx, bi * K1 + acc - 1 + num_ctx_tokens) + tl.store(out_ptr + i, ids, mask=is_ctx | is_gen) + + +def kept_row_ids( + seq_lens: torch.Tensor, + batch_indices: torch.Tensor, + num_accepted: torch.Tensor, + num_contexts: int, + num_gens: int, + draft_len: int, + num_ctx_tokens: int, +) -> torch.Tensor: + """The draft loop's step-0 gather ids in one launch: contexts ``cumsum(seq_lens)[i] - 1``, generation requests + ``batch_indices[g] * (draft_len + 1) + num_accepted[i] - 1 + num_ctx_tokens`` (int64).""" + n = num_contexts + num_gens + out = torch.empty((n,), dtype=torch.int64, device=num_accepted.device) + if n: + _kept_row_ids_kernel[(1,)]( + seq_lens, + batch_indices, + num_accepted, + out, + num_contexts, + num_gens, + num_ctx_tokens, + K1=draft_len + 1, + BLOCK=max(16, triton.next_power_of_2(n)), + num_warps=1, + ) + return out + + +@triton.jit(do_not_specialize=["a_stride", "b_stride"]) +def _gather_rows2_kernel( + a_ptr, + b_ptr, + ids_ptr, + a_out_ptr, + b_out_ptr, + a_stride, + b_stride, + H: tl.constexpr, + BLOCK: tl.constexpr, +): + r = tl.program_id(0) + cols = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK) + ok = cols < H + src = tl.load(ids_ptr + r).to(tl.int64) + tl.store( + a_out_ptr + r.to(tl.int64) * H + cols, + tl.load(a_ptr + src * a_stride + cols, mask=ok), + mask=ok, + ) + tl.store( + b_out_ptr + r.to(tl.int64) * H + cols, + tl.load(b_ptr + src * b_stride + cols, mask=ok), + mask=ok, + ) + + +def gather_rows2( + a: torch.Tensor, b: torch.Tensor, ids: torch.Tensor +) -> Tuple[torch.Tensor, torch.Tensor]: + """``(a.index_select(0, ids), b.index_select(0, ids))``, in one launch for 2-D tensors of one width and dtype + with unit column stride.""" + if ( + a.dim() != 2 + or b.dim() != 2 + or a.shape[1] != b.shape[1] + or a.dtype != b.dtype + or a.stride(1) != 1 + or b.stride(1) != 1 + or ids.dim() != 1 + ): + return a.index_select(0, ids), b.index_select(0, ids) + n, h = ids.numel(), a.shape[1] + a_out = torch.empty((n, h), dtype=a.dtype, device=a.device) + b_out = torch.empty((n, h), dtype=b.dtype, device=b.device) + if n: + block = min(1024, triton.next_power_of_2(h)) + _gather_rows2_kernel[(n, triton.cdiv(h, block))]( + a, b, ids, a_out, b_out, a.stride(0), b.stride(0), H=h, BLOCK=block, num_warps=4 + ) + return a_out, b_out + + +__all__ = ["DraftKeptRows", "gather_rows2", "generation_only_on_every_rank", "kept_row_ids"] diff --git a/tensorrt_llm/_torch/utils.py b/tensorrt_llm/_torch/utils.py index 7cfa0b8ad141..8ec836517a99 100644 --- a/tensorrt_llm/_torch/utils.py +++ b/tensorrt_llm/_torch/utils.py @@ -35,6 +35,7 @@ 'MlaIndexerAux', 'MlaCompressor', 'MoeSharedGate', + 'MoeExpertPrefetch', ] AuxStreamType = Enum( 'AuxStreamType', diff --git a/tensorrt_llm/functional.py b/tensorrt_llm/functional.py index e5c94b57e684..a0d079f1ba59 100644 --- a/tensorrt_llm/functional.py +++ b/tensorrt_llm/functional.py @@ -146,6 +146,7 @@ def __init__( enable_allreduce: bool = True, trigger_completion_at_end: bool = True, fp8_payload: bool = False, + l2_prefetch: Optional[Tensor] = None, ): self.strategy = strategy self.fusion_op = fusion_op @@ -161,6 +162,8 @@ def __init__( # Torch MNNVL path only (lossy): two-shot calls fused with a residual RMSNorm exchange E4M3 values # with one FP32 scale per 256 elements instead of BF16 (see MNNVLAllReduce.supports_fp8_payload). self.fp8_payload = fp8_payload + # Torch MNNVL fused-norm path only: a weight the all-reduce kernel pulls into L2 for the GEMM after it. + self.l2_prefetch = l2_prefetch assert fusion_op in (AllReduceFusionOp.NONE.value, AllReduceFusionOp.RMS_NORM.value) or (residual is not None) @@ -193,6 +196,8 @@ def __init__( is_cutlass_min_latency: bool = False, shared_expert_gate: Optional[Tensor] = None, fusion_op: AllReduceFusionOp = AllReduceFusionOp.NONE, + l2_prefetch: Optional[Tensor] = None, + fc2_lamport: bool = False, ): super().__init__( fusion_op=fusion_op, @@ -203,6 +208,7 @@ def __init__( norm_pre_residual_weight=norm_pre_residual_weight, eps=eps, enable_allreduce=enable_allreduce, + l2_prefetch=l2_prefetch, ) self.device_num_experts = device_num_experts self.expert_scale_factor = expert_scale_factor @@ -210,6 +216,9 @@ def __init__( self.shared_expert_output = shared_expert_output # Torch MNNVL path only: logits of the shared-expert gate; the shared output is scaled by their sigmoid. self.shared_expert_gate = shared_expert_gate + # Torch MNNVL fused-norm path only: the un-finalized fc2 rows are in a Lamport FC2 buffer, which the fold + # polls instead of waiting for FC2 (MnnvlAllReduceNorm.__call__). + self.fc2_lamport = fc2_lamport self.is_cutlass_min_latency = is_cutlass_min_latency def is_valid(self): diff --git a/tensorrt_llm/llmapi/disagg_utils.py b/tensorrt_llm/llmapi/disagg_utils.py index 73830645a71b..65cf887460ba 100644 --- a/tensorrt_llm/llmapi/disagg_utils.py +++ b/tensorrt_llm/llmapi/disagg_utils.py @@ -218,6 +218,33 @@ def validate_etcd_options(self) -> None: "require an etcd:// cluster_uri") +# The output-length predictors (serve/output_length_predictor.py implements them). +OutputLengthPredictorName = Literal["ridge", "ridge_gbm"] + + +class OutputLengthPredictionConfig(StrictBaseModel): + """Generation priority from an online prediction of each request's output length. + + After the context phase the orchestrator predicts the reply's length from the + conversation's earlier replies (``conversation_params.conversation_id``) and the + prompt length, never from ``max_tokens``, and sets the generation request's + ``priority`` (higher for shorter replies). The predictor learns online in the + coordinator. Generation servers order by it with + ``scheduler_config.waiting_queue_policy: priority``. Requires + ``schedule_style: context_first``; a request served without a context + phase (conditional disaggregation) gets the prior's priority. + """ + + predictor: OutputLengthPredictorName = Field( + default="ridge", + description=( + "'ridge': a ridge regression on the request's history features, " + "refit every 120 s. 'ridge_gbm': also a gradient-boosted tree " + "ensemble refit every 300 s in a separate process, which needs " + "numpy and scikit-learn in the server's Python environment " + "(checked at startup).")) + + @dataclass class DisaggServerConfig(): server_configs: List[CtxGenServerConfig] @@ -270,6 +297,8 @@ class DisaggServerConfig(): # servers when they expose per-frontend affinity ports: context requests # with a conversation id go to the port of one frontend. ctx_frontend_affinity: Optional[Tuple[int, int]] = None + # Generation priority from the predicted output length; None: off. + output_length_prediction: Optional[OutputLengthPredictionConfig] = None class MetadataServerConfig(StrictBaseModel): @@ -408,6 +437,7 @@ def extract_disagg_cfg( internal_request_auth_key: Optional[str] = None, conversation_affinity_header_for_subagents: Optional[str] = None, subagent_affinity_scope: Literal['context', 'both'] = 'context', + output_length_prediction: Optional[OutputLengthPredictionConfig] = None, **kwargs: Any) -> DisaggServerConfig: context_servers = context_servers or {} generation_servers = generation_servers or {} @@ -448,6 +478,21 @@ def extract_disagg_cfg( gen_router_config = extract_router_config(generation_servers) ctx_router_config.server_role = ServerRole.CONTEXT gen_router_config.server_role = ServerRole.GENERATION + if ctx_router_config.args.get("max_queue_wait_s") is not None: + raise ValueError( + "context_servers.router.max_queue_wait_s is a generation router " + "option (pooled generation dispatch); remove it, or set it on " + "generation_servers.router together with max_requests_per_server") + if (gen_router_config.args.get("max_queue_wait_s") is not None + and gen_router_config.args.get("max_requests_per_server") is None): + raise ValueError("generation_servers.router.max_queue_wait_s needs " + "max_requests_per_server") + if gen_router_config.args.get("max_requests_per_server") is not None: + # The pooled generation router fails a request that waits for a seat past + # the context servers' KV transfer timeout. This is the fallback until the + # context servers report their own value in /server_info. + gen_router_config.args["kv_transfer_timeout_ms"] = ( + _ctx_kv_transfer_timeout_ms(context_servers)) if disagg_cluster: disagg_cluster_config = extract_disagg_cluster_config(disagg_cluster) else: @@ -503,10 +548,28 @@ def extract_disagg_cfg( f"{subagent_affinity_scope!r}") config.subagent_affinity_scope = subagent_affinity_scope config.ctx_frontend_affinity = ctx_frontend_affinity + if output_length_prediction is not None: + config.output_length_prediction = ( + OutputLengthPredictionConfig.model_validate( + output_length_prediction)) + check_output_length_prediction_schedule(config) _warn_if_subagent_affinity_inactive(config) return config +def check_output_length_prediction_schedule(config: DisaggServerConfig) -> None: + """Refuse output_length_prediction with schedule_style generation_first. + + Runs again in OpenAIDisaggregatedService, after the CLI / env override of schedule_style. + """ + if (config.output_length_prediction is not None + and config.schedule_style == "generation_first"): + # The prediction needs the context phase's prompt length; a + # generation_first request reaches its generation server without it. + raise ValueError("output_length_prediction requires schedule_style " + "'context_first'") + + def _warn_if_subagent_affinity_inactive(config: DisaggServerConfig) -> None: """Warn when the configured fleets do not support sub-agent affinity.""" if not config.conversation_affinity_header_for_subagents: @@ -544,6 +607,19 @@ def _router_type(router_config: Optional[RouterConfig]) -> Optional[str]: "router type; sub-agent instance affinity will be inactive there.") +def _ctx_kv_transfer_timeout_ms(context_servers: dict) -> Optional[int]: + """``context_servers.cache_transceiver_config.kv_transfer_timeout_ms``, else its default. + + The pooled generation router prefers the value the context servers report in + ``/server_info`` (their own ``--config``); this one applies until they do. + """ + cfg = context_servers.get("cache_transceiver_config") or {} + if "kv_transfer_timeout_ms" in cfg: + return cfg["kv_transfer_timeout_ms"] + from .llm_args import CacheTransceiverConfig + return CacheTransceiverConfig.model_fields["kv_transfer_timeout_ms"].default + + def extract_ctx_gen_cfgs(type: Literal['ctx', 'gen'], num_instances: int = 1, urls: Optional[List[str]] = None, diff --git a/tensorrt_llm/llmapi/llm_args.py b/tensorrt_llm/llmapi/llm_args.py index 8cb51d8e3b57..d949611c31f6 100644 --- a/tensorrt_llm/llmapi/llm_args.py +++ b/tensorrt_llm/llmapi/llm_args.py @@ -2331,6 +2331,18 @@ class AttentionDpConfig(StrictBaseModel): "Active prompt tokens estimate work, not cached KV residency. Existing " "conversation->rank pins are unaffected. Only used when " "kv_cache_routing_conversation_affinity is True.") + kv_cache_routing_home_wait_rounds: Optional[PositiveInt] = Field( + default=None, + description= + "Conversation-affinity routing: a returning conversation whose home " + "rank is full waits for a slot there for up to this many scheduling " + "rounds in which another rank had room, then overflows by " + "kv_cache_routing_new_conv_placement (keeping its home rank). Later " + "requests of the same admission group (priority) may pass a waiting " + "one on any rank; later groups may pass it on other ranks only, not " + "into its home rank. None overflows at once. Requires " + "kv_cache_routing_conversation_affinity=True.", + status="prototype") @model_validator(mode='after') def validate_attention_dp_config(self) -> 'AttentionDpConfig': @@ -2343,6 +2355,11 @@ def validate_attention_dp_config(self) -> 'AttentionDpConfig': raise ValueError( "attention_dp_config.timeout_iters must be greater or equal to 0 when enable_balance is true" ) + if (self.kv_cache_routing_home_wait_rounds is not None + and not self.kv_cache_routing_conversation_affinity): + raise ValueError( + "attention_dp_config.kv_cache_routing_home_wait_rounds requires " + "kv_cache_routing_conversation_affinity=True") return self @@ -4640,6 +4657,14 @@ def _to_pybind(self): dynamic_batch_moving_average_window) +_PositiveFiniteFloat = Annotated[float, + PydanticField(gt=0, allow_inf_nan=False)] +# Remote cache timeouts become C++ millisecond deadlines; 1e6 s (11.6 days) is +# far past any wait yet far inside their range. +_RemoteTimeoutSeconds = Annotated[ + float, PydanticField(gt=0, le=1e6, allow_inf_nan=False)] + + class GenPreemptionConfig(StrictBaseModel): """GEN slot preemption on a disaggregated generation worker. @@ -4696,6 +4721,17 @@ class SchedulerConfig(StrictBaseModel, PybindMirror): default=WaitingQueuePolicy.FCFS, description="The waiting queue scheduling policy") + waiting_queue_max_wait_s: Optional[_PositiveFiniteFloat] = Field( + default=None, + description=( + "With waiting_queue_policy='priority': a request that has waited " + "this many seconds since it reached the server (in disaggregated " + "serving, the orchestrator) goes ahead of every request that has " + "not, oldest first. None: no cap. Keep it at or below the context " + "servers' cache_transceiver_config.kv_transfer_timeout_ms, whose " + "clock starts later (after prefill)."), + status="prototype") + use_python_scheduler: bool = Field( default=False, description="Use pure-Python scheduler instead of C++ scheduler.") @@ -4733,6 +4769,14 @@ class SchedulerConfig(StrictBaseModel, PybindMirror): "disables it."), status="prototype") + @model_validator(mode="after") + def validate_waiting_queue_max_wait_s(self) -> 'SchedulerConfig': + if (self.waiting_queue_max_wait_s is not None + and self.waiting_queue_policy != WaitingQueuePolicy.PRIORITY): + raise ValueError("scheduler_config.waiting_queue_max_wait_s " + "requires waiting_queue_policy='priority'") + return self + @model_validator(mode="after") def validate_context_starvation_iterations(self) -> 'SchedulerConfig': if (self.context_starvation_iterations is not None @@ -5274,6 +5318,187 @@ class KvPoolRebalanceConfig(StrictBaseModel): "should be attempted.") +# Donors publish host memory in chunks of this many bytes (remote_donor.py). +REMOTE_CACHE_CHUNK_BYTES = 1 << 30 +# Default of RemoteCacheConfig.donor_reserve_size. +REMOTE_CACHE_DONOR_RESERVE_BYTES = 24 << 30 +# One RemoteCacheConfig.ucx_devices entry, stripped: a name without ':' or ',', +# then optionally ':' or ':1' (NIXL's UCX backend uses port 1 of each device). +_UCX_DEVICE_ENTRY = r"\s*[^\s,:][^,:]*(:1?)?\s*" +REMOTE_CACHE_UCX_DEVICES_PATTERN = ( + rf"^{_UCX_DEVICE_ENTRY}(,{_UCX_DEVICE_ENTRY})*$") + + +class RemoteNixlTransportConfig(StrictBaseModel): + """Remote cache transport over one-sided NIXL RDMA.""" + + kind: Literal["nixl"] = Field( + default="nixl", + status="prototype", + description="Selects this transport. Every rank sharing `directory` " + "must use the same transport.") + + ucx_devices: Optional[str] = Field( + default=None, + pattern=REMOTE_CACHE_UCX_DEVICES_PATTERN, + status="prototype", + description= + "Comma-separated UCX devices of the remote level's and the donor's NIXL " + "agents (for example 'mlx5_0:1'), each '' or ':1' " + "(NIXL's UCX backend uses port 1); '{GPU}' is replaced by the rank's " + "physical GPU index. None uses the process's UCX environment.") + + transfer_timeout_s: _RemoteTimeoutSeconds = Field( + default=30.0, + status="prototype", + description= + "Seconds one batch of page transfers of a remote level may take before " + "the level fails, e.g. on a donor that died. At most 1e6.") + + +class RemoteFabricTransportConfig(StrictBaseModel): + """Remote cache transport over CUDA fabric memory. + + Claimants in the same multi-node NVLink domain copy it over NVLink. + """ + + kind: Literal["fabric"] = Field( + status="prototype", + description="Selects this transport. Every rank sharing `directory` " + "must use the same transport.") + + donor_reserve_size: NonNegativeInt = Field( + default=REMOTE_CACHE_DONOR_RESERVE_BYTES, + status="prototype", + description= + "Bytes of free plus reclaimable memory each host NUMA node keeps for " + "the processes on it while a donation is placed. Chunks go to the GPU's " + "node first, then to the others; a donation that does not fit is " + "published short.") + + compact_host_memory: bool = Field( + default=False, + status="prototype", + description= + "Before a node that refuses a donated chunk is left, run up to 64 " + "reclaim-and-compact passes on it (fault in and release node-bound " + "huge pages under a per-node lock that donors on one host take in " + "turn), so fragmented or page-cache-filled memory can still take the " + "donation. False publishes what fits and leaves compaction to the job " + "prolog.") + + +RemoteTransportConfig: TypeAlias = Annotated[ + Union[RemoteNixlTransportConfig, RemoteFabricTransportConfig], + Field(discriminator="kind"), +] + + +class RemoteDonorConfig(StrictBaseModel): + """Host memory this rank donates to remote cache levels.""" + + size: int = Field( + ge=REMOTE_CACHE_CHUNK_BYTES, + status="prototype", + description= + "Bytes donated for the lifetime of the process, in whole 1 GiB chunks " + "(a remainder below one chunk is not donated; the rank logs the size " + "it donates).") + + +class RemoteExpectedDonorsConfig(StrictBaseModel): + """The job's donors and claims, which only the launcher can count.""" + + num_donors: PositiveInt = Field( + status="prototype", + description="Number of donating ranks the job starts.") + + claim_size: PositiveInt = Field( + status="prototype", + description="Bytes all ranks of the job claim from `directory` together." + ) + + +class RemoteLevelConfig(StrictBaseModel): + """This rank's remote cache level, in chunks of donated memory.""" + + size: PositiveInt = Field( + status="prototype", + description= + "Bytes of the level. Pages are stored as the cold tiers store them: " + "byte copies, or encoded by a lossy cold-page codec " + "(kv_cache_compression_config) when one is set. It takes the disk " + "level's place, so it cannot be combined with `disk_cache_size`.") + + pool_ratio: Optional[List[_PositiveFiniteFloat]] = Field( + default=None, + min_length=1, + status="prototype", + description= + "Split of `size` across layer groups, one positive weight per layer " + "group in KV cache manager v2 layer-group ID order (normalized). None " + "follows the hot tier's split.") + + expected: Optional[RemoteExpectedDonorsConfig] = Field( + default=None, + status="prototype", + description= + "With it, the rank waits until these donors have reported and fails " + "at once if they cannot cover the claims, instead of after a claim " + "wait.") + + donor_wait_timeout_s: _RemoteTimeoutSeconds = Field( + default=900.0, + status="prototype", + description= + "Seconds the rank waits for donors, applied to each wait on its own: " + "for the expected donors to report, and for each chunk claim. Donors " + "publish while their own servers start, so this bounds the job's " + "startup skew per wait, not in total. At most 1e6.") + + +class RemoteCacheConfig(StrictBaseModel): + """KV cache manager v2 remote cache level in host memory that other ranks donate. + + A rank with `level` gets a cache level below the host tier whose slots live + in memory that ranks with `donor` publish in `directory`. + """ + + directory: str = Field( + min_length=1, + status="prototype", + description= + "Rendezvous directory, on a file system every rank of the job sees, where " + "donors publish their memory and remote cache levels claim chunks of it. " + "Environment variables are expanded, and one that is not set is an " + "error; the directory is created if missing. Use one directory per job." + ) + + transport: RemoteTransportConfig = Field( + default_factory=RemoteNixlTransportConfig, + status="prototype", + description= + "How pages move: {kind: nixl} (one-sided NIXL RDMA, the default) or " + "{kind: fabric} (CUDA fabric memory copied over NVLink).") + + donor: Optional[RemoteDonorConfig] = Field( + default=None, + status="prototype", + description="This rank's donation; None donates nothing.") + + level: Optional[RemoteLevelConfig] = Field( + default=None, + status="prototype", + description="This rank's remote cache level; None gives it none.") + + @model_validator(mode="after") + def validate_remote_cache(self) -> 'RemoteCacheConfig': + if self.donor is None and self.level is None: + raise ValueError( + "remote_cache_config needs a `donor`, a `level`, or both") + return self + + # Mixed-precision KV dtype: "mixed__". The # first/last tokens and the attention inputs use the second dtype; # the full history is stored in the first. Requires KV cache manager V2. @@ -5338,6 +5563,13 @@ class KvCacheConfig(StrictBaseModel, PybindMirror): description= "Directory used for disk KV cache files. Must be set when `disk_cache_size` is positive." ) + # This is a pure python field, not a pybind field. It is only for the Pytorch backend. + remote_cache_config: Optional[RemoteCacheConfig] = Field( + default=None, + status="prototype", + description= + "KV cache manager v2 remote cache level in host memory that other ranks " + "donate (usually generation ranks to context ranks). None disables it.") cross_kv_cache_fraction: Optional[float] = Field( default=None, description= @@ -5513,6 +5745,19 @@ class KvCacheConfig(StrictBaseModel, PybindMirror): "The maximum utilization of the KV cache for resume. Default is 95%. Only used when using KV cache manager v2 (experimental)." ) + # This is a pure python field, not a pybind field. It is only for the Pytorch backend. + defer_generation_only_release: bool = Field( + default=False, + status="prototype", + description="Release the KV cache of a finished generation-only request " + "(disaggregated generation server) after the next forward is enqueued, " + "so that the host-side release overlaps GPU work. The pages return one " + "iteration later, or as soon as the scheduler runs out of pages, before " + "it suspends or recompute-pauses a running request. Their KV cache events " + "are published one iteration later too, " + "or in the same iteration when the server goes idle. Requires KV cache manager v2 and the overlap scheduler " + "without pipeline parallelism.") + enable_kv_pool_rebalance: bool = Field( default=False, status="prototype", @@ -5791,6 +6036,35 @@ def validate_disk_cache_config(self): ) return self + @model_validator(mode='after') + def validate_remote_cache_config(self) -> 'KvCacheConfig': + remote = self.remote_cache_config + if remote is None: + return self + if self.use_kv_cache_manager_v2 is False: + raise ValueError("kv_cache_config.remote_cache_config requires " + "use_kv_cache_manager_v2") + if remote.level is not None and self.disk_cache_size: + raise ValueError( + "kv_cache_config.remote_cache_config.level and " + "disk_cache_size cannot both be set: the remote level takes the " + "disk level's place") + if remote.level is not None and self.enable_kv_pool_rebalance: + raise ValueError( + "kv_cache_config.remote_cache_config.level and " + "enable_kv_pool_rebalance cannot both be set: a rebalance " + "would claim donor chunks while every request waits") + return self + + @model_validator(mode='after') + def validate_defer_generation_only_release(self) -> 'KvCacheConfig': + if (self.defer_generation_only_release + and self.use_kv_cache_manager_v2 is False): + raise ValueError( + "kv_cache_config.defer_generation_only_release requires " + "kv_cache_config.use_kv_cache_manager_v2=True.") + return self + @model_validator(mode='after') def validate_mamba_snapshot_offsets(self) -> 'KvCacheConfig': state_config = self.mamba_state_config @@ -7884,6 +8158,35 @@ def validate_gen_preemption(self) -> 'TorchLlmArgs': "not support pipeline parallelism or attention DP.") return self + @model_validator(mode="after") + def warn_waiting_queue_max_wait_s(self) -> 'TorchLlmArgs': + scheduler = self.scheduler_config + transceiver = self.cache_transceiver_config + if (scheduler.waiting_queue_max_wait_s is not None + and transceiver is not None + and transceiver.kv_transfer_timeout_ms is not None + and scheduler.waiting_queue_max_wait_s * 1000 + > transceiver.kv_transfer_timeout_ms): + logger.warning( + "scheduler_config.waiting_queue_max_wait_s " + f"({scheduler.waiting_queue_max_wait_s} s) exceeds " + "cache_transceiver_config.kv_transfer_timeout_ms " + f"({transceiver.kv_transfer_timeout_ms} ms): a request passed " + "over that long may find its context server's KV transfer " + "timed out.") + return self + + @model_validator(mode="after") + def validate_defer_generation_only_release(self) -> 'TorchLlmArgs': + if self.kv_cache_config.defer_generation_only_release and ( + self.disable_overlap_scheduler + or self.pipeline_parallel_size > 1): + raise ValueError( + "kv_cache_config.defer_generation_only_release is used only " + "by the overlap scheduler loop, which needs " + "disable_overlap_scheduler=False and pipeline_parallel_size=1.") + return self + @model_validator(mode="after") def validate_encoder_modes(self) -> 'TorchLlmArgs': if self.encode_only and self.mm_encoder_only: diff --git a/tensorrt_llm/runtime/kv_cache_manager_v2/AGENTS.md b/tensorrt_llm/runtime/kv_cache_manager_v2/AGENTS.md index af9c3756b0b1..6965440411dc 100644 --- a/tensorrt_llm/runtime/kv_cache_manager_v2/AGENTS.md +++ b/tensorrt_llm/runtime/kv_cache_manager_v2/AGENTS.md @@ -10,7 +10,7 @@ This file provides guidance to coding agents when working with code in this dire ## What This Is The Python surface of KVCacheManagerV2, the KV cache management subsystem for TensorRT-LLM. -It manages GPU/host/disk memory for key-value caches used during LLM inference, handling page +It manages GPU/host/disk/remote memory for key-value caches used during LLM inference, handling page allocation, eviction, multi-tier caching, radix-tree-based prefix sharing, and disaggregated serving. diff --git a/tensorrt_llm/runtime/kv_cache_manager_v2/__init__.py b/tensorrt_llm/runtime/kv_cache_manager_v2/__init__.py index 0f6cccec8d9e..4a3bd4687cbc 100644 --- a/tensorrt_llm/runtime/kv_cache_manager_v2/__init__.py +++ b/tensorrt_llm/runtime/kv_cache_manager_v2/__init__.py @@ -153,6 +153,10 @@ class _KVCacheManagerConfigFieldSpec: LogicError = _cpp.LogicError OutOfMemoryError = _cpp.OutOfMemoryError OutOfPagesError = _cpp.OutOfPagesError +RemoteMemError = _cpp.RemoteMemError +RemoteCacheTierConfig = _cpp.RemoteCacheTierConfig +RemoteTransferConfig = _cpp.RemoteTransferConfig +RemoteTransport = _cpp.RemoteTransport PageIndexConverter = _cpp.PageIndexConverter PageIndexMode = _cpp.PageIndexMode PageStatus = _cpp.PageStatus @@ -189,7 +193,9 @@ class _KVCacheManagerConfigFieldSpec: BeamIndex = int CacheGroupId = int CacheLevel = int -CacheTierConfig = Union[GpuCacheTierConfig, HostCacheTierConfig, DiskCacheTierConfig] +CacheTierConfig = Union[ + GpuCacheTierConfig, HostCacheTierConfig, DiskCacheTierConfig, RemoteCacheTierConfig +] BatchRow = int CudaStream = int DataRole = str @@ -269,6 +275,10 @@ def typed_range(*args: int) -> range: "MmItemContext", "NDEBUG", "OutOfPagesError", + "RemoteMemError", + "RemoteCacheTierConfig", + "RemoteTransferConfig", + "RemoteTransport", "PageIndexConverter", "PlannedDropHandle", "PoolGroupPeakBlockStats", diff --git a/tensorrt_llm/runtime/kv_cache_manager_v2/__init__.pyi b/tensorrt_llm/runtime/kv_cache_manager_v2/__init__.pyi index 67d9a0de395c..97573230430a 100644 --- a/tensorrt_llm/runtime/kv_cache_manager_v2/__init__.pyi +++ b/tensorrt_llm/runtime/kv_cache_manager_v2/__init__.pyi @@ -67,6 +67,9 @@ class LogicError(Exception): class OutOfPagesError(Exception): ... +class RemoteMemError(Exception): + """A remote cache level failed a transfer or claim; its contents can no longer be trusted.""" + def poison_reason() -> str | None: """First recorded invariant violation, or None. Never clears, so it is safe to poll.""" @@ -80,6 +83,11 @@ class CacheTier(enum.IntEnum): GPU_MEM = 0 HOST_MEM = 1 DISK = 2 + REMOTE = 3 + +class RemoteTransport(enum.Enum): + NIXL = 0 + FABRIC = 1 class PageStatus(enum.Enum): LOCKED = enum.auto() @@ -279,6 +287,26 @@ class DiskCacheTierConfig: def tier(self) -> CacheTier: ... def validate(self) -> None: ... +@dataclass(slots=True) +class RemoteTransferConfig: + """How a remote tier's pages move, apart from the memory it declares.""" + + transport: RemoteTransport = RemoteTransport.NIXL + timeout_ms: int = ... # how long one batch may take before the level fails + backend_params: dict[str, str] = ... # NIXL only: e.g. {"device_list": "mlx5_0"} + +@dataclass(slots=True) +class RemoteCacheTierConfig: + quota: int + path: str # the rendezvous directory + wait_timeout_ms: int = ... + expected_donors: int = 0 # 0: unknown + pool_ratio: list[float] = ... # empty: the hot level's split + transfer: RemoteTransferConfig = ... + @property + def tier(self) -> CacheTier: ... + def validate(self) -> None: ... + @dataclass(slots=True, frozen=True) class BufferConfig: """One buffer of a layer's KV cache. @@ -1881,6 +1909,10 @@ class KVCacheManager: @property def cache_tier_list(self) -> Sequence[CacheTier]: ... @property + def any_remote_level_failed(self) -> bool: + """Whether any remote level failed on this rank (a transfer, or its donor went away). Lock-free.""" + ... + @property def tokens_per_block(self) -> int: ... @property def event_manager(self) -> Any | None: ... diff --git a/tensorrt_llm/runtime/kv_cache_manager_v2/_introspection.py b/tensorrt_llm/runtime/kv_cache_manager_v2/_introspection.py index 76fce4d39b25..5ddb4f198489 100644 --- a/tensorrt_llm/runtime/kv_cache_manager_v2/_introspection.py +++ b/tensorrt_llm/runtime/kv_cache_manager_v2/_introspection.py @@ -246,6 +246,19 @@ def storage_utilization(manager: Any, cache_level: int = 0) -> list[float]: return list(_cpp().storage_utilization(manager, cache_level)) +def remote_unquiesced_transfers(manager: Any) -> int: + """Release the staging of remote transfers that quiesced after their deadline; return how many still have not.""" + return int(_cpp().remote_unquiesced_transfers(manager)) + + +def level_pool_groups(manager: Any, cache_level: int) -> list[tuple[int, int, list[int]]]: + """Return (slot count, bytes per slot, layer-group IDs) for each pool group of a cache level.""" + return [ + (int(slots), int(slot_bytes), list(life_cycles)) + for slots, slot_bytes, life_cycles in _cpp().level_pool_groups(manager, cache_level) + ] + + def sparse_cache_resident_ordinals(kv_cache: Any, lc_id: int) -> list[int]: """Resident unit ordinal per sparse cache entry, laid out [buffer][entry]. diff --git a/tensorrt_llm/schemas/trtllm-serve-config.schema.json b/tensorrt_llm/schemas/trtllm-serve-config.schema.json index aab69f550f50..c04b8b5959d8 100644 --- a/tensorrt_llm/schemas/trtllm-serve-config.schema.json +++ b/tensorrt_llm/schemas/trtllm-serve-config.schema.json @@ -50,6 +50,30 @@ }, "AttentionDpConfig": { "additionalProperties": false, + "allOf": [ + { + "if": { + "properties": { + "kv_cache_routing_home_wait_rounds": { + "type": "integer" + } + }, + "required": [ + "kv_cache_routing_home_wait_rounds" + ] + }, + "then": { + "properties": { + "kv_cache_routing_conversation_affinity": { + "const": true + } + }, + "required": [ + "kv_cache_routing_conversation_affinity" + ] + } + } + ], "description": "Configuration for attention DP.", "properties": { "batching_wait_iters": { @@ -107,6 +131,21 @@ "title": "Kv Cache Routing Fair Share Multiplier", "type": "number" }, + "kv_cache_routing_home_wait_rounds": { + "anyOf": [ + { + "exclusiveMinimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Conversation-affinity routing: a returning conversation whose home rank is full waits for a slot there for up to this many scheduling rounds in which another rank had room, then overflows by kv_cache_routing_new_conv_placement (keeping its home rank). Later requests of the same admission group (priority) may pass a waiting one on any rank; later groups may pass it on other ranks only, not into its home rank. None overflows at once. Requires kv_cache_routing_conversation_affinity=True.", + "status": "prototype", + "title": "Kv Cache Routing Home Wait Rounds" + }, "kv_cache_routing_load_balance_weight": { "default": 1.0, "description": "Weight (beta) for the load-balance term in KV cache-aware routing. Higher values prioritize load balance over cache affinity. Only used when enable_kv_cache_aware_routing is True.", @@ -3079,6 +3118,84 @@ }, "KvCacheConfig": { "additionalProperties": false, + "allOf": [ + { + "if": { + "properties": { + "remote_cache_config": { + "type": "object" + } + }, + "required": [ + "remote_cache_config" + ] + }, + "then": { + "properties": { + "use_kv_cache_manager_v2": { + "not": { + "const": false + } + } + } + } + }, + { + "if": { + "properties": { + "defer_generation_only_release": { + "const": true + } + }, + "required": [ + "defer_generation_only_release" + ] + }, + "then": { + "properties": { + "use_kv_cache_manager_v2": { + "not": { + "const": false + } + } + } + } + }, + { + "if": { + "properties": { + "remote_cache_config": { + "properties": { + "level": { + "type": "object" + } + }, + "required": [ + "level" + ] + } + }, + "required": [ + "remote_cache_config" + ] + }, + "then": { + "properties": { + "disk_cache_size": { + "enum": [ + 0, + null + ] + }, + "enable_kv_pool_rebalance": { + "not": { + "const": true + } + } + } + } + } + ], "description": "Configuration for the KV cache.", "properties": { "attention_dp_events_gather_period_ms": { @@ -3139,6 +3256,13 @@ "description": "The fraction of the KV Cache memory should be reserved for cross attention. If set to p, self attention will use 1-p of KV Cache memory and cross attention will use p of KV Cache memory. Defaults to None (unset); must be set when using an encoder-decoder model and must not be set otherwise.", "title": "Cross Kv Cache Fraction" }, + "defer_generation_only_release": { + "default": false, + "description": "Release the KV cache of a finished generation-only request (disaggregated generation server) after the next forward is enqueued, so that the host-side release overlaps GPU work. The pages return one iteration later, or as soon as the scheduler runs out of pages, before it suspends or recompute-pauses a running request. Their KV cache events are published one iteration later too, or in the same iteration when the server goes idle. Requires KV cache manager v2 and the overlap scheduler without pipeline parallelism.", + "status": "prototype", + "title": "Defer Generation Only Release", + "type": "boolean" + }, "disk_cache_path": { "anyOf": [ { @@ -3432,6 +3556,19 @@ "status": "prototype", "title": "Pool Ratio" }, + "remote_cache_config": { + "anyOf": [ + { + "$ref": "#/$defs/RemoteCacheConfig" + }, + { + "type": "null" + } + ], + "default": null, + "description": "KV cache manager v2 remote cache level in host memory that other ranks donate (usually generation ranks to context ranks). None disables it.", + "status": "prototype" + }, "secondary_offload_min_priority": { "anyOf": [ { @@ -5643,6 +5780,274 @@ "title": "RayPlacementConfig", "type": "object" }, + "RemoteCacheConfig": { + "additionalProperties": false, + "anyOf": [ + { + "properties": { + "donor": { + "type": "object" + } + }, + "required": [ + "donor" + ] + }, + { + "properties": { + "level": { + "type": "object" + } + }, + "required": [ + "level" + ] + } + ], + "description": "KV cache manager v2 remote cache level in host memory that other ranks donate.\n\nA rank with `level` gets a cache level below the host tier whose slots live\nin memory that ranks with `donor` publish in `directory`.", + "properties": { + "directory": { + "description": "Rendezvous directory, on a file system every rank of the job sees, where donors publish their memory and remote cache levels claim chunks of it. Environment variables are expanded, and one that is not set is an error; the directory is created if missing. Use one directory per job.", + "minLength": 1, + "status": "prototype", + "title": "Directory", + "type": "string" + }, + "donor": { + "anyOf": [ + { + "$ref": "#/$defs/RemoteDonorConfig" + }, + { + "type": "null" + } + ], + "default": null, + "description": "This rank's donation; None donates nothing.", + "status": "prototype" + }, + "level": { + "anyOf": [ + { + "$ref": "#/$defs/RemoteLevelConfig" + }, + { + "type": "null" + } + ], + "default": null, + "description": "This rank's remote cache level; None gives it none.", + "status": "prototype" + }, + "transport": { + "description": "How pages move: {kind: nixl} (one-sided NIXL RDMA, the default) or {kind: fabric} (CUDA fabric memory copied over NVLink).", + "discriminator": { + "mapping": { + "fabric": "#/$defs/RemoteFabricTransportConfig", + "nixl": "#/$defs/RemoteNixlTransportConfig" + }, + "propertyName": "kind" + }, + "oneOf": [ + { + "$ref": "#/$defs/RemoteNixlTransportConfig", + "required": [ + "kind" + ] + }, + { + "$ref": "#/$defs/RemoteFabricTransportConfig", + "required": [ + "kind" + ] + } + ], + "status": "prototype", + "title": "Transport" + } + }, + "required": [ + "directory" + ], + "title": "RemoteCacheConfig", + "type": "object" + }, + "RemoteDonorConfig": { + "additionalProperties": false, + "description": "Host memory this rank donates to remote cache levels.", + "properties": { + "size": { + "description": "Bytes donated for the lifetime of the process, in whole 1 GiB chunks (a remainder below one chunk is not donated; the rank logs the size it donates).", + "minimum": 1073741824, + "status": "prototype", + "title": "Size", + "type": "integer" + } + }, + "required": [ + "size" + ], + "title": "RemoteDonorConfig", + "type": "object" + }, + "RemoteExpectedDonorsConfig": { + "additionalProperties": false, + "description": "The job's donors and claims, which only the launcher can count.", + "properties": { + "claim_size": { + "description": "Bytes all ranks of the job claim from `directory` together.", + "exclusiveMinimum": 0, + "status": "prototype", + "title": "Claim Size", + "type": "integer" + }, + "num_donors": { + "description": "Number of donating ranks the job starts.", + "exclusiveMinimum": 0, + "status": "prototype", + "title": "Num Donors", + "type": "integer" + } + }, + "required": [ + "num_donors", + "claim_size" + ], + "title": "RemoteExpectedDonorsConfig", + "type": "object" + }, + "RemoteFabricTransportConfig": { + "additionalProperties": false, + "description": "Remote cache transport over CUDA fabric memory.\n\nClaimants in the same multi-node NVLink domain copy it over NVLink.", + "properties": { + "compact_host_memory": { + "default": false, + "description": "Before a node that refuses a donated chunk is left, run up to 64 reclaim-and-compact passes on it (fault in and release node-bound huge pages under a per-node lock that donors on one host take in turn), so fragmented or page-cache-filled memory can still take the donation. False publishes what fits and leaves compaction to the job prolog.", + "status": "prototype", + "title": "Compact Host Memory", + "type": "boolean" + }, + "donor_reserve_size": { + "default": 25769803776, + "description": "Bytes of free plus reclaimable memory each host NUMA node keeps for the processes on it while a donation is placed. Chunks go to the GPU's node first, then to the others; a donation that does not fit is published short.", + "minimum": 0, + "status": "prototype", + "title": "Donor Reserve Size", + "type": "integer" + }, + "kind": { + "const": "fabric", + "description": "Selects this transport. Every rank sharing `directory` must use the same transport.", + "status": "prototype", + "title": "Kind", + "type": "string" + } + }, + "required": [ + "kind" + ], + "title": "RemoteFabricTransportConfig", + "type": "object" + }, + "RemoteLevelConfig": { + "additionalProperties": false, + "description": "This rank's remote cache level, in chunks of donated memory.", + "properties": { + "donor_wait_timeout_s": { + "default": 900.0, + "description": "Seconds the rank waits for donors, applied to each wait on its own: for the expected donors to report, and for each chunk claim. Donors publish while their own servers start, so this bounds the job's startup skew per wait, not in total. At most 1e6.", + "exclusiveMinimum": 0, + "maximum": 1000000.0, + "status": "prototype", + "title": "Donor Wait Timeout S", + "type": "number" + }, + "expected": { + "anyOf": [ + { + "$ref": "#/$defs/RemoteExpectedDonorsConfig" + }, + { + "type": "null" + } + ], + "default": null, + "description": "With it, the rank waits until these donors have reported and fails at once if they cannot cover the claims, instead of after a claim wait.", + "status": "prototype" + }, + "pool_ratio": { + "anyOf": [ + { + "items": { + "exclusiveMinimum": 0, + "type": "number" + }, + "minItems": 1, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Split of `size` across layer groups, one positive weight per layer group in KV cache manager v2 layer-group ID order (normalized). None follows the hot tier's split.", + "status": "prototype", + "title": "Pool Ratio" + }, + "size": { + "description": "Bytes of the level. Pages are stored as the cold tiers store them: byte copies, or encoded by a lossy cold-page codec (kv_cache_compression_config) when one is set. It takes the disk level's place, so it cannot be combined with `disk_cache_size`.", + "exclusiveMinimum": 0, + "status": "prototype", + "title": "Size", + "type": "integer" + } + }, + "required": [ + "size" + ], + "title": "RemoteLevelConfig", + "type": "object" + }, + "RemoteNixlTransportConfig": { + "additionalProperties": false, + "description": "Remote cache transport over one-sided NIXL RDMA.", + "properties": { + "kind": { + "const": "nixl", + "default": "nixl", + "description": "Selects this transport. Every rank sharing `directory` must use the same transport.", + "status": "prototype", + "title": "Kind", + "type": "string" + }, + "transfer_timeout_s": { + "default": 30.0, + "description": "Seconds one batch of page transfers of a remote level may take before the level fails, e.g. on a donor that died. At most 1e6.", + "exclusiveMinimum": 0, + "maximum": 1000000.0, + "status": "prototype", + "title": "Transfer Timeout S", + "type": "number" + }, + "ucx_devices": { + "anyOf": [ + { + "pattern": "^\\s*[^\\s,:][^,:]*(:1?)?\\s*(,\\s*[^\\s,:][^,:]*(:1?)?\\s*)*$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Comma-separated UCX devices of the remote level's and the donor's NIXL agents (for example 'mlx5_0:1'), each '' or ':1' (NIXL's UCX backend uses port 1); '{GPU}' is replaced by the rank's physical GPU index. None uses the process's UCX environment.", + "status": "prototype", + "title": "Ucx Devices" + } + }, + "title": "RemoteNixlTransportConfig", + "type": "object" + }, "ReorderRequestPolicyConfig": { "additionalProperties": false, "description": "Configuration for request reordering policy.", @@ -6295,6 +6700,29 @@ }, "SchedulerConfig": { "additionalProperties": false, + "allOf": [ + { + "if": { + "not": { + "properties": { + "waiting_queue_policy": { + "const": "priority" + } + }, + "required": [ + "waiting_queue_policy" + ] + } + }, + "then": { + "properties": { + "waiting_queue_max_wait_s": { + "const": null + } + } + } + } + ], "properties": { "capacity_scheduler_policy": { "$ref": "#/$defs/CapacitySchedulerPolicy", @@ -6363,6 +6791,21 @@ "title": "Use Python Scheduler", "type": "boolean" }, + "waiting_queue_max_wait_s": { + "anyOf": [ + { + "exclusiveMinimum": 0, + "type": "number" + }, + { + "type": "null" + } + ], + "default": null, + "description": "With waiting_queue_policy='priority': a request that has waited this many seconds since it reached the server (in disaggregated serving, the orchestrator) goes ahead of every request that has not, oldest first. None: no cap. Keep it at or below the context servers' cache_transceiver_config.kv_transfer_timeout_ms, whose clock starts later (after prefill).", + "status": "prototype", + "title": "Waiting Queue Max Wait S" + }, "waiting_queue_policy": { "$ref": "#/$defs/WaitingQueuePolicy", "default": "fcfs", @@ -7086,6 +7529,38 @@ } } } + }, + { + "if": { + "properties": { + "kv_cache_config": { + "properties": { + "defer_generation_only_release": { + "const": true + } + }, + "required": [ + "defer_generation_only_release" + ], + "type": "object" + } + }, + "required": [ + "kv_cache_config" + ] + }, + "then": { + "properties": { + "disable_overlap_scheduler": { + "not": { + "const": true + } + }, + "pipeline_parallel_size": { + "maximum": 1 + } + } + } } ], "description": "Static YAML checks only; runtime validation remains authoritative.", diff --git a/tensorrt_llm/schemas/trtllm-serve-disagg-config.schema.json b/tensorrt_llm/schemas/trtllm-serve-disagg-config.schema.json index d3501ead03bc..c6a4856ae519 100644 --- a/tensorrt_llm/schemas/trtllm-serve-disagg-config.schema.json +++ b/tensorrt_llm/schemas/trtllm-serve-disagg-config.schema.json @@ -50,6 +50,30 @@ }, "AttentionDpConfig": { "additionalProperties": false, + "allOf": [ + { + "if": { + "properties": { + "kv_cache_routing_home_wait_rounds": { + "type": "integer" + } + }, + "required": [ + "kv_cache_routing_home_wait_rounds" + ] + }, + "then": { + "properties": { + "kv_cache_routing_conversation_affinity": { + "const": true + } + }, + "required": [ + "kv_cache_routing_conversation_affinity" + ] + } + } + ], "description": "Configuration for attention DP.", "properties": { "batching_wait_iters": { @@ -107,6 +131,21 @@ "title": "Kv Cache Routing Fair Share Multiplier", "type": "number" }, + "kv_cache_routing_home_wait_rounds": { + "anyOf": [ + { + "exclusiveMinimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Conversation-affinity routing: a returning conversation whose home rank is full waits for a slot there for up to this many scheduling rounds in which another rank had room, then overflows by kv_cache_routing_new_conv_placement (keeping its home rank). Later requests of the same admission group (priority) may pass a waiting one on any rank; later groups may pass it on other ranks only, not into its home rank. None overflows at once. Requires kv_cache_routing_conversation_affinity=True.", + "status": "prototype", + "title": "Kv Cache Routing Home Wait Rounds" + }, "kv_cache_routing_load_balance_weight": { "default": 1.0, "description": "Weight (beta) for the load-balance term in KV cache-aware routing. Higher values prioritize load balance over cache affinity. Only used when enable_kv_cache_aware_routing is True.", @@ -1909,6 +1948,38 @@ } } } + }, + { + "if": { + "properties": { + "kv_cache_config": { + "properties": { + "defer_generation_only_release": { + "const": true + } + }, + "required": [ + "defer_generation_only_release" + ], + "type": "object" + } + }, + "required": [ + "kv_cache_config" + ] + }, + "then": { + "properties": { + "disable_overlap_scheduler": { + "not": { + "const": true + } + }, + "pipeline_parallel_size": { + "maximum": 1 + } + } + } } ], "properties": { @@ -3266,7 +3337,80 @@ }, "router": { "additionalProperties": true, + "allOf": [ + { + "if": { + "properties": { + "max_queue_wait_s": { + "type": "number" + } + }, + "required": [ + "max_queue_wait_s" + ] + }, + "then": { + "properties": { + "max_requests_per_server": { + "type": "integer" + } + }, + "required": [ + "max_requests_per_server" + ] + } + }, + { + "if": { + "properties": { + "max_requests_per_server": { + "type": "integer" + } + }, + "required": [ + "max_requests_per_server" + ] + }, + "then": { + "properties": { + "type": { + "pattern": "^[lL][oO][aA][dD]_[bB][aA][lL][aA][nN][cC][iI][nN][gG]$", + "type": "string" + }, + "use_tokens": { + "enum": [ + false, + null, + 0, + "", + [], + {} + ] + } + }, + "required": [ + "type" + ] + } + } + ], "properties": { + "max_queue_wait_s": { + "description": "Pooled generation dispatch: seconds after which a waiting request goes first (needs max_requests_per_server).", + "exclusiveMinimum": 0, + "type": [ + "number", + "null" + ] + }, + "max_requests_per_server": { + "description": "Pooled generation dispatch: requests each generation server runs at once (load_balancing generation router only).", + "minimum": 1, + "type": [ + "integer", + "null" + ] + }, "type": { "default": "round_robin", "title": "Type", @@ -5001,6 +5145,84 @@ }, "KvCacheConfig": { "additionalProperties": false, + "allOf": [ + { + "if": { + "properties": { + "remote_cache_config": { + "type": "object" + } + }, + "required": [ + "remote_cache_config" + ] + }, + "then": { + "properties": { + "use_kv_cache_manager_v2": { + "not": { + "const": false + } + } + } + } + }, + { + "if": { + "properties": { + "defer_generation_only_release": { + "const": true + } + }, + "required": [ + "defer_generation_only_release" + ] + }, + "then": { + "properties": { + "use_kv_cache_manager_v2": { + "not": { + "const": false + } + } + } + } + }, + { + "if": { + "properties": { + "remote_cache_config": { + "properties": { + "level": { + "type": "object" + } + }, + "required": [ + "level" + ] + } + }, + "required": [ + "remote_cache_config" + ] + }, + "then": { + "properties": { + "disk_cache_size": { + "enum": [ + 0, + null + ] + }, + "enable_kv_pool_rebalance": { + "not": { + "const": true + } + } + } + } + } + ], "description": "Configuration for the KV cache.", "properties": { "attention_dp_events_gather_period_ms": { @@ -5061,6 +5283,13 @@ "description": "The fraction of the KV Cache memory should be reserved for cross attention. If set to p, self attention will use 1-p of KV Cache memory and cross attention will use p of KV Cache memory. Defaults to None (unset); must be set when using an encoder-decoder model and must not be set otherwise.", "title": "Cross Kv Cache Fraction" }, + "defer_generation_only_release": { + "default": false, + "description": "Release the KV cache of a finished generation-only request (disaggregated generation server) after the next forward is enqueued, so that the host-side release overlaps GPU work. The pages return one iteration later, or as soon as the scheduler runs out of pages, before it suspends or recompute-pauses a running request. Their KV cache events are published one iteration later too, or in the same iteration when the server goes idle. Requires KV cache manager v2 and the overlap scheduler without pipeline parallelism.", + "status": "prototype", + "title": "Defer Generation Only Release", + "type": "boolean" + }, "disk_cache_path": { "anyOf": [ { @@ -5354,6 +5583,19 @@ "status": "prototype", "title": "Pool Ratio" }, + "remote_cache_config": { + "anyOf": [ + { + "$ref": "#/$defs/RemoteCacheConfig" + }, + { + "type": "null" + } + ], + "default": null, + "description": "KV cache manager v2 remote cache level in host memory that other ranks donate (usually generation ranks to context ranks). None disables it.", + "status": "prototype" + }, "secondary_offload_min_priority": { "anyOf": [ { @@ -7010,6 +7252,24 @@ "title": "Nvfp4GemmConfig", "type": "object" }, + "OutputLengthPredictionConfig": { + "additionalProperties": false, + "description": "Generation priority from an online prediction of each request's output length.\n\nAfter the context phase the orchestrator predicts the reply's length from the\nconversation's earlier replies (``conversation_params.conversation_id``) and the\nprompt length, never from ``max_tokens``, and sets the generation request's\n``priority`` (higher for shorter replies). The predictor learns online in the\ncoordinator. Generation servers order by it with\n``scheduler_config.waiting_queue_policy: priority``. Requires\n``schedule_style: context_first``; a request served without a context\nphase (conditional disaggregation) gets the prior's priority.", + "properties": { + "predictor": { + "default": "ridge", + "description": "'ridge': a ridge regression on the request's history features, refit every 120 s. 'ridge_gbm': also a gradient-boosted tree ensemble refit every 300 s in a separate process, which needs numpy and scikit-learn in the server's Python environment (checked at startup).", + "enum": [ + "ridge", + "ridge_gbm" + ], + "title": "Predictor", + "type": "string" + } + }, + "title": "OutputLengthPredictionConfig", + "type": "object" + }, "PARDDecodingConfig": { "additionalProperties": false, "description": "Configuration for PARD (Parallel Draft) speculative decoding.\n\nPARD is a target-independent speculative decoding method that uses\nmask tokens to predict multiple draft tokens in parallel within a\nsingle forward pass.\n\nKey features:\n- Target-independent: doesn't use target model hidden states\n- Parallel prediction: all K draft tokens in one forward pass\n- Shared mask token: uses the same mask_token_id across all positions\n\nReference: https://arxiv.org/pdf/2504.18583", @@ -7565,6 +7825,274 @@ "title": "RayPlacementConfig", "type": "object" }, + "RemoteCacheConfig": { + "additionalProperties": false, + "anyOf": [ + { + "properties": { + "donor": { + "type": "object" + } + }, + "required": [ + "donor" + ] + }, + { + "properties": { + "level": { + "type": "object" + } + }, + "required": [ + "level" + ] + } + ], + "description": "KV cache manager v2 remote cache level in host memory that other ranks donate.\n\nA rank with `level` gets a cache level below the host tier whose slots live\nin memory that ranks with `donor` publish in `directory`.", + "properties": { + "directory": { + "description": "Rendezvous directory, on a file system every rank of the job sees, where donors publish their memory and remote cache levels claim chunks of it. Environment variables are expanded, and one that is not set is an error; the directory is created if missing. Use one directory per job.", + "minLength": 1, + "status": "prototype", + "title": "Directory", + "type": "string" + }, + "donor": { + "anyOf": [ + { + "$ref": "#/$defs/RemoteDonorConfig" + }, + { + "type": "null" + } + ], + "default": null, + "description": "This rank's donation; None donates nothing.", + "status": "prototype" + }, + "level": { + "anyOf": [ + { + "$ref": "#/$defs/RemoteLevelConfig" + }, + { + "type": "null" + } + ], + "default": null, + "description": "This rank's remote cache level; None gives it none.", + "status": "prototype" + }, + "transport": { + "description": "How pages move: {kind: nixl} (one-sided NIXL RDMA, the default) or {kind: fabric} (CUDA fabric memory copied over NVLink).", + "discriminator": { + "mapping": { + "fabric": "#/$defs/RemoteFabricTransportConfig", + "nixl": "#/$defs/RemoteNixlTransportConfig" + }, + "propertyName": "kind" + }, + "oneOf": [ + { + "$ref": "#/$defs/RemoteNixlTransportConfig", + "required": [ + "kind" + ] + }, + { + "$ref": "#/$defs/RemoteFabricTransportConfig", + "required": [ + "kind" + ] + } + ], + "status": "prototype", + "title": "Transport" + } + }, + "required": [ + "directory" + ], + "title": "RemoteCacheConfig", + "type": "object" + }, + "RemoteDonorConfig": { + "additionalProperties": false, + "description": "Host memory this rank donates to remote cache levels.", + "properties": { + "size": { + "description": "Bytes donated for the lifetime of the process, in whole 1 GiB chunks (a remainder below one chunk is not donated; the rank logs the size it donates).", + "minimum": 1073741824, + "status": "prototype", + "title": "Size", + "type": "integer" + } + }, + "required": [ + "size" + ], + "title": "RemoteDonorConfig", + "type": "object" + }, + "RemoteExpectedDonorsConfig": { + "additionalProperties": false, + "description": "The job's donors and claims, which only the launcher can count.", + "properties": { + "claim_size": { + "description": "Bytes all ranks of the job claim from `directory` together.", + "exclusiveMinimum": 0, + "status": "prototype", + "title": "Claim Size", + "type": "integer" + }, + "num_donors": { + "description": "Number of donating ranks the job starts.", + "exclusiveMinimum": 0, + "status": "prototype", + "title": "Num Donors", + "type": "integer" + } + }, + "required": [ + "num_donors", + "claim_size" + ], + "title": "RemoteExpectedDonorsConfig", + "type": "object" + }, + "RemoteFabricTransportConfig": { + "additionalProperties": false, + "description": "Remote cache transport over CUDA fabric memory.\n\nClaimants in the same multi-node NVLink domain copy it over NVLink.", + "properties": { + "compact_host_memory": { + "default": false, + "description": "Before a node that refuses a donated chunk is left, run up to 64 reclaim-and-compact passes on it (fault in and release node-bound huge pages under a per-node lock that donors on one host take in turn), so fragmented or page-cache-filled memory can still take the donation. False publishes what fits and leaves compaction to the job prolog.", + "status": "prototype", + "title": "Compact Host Memory", + "type": "boolean" + }, + "donor_reserve_size": { + "default": 25769803776, + "description": "Bytes of free plus reclaimable memory each host NUMA node keeps for the processes on it while a donation is placed. Chunks go to the GPU's node first, then to the others; a donation that does not fit is published short.", + "minimum": 0, + "status": "prototype", + "title": "Donor Reserve Size", + "type": "integer" + }, + "kind": { + "const": "fabric", + "description": "Selects this transport. Every rank sharing `directory` must use the same transport.", + "status": "prototype", + "title": "Kind", + "type": "string" + } + }, + "required": [ + "kind" + ], + "title": "RemoteFabricTransportConfig", + "type": "object" + }, + "RemoteLevelConfig": { + "additionalProperties": false, + "description": "This rank's remote cache level, in chunks of donated memory.", + "properties": { + "donor_wait_timeout_s": { + "default": 900.0, + "description": "Seconds the rank waits for donors, applied to each wait on its own: for the expected donors to report, and for each chunk claim. Donors publish while their own servers start, so this bounds the job's startup skew per wait, not in total. At most 1e6.", + "exclusiveMinimum": 0, + "maximum": 1000000.0, + "status": "prototype", + "title": "Donor Wait Timeout S", + "type": "number" + }, + "expected": { + "anyOf": [ + { + "$ref": "#/$defs/RemoteExpectedDonorsConfig" + }, + { + "type": "null" + } + ], + "default": null, + "description": "With it, the rank waits until these donors have reported and fails at once if they cannot cover the claims, instead of after a claim wait.", + "status": "prototype" + }, + "pool_ratio": { + "anyOf": [ + { + "items": { + "exclusiveMinimum": 0, + "type": "number" + }, + "minItems": 1, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Split of `size` across layer groups, one positive weight per layer group in KV cache manager v2 layer-group ID order (normalized). None follows the hot tier's split.", + "status": "prototype", + "title": "Pool Ratio" + }, + "size": { + "description": "Bytes of the level. Pages are stored as the cold tiers store them: byte copies, or encoded by a lossy cold-page codec (kv_cache_compression_config) when one is set. It takes the disk level's place, so it cannot be combined with `disk_cache_size`.", + "exclusiveMinimum": 0, + "status": "prototype", + "title": "Size", + "type": "integer" + } + }, + "required": [ + "size" + ], + "title": "RemoteLevelConfig", + "type": "object" + }, + "RemoteNixlTransportConfig": { + "additionalProperties": false, + "description": "Remote cache transport over one-sided NIXL RDMA.", + "properties": { + "kind": { + "const": "nixl", + "default": "nixl", + "description": "Selects this transport. Every rank sharing `directory` must use the same transport.", + "status": "prototype", + "title": "Kind", + "type": "string" + }, + "transfer_timeout_s": { + "default": 30.0, + "description": "Seconds one batch of page transfers of a remote level may take before the level fails, e.g. on a donor that died. At most 1e6.", + "exclusiveMinimum": 0, + "maximum": 1000000.0, + "status": "prototype", + "title": "Transfer Timeout S", + "type": "number" + }, + "ucx_devices": { + "anyOf": [ + { + "pattern": "^\\s*[^\\s,:][^,:]*(:1?)?\\s*(,\\s*[^\\s,:][^,:]*(:1?)?\\s*)*$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Comma-separated UCX devices of the remote level's and the donor's NIXL agents (for example 'mlx5_0:1'), each '' or ':1' (NIXL's UCX backend uses port 1); '{GPU}' is replaced by the rank's physical GPU index. None uses the process's UCX environment.", + "status": "prototype", + "title": "Ucx Devices" + } + }, + "title": "RemoteNixlTransportConfig", + "type": "object" + }, "ReorderRequestPolicyConfig": { "additionalProperties": false, "description": "Configuration for request reordering policy.", @@ -8217,6 +8745,29 @@ }, "SchedulerConfig": { "additionalProperties": false, + "allOf": [ + { + "if": { + "not": { + "properties": { + "waiting_queue_policy": { + "const": "priority" + } + }, + "required": [ + "waiting_queue_policy" + ] + } + }, + "then": { + "properties": { + "waiting_queue_max_wait_s": { + "const": null + } + } + } + } + ], "properties": { "capacity_scheduler_policy": { "$ref": "#/$defs/CapacitySchedulerPolicy", @@ -8285,6 +8836,21 @@ "title": "Use Python Scheduler", "type": "boolean" }, + "waiting_queue_max_wait_s": { + "anyOf": [ + { + "exclusiveMinimum": 0, + "type": "number" + }, + { + "type": "null" + } + ], + "default": null, + "description": "With waiting_queue_policy='priority': a request that has waited this many seconds since it reached the server (in disaggregated serving, the orchestrator) goes ahead of every request that has not, oldest first. None: no cap. Keep it at or below the context servers' cache_transceiver_config.kv_transfer_timeout_ms, whose clock starts later (after prefill).", + "status": "prototype", + "title": "Waiting Queue Max Wait S" + }, "waiting_queue_policy": { "$ref": "#/$defs/WaitingQueuePolicy", "default": "fcfs", @@ -9019,6 +9585,59 @@ } } } + }, + { + "if": { + "properties": { + "kv_cache_config": { + "properties": { + "defer_generation_only_release": { + "const": true + } + }, + "required": [ + "defer_generation_only_release" + ], + "type": "object" + } + }, + "required": [ + "kv_cache_config" + ] + }, + "then": { + "properties": { + "disable_overlap_scheduler": { + "not": { + "const": true + } + }, + "pipeline_parallel_size": { + "maximum": 1 + } + } + } + }, + { + "if": { + "properties": { + "output_length_prediction": { + "type": "object" + } + }, + "required": [ + "output_length_prediction" + ] + }, + "then": { + "properties": { + "schedule_style": { + "not": { + "const": "generation_first" + } + } + } + } } ], "description": "Static YAML checks only; runtime validation remains authoritative.", @@ -9197,7 +9816,22 @@ "context_servers": { "anyOf": [ { - "$ref": "#/$defs/DisaggServerBlock" + "allOf": [ + { + "$ref": "#/$defs/DisaggServerBlock" + }, + { + "properties": { + "router": { + "properties": { + "max_requests_per_server": { + "type": "null" + } + } + } + } + } + ] }, { "type": "null" @@ -10219,6 +10853,17 @@ "status": "prototype", "title": "Otlp Traces Endpoint" }, + "output_length_prediction": { + "anyOf": [ + { + "$ref": "#/$defs/OutputLengthPredictionConfig" + }, + { + "type": "null" + } + ], + "default": null + }, "peft_cache_config": { "anyOf": [ { diff --git a/tensorrt_llm/serve/coordinator_server.py b/tensorrt_llm/serve/coordinator_server.py index 90e1f6812ba7..7f77db7e1ea5 100644 --- a/tensorrt_llm/serve/coordinator_server.py +++ b/tensorrt_llm/serve/coordinator_server.py @@ -37,7 +37,7 @@ import asyncio import socket from contextlib import asynccontextmanager -from typing import Optional +from typing import Awaitable, Optional, TypeVar import msgpack import uvicorn @@ -48,10 +48,63 @@ from tensorrt_llm.serve._telemetry import create_uvicorn_server from tensorrt_llm.serve.cluster_storage import HttpClusterStorageServer from tensorrt_llm.serve.disagg_coordinator import DisaggCoordinatorService +from tensorrt_llm.serve.output_length_predictor import MAX_TOKENS, RECORD_BATCH_MAX, is_token_count +from tensorrt_llm.serve.seat_pool import NoGenerationSeatError from tensorrt_llm.version import __version__ as VERSION TIMEOUT_KEEP_ALIVE = 10 # seconds +# Accept queue of the fleet UNIX socket: a burst opens one connect per concurrent +# /select, and a connect to a full queue fails with ENOTCONN on its first send. +# The kernel caps the value at net.core.somaxconn. +COORDINATOR_UDS_BACKLOG = 16384 +# uvicorn's default accept queue: a cap at or above it is only logged, not warned about. +UVICORN_DEFAULT_BACKLOG = 2048 MSGPACK_MEDIA_TYPE = "application/msgpack" +# How often serving checks whether a uvicorn server began its shutdown (uvicorn's own tick). +SHUTDOWN_POLL_S = 0.1 +_T = TypeVar("_T") + + +class _ClientDisconnected(Exception): + """The client of a waiting request closed its connection.""" + + +async def _wait_for_disconnect(raw_req: Request) -> None: + """Return once the client of ``raw_req``, whose body was read, closes its connection.""" + while (await raw_req.receive())["type"] != "http.disconnect": + pass + + +async def _until_disconnect(raw_req: Request, selection: Awaitable[_T]) -> _T: + """Await ``selection``; cancel it and raise ``_ClientDisconnected`` if the client leaves first. + + uvicorn does not cancel a handler whose client disconnected, so a pooled select of a fleet + worker that died would otherwise keep its place in the seat queue and later take a seat. + """ + selecting = asyncio.ensure_future(selection) + watching = asyncio.ensure_future(_wait_for_disconnect(raw_req)) + try: + await asyncio.wait((selecting, watching), return_when=asyncio.FIRST_COMPLETED) + if not selecting.done() and not watching.cancelled() and watching.exception() is None: + selecting.cancel() + try: + return await selecting + except asyncio.CancelledError: + raise _ClientDisconnected() from None + return await selecting + finally: + watching.cancel() + # Also when this handler itself is cancelled. + selecting.cancel() + + +def _effective_uds_backlog() -> int: + """COORDINATOR_UDS_BACKLOG as capped by net.core.somaxconn, where Linux exposes it.""" + try: + with open("/proc/sys/net/core/somaxconn") as f: + return min(COORDINATOR_UDS_BACKLOG, int(f.read())) + except (OSError, ValueError): + return COORDINATOR_UDS_BACKLOG class CoordinatorServer: @@ -59,6 +112,8 @@ class CoordinatorServer: def __init__(self, coordinator: DisaggCoordinatorService) -> None: self._coordinator = coordinator + # The uvicorn servers of the running __call__. + self.servers: list[uvicorn.Server] = [] @asynccontextmanager async def lifespan(app: FastAPI): @@ -70,6 +125,7 @@ async def lifespan(app: FastAPI): self.app.add_api_route("/select", self.select, methods=["POST"]) self.app.add_api_route("/finish", self.finish, methods=["POST"]) self.app.add_api_route("/renew", self.renew, methods=["POST"]) + self.app.add_api_route("/output_length", self.output_length, methods=["POST"]) self.app.add_api_route("/cluster_info", self.cluster_info, methods=["GET"]) self.app.add_api_route("/health", self.health, methods=["GET"]) self.app.add_api_route("/version", self.version, methods=["GET"]) @@ -109,10 +165,18 @@ async def select(self, raw_req: Request) -> Response: exclude_server = body.get("exclude_server") if exclude_server is not None and not isinstance(exclude_server, str): return self._response({"error": "exclude_server must be a string"}, status_code=400) + selection = self._coordinator.select(role, body["routing_key"], req_id, exclude_server) try: - server, info, req_id = await self._coordinator.select( - role, body["routing_key"], req_id, exclude_server - ) + if self._pooled(role): + server, info, req_id = await _until_disconnect(raw_req, selection) + else: + server, info, req_id = await selection + except _ClientDisconnected: + # Nobody reads this reply; the cancelled wait gave its place or seat back. + return self._response({"error": "client disconnected"}, status_code=503) + except NoGenerationSeatError as e: + # Overload, not a fault: the frontend answers its client 503 too. + return self._response({"error": str(e), "no_generation_seat": True}, status_code=503) except ValueError as e: return self._response({"error": str(e)}, status_code=503) except Exception as e: # noqa: BLE001 @@ -120,6 +184,12 @@ async def select(self, raw_req: Request) -> Response: return self._response({"error": str(e)}, status_code=500) return self._response({"server": server, "info": info, "req_id": req_id}) + def _pooled(self, role: str) -> bool: + """Whether a select for ``role`` may wait for a seat (a pooled router).""" + if role in ("context", "ctx"): + return self._coordinator.ctx_router.pooled + return self._coordinator.gen_router.pooled + async def finish(self, raw_req: Request) -> Response: try: body = msgpack.unpackb(await raw_req.body(), raw=False) @@ -141,6 +211,68 @@ async def finish(self, raw_req: Request) -> Response: await self._coordinator.finish(role, req_id, success) return self._response({}) + @staticmethod + def _output_length_error( + conv: object, isl: object, out: object = 0.0, key: object = None + ) -> Optional[str]: + """Why a prediction's or reply's fields are invalid, or None.""" + if conv is not None and not isinstance(conv, str): + return "conv must be a string or null" + if not is_token_count(isl): + return f"isl must be a finite number in [0, {MAX_TOKENS:.0f}]" + if key is not None and (not isinstance(key, int) or isinstance(key, bool)): + return "key must be an integer or null" + if out is None and key is not None: + return None # a failed request: its prediction row is dropped + if not is_token_count(out): + return f"out must be a finite number in [0, {MAX_TOKENS:.0f}], or null with a key" + return None + + async def output_length(self, raw_req: Request) -> Response: + """Output-length prediction (``output_length_prediction``) for frontends. + + POST {"op": "predict", "conv", "isl"} -> {"tokens", "key"}, and + POST {"op": "record", "records": [[conv, isl, out, key], ...]} -> {"learned"} (``out`` + null with a ``key``: the request failed, its prediction row is dropped). + """ + try: + body = msgpack.unpackb(await raw_req.body(), raw=False) + except Exception as e: + return self._response({"error": f"invalid MessagePack body: {e}"}, status_code=400) + if not isinstance(body, dict) or body.get("op") not in ("predict", "record"): + return self._response({"error": "op must be 'predict' or 'record'"}, status_code=400) + try: + if body["op"] == "predict": + conv, isl = body.get("conv"), body.get("isl") + error = self._output_length_error(conv, isl) + if error: + return self._response({"error": error}, status_code=400) + tokens, key = await self._coordinator.predict_output_length(conv, isl) + return self._response({"tokens": tokens, "key": key}) + records = body.get("records") + if not isinstance(records, list) or len(records) > RECORD_BATCH_MAX: + return self._response( + {"error": f"records must be a list of at most {RECORD_BATCH_MAX} entries"}, + status_code=400, + ) + for record in records: + if not isinstance(record, list) or len(record) != 4: + return self._response( + {"error": "a record is [conv, isl, out, key]"}, status_code=400 + ) + error = self._output_length_error(*record) + if error: + return self._response({"error": error}, status_code=400) + learned = await self._coordinator.record_output_lengths( + [ + (conv, float(isl), None if out is None else float(out), key) + for conv, isl, out, key in records + ] + ) + return self._response({"learned": learned}) + except ValueError as e: + return self._response({"error": str(e)}, status_code=503) + async def renew(self, raw_req: Request) -> Response: try: body = msgpack.unpackb(await raw_req.body(), raw=False) @@ -198,21 +330,59 @@ async def __call__( if uds: # uvicorn.Config binds uds XOR host:port, so run two Servers: UDS for # the fleet (hot path) and TCP for health/external clients. - import asyncio as _asyncio - await self._coordinator.start() + backlog = _effective_uds_backlog() + if backlog < COORDINATOR_UDS_BACKLOG: + log = logger.warning if backlog < UVICORN_DEFAULT_BACKLOG else logger.info + log( + f"Coordinator UNIX socket accept queue is {backlog}, capped by " + f"net.core.somaxconn (requested {COORDINATOR_UDS_BACKLOG}); raise the " + "sysctl if routers report coordinator connect failures under bursts." + ) try: - uds_cfg = uvicorn.Config(self.app, uds=uds, lifespan="off", **kwargs) + uds_cfg = uvicorn.Config( + self.app, uds=uds, lifespan="off", backlog=COORDINATOR_UDS_BACKLOG, **kwargs + ) tcp_cfg = uvicorn.Config(self.app, host=host, port=port, lifespan="off", **kwargs) - await _asyncio.gather( - create_uvicorn_server(uds_cfg).serve(), - create_uvicorn_server(tcp_cfg).serve(sockets=sockets), + await self._serve( + [ + (create_uvicorn_server(uds_cfg), None), + (create_uvicorn_server(tcp_cfg), sockets), + ] ) finally: await self._coordinator.stop() else: config = uvicorn.Config(self.app, host=host, port=port, **kwargs) - await create_uvicorn_server(config).serve(sockets=sockets) + await self._serve([(create_uvicorn_server(config), sockets)]) + + async def _serve( + self, servers: list[tuple[uvicorn.Server, Optional[list[socket.socket]]]] + ) -> None: + """Run ``servers`` (with their sockets); fail the seat waiters once one of them stops. + + uvicorn's graceful shutdown waits for every request in flight, and a pooled /select + waiting for a generation seat ends only at its seat or its KV transfer deadline (none + without one), so the lifespan exit or the caller's ``stop()`` would come too late. + """ + self.servers = [server for server, _ in servers] + watcher = asyncio.create_task(self._fail_seat_waiters_at_shutdown()) + try: + # A listener without sockets (UDS) binds its own. + await asyncio.gather( + *( + server.serve() if socks is None else server.serve(sockets=socks) + for server, socks in servers + ) + ) + finally: + watcher.cancel() + await asyncio.gather(watcher, return_exceptions=True) + + async def _fail_seat_waiters_at_shutdown(self) -> None: + while not any(server.should_exit for server in self.servers): + await asyncio.sleep(SHUTDOWN_POLL_S) + await self._coordinator.fail_seat_waiters() def serve_coordinator(host: str, port: int, coordinator: DisaggCoordinatorService) -> None: diff --git a/tensorrt_llm/serve/disagg_coordinator.py b/tensorrt_llm/serve/disagg_coordinator.py index 4b2aa03cf6b4..f7417c2d8aa9 100644 --- a/tensorrt_llm/serve/disagg_coordinator.py +++ b/tensorrt_llm/serve/disagg_coordinator.py @@ -39,7 +39,8 @@ import os import time from abc import ABC, abstractmethod -from typing import Any, Dict, Optional, Tuple +from collections import OrderedDict +from typing import Any, Dict, Optional, Sequence, Tuple import aiohttp import msgpack @@ -62,6 +63,15 @@ from tensorrt_llm.serve.disagg_auto_scaling import DisaggClusterManager, WorkerInfo from tensorrt_llm.serve.metadata_server import create_metadata_server from tensorrt_llm.serve.openai_client import OpenAIClient +from tensorrt_llm.serve.output_length_predictor import ( + MAX_PENDING_ROWS, + OUTPUT_LENGTH_KEY, + PRIOR_TOKENS, + OnlineLengthPredictor, + is_token_count, + priority_of, + throttled, +) from tensorrt_llm.serve.render.fingerprint import fingerprint_summary from tensorrt_llm.serve.router import ( ROUTING_CONTENT_REQUIRED, @@ -81,6 +91,12 @@ COORDINATOR_RESERVATION_TIMEOUT_ENV = "TRTLLM_DISAGG_COORDINATOR_RESERVATION_TIMEOUT" COORDINATOR_RESERVATION_TIMEOUT_DEFAULT_S = 180.0 +# A pooled generation seat is released by its /finish, which the fleet worker retries until +# delivered; this expiry only reclaims the seat of a request whose frontend died without one, +# so it must outlast the longest generation. The env timeout above, which expires non-pooled +# reservations (``_reservation_timeout_for``), can lengthen it but not shorten it: a shorter +# expiry would hand on a seat still streaming. +POOLED_RESERVATION_TIMEOUT_S = 6 * 3600.0 COORDINATOR_RESERVATION_LOCK_STRIPES = 256 COORDINATOR_STATE_SYNC_INTERVAL_S = 3.0 @@ -94,6 +110,23 @@ def coordinator_reservation_timeout() -> float: ) +def reservation_timeout( + configured_s: Optional[float] = None, request_timeout_s: Optional[float] = None +) -> float: + """A reservation's expiry: ``configured_s`` (else the env timeout), at least the request timeout.""" + configured = coordinator_reservation_timeout() if configured_s is None else configured_s + return max(configured, request_timeout_s or 0) + + +def pooled_reservation_timeout(reservation_timeout_s: float) -> float: + """A pooled seat's expiry, given :func:`reservation_timeout`. + + The fleet worker's ``/finish`` retry window uses the same value, so it retries as long as the + coordinator holds the seat. + """ + return max(reservation_timeout_s, POOLED_RESERVATION_TIMEOUT_S) + + class DisaggCoordinator(ABC): """Abstract coordinator: ctx/gen routers + readiness + cluster info + lifecycle. @@ -123,6 +156,25 @@ async def stop(self) -> None: ... @abstractmethod async def get_disagg_request_id(self) -> int: ... + async def predict_output_length( + self, conv_id: Optional[str], prompt_tokens: float + ) -> Tuple[float, int]: + """Predict a generation request's output tokens (``output_length_prediction``). + + Returns the prediction and a key that ``record_output_length`` passes back. + """ + raise NotImplementedError("output_length_prediction is not configured") + + async def record_output_lengths( + self, records: Sequence[Tuple[Optional[str], float, Optional[float], Optional[int]]] + ) -> int: + """Learn finished replies, each ``(conv_id, prompt_tokens, output_tokens, key)``. + + ``output_tokens`` None reports a request that failed: its prediction row is dropped. + Returns how many were learned. + """ + raise NotImplementedError("output_length_prediction is not configured") + class DisaggCoordinatorService(DisaggCoordinator): """In-process coordinator owning the ctx/gen routers and all cluster state. @@ -178,14 +230,8 @@ def __init__( ) self._server_start_timeout_secs = server_start_timeout_secs self._health_check_interval_secs = health_check_interval_secs - configured_reservation_timeout = ( - coordinator_reservation_timeout() - if reservation_timeout_secs is None - else reservation_timeout_secs - ) - self._reservation_timeout_secs = max( - configured_reservation_timeout, - request_timeout_secs or 0, + self._reservation_timeout_secs = reservation_timeout( + reservation_timeout_secs, request_timeout_secs ) self._reservation_tasks: dict[tuple[str, int], asyncio.Task] = {} self._reservation_locks = [ @@ -195,6 +241,16 @@ def __init__( self._ctx_client: Optional[OpenAIClient] = None self._gen_client: Optional[OpenAIClient] = None self._disagg_cluster_manager: Optional[DisaggClusterManager] = None + # One predictor for every frontend, so that it learns from all replies. + self._output_length_predictor: Optional[OnlineLengthPredictor] = None + self._output_length_errors = 0 + # The prediction key of each generation request predicted in /select, until its /finish: + # a repeated select reuses it, and a failed one drops its row. + self._prediction_keys: OrderedDict[int, int] = OrderedDict() + if config.output_length_prediction is not None: + self._output_length_predictor = OnlineLengthPredictor( + config.output_length_prediction.predictor + ) @property def ctx_router(self) -> Router: @@ -229,12 +285,39 @@ def _api_lat(self, name: str): return cache[name] async def select( - self, role: str, routing_key, req_id, exclude_server: Optional[str] - ) -> Tuple[Optional[str], dict, Optional[str]]: + self, role: str, routing_key: Any, req_id: int, exclude_server: Optional[str] + ) -> Tuple[Optional[str], dict, Optional[int]]: _t0 = time.monotonic() normalized_role = self._normalize_role(role) router = self._router_for_role(normalized_role) reservation_key = (normalized_role, req_id) + prediction = self._predict_in_select(normalized_role, routing_key, req_id) + try: + if router.pooled: + server, info, request_id = await self._select_pooled( + router, role, routing_key, req_id, exclude_server, _t0 + ) + return server, self._with_prediction(info, prediction), request_id + server, info, request_id = await self._select_reserved( + router, routing_key, req_id, exclude_server, reservation_key + ) + except BaseException: + if prediction is not None: + # No placement (no seat, a disconnected client): the request will not report. + self._drop_prediction(req_id) + raise + self._api_lat(f"select[{role}]").record(time.monotonic() - _t0) + return server, self._with_prediction(self._compact_route_info(info), prediction), request_id + + async def _select_reserved( + self, + router: Router, + routing_key: Any, + req_id: int, + exclude_server: Optional[str], + reservation_key: Tuple[str, int], + ) -> Tuple[Optional[str], dict, Optional[int]]: + """Select through a non-pooled router under the reservation lock, and reserve the server.""" async with self._reservation_lock(reservation_key): previous = self._reservation_tasks.pop(reservation_key, None) if previous is not None: @@ -249,7 +332,97 @@ async def select( self._reservation_tasks[reservation_key] = asyncio.create_task( self._expire_reservation(reservation_key, router) ) - self._api_lat(f"select[{role}]").record(time.monotonic() - _t0) + return server, info, request_id + + def _drop_prediction(self, req_id: int) -> None: + key = self._prediction_keys.pop(req_id, None) + if key is not None and self._output_length_predictor is not None: + self._output_length_predictor.record(None, 0.0, None, key, time.monotonic()) + + def _predict_in_select(self, role: str, routing_key: Any, req_id: int) -> Optional[dict]: + """Predict a generation request's output length from its routing key's ``OUTPUT_LENGTH_KEY``. + + The prediction's priority replaces the key's ``priority``, so a pooled router orders by it. A predictor + error gives the key the prior's priority and returns None (the frontend then uses the prior too). + """ + if not isinstance(routing_key, dict): + return None + inputs = routing_key.pop(OUTPUT_LENGTH_KEY, None) + if ( + inputs is None + or role != "generation" + or self._output_length_predictor is None + or not isinstance(inputs, dict) + ): + return None + conv, isl = inputs.get("conv"), inputs.get("isl") + if (conv is not None and not isinstance(conv, str)) or not is_token_count(isl): + return None + try: + tokens, key = self._output_length_predictor.predict( + conv, float(isl), time.monotonic(), self._prediction_keys.get(req_id) + ) + except Exception as e: # noqa: BLE001 (an admission hint is never worth failing a placement) + self._output_length_errors += 1 + if throttled(self._output_length_errors): + logger.warning( + f"[output_length] prediction #{self._output_length_errors} in /select failed, " + f"prior used: {type(e).__name__}: {e}" + ) + routing_key["priority"] = priority_of(PRIOR_TOKENS) + return None + keys = self._prediction_keys + keys[req_id] = key + keys.move_to_end(req_id) + if len(keys) > MAX_PENDING_ROWS: + keys.popitem(last=False) + priority = priority_of(tokens) + routing_key["priority"] = priority + return {"tokens": tokens, "key": key, "priority": priority} + + @staticmethod + def _with_prediction(info: dict, prediction: Optional[dict]) -> dict: + if prediction is not None: + info[OUTPUT_LENGTH_KEY] = prediction + return info + + def _reservation_timeout_for(self, router: Router) -> float: + if router.pooled: + return pooled_reservation_timeout(self._reservation_timeout_secs) + return self._reservation_timeout_secs + + async def _select_pooled( + self, + router: Router, + role: str, + routing_key: Any, + req_id: int, + exclude_server: Optional[str], + t0: float, + ) -> Tuple[Optional[str], dict, Optional[int]]: + """Select through a pooled router, which may wait for a free seat. + + The wait does not take the striped reservation lock: ``finish`` takes that lock to + free seats, so a waiter holding it could block the finish its seat depends on. A + repeated select for the same ``req_id`` gets the same seat from the router and only + renews the reservation's expiry, which is ``POOLED_RESERVATION_TIMEOUT_S``: the seat + must not be handed on while its generation still streams. + + Nothing is awaited between the seat grant and its reservation, so a caller cancelled + while it waits (its client left) either gives its place or seat back in the router's + wait, or returns with the reservation armed. + """ + reservation_key = (self._normalize_role(role), req_id) + server, info, request_id = await router.get_next_server_by_key( + routing_key, req_id=req_id, exclude_server=exclude_server + ) + previous = self._reservation_tasks.pop(reservation_key, None) + if previous is not None: + previous.cancel() + self._reservation_tasks[reservation_key] = asyncio.create_task( + self._expire_reservation(reservation_key, router) + ) + self._api_lat(f"select[{role}]").record(time.monotonic() - t0) return server, self._compact_route_info(info), request_id @staticmethod @@ -267,10 +440,30 @@ def _compact_route_info(info: dict) -> dict: async def get_disagg_request_id(self) -> int: return get_global_disagg_request_id(self._config.node_id) + def _length_predictor(self) -> OnlineLengthPredictor: + if self._output_length_predictor is None: + raise ValueError("output_length_prediction is not configured") + return self._output_length_predictor + + async def predict_output_length( + self, conv_id: Optional[str], prompt_tokens: float + ) -> Tuple[float, int]: + return self._length_predictor().predict(conv_id, float(prompt_tokens), time.monotonic()) + + async def record_output_lengths( + self, records: Sequence[Tuple[Optional[str], float, Optional[float], Optional[int]]] + ) -> int: + predictor = self._length_predictor() + now = time.monotonic() + return sum(predictor.record(conv, isl, out, key, now) for conv, isl, out, key in records) + async def finish(self, role: str, req_id, success: bool = True) -> None: _t0 = time.monotonic() normalized_role = self._normalize_role(role) reservation_key = (normalized_role, req_id) + if normalized_role == "generation": + # Its frontend reports the reply (or the failure) by the key itself. + self._prediction_keys.pop(req_id, None) async with self._reservation_lock(reservation_key): reservation = self._reservation_tasks.pop(reservation_key, None) if reservation is not None: @@ -294,8 +487,9 @@ async def renew(self, role: str, req_id) -> None: ) async def _expire_reservation(self, key: tuple[str, int], router: Router) -> None: + timeout_s = self._reservation_timeout_for(router) try: - await asyncio.sleep(self._reservation_timeout_secs) + await asyncio.sleep(timeout_s) except asyncio.CancelledError: raise async with self._reservation_lock(key): @@ -304,7 +498,7 @@ async def _expire_reservation(self, key: tuple[str, int], router: Router) -> Non self._reservation_tasks.pop(key, None) logger.warning( f"Releasing stale coordinator reservation for role={key[0]}, " - f"req_id={key[1]} after {self._reservation_timeout_secs}s" + f"req_id={key[1]} after {timeout_s}s" ) await router.finish_request_by_id(key[1], False) @@ -356,7 +550,20 @@ async def start(self) -> None: ) await self._wait_for_all_servers_ready() + async def fail_seat_waiters(self) -> None: + """Fail the requests waiting for a generation seat and refuse new ones (shutdown). + + They would otherwise hold their /select open until a seat frees or their KV transfer + deadline passes. Idempotent. + """ + for router in (self._ctx_router, self._gen_router): + if router.pooled: + failed = await router.fail_waiters("the disaggregated coordinator is stopping") + if failed: + logger.info(f"Failed {failed} requests waiting for a seat at shutdown") + async def stop(self) -> None: + await self.fail_seat_waiters() reservations = list(self._reservation_tasks.values()) self._reservation_tasks.clear() for reservation in reservations: @@ -662,6 +869,50 @@ async def get_disagg_request_id(self) -> int: # hop. See disagg_utils.get_global_disagg_request_id. return get_global_disagg_request_id(self._node_id, self._process_id) + async def _output_length_call(self, body: Dict[str, Any]) -> Dict[str, Any]: + async with self.session.post( + f"{self._remote_url}/output_length", + data=msgpack.packb(body, use_bin_type=True), + headers={"Content-Type": "application/msgpack"}, + timeout=self._request_timeout_s, + ) as resp: + reply = msgpack.unpackb(await resp.read(), raw=False) + if resp.status != 200: + raise RuntimeError(f"coordinator /output_length returned {resp.status}: {reply}") + return reply + + async def predict_output_length( + self, conv_id: Optional[str], prompt_tokens: float + ) -> Tuple[float, int]: + reply = await self._output_length_call( + {"op": "predict", "conv": conv_id, "isl": float(prompt_tokens)} + ) + return float(reply["tokens"]), int(reply["key"]) + + async def record_output_lengths( + self, records: Sequence[Tuple[Optional[str], float, Optional[float], Optional[int]]] + ) -> int: + reply = await self._output_length_call( + { + "op": "record", + "records": [ + [conv, float(isl), None if out is None else float(out), key] + for conv, isl, out, key in records + ], + } + ) + return int(reply["learned"]) + + def enable_output_length_prediction_in_select(self) -> bool: + """Have ``/select`` predict the output length of delegated generation placements. + + Returns whether the generation router is delegated (else the frontend asks + ``/output_length``). + """ + if isinstance(self._gen_router, CoordinatorDelegatingRouter): + return self._gen_router.enable_output_length_prediction() + return False + async def is_ready(self) -> bool: return self._is_ready diff --git a/tensorrt_llm/serve/openai_disagg_server.py b/tensorrt_llm/serve/openai_disagg_server.py index 3510575cdaf4..e916d7cdd389 100644 --- a/tensorrt_llm/serve/openai_disagg_server.py +++ b/tensorrt_llm/serve/openai_disagg_server.py @@ -55,6 +55,7 @@ validate_http_cluster_storage_scope) from tensorrt_llm.serve.conversation_id import (extract_subagent_parent_id, resolve_request_conversation_id) +from tensorrt_llm.serve.coordinator_server import SHUTDOWN_POLL_S from tensorrt_llm.serve.disagg_coordinator import (CoordinatorClient, DisaggCoordinatorService) from tensorrt_llm.serve.kv_hints import KvHintsRoute @@ -75,6 +76,7 @@ guard_responses_stream, stream_error_event) from tensorrt_llm.serve.router import Router +from tensorrt_llm.serve.seat_pool import NoGenerationSeatError from tensorrt_llm.usage import TerminalOutcome, record_termination_observation from tensorrt_llm.version import __version__ as VERSION @@ -430,8 +432,8 @@ def _extract_conversation_id( # Give parent-only requests an independent conversation identity. if req.conversation_params is None: - req.conversation_params = ConversationParams( - conversation_id=f"subagent:{uuid.uuid4()}") + req.conversation_params = ConversationParams.for_one_request( + f"subagent:{uuid.uuid4()}") req.conversation_params.subagent_affinity_id = parent def _wrap_entry_point(self, entry_point: Callable, request_type: type = UCompletionRequest) -> Callable: @@ -615,6 +617,12 @@ def _handle_exception(self, exception): self._perf_metrics_collector.http_exceptions.inc() logger.error(f"HTTPException {exception.status_code} {exception.detail}: ", traceback.format_exc()) raise exception + elif isinstance(exception, NoGenerationSeatError): + # Overload (no generation seat in time, or shutdown): the client + # should retry, so 503 without a traceback. + self._perf_metrics_collector.http_exceptions.inc() + logger.warning(f"Generation request rejected: {exception}") + raise HTTPException(status_code=503, detail=str(exception)) from exception elif isinstance(exception, UnusedChatTemplateKwargsError): # Raised while this server tokenizes a chat request for routing. # It is a client mistake (a chat_template_kwargs key the template @@ -646,7 +654,29 @@ async def __call__(self, host: str, port: int, sockets: list[socket.socket] | No port=port, log_level=logger.level, timeout_keep_alive=keep_alive_timeout) - await create_uvicorn_server(config).serve(sockets=sockets) + server = create_uvicorn_server(config) + if not isinstance(self._coordinator, DisaggCoordinatorService): + await server.serve(sockets=sockets) + return + watcher = asyncio.create_task( + self._fail_seat_waiters_at_shutdown(server)) + try: + await server.serve(sockets=sockets) + finally: + watcher.cancel() + await asyncio.gather(watcher, return_exceptions=True) + + async def _fail_seat_waiters_at_shutdown(self, + server: uvicorn.Server) -> None: + """Fail the requests waiting for a generation seat once shutdown begins. + + uvicorn's graceful shutdown waits for every request in flight, so the + lifespan teardown that also fails them would run only after they got a + seat or their KV transfer deadline (as in ``CoordinatorServer``). + """ + while not server.should_exit: + await asyncio.sleep(SHUTDOWN_POLL_S) + await self._coordinator.fail_seat_waiters() async def _sync_server_clock(self, server: str): """ Sync the ctx/gen server's steady clock with the disagg-server's steady clock (in case NTP service is not running). diff --git a/tensorrt_llm/serve/openai_disagg_service.py b/tensorrt_llm/serve/openai_disagg_service.py index c62d62b31f8e..d3c6b4743071 100644 --- a/tensorrt_llm/serve/openai_disagg_service.py +++ b/tensorrt_llm/serve/openai_disagg_service.py @@ -21,13 +21,18 @@ from fastapi import HTTPException from tensorrt_llm._utils import get_global_steady_clock_now_in_seconds -from tensorrt_llm.llmapi.disagg_utils import ConditionalDisaggConfig, DisaggServerConfig, ServerRole +from tensorrt_llm.llmapi.disagg_utils import ( + ConditionalDisaggConfig, + DisaggServerConfig, + ServerRole, + check_output_length_prediction_schedule, +) from tensorrt_llm.logger import logger from tensorrt_llm.serve.anthropic_protocol import ( AnthropicCountTokensRequest, AnthropicCountTokensResponse, ) -from tensorrt_llm.serve.disagg_coordinator import DisaggCoordinator +from tensorrt_llm.serve.disagg_coordinator import CoordinatorClient, DisaggCoordinator from tensorrt_llm.serve.openai_client import OpenAIClient from tensorrt_llm.serve.openai_protocol import ( ChatCompletionRequest, @@ -45,6 +50,7 @@ UsageInfo, ) from tensorrt_llm.serve.openai_service import OpenAIService +from tensorrt_llm.serve.output_length_predictor import RECORD_FLUSH_S, OutputLengthPriority from tensorrt_llm.serve.responses_utils import ( ResponseHooks, UCompletionResponseOrGenerator, @@ -158,6 +164,8 @@ def __init__( client_factory: Callable[[Router, ServerRole], OpenAIClient], req_timeout_secs: int = 180, ): + # schedule_style may have been overridden (CLI -s, TLLM_DISAGG_SCHEDULE_STYLE) after parsing. + check_output_length_prediction_schedule(config) self._config = config # The service drives the coordinator's ctx/gen routers uniformly, so serving # is identical whether the router is the real one (single-process) or a @@ -172,6 +180,22 @@ def __init__( # Opt-in: ask context workers to return prompt_token_ids as base64 int32. self._tokids_ctxbytes = config.gen_tokids_ctxbytes self._subagent_affinity_scope = config.subagent_affinity_scope + # Generation priority from the predicted output length (output_length_prediction). + self._output_length_priority: Optional[OutputLengthPriority] = None + if config.output_length_prediction is not None: + # A fleet worker whose generation placement goes through the coordinator gets the + # prediction from /select, and reports replies in batches. + remote = isinstance(coordinator, CoordinatorClient) + self._output_length_priority = OutputLengthPriority( + coordinator, + config.output_length_prediction.predictor, + via_select=remote and coordinator.enable_output_length_prediction_in_select(), + record_flush_s=RECORD_FLUSH_S if remote else 0.0, + ) + # Requests without a priority field (/v1/responses) are not predicted: a pooled + # generation router seats them at the prior's priority. + self._gen_router.set_unpredicted_priority(self._output_length_priority.prior_priority) + logger.info(self._output_length_priority.startup_line()) self._ctx_client = None self._gen_client = None @@ -310,6 +334,7 @@ async def _send_disagg_request_ctx_first( need_ctx = need_ctx and not benchmark_gen_only ctx_response = None gen_req = request + length_ticket = None if need_ctx: try: # Mark ctx-dispatch start: arrival->here is the pre-ctx wait in the @@ -333,6 +358,12 @@ async def _send_disagg_request_ctx_first( if hooks: hooks.on_disagg_request_id(disagg_request_id) gen_req = self._get_gen_request(request, ctx_response, disagg_request_id) + if self._output_length_priority is not None: + # Before the generation placement, which orders by the priority it sets + # (or, in a fleet, predicts it in the same /select). + length_ticket = await self._output_length_priority.assign( + gen_req, placed_later=not gen_server + ) except Exception: if gen_server: await self._gen_router.finish_request( @@ -345,19 +376,40 @@ async def _send_disagg_request_ctx_first( # benchmark-only path above is the only trusted source here. if not benchmark_gen_only: gen_req = request.model_copy(update={"disaggregated_params": None}) + if self._output_length_priority is not None: + # No context phase, so no prompt length to predict from; a priority the + # client sent must not go ahead of the predicted ones. + self._output_length_priority.assign_prior(gen_req) self._strip_gen_subagent_affinity(gen_req) if ctx_response is None or self._need_gen(ctx_response): - if not gen_server: - gen_server, _ = await self._gen_router.get_next_server( - gen_req, exclude_server=ctx_server, req_id=disagg_request_id + try: + if not gen_server: + if ctx_response is not None: + # A pooled generation router ages the request from its arrival and + # bounds its wait by the context servers' KV transfer timeout, which + # runs from here. Stamped again below to include this wait. + self._stamp_orig_elapsed(gen_req, arrival_time) + gen_server, gen_route_info = await self._gen_router.get_next_server( + gen_req, exclude_server=ctx_server, req_id=disagg_request_id + ) + gen_reservation_id = disagg_request_id + if length_ticket is not None: + self._output_length_priority.placed(length_ticket, gen_req, gen_route_info) + self._stamp_orig_elapsed(gen_req, arrival_time) + gen_response = await self._gen_client.send_request( + gen_req, server=gen_server, hooks=hooks, req_id=gen_reservation_id ) - gen_reservation_id = disagg_request_id - self._stamp_orig_elapsed(gen_req, arrival_time) - gen_response = await self._gen_client.send_request( - gen_req, server=gen_server, hooks=hooks, req_id=gen_reservation_id - ) + except BaseException: + if length_ticket is not None: + # No reply will come: the coordinator drops the request's prediction row. + self._output_length_priority.abandon(length_ticket) + raise + if length_ticket is not None: + gen_response = self._output_length_priority.track(gen_response, length_ticket) return gen_response else: + if length_ticket is not None: + self._output_length_priority.track(ctx_response, length_ticket) if gen_server: await self._gen_router.finish_request(request, req_id=gen_reservation_id) if hooks: @@ -636,9 +688,17 @@ async def _send_disagg_request_gen_first( # # Fix: eagerly start consuming the gen generator in a background # task so the HTTP POST fires, then pipe chunks through a queue. - gen_response = await self._gen_client.send_request( - gen_req, server=gen_server, hooks=hooks, req_id=disagg_request_id - ) + try: + gen_response = await self._gen_client.send_request( + gen_req, server=gen_server, hooks=hooks, req_id=disagg_request_id + ) + except (Exception, asyncio.CancelledError): + # No context task owns the context reservation yet (e.g. a pooled + # generation router found no seat): release it here. + await self._ctx_router.finish_request( + request, success=False, req_id=disagg_request_id + ) + raise queue: asyncio.Queue = asyncio.Queue() gen_error: asyncio.Future[None] = asyncio.get_running_loop().create_future() diff --git a/tensorrt_llm/serve/openai_protocol.py b/tensorrt_llm/serve/openai_protocol.py index 0b0996bd0929..c5a03a04dbef 100644 --- a/tensorrt_llm/serve/openai_protocol.py +++ b/tensorrt_llm/serve/openai_protocol.py @@ -48,7 +48,7 @@ from openai.types.shared import Metadata, Reasoning from openai_harmony import ReasoningEffort from pydantic import (AliasChoices, BaseModel, ConfigDict, Field, - NonNegativeInt, PositiveInt, field_validator, + NonNegativeInt, PositiveInt, PrivateAttr, field_validator, model_serializer, model_validator) from typing_extensions import Annotated, Required, TypeAlias, TypedDict @@ -378,6 +378,21 @@ class ConversationParams(OpenAIBaseModel): "affinity; forwarded to workers as a header, never in the " "body.")) + # The server generated conversation_id for one request; it never recurs. + _generated_for_one_request: bool = PrivateAttr(default=False) + + @classmethod + def for_one_request(cls, conversation_id: str) -> "ConversationParams": + """Params with a ``conversation_id`` generated for one request.""" + params = cls(conversation_id=conversation_id) + params._generated_for_one_request = True + return params + + @property + def generated_for_one_request(self) -> bool: + """Whether ``conversation_id`` was generated for one request.""" + return self._generated_for_one_request + @field_validator("conversation_id", mode="before") @classmethod def validate_conversation_id(cls, value: Any) -> str: diff --git a/tensorrt_llm/serve/openai_server.py b/tensorrt_llm/serve/openai_server.py index 573cfce80f4b..8f864da62b93 100644 --- a/tensorrt_llm/serve/openai_server.py +++ b/tensorrt_llm/serve/openai_server.py @@ -3921,6 +3921,13 @@ async def get_server_info(self) -> JSONResponse: if args is not None: if args.max_batch_size is not None: content["max_batch_size"] = args.max_batch_size + # A pooled generation router bounds the seat wait by it; null (no + # timeout) is reported too, so the router can tell it from unset. + cache_transceiver_config = getattr(args, "cache_transceiver_config", + None) + if cache_transceiver_config is not None: + content[ + "kv_transfer_timeout_ms"] = cache_transceiver_config.kv_transfer_timeout_ms kv_cache_config = args.kv_cache_config if kv_cache_config is not None: content[ diff --git a/tensorrt_llm/serve/output_length_predictor.py b/tensorrt_llm/serve/output_length_predictor.py new file mode 100644 index 000000000000..abb00f5b22f5 --- /dev/null +++ b/tensorrt_llm/serve/output_length_predictor.py @@ -0,0 +1,1173 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Online output-length prediction for the generation admission order in disaggregated serving. + +Enabled by ``output_length_prediction`` in the disaggregated server config. After a request's context +phase, the orchestrator predicts its output length and writes +``priority = 1 / (1 + tokens / PRIORITY_SCALE_TOKENS)`` (strictly decreasing in the prediction) into the +generation request's ``priority``. Generation servers that run ``waiting_queue_policy: priority`` then +admit the shortest predicted reply first, and a pooled generation router places in the same order. + +The predictor learns from the replies of the running server only; nothing is loaded or saved. It lives +in the coordinator (one per orchestrator), so it sees the replies of every frontend. Its inputs are the +conversation's earlier replies (keyed by ``conversation_params.conversation_id``) and the context +phase's prompt length; the request's ``max_tokens`` is never read. + +Per conversation it keeps the recorded replies' count, last / EMA(0.5) / mean / max output tokens and +the last prompt length. A reply without a conversation id trains the global models (median, ridge, +trees) with an empty history. A request's 7 features: log1p of the history count, of its prompt tokens, and +of the last / EMA / mean / max output tokens (NaN without history), and the signed log1p of the tokens +appended since the last reply (NaN without history). Rules: a history of exactly one reply with a +prompt under 1,500 tokens is dropped when the next request appends over 10,000 tokens (a new prefix), +and replies of at most 2 tokens (cache primers) are not learned. + +Predictors, each taking over at its first fit: + * a conversation with history gets its EMA(0.5); otherwise the median of the last + ``MEDIAN_WINDOW`` learned replies, or ``PRIOR_TOKENS`` before the first; + * ``ridge``: a ridge regression of log1p(output tokens) on the features (NaN as -1 plus a missing + indicator per feature), refit every ``RIDGE_REFIT_S`` on the replies learned so far; + * ``ridge_gbm``: also a gradient-boosted tree ensemble on the same target (scikit-learn + ``HistGradientBoostingRegressor``), refit every ``GBM_REFIT_S`` on the last ``GBM_MAX_ROWS`` + learned replies in a separate Python process off the request path; the coordinator evaluates + its trees itself. + +In a fleet (``num_workers > 1``) a generation router placed by the coordinator gets the prediction +from ``/select`` (the routing key carries ``OUTPUT_LENGTH_KEY``), so it costs no extra round trip; +otherwise the frontend asks the coordinator's ``/output_length``. Finished replies go back in +batches. Only requests with a ``priority`` field (completions and chat completions) are predicted; +``/v1/responses`` requests are not. +""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import math +import os +import re +import subprocess # nosec B404 - runs sys.executable -I with a fixed argv, no shell +import sys +import threading +import time +from array import array +from bisect import bisect_left, insort +from collections import OrderedDict, deque +from typing import TYPE_CHECKING, Any, AsyncIterator, List, Optional, Protocol, Tuple, get_args + +from tensorrt_llm.llmapi.disagg_utils import OutputLengthPredictorName as PredictorName +from tensorrt_llm.logger import logger + +if TYPE_CHECKING: + from tensorrt_llm.serve.disagg_coordinator import DisaggCoordinator + from tensorrt_llm.serve.openai_protocol import ( + ChatCompletionRequest, + CompletionRequest, + ResponsesRequest, + ) + from tensorrt_llm.serve.responses_utils import UCompletionResponseOrGenerator + + # A request the orchestrator sends to a generation server. + GenerationRequest = CompletionRequest | ChatCompletionRequest | ResponsesRequest + +PREDICTORS = get_args(PredictorName) + +# priority = 1 / (1 + tokens / scale); the admission order does not depend on the scale. +PRIORITY_SCALE_TOKENS = 1024.0 +# Neutral starting value: the prediction before any reply is learned (the learned median replaces it +# after the first reply) and for a request the coordinator could not predict. +PRIOR_TOKENS = 400.0 +PREDICT_TIMEOUT_S = 1.0 +RECORD_TIMEOUT_S = 5.0 +STATS_LOG_PERIOD_S = 30.0 +# Routing-key and route-info entry of a /select that predicts the output length. +OUTPUT_LENGTH_KEY = "output_length" +# Finished replies go to the coordinator in batches: at most this many, at most this late. +RECORD_BATCH_MAX = 512 +RECORD_FLUSH_S = 0.05 +# Warn if none of this many reported replies was learned. +NOTHING_LEARNED_WARN_AFTER = 1000 + +FEATURES = ("turn", "isl", "prev_out", "ema_out", "mean_out", "max_out", "appended") +RESET_MAX_PREV_ISL = 1500.0 +RESET_MIN_APPENDED = 10000.0 +SKIP_MAX_OUT = 2.0 +MAX_CONVERSATIONS = 50000 +# A longer conversation id is keyed by its digest, which bounds the table's memory. +MAX_CONVERSATION_ID_CHARS = 128 +# Features of predicted requests whose reply has not been learned yet. A row leaves when its reply +# is learned or reported failed, when it is older than PENDING_MAX_AGE_S (the coordinator's pooled +# seat expiry: no generation runs longer), or, past this many rows, oldest first. +MAX_PENDING_ROWS = 200000 +PENDING_MAX_AGE_S = 6 * 3600.0 +# The median prior covers the last this many learned replies. +MEDIAN_WINDOW = 10000 + +RIDGE_REFIT_S = 120.0 +RIDGE_ALPHA = 1.0 +RIDGE_MIN_ROWS = 200 +GBM_REFIT_S = 300.0 +GBM_MIN_ROWS = 1000 +GBM_THREADS = 4 +GBM_FIT_TIMEOUT_S = 600.0 +# The tree ensemble is fitted on the last this many learned replies (8 doubles each). +GBM_MAX_ROWS = 250000 +# A fitted ensemble goes live only if the coordinator's tree walk matches scikit-learn's predict. +GBM_EXPORT_TOL = 1e-6 +GBM_PARAMS = { + "max_iter": 300, + "learning_rate": 0.05, + "max_leaf_nodes": 15, + "min_samples_leaf": 200, + "l2_regularization": 1.0, + "early_stopping": True, + "validation_fraction": 0.1, + "random_state": 0, +} + +NAN = float("nan") +# Prompt and reply lengths are valid up to this many tokens, far beyond any model's context window. It bounds the +# log1p features and targets the models learn (<= 16.7), and a model's log prediction is clamped to it. +MAX_TOKENS = float(2**24) +_LOG1P_MAX_TOKENS = math.log1p(MAX_TOKENS) + +# A conversation's history as passed to features(): (count, last out, EMA out, sum out, max out, last prompt). +Snapshot = Tuple[float, float, float, float, float, float] + + +def is_token_count(value: Any) -> bool: + """Whether ``value`` is a number in [0, ``MAX_TOKENS``] (not a bool or NaN).""" + return ( + isinstance(value, (int, float)) and not isinstance(value, bool) and 0 <= value <= MAX_TOKENS + ) + + +def _tokens_of(log1p_tokens: float) -> float: + """A model's log1p prediction as tokens, clamped to [0, ``MAX_TOKENS``] (NaN stays NaN).""" + return math.expm1(min(max(log1p_tokens, 0.0), _LOG1P_MAX_TOKENS)) + + +def priority_of(tokens: float) -> float: + """Map predicted output tokens into [0, 1], decreasing: shorter replies go first. + + A NaN prediction gets the prior's priority. + """ + tokens = float(tokens) + if tokens != tokens: + tokens = PRIOR_TOKENS + return 1.0 / (1.0 + max(tokens, 0.0) / PRIORITY_SCALE_TOKENS) + + +class _History: + __slots__ = ("n", "last_out", "ema", "sum_out", "max_out", "last_isl") + + def __init__(self) -> None: + self.n = 0 + self.last_out = NAN + self.ema = NAN + self.sum_out = 0.0 + self.max_out = NAN + self.last_isl = NAN + + def record(self, isl: float, out: float) -> None: + self.ema = out if self.n == 0 else 0.5 * out + 0.5 * self.ema + self.sum_out += out + self.max_out = out if self.n == 0 else max(self.max_out, out) + self.last_out = out + self.last_isl = isl + self.n += 1 + + def snapshot(self) -> Snapshot: + return (float(self.n), self.last_out, self.ema, self.sum_out, self.max_out, self.last_isl) + + +def _table_key(conv_id: str) -> str | bytes: + """``conv_id``, or a 16-byte digest of it when longer than ``MAX_CONVERSATION_ID_CHARS``.""" + if len(conv_id) <= MAX_CONVERSATION_ID_CHARS: + return conv_id + return hashlib.blake2b(conv_id.encode(errors="surrogatepass"), digest_size=16).digest() + + +class ConversationLengthTable: + """Per-conversation reply history (least recently used conversations evicted).""" + + def __init__(self, max_conversations: int = MAX_CONVERSATIONS) -> None: + self.max_conversations = max_conversations + self._histories: OrderedDict[str | bytes, _History] = OrderedDict() + self.resets = 0 + self.recorded = 0 + self.skipped = 0 + + def __len__(self) -> int: + return len(self._histories) + + def snapshot_for(self, conv_id: Optional[str], isl: float) -> Optional[Snapshot]: + """The conversation's history for a new request, after the reset rule; None without one.""" + if conv_id is None: + return None + key = _table_key(conv_id) + history = self._histories.get(key) + if history is None: + return None + self._histories.move_to_end(key) + if ( + history.n == 1 + and history.last_isl < RESET_MAX_PREV_ISL + and isl - history.last_isl - history.last_out > RESET_MIN_APPENDED + ): + del self._histories[key] + self.resets += 1 + return None + return history.snapshot() + + def record(self, conv_id: str, isl: float, out: float) -> None: + """Add a finished reply to its conversation's history. + + :meth:`OnlineLengthPredictor.record` decides which replies are learned (and counts the + skipped cache primers in ``skipped``). + """ + key = _table_key(conv_id) + history = self._histories.get(key) + if history is None: + history = self._histories[key] = _History() + if len(self._histories) > self.max_conversations: + self._histories.popitem(last=False) + else: + self._histories.move_to_end(key) + history.record(float(isl), float(out)) + self.recorded += 1 + + +def _log1p_nonneg(value: float) -> float: + return NAN if value != value else math.log1p(max(value, 0.0)) + + +def _signed_log1p(value: float) -> float: + if value != value: + return NAN + return math.copysign(math.log1p(abs(value)), value) if value != 0.0 else 0.0 + + +def features(snapshot: Optional[Snapshot], isl: float) -> list: + """The predictors' input row for a request with ``isl`` prompt tokens and a history (None: none).""" + isl = float(isl) + if snapshot is None or snapshot[0] <= 0: + return [0.0, _log1p_nonneg(isl), NAN, NAN, NAN, NAN, NAN] + n, last_out, ema, sum_out, max_out, last_isl = (float(v) for v in snapshot) + return [ + math.log1p(n), + _log1p_nonneg(isl), + _log1p_nonneg(last_out), + _log1p_nonneg(ema), + _log1p_nonneg(sum_out / n), + _log1p_nonneg(max_out), + _signed_log1p(isl - last_isl - last_out), + ] + + +class TreeEnsemble: + """Raw prediction of a fitted ``HistGradientBoostingRegressor``: baseline + one leaf per tree. + + A node is ``(is_leaf, value, feature, threshold, missing_go_to_left, left, right)``. + """ + + def __init__(self, baseline: float, trees: list) -> None: + self.baseline = float(baseline) + self.trees = [[tuple(node) for node in tree] for tree in trees] + + def raw(self, x: list) -> float: + acc = self.baseline + for nodes in self.trees: + i = 0 + while True: + is_leaf, value, feature, threshold, missing_left, left, right = nodes[i] + if is_leaf: + acc += value + break + v = x[feature] + if v != v: + i = left if missing_left else right + else: + i = left if v <= threshold else right + return acc + + +class RunningMedian: + """Median of the last ``window`` values added (the mean of the two middle values for an even count). + + ``n`` counts every value added. + """ + + __slots__ = ("_recent", "_sorted", "window", "n") + + def __init__(self, window: int = MEDIAN_WINDOW) -> None: + self.window = window + self._recent: deque = deque() + self._sorted: list = [] + self.n = 0 + + def add(self, value: float) -> None: + value = float(value) + self._recent.append(value) + insort(self._sorted, value) + if len(self._recent) > self.window: + del self._sorted[bisect_left(self._sorted, self._recent.popleft())] + self.n += 1 + + def value(self) -> float: + k = len(self._sorted) + if not k: + return NAN + if k % 2: + return self._sorted[k // 2] + return (self._sorted[k // 2 - 1] + self._sorted[k // 2]) / 2.0 + + +def ridge_row(x: list) -> list: + """The ridge's design row: the features with NaN as -1, then a 0/1 missing indicator per feature.""" + return [-1.0 if v != v else float(v) for v in x] + [1.0 if v != v else 0.0 for v in x] + + +def _solve(a: list, b: list) -> list: + """Solve ``a @ w = b`` by Gaussian elimination with partial pivoting (``a`` and ``b`` are consumed).""" + n = len(b) + for k in range(n): + p = max(range(k, n), key=lambda r: abs(a[r][k])) + if a[p][k] == 0.0: + raise ZeroDivisionError("singular ridge system") + if p != k: + a[k], a[p] = a[p], a[k] + b[k], b[p] = b[p], b[k] + row_k, pivot = a[k], a[k][k] + for r in range(k + 1, n): + f = a[r][k] / pivot + if f != 0.0: + row_r = a[r] + for c in range(k, n): + row_r[c] -= f * row_k[c] + b[r] -= f * b[k] + w = [0.0] * n + for k in range(n - 1, -1, -1): + w[k] = (b[k] - sum(a[k][c] * w[c] for c in range(k + 1, n))) / a[k][k] + return w + + +class OnlineRidge: + """Ridge regression kept as running means and centered co-moments. + + ``fit`` solves ``(Cxx + alpha I) w = Cxy`` with ``intercept = mean(y) - mean(x) @ w``: scikit-learn's + ``Ridge(alpha)`` on the same rows (the intercept is not penalized). + """ + + def __init__(self, dim: int, alpha: float = RIDGE_ALPHA) -> None: + self.dim = dim + self.alpha = float(alpha) + self.n = 0 + self.mean_x = [0.0] * dim + self.mean_y = 0.0 + self.cxx = [[0.0] * dim for _ in range(dim)] + self.cxy = [0.0] * dim + self.coef: Optional[list] = None + self.intercept = NAN + self.fit_rows = 0 + + def add(self, z: list, y: float) -> None: + """Welford update: ``C += (z - old mean) (z - new mean)^T``.""" + self.n += 1 + n = self.n + dx = [zi - mi for zi, mi in zip(z, self.mean_x)] + self.mean_x = [mi + di / n for mi, di in zip(self.mean_x, dx)] + self.mean_y += (y - self.mean_y) / n + ex = [zi - mi for zi, mi in zip(z, self.mean_x)] + ey = y - self.mean_y + for i in range(self.dim): + di = dx[i] + if di != 0.0: + row = self.cxx[i] + for j in range(self.dim): + row[j] += di * ex[j] + self.cxy[i] += di * ey + + def fit(self) -> None: + d = self.dim + a = [ + [ + 0.5 * (self.cxx[i][j] + self.cxx[j][i]) + (self.alpha if i == j else 0.0) + for j in range(d) + ] + for i in range(d) + ] + w = _solve(a, list(self.cxy)) + self.coef = w + self.intercept = self.mean_y - sum(wi * mi for wi, mi in zip(w, self.mean_x)) + self.fit_rows = self.n + + def raw(self, z: list) -> float: + return self.intercept + sum(wi * zi for wi, zi in zip(self.coef, z)) + + +# The fit process: numpy + scikit-learn only. The header (with the server's sys.path, which -I drops) +# is argv[1], the rows come in on stdin, the trees go out as JSON on stdout, with the largest difference +# between its tree walk and scikit-learn's predict on up to 2,000 rows. +_GBM_FIT_SCRIPT = r""" +import json, os, sys, time +header = json.loads(sys.argv[1]) +sys.path[:0] = header["sys_path"] +try: + os.nice(10) +except OSError: + pass +import numpy as np +from sklearn.ensemble import HistGradientBoostingRegressor +n, d = header["n"], header["d"] +data = np.frombuffer(sys.stdin.buffer.read(), dtype=np.float64).reshape(n, d + 1) +X, y = data[:, :d], data[:, d] +t0 = time.perf_counter() +model = HistGradientBoostingRegressor(**header["params"]).fit(X, y) +fit_s = time.perf_counter() - t0 +trees = [] +for predictors in model._predictors: + nodes = predictors[0].nodes + if len(predictors) != 1 or bool(np.any(nodes["is_categorical"])): + raise SystemExit("unsupported tree") + trees.append([[bool(r["is_leaf"]), float(r["value"]), int(r["feature_idx"]), float(r["num_threshold"]), + bool(r["missing_go_to_left"]), int(r["left"]), int(r["right"])] for r in nodes]) +baseline = float(np.asarray(model._baseline_prediction).ravel()[0]) +def walk(x): + acc = baseline + for nodes in trees: + i = 0 + while True: + leaf, v, f, thr, ml, le, ri = nodes[i] + if leaf: + acc += v + break + xv = x[f] + i = (le if ml else ri) if xv != xv else (le if xv <= thr else ri) + return acc +k = min(n, 2000) +ref = model.predict(X[:k]) if k else [] +diff = max((abs(walk([float(v) for v in X[j]]) - float(ref[j])) for j in range(k)), default=0.0) +json.dump({"baseline": baseline, "trees": trees, "n_iter": int(model.n_iter_), "fit_s": fit_s, + "export_max_abs_diff": diff}, sys.stdout) +""" + + +def child_sys_path() -> List[str]: + """The server's import path for a ``-I`` child: ``sys.path`` without the working directory. + + ``-I`` ignores ``PYTHONPATH`` and the user site (where scikit-learn may be installed) and keeps + the working directory off the path; the child prepends this list instead. + """ + cwd = os.getcwd() + return [ + entry + for entry in sys.path + if entry and os.path.isabs(entry) and os.path.realpath(entry) != os.path.realpath(cwd) + ] + + +# Rows of the startup check, enough for trees with splits under GBM_PARAMS' min_samples_leaf. +GBM_CHECK_ROWS = 1000 +GBM_CHECK_TIMEOUT_S = 120.0 + + +def _gbm_check_rows(n: int) -> array: + """``n`` deterministic synthetic training rows: the features (some missing), then the target.""" + rows = array("d") + for i in range(n): + rows.extend( + NAN if (i + j) % 7 == 0 else float((i * (j + 3)) % 97) for j in range(len(FEATURES)) + ) + rows.append(math.log1p(float((i * 37) % 2000))) + return rows + + +def _gbm_fit_problem(result: dict) -> Optional[str]: + """Why a tree fit's result cannot go live (a failed fit, or a tree walk unlike predict), or None.""" + if "error" in result: + return str(result["error"]) + diff = result.get("export_max_abs_diff") + if diff is None or not diff <= GBM_EXPORT_TOL: + return f"export check {diff}" + return None + + +def check_gbm_dependencies(python: Optional[str] = None) -> None: + """Raise ImportError unless the fit process can fit and export trees with scikit-learn. + + Runs the refit itself (:class:`SubprocessGbmFitter`) once on synthetic rows and applies the + checks that put a refit live, so what passes here also passes at every refit. + """ + fitter = SubprocessGbmFitter(timeout_s=GBM_CHECK_TIMEOUT_S, python=python, sync=True) + fitter.start(_gbm_check_rows(GBM_CHECK_ROWS), GBM_CHECK_ROWS, {}) + problem = _gbm_fit_problem(fitter.poll() or {"error": "no result"}) + if problem is not None: + raise ImportError( + "output_length_prediction.predictor='ridge_gbm' fits its trees with numpy and " + "scikit-learn and reads them from HistGradientBoostingRegressor's fitted predictors, " + f"which {fitter.python} cannot do ({problem.strip()[-300:]}); " + "install a scikit-learn that provides them or use predictor='ridge'" + ) + + +class SubprocessGbmFitter: + """Fits the tree ensemble off the request path, in a separate Python process. + + ``start`` hands the rows to a background thread, which serializes them and runs the process; + ``poll`` returns its result once. ``sync=True`` fits inside ``start`` (tests). + """ + + def __init__( + self, + threads: int = GBM_THREADS, + timeout_s: float = GBM_FIT_TIMEOUT_S, + python: Optional[str] = None, + sync: bool = False, + ) -> None: + self.threads = threads + self.timeout_s = timeout_s + self.python = python or sys.executable + self.sync = sync + self._lock = threading.Lock() + self._thread: Optional[threading.Thread] = None + self._result: Optional[dict] = None + + def busy(self) -> bool: + return self._thread is not None and self._thread.is_alive() + + def start(self, rows: array, n: int, meta: dict) -> None: + """Fit on ``rows`` (``n`` rows of the features and the target; not modified afterwards).""" + header = {"n": n, "d": len(FEATURES), "params": GBM_PARAMS, "sys_path": child_sys_path()} + if self.sync: + self._finish(self._run(header, rows), meta) + return + self._thread = threading.Thread( + target=lambda: self._finish(self._run(header, rows), meta), + name="output-length-gbm-fit", + daemon=True, + ) + self._thread.start() + + def _run(self, header: dict, rows: array) -> dict: + env = dict(os.environ) + env.update(OMP_NUM_THREADS=str(self.threads), OPENBLAS_NUM_THREADS="1", MKL_NUM_THREADS="1") + try: + result = subprocess.run( + [self.python, "-I", "-c", _GBM_FIT_SCRIPT, json.dumps(header)], + input=rows.tobytes(), + capture_output=True, + timeout=self.timeout_s, + env=env, + check=False, + ) + except (OSError, subprocess.TimeoutExpired) as e: + return {"error": f"{type(e).__name__}: {e}"} + if result.returncode != 0: + return { + "error": f"exit {result.returncode}: {result.stderr.decode(errors='replace')[-1500:]}" + } + try: + return json.loads(result.stdout) + except ValueError as e: + return {"error": f"unreadable fit output: {e}"} + + def _finish(self, result: dict, meta: dict) -> None: + result.update(meta) + with self._lock: + self._result = result + + def poll(self) -> Optional[dict]: + with self._lock: + result, self._result = self._result, None + return result + + +class GbmFitter(Protocol): + """What :class:`OnlineLengthPredictor` needs of a tree fitter (:class:`SubprocessGbmFitter`).""" + + def busy(self) -> bool: ... + + def start(self, rows: array, n: int, meta: dict) -> None: ... + + def poll(self) -> Optional[dict]: ... + + +class OnlineLengthPredictor: + """The coordinator's predictor: the conversation table and the online models. + + Events carry their time ``t`` (``time.monotonic()`` in the coordinator), so the same events give the + same predictions, except that a tree ensemble goes live at the first event after its fit returns. + Its memory is bounded: ``MAX_CONVERSATIONS`` histories, ``MAX_PENDING_ROWS`` predicted rows, + ``MEDIAN_WINDOW`` replies for the median and ``GBM_MAX_ROWS`` training rows for the trees. + """ + + def __init__(self, predictor: PredictorName, gbm_fitter: Optional[GbmFitter] = None) -> None: + if predictor not in PREDICTORS: + raise ValueError(f"predictor must be one of {PREDICTORS}, got {predictor!r}") + self.predictor = predictor + self.table = ConversationLengthTable() + self.median = RunningMedian() + self.ridge = OnlineRidge(2 * len(FEATURES)) + self.gbm_on = predictor == "ridge_gbm" + self.gbm_fitter = gbm_fitter + if self.gbm_on and self.gbm_fitter is None: + check_gbm_dependencies() + self.gbm_fitter = SubprocessGbmFitter() + # The last GBM_MAX_ROWS training rows (features + target), a ring once full. + self.gbm_rows = array("d") + self.gbm_max_rows = GBM_MAX_ROWS + self.gbm_n = 0 + self.gbm: Optional[TreeEnsemble] = None + self.gbm_fits = 0 + self.gbm_errors = 0 + self.gbm_busy_skips = 0 + self.ridge_fits = 0 + self.t0: Optional[float] = None + self.next_ridge_fit = math.inf + self.next_gbm_fit = math.inf + # Prediction key -> (time of the prediction, features), oldest first. + self._pending: OrderedDict[int, Tuple[float, list]] = OrderedDict() + self._next_key = 0 + self.unmatched = 0 + self.dropped = 0 + self.learned = 0 + self.without_conversation = 0 + self.invalid = 0 + self.reported = 0 + self.sources = {"prior": 0, "median": 0, "ema": 0, "ridge": 0, "gbm": 0} + self._last_stats = time.monotonic() + + def _tick(self, t: float) -> None: + """Start the clock at the first event, then run every refit boundary at or before ``t``.""" + if self.t0 is None: + self.t0 = t + self.next_ridge_fit = t + RIDGE_REFIT_S + if self.gbm_on: + self.next_gbm_fit = t + GBM_REFIT_S + return + if t >= self.next_ridge_fit: + # One fit for every boundary passed: no rows arrive between them, so it is the same. + if self.ridge.n >= RIDGE_MIN_ROWS: + self.ridge.fit() + self.ridge_fits += 1 + self.next_ridge_fit += RIDGE_REFIT_S * ( + 1 + math.floor((t - self.next_ridge_fit) / RIDGE_REFIT_S) + ) + while t >= self.next_gbm_fit: + rows = min(self.gbm_n, self.gbm_max_rows) + if rows >= GBM_MIN_ROWS: + if self.gbm_fitter.busy(): + self.gbm_busy_skips += 1 + else: + meta = {"rows": rows, "boundary_s": self.next_gbm_fit - self.t0} + # A bounded copy: later replies overwrite the ring while the fit runs. + self.gbm_fitter.start(self.gbm_rows[: rows * (len(FEATURES) + 1)], rows, meta) + self.next_gbm_fit += GBM_REFIT_S + if self.gbm_on: + result = self.gbm_fitter.poll() + if result is not None: + self._install_gbm(result) + + def _add_gbm_row(self, x: list, y: float) -> None: + width = len(FEATURES) + 1 + row = array("d", x) + row.append(y) + if self.gbm_n < self.gbm_max_rows: + self.gbm_rows.extend(row) + else: + i = (self.gbm_n % self.gbm_max_rows) * width + self.gbm_rows[i : i + width] = row + self.gbm_n += 1 + + def _install_gbm(self, result: dict) -> None: + problem = _gbm_fit_problem(result) + if problem is not None: + self.gbm_errors += 1 + logger.warning( + f"[output_length] tree fit on {result.get('rows')} replies failed, the current model " + f"stays: {problem}" + ) + return + diff = result["export_max_abs_diff"] + self.gbm = TreeEnsemble(result["baseline"], result["trees"]) + self.gbm_fits += 1 + logger.info( + f"[output_length] tree fit #{self.gbm_fits} live: {result['rows']} replies, {result['n_iter']} " + f"iterations, fit {result['fit_s']:.2f} s, export check {diff:.1e}" + ) + + def predict( + self, conv_id: Optional[str], isl: float, t: float, key: Optional[int] = None + ) -> Tuple[float, int]: + """(predicted output tokens, key): the key goes back with the reply, so its features can be learned. + + A ``key`` still pending (the same request predicted again, e.g. a repeated ``/select``) is + reused, so the request keeps one row. Raises ValueError unless ``isl`` is a finite number + in [0, ``MAX_TOKENS``]. + """ + if not is_token_count(isl): + raise ValueError( + f"prompt tokens must be a finite number in [0, {MAX_TOKENS:.0f}], got {isl!r}" + ) + self._tick(t) + snapshot = self.table.snapshot_for(conv_id, isl) + x = features(snapshot, isl) + tokens, source = NAN, "prior" + if self.gbm is not None: + tokens, source = _tokens_of(self.gbm.raw(x)), "gbm" + elif self.ridge.coef is not None: + tokens, source = _tokens_of(self.ridge.raw(ridge_row(x))), "ridge" + elif snapshot is not None: + tokens, source = snapshot[2], "ema" + elif self.median.n: + tokens, source = self.median.value(), "median" + if not math.isfinite(tokens): + tokens, source = PRIOR_TOKENS, "prior" + self.sources[source] += 1 + if key is None or key not in self._pending: + key = self._next_key + self._next_key += 1 + self._pending[key] = (t, x) + self._pending.move_to_end(key) + pending = self._pending + while pending and ( + len(pending) > MAX_PENDING_ROWS + or t - next(iter(pending.values()))[0] > PENDING_MAX_AGE_S + ): + pending.popitem(last=False) + self._maybe_log_stats() + return tokens, key + + def record( + self, + conv_id: Optional[str], + isl: float, + out: Optional[float], + key: Optional[int], + t: float, + ) -> bool: + """Learn a finished reply of ``out`` tokens; returns whether it was learned. + + ``out`` None reports a request that ended without a reply length (failed, interrupted): + its row is dropped, nothing is learned. Not learned either: an ``isl`` / ``out`` outside + [0, ``MAX_TOKENS``] (or NaN), and a reply of at most ``SKIP_MAX_OUT`` tokens (a cache + primer). A reply without a conversation id trains the global models only. + """ + self._tick(t) + row = self._pending.pop(key, None) if key is not None else None + if out is None: + self.dropped += row is not None + return False + self.reported += 1 + x = row[1] if row is not None else None + if not (is_token_count(isl) and is_token_count(out)): + self.invalid += 1 + return self._learned(False) + if out <= SKIP_MAX_OUT: + self.table.skipped += 1 + return self._learned(False) + if conv_id is None: + self.without_conversation += 1 + if x is None: + # Without a conversation the features never depend on history. + x = features(None, isl) + else: + self.table.record(conv_id, isl, out) + self.median.add(out) + if x is None: + self.unmatched += 1 + else: + y = math.log1p(out) + self.ridge.add(ridge_row(x), y) + if self.gbm_on: + self._add_gbm_row(x, y) + return self._learned(True) + + def _learned(self, learned: bool) -> bool: + self.learned += learned + if self.reported == NOTHING_LEARNED_WARN_AFTER and not self.learned: + logger.warning( + f"[output_length] none of the first {self.reported} replies was learned " + f"({self.invalid} invalid, {self.table.skipped} of at most {SKIP_MAX_OUT:g} tokens): " + f"every generation request keeps the prior's priority" + ) + self._maybe_log_stats() + return learned + + def stats_line(self) -> str: + sources = ", ".join(f"{k} {v}" for k, v in self.sources.items() if v) or "none" + line = ( + f"[output_length] {self.predictor}: {len(self.table)} conversations, replies learned " + f"{self.learned} ({self.without_conversation} without a conversation id; skipped " + f"{self.table.skipped}, invalid {self.invalid}, resets {self.table.resets}), median " + f"{self.median.value():.1f} tokens; predictions by source: {sources}; ridge fits {self.ridge_fits}" + ) + if self.gbm_on: + line += f"; tree fits {self.gbm_fits}, errors {self.gbm_errors}, busy skips {self.gbm_busy_skips}" + return ( + line + + f"; pending {len(self._pending)}, replies without their features {self.unmatched}, " + f"failed requests dropped {self.dropped}" + ) + + def _maybe_log_stats(self) -> None: + now = time.monotonic() + if now - self._last_stats >= STATS_LOG_PERIOD_S: + self._last_stats = now + logger.info(self.stats_line()) + + +def request_inputs(request: Any) -> Tuple[Optional[str], Optional[float]]: + """(conversation id, prompt tokens) of a generation request after its context phase. + + Reads ``conversation_params.conversation_id`` and ``disaggregated_params.ctx_usage.prompt_tokens`` + only; in particular never ``max_tokens``. An id the server generated for one request (a + sub-agent call with only its parent's header) names no conversation: None. + """ + conversation = getattr(request, "conversation_params", None) + conv_id = None + if conversation is not None and not getattr(conversation, "generated_for_one_request", False): + conv_id = getattr(conversation, "conversation_id", None) + params = getattr(request, "disaggregated_params", None) + usage = getattr(params, "ctx_usage", None) if params is not None else None + isl = getattr(usage, "prompt_tokens", None) if usage is not None else None + return (str(conv_id) if conv_id is not None else None, float(isl) if isl is not None else None) + + +_USAGE_MARK = b'"completion_tokens"' +# A line with a ``choices`` key that is an empty list or null; a line with a non-empty one is +# not a usage-only chunk, so it is not decoded (with continuous usage every chunk has usage). +_NO_CHOICES = re.compile(rb'"choices"\s*:\s*(?:\[\s*\]|null)') + + +def _sse_json(event: bytes) -> Optional[dict]: + """The JSON object of an SSE event's ``data:`` line, else None.""" + for line in event.split(b"\n"): + line = line.strip() + if not line.startswith(b"data:"): + continue + payload = line[5:].strip() + if not payload or payload == b"[DONE]": + return None + try: + obj = json.loads(payload) + except ValueError: + return None + return obj if isinstance(obj, dict) else None + return None + + +def completion_tokens_in(data: bytes) -> Tuple[Optional[int], bool]: + """Scan SSE ``data:`` lines for a usage-only chunk's ``usage.completion_tokens``: (value, True). + + (None, False) without one. Only lines that may be such a chunk are decoded. + """ + if _USAGE_MARK not in data: + return None, False + found, final = None, False + for line in data.split(b"\n"): + if (b'"choices"' in line and not _NO_CHOICES.search(line)) or _USAGE_MARK not in line: + continue + obj = _sse_json(line) + usage = obj.get("usage") if obj is not None else None + if isinstance(usage, dict) and usage.get("completion_tokens") is not None: + found = int(usage["completion_tokens"]) + final = not obj.get("choices") + return found, final + + +class _Ticket: + __slots__ = ("conv_id", "isl", "key", "sequences", "recorded", "via_select", "strip_usage") + + def __init__( + self, conv_id: Optional[str], isl: float, key: Optional[int], sequences: int = 1 + ) -> None: + self.conv_id = conv_id + self.isl = isl + self.key = key + # Returned sequences (``n``): the reply's usage sums their lengths. + self.sequences = sequences + self.recorded = False + # The prediction comes with the generation placement (/select). + self.via_select = False + # The client did not ask for streamed usage: drop the final usage-only chunk. + self.strip_usage = False + + +def throttled(count: int) -> bool: + """Whether the ``count``-th occurrence of a repeated warning is logged: the first 10, then every 1000th.""" + return count <= 10 or count % 1000 == 0 + + +class OutputLengthPriority: + """Frontend side: set the generation request's priority, then report its reply's length. + + ``coordinator`` provides ``predict_output_length`` and ``record_output_lengths`` + (:class:`~tensorrt_llm.serve.disagg_coordinator.DisaggCoordinator`). With ``via_select``, a + request placed after :meth:`assign` gets its prediction from the generation placement + (:meth:`placed`) instead of a separate call. Replies are reported in batches of up to + ``RECORD_BATCH_MAX``, at most ``record_flush_s`` after the first of a batch. + """ + + def __init__( + self, + coordinator: DisaggCoordinator, + predictor: PredictorName, + via_select: bool = False, + record_flush_s: float = 0.0, + ) -> None: + self._coordinator = coordinator + self.predictor = predictor + self.via_select = via_select + self.record_flush_s = record_flush_s + self.prior_priority = priority_of(PRIOR_TOKENS) + self._tasks: set = set() + self._batch: List[Tuple[Optional[str], float, Optional[float], Optional[int]]] = [] + self._flush_task: Optional[asyncio.Task] = None + self.assigned = 0 + self.missing = 0 + self.recorded = 0 + self.no_usage = 0 + self.record_errors = 0 + self._call_ms: list = [] + self._last_stats = time.monotonic() + + def startup_line(self) -> str: + return ( + f"[output_length] generation priority from the predicted output length ({self.predictor}, " + f"learned online in the coordinator{', predicted in /select' if self.via_select else ''}): " + f"priority = 1 / (1 + tokens / {PRIORITY_SCALE_TOKENS:g}); " + f"without a prediction, {PRIOR_TOKENS:g} tokens (priority {self.prior_priority:.4f}); max_tokens " + f"is never read; /v1/responses requests are not predicted (they wait for a pooled " + f"generation seat at the prior's priority, and get the default priority on the " + f"generation server)" + ) + + async def assign( + self, gen_req: GenerationRequest, placed_later: bool = False + ) -> Optional[_Ticket]: + """Set ``gen_req.priority`` from the prediction; the ticket (None: nothing to learn) records the reply. + + With ``placed_later`` and ``via_select`` the prediction comes with the placement + (:meth:`placed`). A streamed request asks the generation server for its usage, which + :meth:`track` reads (and drops from the stream if the client did not ask for it). + Never raises: without a prediction (no prompt tokens, a coordinator error or timeout) the + request gets the prior's priority. + """ + if "priority" not in getattr(type(gen_req), "model_fields", {}): + return None + conv_id, isl = request_inputs(gen_req) + if isl is None: + self._miss(gen_req, "no prompt tokens") + return None + n = getattr(gen_req, "n", None) + sequences = n if isinstance(n, int) and not isinstance(n, bool) and n > 1 else 1 + ticket = _Ticket(conv_id, isl, None, sequences) + self._request_usage(gen_req, ticket) + if self.via_select and placed_later: + ticket.via_select = True + return ticket + t0 = time.perf_counter() + try: + tokens, key = await asyncio.wait_for( + self._coordinator.predict_output_length(conv_id, isl), PREDICT_TIMEOUT_S + ) + except Exception as e: # noqa: BLE001 (an admission hint is never worth failing a request) + self._miss(gen_req, f"{type(e).__name__}: {e}") + return ticket + self._call_ms.append((time.perf_counter() - t0) * 1e3) + gen_req.priority = priority_of(tokens) + ticket.key = key + self.assigned += 1 + self._maybe_log_stats() + return ticket + + def assign_prior(self, gen_req: GenerationRequest) -> None: + """Give a request served without a context phase the prior's priority (nothing is learned).""" + if "priority" in getattr(type(gen_req), "model_fields", {}): + gen_req.priority = self.prior_priority + + @staticmethod + def _request_usage(gen_req: GenerationRequest, ticket: _Ticket) -> None: + if not getattr(gen_req, "stream", False): + return + options = getattr(gen_req, "stream_options", None) + if options is not None and options.include_usage: + return + from tensorrt_llm.serve.openai_protocol import StreamOptions + + # Without include_usage the client also gets no per-chunk usage. + gen_req.stream_options = StreamOptions(include_usage=True, continuous_usage_stats=False) + ticket.strip_usage = True + + def placed( + self, ticket: Optional[_Ticket], gen_req: GenerationRequest, route_info: Optional[dict] + ) -> None: + """Take the prediction from the generation placement's route info (``via_select``).""" + if ticket is None or not ticket.via_select: + return + prediction = route_info.get(OUTPUT_LENGTH_KEY) if isinstance(route_info, dict) else None + key = prediction.get("key") if isinstance(prediction, dict) else None + if not isinstance(key, int) or isinstance(key, bool): + self._miss(gen_req, "the generation placement returned no prediction") + return + ticket.key = key + self.assigned += 1 + self._maybe_log_stats() + + def _miss(self, gen_req: GenerationRequest, reason: str) -> None: + self.missing += 1 + gen_req.priority = self.prior_priority + if throttled(self.missing): + logger.warning(f"[output_length] no prediction #{self.missing}, prior used: {reason}") + + def abandon(self, ticket: Optional[_Ticket]) -> None: + """The request failed before its reply: the coordinator drops its row unlearned.""" + if ticket is not None: + self._record(ticket, None) + + def _record(self, ticket: _Ticket, out: Optional[int]) -> None: + if ticket.recorded: + return + ticket.recorded = True + if out is None: + self.no_usage += 1 + if ticket.key is None: + return + # No length to learn: report it, so the coordinator drops its row. + self._batch.append((ticket.conv_id, ticket.isl, None, ticket.key)) + else: + self.recorded += 1 + # Learn the length of one sequence. + self._batch.append( + (ticket.conv_id, ticket.isl, float(out) / ticket.sequences, ticket.key) + ) + if len(self._batch) >= RECORD_BATCH_MAX: + self._send(self._take_batch()) + elif self._flush_task is None: + self._flush_task = asyncio.get_running_loop().create_task(self._flush_later()) + + def _take_batch(self) -> list: + batch, self._batch = self._batch, [] + return batch + + async def _flush_later(self) -> None: + try: + await asyncio.sleep(self.record_flush_s) + finally: + self._flush_task = None + if self._batch: + self._send(self._take_batch()) + + def _send(self, batch: list) -> None: + async def _post() -> None: + try: + await asyncio.wait_for( + self._coordinator.record_output_lengths(batch), RECORD_TIMEOUT_S + ) + except Exception as e: # noqa: BLE001 (learning must not fail the request) + self.record_errors += 1 + if throttled(self.record_errors): + logger.warning( + f"[output_length] recording {len(batch)} replies failed " + f"(#{self.record_errors}): {type(e).__name__}: {e}" + ) + + task = asyncio.get_running_loop().create_task(_post()) + self._tasks.add(task) + task.add_done_callback(self._tasks.discard) + + def track( + self, response: UCompletionResponseOrGenerator, ticket: Optional[_Ticket] + ) -> UCompletionResponseOrGenerator: + """Report the reply's ``usage.completion_tokens``: wraps a stream, reads a complete response.""" + if ticket is None: + return response + if hasattr(response, "__aiter__"): + return self._track_stream(response, ticket) + usage = getattr(response, "usage", None) + out = getattr(usage, "completion_tokens", None) if usage is not None else None + self._record(ticket, int(out) if out is not None else None) + return response + + async def _track_stream(self, stream: AsyncIterator, ticket: _Ticket) -> AsyncIterator[bytes]: + """Relay ``stream``; learn from its final usage-only chunk only (an interrupted stream is not learned). + + With ``ticket.strip_usage`` the stream is relayed in whole SSE events, without that chunk. + """ + carry = b"" + try: + async for chunk in stream: + if ticket.recorded and not ticket.strip_usage: + yield chunk + continue + data = chunk if isinstance(chunk, (bytes, bytearray)) else str(chunk).encode() + scan = carry + bytes(data) + if ticket.strip_usage: + end = scan.rfind(b"\n\n") + if end < 0: + carry = scan + continue + carry = scan[end + 2 :] + events = scan[: end + 2] + kept = self._drop_final_usage(events, ticket) + if kept: + yield kept + continue + newline = scan.rfind(b"\n") + carry = scan[newline + 1 :][-4096:] if newline >= 0 else scan[-4096:] + if newline >= 0: + out, final = completion_tokens_in(scan[: newline + 1]) + if out is not None and final: + self._record(ticket, out) + yield chunk + if ticket.strip_usage and carry: + kept = self._drop_final_usage(carry, ticket) + carry = b"" + if kept: + yield kept + finally: + if not ticket.recorded: + self._record(ticket, None) + + def _drop_final_usage(self, events: bytes, ticket: _Ticket) -> bytes: + """``events`` (whole SSE events) without the final usage-only chunk, which is recorded.""" + if _USAGE_MARK not in events: + return events + kept = [] + for event in events.split(b"\n\n"): + obj = _sse_json(event) if _USAGE_MARK in event else None + usage = obj.get("usage") if obj is not None else None + if isinstance(usage, dict) and not obj.get("choices"): + if usage.get("completion_tokens") is not None: + self._record(ticket, int(usage["completion_tokens"])) + continue + kept.append(event) + return b"\n\n".join(kept) + + def _maybe_log_stats(self) -> None: + now = time.monotonic() + if now - self._last_stats < STATS_LOG_PERIOD_S: + return + self._last_stats = now + ms = sorted(self._call_ms) + self._call_ms = [] + p50 = ms[len(ms) // 2] if ms else NAN + logger.info( + f"[output_length] assigned {self.assigned}, missing {self.missing}, replies recorded {self.recorded} / " + f"without final usage {self.no_usage} / record errors {self.record_errors}; coordinator call p50 " + f"{p50:.2f} ms, max {ms[-1] if ms else NAN:.2f} ms" + ) diff --git a/tensorrt_llm/serve/router.py b/tensorrt_llm/serve/router.py index b0b6f8e24360..510de1d8a859 100644 --- a/tensorrt_llm/serve/router.py +++ b/tensorrt_llm/serve/router.py @@ -18,7 +18,7 @@ from abc import ABC, abstractmethod from array import array from collections import OrderedDict -from typing import Awaitable, Callable, Dict, Iterable, List, Optional +from typing import Any, Awaitable, Callable, Dict, Iterable, List, Optional import aiohttp import msgpack @@ -31,6 +31,8 @@ from tensorrt_llm.serve.metadata_server import JsonDictionary from tensorrt_llm.serve.openai_protocol import (ChatCompletionRequest, ResponsesRequest) +from tensorrt_llm.serve.output_length_predictor import (OUTPUT_LENGTH_KEY, + request_inputs) # Shared tokenization / block-hashing utilities (single source of truth). # Re-exported here for backward compat. from tensorrt_llm.serve.router_utils import ( # noqa: F401 @@ -38,9 +40,13 @@ KV_CACHE_HASH_ALGO_V2_SHA256_64, KV_CACHE_HASH_ALGOS, BlockHash, BlockHashMixin, OpenAIRequest, block_key_hasher, get_request_num_tokens, hash_v1_block_key, responses_request_text, truncate_sha256_hash_to_int64) +from tensorrt_llm.serve.seat_pool import (NoGenerationSeatError, SeatPool, + Waiter, priority_or_default) _MSGPACK_HEADERS = {"Content-Type": "application/msgpack"} -COORDINATOR_SELECT_MAX_ATTEMPTS = 2 +# Retries ride out a burst that fills the coordinator's accept queue; select is +# idempotent per req_id (see _post_select), so a replay is safe. +COORDINATOR_SELECT_MAX_ATTEMPTS = 4 COORDINATOR_SELECT_RETRY_DELAY_S = 0.05 COORDINATOR_FINISH_MAX_ATTEMPTS = 3 COORDINATOR_FINISH_RETRY_DELAY_S = 0.1 @@ -48,6 +54,17 @@ COORDINATOR_FINISH_WORKERS = 16 COORDINATOR_FINISH_QUEUE_SIZE = 4096 COORDINATOR_FINISH_DRAIN_TIMEOUT_S = 5.0 +# Backoff cap of a pooled /finish, which is retried until delivered (see _finish_async). +COORDINATOR_POOLED_FINISH_MAX_RETRY_DELAY_S = 5.0 +# A fleet worker's bound on a pooled generation /select, which waits for a free seat. +POOLED_SELECT_TIMEOUT_S = 3600.0 +# How long, and for how many request ids, a pooled router placed by id remembers a /finish: a +# /select for that id arriving later (it raced the finish of a cancelled request) is refused. +POOLED_FINISHED_TTL_S = 600.0 +POOLED_FINISHED_MAX = 1 << 17 +_UNREAD = object() +# The context servers report a null kv_transfer_timeout_ms: no seat-wait bound. +_NO_KV_TIMEOUT = object() # Max number of conversations whose home-server pin is retained (LRU). ROUTE_AFFINITY_CACHE_SIZE = 50000 @@ -319,11 +336,16 @@ async def _unregister_request(self, request: OpenAIRequest) -> str: await self._server_state[server].decrement_load(request) return server - def _select_least_loaded(self, - exclude_server: Optional[str] = None - ) -> Optional[str]: - """Pick the server with the lowest load. Round-robin breaks ties.""" - candidates = [s for s in self._servers if s != exclude_server] + def _select_least_loaded( + self, + exclude_server: Optional[str] = None, + candidates: Optional[List[str]] = None) -> Optional[str]: + """Pick the server with the lowest load. Round-robin breaks ties. + + ``candidates`` (default: every server but ``exclude_server``) are the servers to pick from. + """ + if candidates is None: + candidates = [s for s in self._servers if s != exclude_server] if not candidates: return None loads = {s: self._get_server_load(s) for s in candidates} @@ -338,6 +360,11 @@ def _select_least_loaded(self, class Router(ABC): + # True for a router whose placement may wait for capacity (a generation seat). The coordinator + # then runs its select outside the reservation lock that its finish takes, waits for it longer + # (POOLED_SELECT_TIMEOUT_S), and fails its waiters (fail_waiters) when it stops. + pooled: bool = False + def __init__( self, server_role: ServerRole, @@ -397,6 +424,10 @@ def prepared_servers(self) -> set[str]: def server_role(self) -> ServerRole: return self._server_role + def server_infos(self) -> dict[str, dict]: + """The ``/server_info`` of every prepared server, by server.""" + return self._server_info + @staticmethod def _ensure_url(server: str) -> str: return server if server.startswith("http") else f"http://{server}" @@ -500,6 +531,15 @@ async def finish_request(self, req_id: Optional[int] = None): pass + async def fail_waiters(self, reason: str) -> int: + """Fail every request waiting for capacity (``pooled`` routers); returns how many.""" + del reason + return 0 + + def set_unpredicted_priority(self, priority: float) -> None: + """The priority of requests whose model has no ``priority`` field (``pooled`` routers).""" + del priority + async def renew_request(self, request: OpenAIRequest, req_id: Optional[int] = None) -> None: @@ -847,6 +887,386 @@ async def finish_request_by_id(self, req_id, success=True): await self._server_state[server].decrement_load_by(num_tokens) +class PooledLoadBalancingRouter(LoadBalancingRouter): + """Generation router that queues requests until a server has a free seat. + + Built for ``load_balancing`` with ``max_requests_per_server`` (generation only). A + server with fewer active requests than that has a free seat. With a free seat and + nobody waiting, a request is placed at once by the parent's rule (least loaded, + round-robin among ties); otherwise it waits in one queue (:class:`SeatPool`), and + each finished request gives its seat to the first waiter in order: the highest + request priority first, ties in arrival order, and with ``max_queue_wait_s`` the + requests that waited that long first. In disaggregated serving the coordinator owns + the queue; its ``select`` waits for the seat outside the reservation lock. + + A request whose context phase has finished (``disaggregated_params.orig_elapsed_s`` + set) ages from its arrival at the orchestrator. With ``kv_transfer_timeout_ms`` every + request fails once it has waited that long for a seat (see :mod:`seat_pool` for what the + context side does by then). The value is the smallest one the context servers report in + ``/server_info`` (:meth:`set_context_router`), else the configured one; there is no bound + when they all report null. + + A seat is released on the server state it was taken from: a server that leaves while + requests hold its seats keeps that state, and gets it back if it rejoins, so its seat + count stays right across a re-registration. + + Placed by request id (the coordinator), the router remembers each finished id for + ``POOLED_FINISHED_TTL_S`` and refuses a later select for it: a cancelled request's + /finish can overtake its own /select. After :meth:`fail_waiters` (shutdown) it refuses + every new request. + """ + + pooled = True + + def __init__(self, + server_role: ServerRole, + servers: List[str] = None, + metadata_server_cfg: MetadataServerConfig = None, + metadata_server: JsonDictionary = None, + use_tokens: bool = False, + max_requests_per_server: int = 1, + max_queue_wait_s: Optional[float] = None, + kv_transfer_timeout_ms: Optional[float] = None, + **kwargs: Any) -> None: + if server_role != ServerRole.GENERATION: + raise ValueError( + "max_requests_per_server is a generation router option") + if use_tokens: + raise ValueError( + "max_requests_per_server counts requests; it cannot be " + "combined with use_tokens") + super().__init__(server_role, + servers, + metadata_server_cfg, + metadata_server, + use_tokens=False, + **kwargs) + self._configured_kv_timeout_ms = kv_transfer_timeout_ms + self._pool = SeatPool( + max_requests_per_server, + max_queue_wait_s, + kv_transfer_timeout_s=(None if kv_transfer_timeout_ms is None else + kv_transfer_timeout_ms / 1000.0)) + # The server state each granted seat was taken from, by request id. + self._seat_state: dict[int, ServerState] = {} + # Removed servers that still have seated requests, by server. + self._departed_state: dict[str, ServerState] = {} + self._context_router: Optional[Router] = None + # The value last read from the context servers (_UNREAD: none yet). + self._reported_kv_timeout_ms: Any = _UNREAD + # Request ids finished by id -> when, oldest first. + self._finished_ids: OrderedDict[int, float] = OrderedDict() + # Set by fail_waiters: why new requests are refused. + self._stopping_reason: Optional[str] = None + # The priority of a request whose model has no priority field (set_unpredicted_priority). + self._unpredicted_priority: Optional[float] = None + logger.info(f"PooledLoadBalancingRouter: " + f"{self._pool.describe(len(self._servers))}") + self._warn_if_cap_exceeds_kv_timeout(kv_transfer_timeout_ms) + + def _warn_if_cap_exceeds_kv_timeout( + self, kv_transfer_timeout_ms: Optional[float]) -> None: + max_queue_wait_s = self._pool.max_wait_s + if (max_queue_wait_s is not None and kv_transfer_timeout_ms is not None + and max_queue_wait_s * 1000.0 > kv_transfer_timeout_ms): + logger.warning( + f"max_queue_wait_s ({max_queue_wait_s} s) exceeds the context " + f"servers' kv_transfer_timeout_ms ({kv_transfer_timeout_ms} " + f"ms): a request fails at that timeout before the cap can " + f"move it ahead") + + def set_context_router(self, context_router: Router) -> None: + """Bound the seat wait by the KV transfer timeout the context servers report.""" + self._context_router = context_router + + def _refresh_kv_timeout(self) -> None: + """Use the smallest ``kv_transfer_timeout_ms`` in the context servers' ``/server_info``. + + No bound when every context server that reports the key reports null (no timeout). + """ + if self._context_router is None: + return + reported = [ + info["kv_transfer_timeout_ms"] + for info in self._context_router.server_infos().values() + if "kv_transfer_timeout_ms" in info + ] + bounds = [ + value for value in reported if isinstance(value, (int, float)) + and not isinstance(value, bool) and value > 0 + ] + if bounds: + value = min(bounds) + elif reported and all(value is None for value in reported): + value = _NO_KV_TIMEOUT + else: + value = None + if value == self._reported_kv_timeout_ms: + return + self._reported_kv_timeout_ms = value + if value is _NO_KV_TIMEOUT: + value = None + logger.info( + "PooledLoadBalancingRouter: the context servers have no " + "kv_transfer_timeout_ms; generation requests wait for a " + "seat without a bound") + elif value is None: + value = self._configured_kv_timeout_ms + logger.warning( + "PooledLoadBalancingRouter: no context server reports " + "kv_transfer_timeout_ms in /server_info; generation requests " + f"wait at most the configured {value} ms for a seat") + else: + logger.info(f"PooledLoadBalancingRouter: generation requests wait " + f"at most {value} ms for a seat, the context servers' " + f"smallest kv_transfer_timeout_ms") + self._pool.kv_transfer_timeout_s = (None if value is None else value / + 1000.0) + self._warn_if_cap_exceeds_kv_timeout(value) + + def set_unpredicted_priority(self, priority: float) -> None: + """Give requests whose model has no ``priority`` field (``/v1/responses``) this priority. + + ``output_length_prediction`` sets the prior's priority here; without it they rank at + the default priority. + """ + self._unpredicted_priority = priority + + def _request_priority(self, request: OpenAIRequest) -> Optional[float]: + """The request's ``priority`` field, else the unpredicted priority. + + A ``priority`` a client sent to a request model that allows extra fields + (``ResponsesRequest``) is not a priority field and is ignored. + """ + if "priority" in getattr(type(request), "model_fields", {}): + return request.priority + return self._unpredicted_priority + + @staticmethod + def _orig_elapsed_s(request: OpenAIRequest) -> Optional[float]: + params = getattr(request, "disaggregated_params", None) + return getattr(params, "orig_elapsed_s", None) + + def routing_key(self, request: OpenAIRequest) -> dict: + """The parent's key plus the priority and, past the context phase, ``orig_elapsed_s``.""" + key = super().routing_key(request) + key["priority"] = priority_or_default(self._request_priority(request)) + orig_elapsed_s = self._orig_elapsed_s(request) + if orig_elapsed_s is not None: + key["orig_elapsed_s"] = orig_elapsed_s + return key + + def _on_servers_updated(self, old_servers: list[str], + new_servers: list[str]) -> None: + # A leaving server keeps its state while requests hold its seats; it + # gets that state back if it rejoins, so their releases stay counted. + for server in old_servers: + state = self._server_state.get(server) + if (server not in new_servers and state is not None + and state._num_active_requests > 0): + self._departed_state[server] = state + super()._on_servers_updated(old_servers, new_servers) + for server in new_servers: + state = self._departed_state.pop(server, None) + if state is not None: + self._server_state[server] = state + if len(self._pool): + # New servers may seat waiters; called with the lock held. + try: + asyncio.get_running_loop().create_task(self._redispatch()) + except RuntimeError: + pass + + async def _redispatch(self) -> None: + async with self._lock: + await self._dispatch_locked() + + def _active_servers(self) -> List[str]: + return [s for s in self._servers if s in self._server_state] + + def _expire_locked(self, waiter: Optional[Waiter] = None) -> None: + """Fail the waiters past their KV transfer deadline, and ``waiter``.""" + for expired in self._pool.expire(waiter): + if not expired.future.done(): + expired.future.set_exception( + NoGenerationSeatError(self._pool.expiry_message(expired))) + + async def fail_waiters(self, reason: str) -> int: + """Fail the requests waiting for a seat and refuse new ones (shutdown).""" + async with self._lock: + self._stopping_reason = reason + waiters = self._pool.waiters() + for waiter in waiters: + self._pool.remove(waiter.rid) + if not waiter.future.done(): + waiter.future.set_exception(NoGenerationSeatError(reason)) + return len(waiters) + + async def _dispatch_locked(self) -> None: + """Give free seats to waiters, best first. Called with ``self._lock`` held.""" + self._expire_locked() + while len(self._pool): + free = [ + s for s in self._active_servers() + if self._get_server_load(s) < self._pool.seats + ] + picked = self._pool.pick(free) + if picked is None: + break + waiter, candidates = picked + server = self._select_least_loaded(candidates=candidates) + state = self._server_state[server] + await state.increment_load_by(0) + self._req_routing_table[waiter.rid] = server + self._seat_state[waiter.rid] = state + self._pool.record_grant(waiter) + if not waiter.future.done(): + waiter.future.set_result(server) + servers = self._active_servers() + self._pool.maybe_log_stats( + sum(self._get_server_load(s) for s in servers), + self._pool.seats * len(servers)) + + async def _acquire(self, + rid: int, + priority: Optional[float], + exclude_server: Optional[str], + orig_elapsed_s: Optional[float] = None, + by_id: bool = False) -> str: + """Wait for a seat and return its server. + + A repeated call for a request that holds a seat returns that seat; one for a + waiting request shares its place in the queue. Raises ``NoGenerationSeatError`` + once the request has waited the context servers' KV transfer timeout (every + waiter, when that timeout is known) or when :meth:`fail_waiters` runs at + shutdown (also for a new request afterwards), and ``ValueError`` if the request + is finished while it waits or, with ``by_id``, was finished before this call. + """ + async with self._lock: + server = self._req_routing_table.get(rid) + if server is not None: + return server + waiter = self._pool.waiter(rid) + if waiter is None: + if self._stopping_reason is not None: + raise NoGenerationSeatError(self._stopping_reason) + if by_id and self._was_finished_locked(rid): + raise ValueError(f"generation request {rid} was finished " + f"before its placement") + self._refresh_kv_timeout() + waiter = self._pool.add( + rid, priority, exclude_server, + asyncio.get_running_loop().create_future(), orig_elapsed_s) + waiter.holders += 1 + await self._dispatch_locked() + waiter.arriving = False + try: + try: + return await asyncio.wait_for(asyncio.shield(waiter.future), + self._pool.remaining_s(waiter)) + except asyncio.TimeoutError: + async with self._lock: + if not waiter.future.done(): + self._expire_locked(waiter) + return await asyncio.shield(waiter.future) + except asyncio.CancelledError: + async with self._lock: + waiter.holders -= 1 + if waiter.holders <= 0: + if (waiter.future.done() and not waiter.future.cancelled() + and waiter.future.exception() is None): + # Placed, but nobody will use the seat: give it back. + await self._release_locked(rid) + elif self._pool.remove(rid) is not None: + waiter.future.cancel() + raise + + async def _release_locked(self, rid: int) -> None: + server = self._req_routing_table.pop(rid, None) + if server is None: + # Finished before its placement: drop it from the queue. + waiter = self._pool.remove(rid) + if waiter is not None and not waiter.future.done(): + waiter.future.set_exception( + ValueError( + "generation request finished while waiting for a seat")) + return + # Release on the state the seat was taken from, even if its server has + # left (and maybe rejoined) since. + state = self._seat_state.pop(rid, None) + if state is not None: + await state.decrement_load_by(0) + if (state._num_active_requests <= 0 + and self._departed_state.get(server) is state): + del self._departed_state[server] + await self._dispatch_locked() + + async def get_next_server(self, + request: OpenAIRequest, + exclude_server: Optional[str] = None, + req_id: Optional[int] = None) -> tuple[str, dict]: + del req_id + self._validate_servers_available() + server = await self._acquire(id(request), + self._request_priority(request), + exclude_server, + self._orig_elapsed_s(request)) + return server, {"server_info": self._server_info.get(server, {})} + + async def finish_request(self, + request: OpenAIRequest, + session: Optional[aiohttp.ClientSession] = None, + success: bool = True, + req_id: Optional[int] = None) -> None: + del session, success, req_id + async with self._lock: + await self._release_locked(id(request)) + + async def get_next_server_by_key( + self, + routing_key: Optional[dict], + exclude_server: Optional[str] = None, + req_id: Optional[int] = None) -> tuple[str, dict, int]: + if req_id is None: + raise ValueError( + "Pooled generation routing through the coordinator requires a " + "request ID") + self._validate_servers_available() + routing_key = routing_key or {} + server = await self._acquire(req_id, + routing_key.get("priority"), + exclude_server, + routing_key.get("orig_elapsed_s"), + by_id=True) + return server, { + "server_info": self._server_info.get(server, {}) + }, req_id + + async def finish_request_by_id(self, + req_id: Optional[int], + success: bool = True) -> None: + del success + if req_id is None: + return + async with self._lock: + self._remember_finished_locked(req_id) + await self._release_locked(req_id) + + def _remember_finished_locked(self, rid: int) -> None: + now = time.monotonic() + finished = self._finished_ids + finished[rid] = now + finished.move_to_end(rid) + while finished and (len(finished) > POOLED_FINISHED_MAX or next( + iter(finished.values())) <= now - POOLED_FINISHED_TTL_S): + finished.popitem(last=False) + + def _was_finished_locked(self, rid: int) -> bool: + finished_at = self._finished_ids.get(rid) + return (finished_at is not None + and time.monotonic() - finished_at < POOLED_FINISHED_TTL_S) + + class KvCacheAwareRouter(BlockHashMixin, LoadBalancingMixin, Router): _server_state_class = KvCacheAwareServerState @@ -1900,6 +2320,14 @@ async def finish_request_by_id(self, req_id, success=True): 0, self._server_content_load[server] - 1) +class _CoordinatorFinishError(RuntimeError): + """A non-200 ``/finish`` reply; a 4xx (malformed request) is not retried for pooled seats.""" + + def __init__(self, status: int, message: str): + super().__init__(message) + self.status = status + + class CoordinatorDelegatingRouter(Router): """Worker-side Router that delegates placement to the disagg coordinator. @@ -1935,11 +2363,28 @@ def __init__(self, self._local = local_router self._role = role # "context" | "generation" self._request_timeout_s = request_timeout_s + # A pooled router's /select waits in the coordinator for a free seat. + self.pooled = local_router.pooled + self._select_timeout_s = (POOLED_SELECT_TIMEOUT_S + if self.pooled else request_timeout_s) + # Ask /select for the output-length prediction (output_length_prediction). + self._predict_output_length = False self._session: Optional[aiohttp.ClientSession] = None + # A pooled seat is a hard admission cap released only by its /finish: the pooled + # queue is unbounded, and each finish is retried until the coordinator would have + # expired the reservation itself. self._finish_queue: asyncio.Queue[tuple[int, bool]] = asyncio.Queue( - maxsize=COORDINATOR_FINISH_QUEUE_SIZE) + maxsize=0 if self.pooled else COORDINATOR_FINISH_QUEUE_SIZE) self._finish_workers: set[asyncio.Task] = set() self._dropped_finishes = 0 + self._pooled_finish_window_s = None + if self.pooled: + from tensorrt_llm.serve.disagg_coordinator import ( + pooled_reservation_timeout, reservation_timeout) + + # The coordinator's own expiry of the seat (it gets the same request timeout). + self._pooled_finish_window_s = pooled_reservation_timeout( + reservation_timeout(request_timeout_s=request_timeout_s)) # Coordinator HTTP-client API latency (includes network round-trip to the # coordinator + its in-process handler). Compare against the owner-side # [coord_api] to isolate the fleet /select|/finish HTTP overhead. @@ -1978,6 +2423,33 @@ async def sync_servers(self, servers: list[str]) -> None: if server in servers } + def set_unpredicted_priority(self, priority: float) -> None: + # The local router computes the routing key's priority. + self._local.set_unpredicted_priority(priority) + + def enable_output_length_prediction(self) -> bool: + """Have the coordinator predict a generation request's output length in ``/select``. + + The routing key then carries the request's conversation id and prompt tokens; the + coordinator orders the placement by the predicted priority and returns the prediction + in the route info under ``OUTPUT_LENGTH_KEY``, which also sets ``request.priority``. + Returns whether it is on: only for a generation router with a dict routing key (not + ``conversation``, whose key is the conversation id). + """ + self._predict_output_length = ( + self._role == "generation" + and not isinstance(self._local, ConversationRouter)) + return self._predict_output_length + + def _output_length_inputs(self, request: OpenAIRequest) -> Optional[dict]: + if not self._predict_output_length or "priority" not in getattr( + type(request), "model_fields", {}): + return None + conv_id, isl = request_inputs(request) + if isl is None: + return None + return {"conv": conv_id, "isl": isl} + def _request_id(self, request: OpenAIRequest, req_id: Optional[int] = None) -> int: @@ -2012,6 +2484,9 @@ async def get_next_server(self, # kv_cache_aware); run it in a thread so it doesn't block the fleet worker # event loop driving the concurrent streams. key = await asyncio.to_thread(self._local.routing_key, request) + prediction_inputs = self._output_length_inputs(request) + if prediction_inputs is not None and isinstance(key, dict): + key[OUTPUT_LENGTH_KEY] = prediction_inputs # Send the request's existing disagg id as the cross-process key (the # coordinator keys pending state by it for /finish); placement must not # change it, since the ctx<->gen KV transfer is keyed by it. @@ -2034,6 +2509,13 @@ async def get_next_server(self, body = await asyncio.shield(selection) info = body.get("info") or {} except asyncio.CancelledError: + if self.pooled: + # A pooled select may wait long for a seat. This finish fails + # its coordinator-side wait at once; the one below releases a + # seat granted before this finish arrived. + await self.finish_request(request, + success=False, + req_id=payload["req_id"]) # /finish must not overtake /select and leave a late reservation. # Keep its existing HTTP timeout/retry bounds, even if the caller # cancels again while we wait to release the original routing ID. @@ -2047,10 +2529,31 @@ async def get_next_server(self, success=False, req_id=payload["req_id"]) raise + except asyncio.TimeoutError: + # The coordinator may hold a reservation (or grant one later). + await self.finish_request(request, + success=False, + req_id=payload["req_id"]) + raise + except Exception: + if self.pooled: + # A select the coordinator took may still wait there, or hold a + # seat whose reply was lost (a transport error, or a refused + # retry); /finish ends either. + await self.finish_request(request, + success=False, + req_id=payload["req_id"]) + raise self._select_lat.record(time.monotonic() - _t0) if body["server"] is None: raise ValueError(f"coordinator /select placed no {self._role} " f"server: {info}") + # Only ConversationRouter asks for content, and it never asks for a prediction. + prediction = info.get(OUTPUT_LENGTH_KEY) + if isinstance(prediction, dict): + priority = prediction.get("priority") + if isinstance(priority, float) and 0.0 <= priority <= 1.0: + request.priority = priority return body["server"], info async def _post_select(self, payload: dict) -> dict: @@ -2072,12 +2575,14 @@ async def _post_select(self, payload: dict) -> dict: f"{self._coordinator_url}/select", data=data, headers=_MSGPACK_HEADERS, - timeout=self._request_timeout_s) as resp: + timeout=self._select_timeout_s) as resp: body = msgpack.unpackb(await resp.read(), raw=False) if resp.status != 200: - raise ValueError( - f"coordinator /select returned {resp.status}: " - f"{body.get('error', body)}") + message = (f"coordinator /select returned " + f"{resp.status}: {body.get('error', body)}") + if body.get("no_generation_seat"): + raise NoGenerationSeatError(message) + raise ValueError(message) return body except aiohttp.ClientConnectionError as e: if attempt == COORDINATOR_SELECT_MAX_ATTEMPTS: @@ -2102,6 +2607,7 @@ async def finish_request(self, try: self._finish_queue.put_nowait((req_id, success)) except asyncio.QueueFull: + # Non-pooled only (the pooled queue is unbounded). self._dropped_finishes += 1 if self._dropped_finishes == 1 or self._dropped_finishes % 1000 == 0: logger.warning( @@ -2140,8 +2646,19 @@ async def _finish_worker(self) -> None: self._finish_queue.task_done() async def _finish_async(self, req_id: int, success: bool): + """POST /finish with retries. + + A non-pooled finish only corrects a soft load counter and gives up after + ``COORDINATOR_FINISH_MAX_ATTEMPTS``. A pooled one frees a seat, so it is retried + with capped backoff until delivered, rejected as malformed (4xx), or past the + coordinator's own expiry of the reservation. + """ _t0 = time.monotonic() - for attempt in range(1, COORDINATOR_FINISH_MAX_ATTEMPTS + 1): + give_up_at = (None if self._pooled_finish_window_s is None else _t0 + + self._pooled_finish_window_s) + attempt = 0 + while True: + attempt += 1 try: async with self.session.post( f"{self._coordinator_url}/finish", @@ -2163,22 +2680,34 @@ async def _finish_async(self, req_id: int, success: bool): body = raw_body.decode(errors="replace") error = body.get("error", body) if isinstance( body, dict) else body - raise RuntimeError( + raise _CoordinatorFinishError( + resp.status, f"coordinator /finish returned {resp.status}: {error}" ) self._finish_lat.record(time.monotonic() - _t0) return except Exception as e: # noqa: BLE001 - if attempt == COORDINATOR_FINISH_MAX_ATTEMPTS: + delay = COORDINATOR_FINISH_RETRY_DELAY_S * (2**min( + attempt - 1, 16)) + if give_up_at is None: + give_up = attempt == COORDINATOR_FINISH_MAX_ATTEMPTS + else: + delay = min(delay, + COORDINATOR_POOLED_FINISH_MAX_RETRY_DELAY_S) + give_up = (isinstance(e, _CoordinatorFinishError) + and 400 <= e.status < 500) or (time.monotonic() + + delay + >= give_up_at) + if give_up: logger.warning( f"CoordinatorDelegatingRouter finish failed after " f"{attempt} attempts: {e}") return - logger.warning( - f"CoordinatorDelegatingRouter finish attempt {attempt} " - f"failed: {e}; retrying") - await asyncio.sleep(COORDINATOR_FINISH_RETRY_DELAY_S * - (2**(attempt - 1))) + if attempt < COORDINATOR_FINISH_MAX_ATTEMPTS or attempt % 100 == 0: + logger.warning( + f"CoordinatorDelegatingRouter finish attempt {attempt} " + f"failed: {e}; retrying") + await asyncio.sleep(delay) async def close(self): if self._finish_workers: @@ -2236,6 +2765,11 @@ def create_router( raise ValueError(f"Unsupported router type: {router_type}. " f"Supported types are: {list(router_map.keys())}") extra_args = router_config.args if router_config else {} + if extra_args.get("max_requests_per_server") is not None: + if router_class is not LoadBalancingRouter: + raise ValueError("max_requests_per_server needs the load_balancing " + f"router, not {router_type}") + router_class = PooledLoadBalancingRouter extra_args["disagg_node_id"] = disagg_node_id return router_class(router_config.server_role if router_config else None, @@ -2271,4 +2805,6 @@ def build_disagg_routers( gen_router = create_router(gen_router_config, gen_servers, metadata_server_cfg, metadata_server, server_preparation_func, disagg_node_id) + if gen_router.pooled: + gen_router.set_context_router(ctx_router) return ctx_router, gen_router diff --git a/tensorrt_llm/serve/seat_pool.py b/tensorrt_llm/serve/seat_pool.py new file mode 100644 index 000000000000..f233d98ff5da --- /dev/null +++ b/tensorrt_llm/serve/seat_pool.py @@ -0,0 +1,363 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The queue of a pooled generation router (``router.PooledLoadBalancingRouter``). + +Every generation server has ``seats`` seats; a request holds one from its placement until it +finishes. A request that finds no free seat waits here, and each freed seat goes to the first +waiter in order that may use that server: the highest request ``priority`` first (the +orchestrator's predicted output length with ``output_length_prediction``), ties in the order +they joined this queue. With ``max_wait_s``, a request that has waited that long since its +arrival goes ahead of every request that has not, earliest arrival first (``(arrival, seq)``, +the order of the generation server's ``AgingPriorityWaitingQueue``). + +A request that comes from a finished context phase carries ``orig_elapsed_s``, its time since it +reached the orchestrator: its wait counts from that arrival. With ``kv_transfer_timeout_s`` (the +context servers' ``kv_transfer_timeout_ms``) every waiter fails once it has been in this queue +that long, less ``KV_DEADLINE_MARGIN`` of it. A C++-transceiver context server counts that timeout +from its KV send, a little before the request joins this queue, so it has dropped the transfer by +then and the margin keeps a seat granted at the deadline from reaching a cancelled send; a +Python-transceiver one holds a send its generation peer has not asked for up to three timeouts +from the send, so there this bound is conservative (with ``generation_first`` the context server +waits the same timeout for the generation side). + +Waiters sit in heaps per excluded server, so a placement costs O(E log W) for E distinct +excluded servers and W waiters, and expiry pops a deadline heap. +""" + +import asyncio +import heapq +import itertools +import math +import time +from dataclasses import dataclass +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple + +from tensorrt_llm.executor.request import DEFAULT_REQUEST_PRIORITY +from tensorrt_llm.logger import logger + +STATS_LOG_PERIOD_S = 30.0 +# A waiter fails this fraction of the KV transfer timeout before it (see the module docstring). +KV_DEADLINE_MARGIN = 0.05 +# A heap is rebuilt from its live waiters once its removed entries outnumber them by this much. +_COMPACT_SLACK = 64 + + +class NoGenerationSeatError(ValueError): + """A generation request got no seat: past its KV transfer deadline, or the coordinator stopped. + + The server is overloaded rather than faulty; the disaggregated server answers 503. + """ + + +def priority_or_default(priority: Any) -> float: + """A request priority as a number in [0, 1]; anything else is the default priority.""" + if isinstance(priority, (int, float)) and not isinstance(priority, bool): + if math.isfinite(priority) and 0.0 <= priority <= 1.0: + return float(priority) + return DEFAULT_REQUEST_PRIORITY + + +@dataclass(eq=False) +class Waiter: + """One request waiting for a seat; ``holders`` counts the callers waiting on its placement.""" + + rid: int + seq: int + arrival: float + priority: float + exclude: Optional[str] + future: Optional["asyncio.Future[str]"] = None + holders: int = 0 + arriving: bool = True + # When the context server's KV transfer times out; None: no bound. + deadline: Optional[float] = None + # When it joined this queue (``arrival`` may be earlier, at the orchestrator). + entered: float = 0.0 + # False once it left the queue; its heap entries are then skipped. + queued: bool = True + + +class _Bucket: + """The waiters that exclude one server: by (-priority, seq) and by (arrival, seq).""" + + __slots__ = ("by_priority", "by_arrival", "live") + + def __init__(self) -> None: + self.by_priority: List[Tuple[float, int, Waiter]] = [] + self.by_arrival: List[Tuple[float, int, Waiter]] = [] + self.live = 0 + + def push(self, waiter: Waiter) -> None: + heapq.heappush(self.by_priority, (-waiter.priority, waiter.seq, waiter)) + heapq.heappush(self.by_arrival, (waiter.arrival, waiter.seq, waiter)) + self.live += 1 + + def discard(self) -> None: + """One of its waiters left; drop the entries of departed waiters once they dominate. + + Either heap can hold them: a granted waiter leaves ``by_priority`` at its head, while + ``by_arrival`` is popped only with a wait cap. + """ + self.live -= 1 + if max(len(self.by_priority), len(self.by_arrival)) > 2 * self.live + _COMPACT_SLACK: + self.by_priority = [e for e in self.by_priority if e[2].queued] + heapq.heapify(self.by_priority) + self.by_arrival = [e for e in self.by_arrival if e[2].queued] + heapq.heapify(self.by_arrival) + + @staticmethod + def _top(heap: List[Tuple[float, int, Waiter]]) -> Optional[Waiter]: + while heap and not heap[0][2].queued: + heapq.heappop(heap) + return heap[0][2] if heap else None + + def first(self, now: float, max_wait_s: Optional[float]) -> Optional[Waiter]: + """Its first waiter: the earliest arrival if that one is aged, else the highest priority.""" + if max_wait_s is not None: + oldest = self._top(self.by_arrival) + if oldest is not None and now - oldest.arrival >= max_wait_s: + return oldest + return self._top(self.by_priority) + + +def _pct(values: List[float], q: float) -> float: + return values[min(len(values) - 1, int(q * len(values)))] + + +class SeatPool: + """Waiters, their order and placement counters. Not thread safe: its router calls it under one lock.""" + + def __init__( + self, + seats: int, + max_wait_s: Optional[float] = None, + clock: Callable[[], float] = time.monotonic, + kv_transfer_timeout_s: Optional[float] = None, + ) -> None: + if isinstance(seats, bool) or not isinstance(seats, int) or seats < 1: + raise ValueError(f"max_requests_per_server={seats!r} must be an integer >= 1") + if max_wait_s is not None and not (math.isfinite(max_wait_s) and max_wait_s > 0.0): + raise ValueError(f"max_queue_wait_s={max_wait_s!r} must be a positive number or None") + self.seats = seats + self.max_wait_s = max_wait_s + self.kv_transfer_timeout_s = kv_transfer_timeout_s + self._clock = clock + # rid -> waiter, in the order they joined (a waiter is never re-inserted). + self._waiters: Dict[int, Waiter] = {} + self._buckets: Dict[Optional[str], _Bucket] = {} + self._deadlines: List[Tuple[float, int, Waiter]] = [] + self._seq = itertools.count() + self._pick_now: Optional[float] = None + self.placed = 0 + self.placed_at_once = 0 + self.reordered = 0 + self.aged = 0 + self.dropped = 0 + self.expired = 0 + self._win_start = clock() + self._win_placed = 0 + self._win_waits: List[float] = [] + + @property + def kv_transfer_timeout_s(self) -> Optional[float]: + return self._kv_transfer_timeout_s + + @kv_transfer_timeout_s.setter + def kv_transfer_timeout_s(self, value: Optional[float]) -> None: + """Bounds the waiters that join from now on; those already waiting keep their deadline.""" + if value is not None and not (math.isfinite(value) and value > 0.0): + raise ValueError(f"kv_transfer_timeout_s={value!r} must be a positive number or None") + self._kv_transfer_timeout_s = value + + def describe(self, num_servers: int) -> str: + cap = ( + f"a request that has waited {self.max_wait_s:g} s goes ahead, oldest first" + if self.max_wait_s is not None + else "no wait cap" + ) + bound = ( + f"a request fails after {self.kv_transfer_timeout_s:g} s here (the context servers' " + f"KV transfer timeout)" + if self.kv_transfer_timeout_s is not None + else "no KV transfer bound" + ) + return ( + f"generation requests wait in one queue for a free seat ({self.seats} per server, " + f"{num_servers} servers), highest request priority first, ties in arrival order; " + f"{cap}; {bound}" + ) + + def __len__(self) -> int: + return len(self._waiters) + + def waiter(self, rid: int) -> Optional[Waiter]: + return self._waiters.get(rid) + + def waiters(self) -> List[Waiter]: + """The waiting requests, in the order they joined.""" + return list(self._waiters.values()) + + def add( + self, + rid: int, + priority: Any, + exclude: Optional[str], + future: Optional["asyncio.Future[str]"], + orig_elapsed_s: Any = None, + ) -> Waiter: + """A new waiter: it arrived ``orig_elapsed_s`` ago (a context phase has run), else now.""" + if rid in self._waiters: + raise ValueError(f"request {rid} is already waiting") + now = self._clock() + arrival = now + if isinstance(orig_elapsed_s, (int, float)) and not isinstance(orig_elapsed_s, bool): + if math.isfinite(orig_elapsed_s): + arrival = now - max(0.0, float(orig_elapsed_s)) + deadline = None + if self.kv_transfer_timeout_s is not None: + deadline = now + self.kv_transfer_timeout_s * (1.0 - KV_DEADLINE_MARGIN) + waiter = Waiter( + rid=rid, + seq=next(self._seq), + arrival=arrival, + priority=priority_or_default(priority), + exclude=exclude, + future=future, + deadline=deadline, + entered=now, + ) + self._waiters[rid] = waiter + bucket = self._buckets.get(exclude) + if bucket is None: + bucket = self._buckets[exclude] = _Bucket() + bucket.push(waiter) + if deadline is not None: + heapq.heappush(self._deadlines, (deadline, waiter.seq, waiter)) + return waiter + + def _discard(self, waiter: Waiter) -> None: + """Take ``waiter`` (still queued) out of the queue.""" + waiter.queued = False + del self._waiters[waiter.rid] + bucket = self._buckets[waiter.exclude] + bucket.discard() + if not bucket.live: + del self._buckets[waiter.exclude] + if not self._waiters: + self._deadlines.clear() + + def remove(self, rid: int) -> Optional[Waiter]: + """Drop a waiter that finished or was cancelled before its placement.""" + waiter = self._waiters.get(rid) + if waiter is not None: + self._discard(waiter) + self.dropped += 1 + return waiter + + def expire(self, waiter: Optional[Waiter] = None) -> List[Waiter]: + """Remove and return the waiters past their deadline, and ``waiter`` if still waiting.""" + expired = [] + if self._deadlines: + now = self._clock() + while self._deadlines and self._deadlines[0][0] <= now: + w = heapq.heappop(self._deadlines)[2] + if w.queued: + self._discard(w) + expired.append(w) + if waiter is not None and waiter.queued: + self._discard(waiter) + expired.append(waiter) + self.expired += len(expired) + return expired + + def remaining_s(self, waiter: Waiter) -> Optional[float]: + """Seconds until ``waiter``'s deadline (>= 0), or None without one.""" + if waiter.deadline is None: + return None + return max(0.0, waiter.deadline - self._clock()) + + def expiry_message(self, waiter: Waiter) -> str: + return ( + f"generation request {waiter.rid} found no free seat within the context servers' KV " + f"transfer timeout ({(waiter.deadline - waiter.entered) / (1.0 - KV_DEADLINE_MARGIN):g} s " + f"less a {KV_DEADLINE_MARGIN:.0%} margin, after it joined the queue; " + f"{self._clock() - waiter.arrival:.1f} s since it arrived); a context server with the " + f"C++ transceiver has dropped the KV cache transfer by then" + ) + + def _is_aged(self, waiter: Waiter, now: float) -> bool: + return self.max_wait_s is not None and now - waiter.arrival >= self.max_wait_s + + def sort_key(self, waiter: Waiter, now: float) -> Tuple: + """Smaller goes first: aged waiters by (arrival, seq), then the rest by (-priority, seq).""" + if self._is_aged(waiter, now): + return (0, waiter.arrival, waiter.seq) + return (1, -waiter.priority, waiter.seq) + + def pick(self, free_servers: Sequence[str]) -> Optional[Tuple[Waiter, List[str]]]: + """The first waiter in order that may use one of ``free_servers``, with those servers.""" + if not self._waiters or not free_servers: + return None + now = self._pick_now = self._clock() + best, best_key, best_servers = None, None, None + for exclude, bucket in self._buckets.items(): + servers = ( + list(free_servers) if exclude is None else [s for s in free_servers if s != exclude] + ) + if not servers: + continue + waiter = bucket.first(now, self.max_wait_s) + if waiter is None: + continue + key = self.sort_key(waiter, now) + if best_key is None or key < best_key: + best, best_key, best_servers = waiter, key, servers + if best is None: + return None + return best, best_servers + + def record_grant(self, waiter: Waiter) -> None: + """``waiter`` (from :meth:`pick`) took a seat; it leaves the queue.""" + now = self._pick_now if self._pick_now is not None else self._clock() + self._pick_now = None + first_seq = next(iter(self._waiters.values())).seq + if waiter.queued: + self._discard(waiter) + self.placed += 1 + self._win_placed += 1 + self.reordered += waiter.seq != first_seq + self.aged += self._is_aged(waiter, now) + self.placed_at_once += waiter.arriving + self._win_waits.append(max(0.0, now - waiter.entered)) + + def maybe_log_stats(self, seats_used: int, seats_total: int) -> Optional[str]: + """The stats line every ``STATS_LOG_PERIOD_S`` with a placement (also returned).""" + now = self._clock() + if now - self._win_start < STATS_LOG_PERIOD_S or not self._win_placed: + return None + waits = sorted(self._win_waits) + line = ( + f"[seat_pool] {self._win_placed} placed in {now - self._win_start:.0f} s, queue wait " + f"p50 / p90 / max {_pct(waits, 0.5):.2f} / {_pct(waits, 0.9):.2f} / {waits[-1]:.2f} s; " + f"{len(self._waiters)} waiting; seats in use {seats_used} / {seats_total}; total placed " + f"{self.placed} ({self.placed_at_once} at once, {self.reordered} ahead of an earlier " + f"arrival, {self.aged} past the cap), dropped {self.dropped}, " + f"{self.expired} past the KV transfer timeout" + ) + self._win_start = now + self._win_placed = 0 + self._win_waits = [] + logger.info(line) + return line diff --git a/tensorrt_llm/tools/layer_wise_benchmarks/runner.py b/tensorrt_llm/tools/layer_wise_benchmarks/runner.py index ef7f7dd25fe8..09be13300a72 100644 --- a/tensorrt_llm/tools/layer_wise_benchmarks/runner.py +++ b/tensorrt_llm/tools/layer_wise_benchmarks/runner.py @@ -28,6 +28,7 @@ BaseMoeLoadBalancer, MoeLoadBalancerIterContext, ) +from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.trtllm_bf16 import TrtllmTrtllmGenBf16Impl from tensorrt_llm._torch.nccl_window_tensor_scope import discard_nccl_window_tensor_outputs from tensorrt_llm._torch.pyexecutor._util import _mamba_conv_layout_kwargs, get_kv_cache_manager_cls from tensorrt_llm._torch.pyexecutor.config_utils import ( @@ -515,6 +516,10 @@ def forward(position_ids, hidden_states, attn_metadata, residual, **kwargs): ) else: hidden_states = layer(position_ids, hidden_states, attn_metadata, **kwargs) + # As the model's own forward: its hook after the last decoder layer (e.g. joining a side stream). + after_decoder_layers = getattr(model.model, "after_decoder_layers", None) + if after_decoder_layers is not None: + after_decoder_layers() return hidden_states, residual def forward_block_residual( @@ -937,12 +942,26 @@ def replace_routing_method_ctx(self, balance_method: BalanceMethod, balance_rati else: run_moe_orig = None + # The TRTLLM-Gen BF16 leaf routes inside its op from the router logits and never calls + # `routing_method.apply`: route on the host while the replacement is in place (the leaf + # asks `_requires_separated_routing` per forward). + backend = getattr(moe_module, "backend", None) + host_routed_backend = backend if isinstance(backend, TrtllmTrtllmGenBf16Impl) else None + if host_routed_backend is not None: + host_routed_backend._requires_separated_routing = lambda: True + # Replace `forward_impl` to ensure that routing results are replaced forward_impl_orig = moe_module.forward_impl moe_module.forward_impl = make_forward_impl_check(moe_module, forward_impl_orig) original_methods.append( - (apply_method_orig, apply_with_sort_orig, run_moe_orig, forward_impl_orig) + ( + apply_method_orig, + apply_with_sort_orig, + run_moe_orig, + forward_impl_orig, + host_routed_backend, + ) ) try: yield @@ -952,12 +971,15 @@ def replace_routing_method_ctx(self, balance_method: BalanceMethod, balance_rati apply_with_sort_orig, run_moe_orig, forward_impl_orig, + host_routed_backend, ) in zip(moe_modules, original_methods): moe_module.routing_method.apply = apply_method_orig moe_module.routing_method.apply_with_sort = apply_with_sort_orig if isinstance(moe_module, TRTLLMGenFusedMoE): moe_module.run_moe = run_moe_orig moe_module.forward_impl = forward_impl_orig + if host_routed_backend is not None: + del host_routed_backend._requires_separated_routing @staticmethod def create_kv_cache_manager( diff --git a/tensorrt_llm/usage/llm_args_golden_manifest.json b/tensorrt_llm/usage/llm_args_golden_manifest.json index fd79bf801643..8216d5e6f4dc 100644 --- a/tensorrt_llm/usage/llm_args_golden_manifest.json +++ b/tensorrt_llm/usage/llm_args_golden_manifest.json @@ -61,6 +61,11 @@ "kind": "value", "path": "attention_dp_config.kv_cache_routing_fair_share_multiplier" }, + { + "capture_policy": "int|none", + "kind": "value", + "path": "attention_dp_config.kv_cache_routing_home_wait_rounds" + }, { "capture_policy": "float", "kind": "value", @@ -695,6 +700,11 @@ "kind": "value", "path": "kv_cache_config.cross_kv_cache_fraction" }, + { + "capture_policy": "bool", + "kind": "value", + "path": "kv_cache_config.defer_generation_only_release" + }, { "capture_policy": "int|none", "kind": "value", @@ -898,6 +908,60 @@ "kind": "value", "path": "kv_cache_config.pool_ratio" }, + { + "capture_policy": "int", + "kind": "value", + "path": "kv_cache_config.remote_cache_config.donor.size" + }, + { + "capture_policy": "float", + "kind": "value", + "path": "kv_cache_config.remote_cache_config.level.donor_wait_timeout_s" + }, + { + "capture_policy": "int", + "kind": "value", + "path": "kv_cache_config.remote_cache_config.level.expected.claim_size" + }, + { + "capture_policy": "int", + "kind": "value", + "path": "kv_cache_config.remote_cache_config.level.expected.num_donors" + }, + { + "capture_policy": "list[float]|none", + "kind": "value", + "path": "kv_cache_config.remote_cache_config.level.pool_ratio" + }, + { + "capture_policy": "int", + "kind": "value", + "path": "kv_cache_config.remote_cache_config.level.size" + }, + { + "capture_policy": "bool", + "kind": "value", + "path": "kv_cache_config.remote_cache_config.transport.compact_host_memory" + }, + { + "capture_policy": "int", + "kind": "value", + "path": "kv_cache_config.remote_cache_config.transport.donor_reserve_size" + }, + { + "allowed_values": [ + "fabric", + "nixl" + ], + "capture_policy": "literal", + "kind": "categorical", + "path": "kv_cache_config.remote_cache_config.transport.kind" + }, + { + "capture_policy": "float", + "kind": "value", + "path": "kv_cache_config.remote_cache_config.transport.transfer_timeout_s" + }, { "capture_policy": "int|none", "kind": "value", @@ -1519,6 +1583,11 @@ "kind": "value", "path": "scheduler_config.use_python_scheduler" }, + { + "capture_policy": "float|none", + "kind": "value", + "path": "scheduler_config.waiting_queue_max_wait_s" + }, { "allowed_values": [ "fcfs", diff --git a/tests/integration/defs/accuracy/references/acceptance_length.yaml b/tests/integration/defs/accuracy/references/acceptance_length.yaml index d13607dd4b21..f30517a4599f 100644 --- a/tests/integration/defs/accuracy/references/acceptance_length.yaml +++ b/tests/integration/defs/accuracy/references/acceptance_length.yaml @@ -65,6 +65,9 @@ TestQwen3_5_35B_A3B::test_bf16_mtp: TestQwen3_5_35B_A3B::test_bf16_mtp_flashinfer_ring_replay: ref_al: 3.504435 min_al: 3.32921325 +TestQwen3_5_35B_A3B::test_bf16_mtp_adp2: + ref_al: 3.505987 + min_al: 3.33068765 TestQwen3_8_Flash_Next::test_fp8_adp4_mtp3_trtllm_ple_offload: ref_al: 1.890148 min_al: 1.7956406 diff --git a/tests/integration/defs/accuracy/test_llm_api_pytorch.py b/tests/integration/defs/accuracy/test_llm_api_pytorch.py index d56ffbfddae7..d9a353ccd2be 100644 --- a/tests/integration/defs/accuracy/test_llm_api_pytorch.py +++ b/tests/integration/defs/accuracy/test_llm_api_pytorch.py @@ -5427,7 +5427,11 @@ def test_bf16(self, moe_backend, tp_size, mocker): extra_acc_spec=extra_acc_spec, extra_evaluator_kwargs=self.EXTRA_EVALUATOR_KWARGS) - def _run_bf16_mtp(self, mocker, acceptance_key): + def _run_bf16_mtp(self, + mocker, + acceptance_key, + tp_size=1, + attention_dp=False): kv_cache_config = KvCacheConfig(free_gpu_memory_fraction=0.8, enable_block_reuse=False) cuda_graph_config = CudaGraphConfig(enable_padding=True, @@ -5437,8 +5441,9 @@ def _run_bf16_mtp(self, mocker, acceptance_key): with LLM(self.MODEL_PATH, trust_remote_code=True, - tensor_parallel_size=1, + tensor_parallel_size=tp_size, moe_expert_parallel_size=1, + enable_attention_dp=attention_dp, max_seq_len=4096, max_batch_size=32, enable_chunked_prefill=True, @@ -5457,6 +5462,19 @@ def _run_bf16_mtp(self, mocker, acceptance_key): def test_bf16_mtp(self, mocker): self._run_bf16_mtp(mocker, "TestQwen3_5_35B_A3B::test_bf16_mtp") + @pytest.mark.skip_less_device(2) + def test_bf16_mtp_adp2(self, mocker): + """MTP under attention DP across mixed and generation-only ranks. + + One rank's new prompts meet the other's generation-only steps, and + both ranks' draft MoE collectives must agree on their sizes (rows + mixed up across ranks show as a lower acceptance length). + """ + self._run_bf16_mtp(mocker, + "TestQwen3_5_35B_A3B::test_bf16_mtp_adp2", + tp_size=2, + attention_dp=True) + def test_bf16_mtp_flashinfer_ring_replay(self, mocker, monkeypatch): """Same as test_bf16_mtp with GDN replay on the FlashInfer ring kernel.""" # "force" fails the test instead of silently falling back to Triton. diff --git a/tests/integration/test_lists/qa/llm_function_core.txt b/tests/integration/test_lists/qa/llm_function_core.txt index 9922805befe4..e388c5f4eae2 100644 --- a/tests/integration/test_lists/qa/llm_function_core.txt +++ b/tests/integration/test_lists/qa/llm_function_core.txt @@ -576,6 +576,7 @@ accuracy/test_llm_api_pytorch.py::TestQwen3_5_35B_A3B::test_bf16[tp2-CUTLASS] accuracy/test_llm_api_pytorch.py::TestQwen3_5_35B_A3B::test_bf16[tp2-TRTLLM] accuracy/test_llm_api_pytorch.py::TestQwen3_5_35B_A3B::test_bf16_branch_snapshot[enable_branch_snapshot=True] accuracy/test_llm_api_pytorch.py::TestQwen3_5_35B_A3B::test_bf16_mtp +accuracy/test_llm_api_pytorch.py::TestQwen3_5_35B_A3B::test_bf16_mtp_adp2 accuracy/test_llm_api_pytorch.py::TestQwen3_5_35B_A3B::test_fp8[enable_block_reuse=False] accuracy/test_llm_api_pytorch.py::TestQwen3_5_35B_A3B::test_fp8[enable_block_reuse=True] accuracy/test_llm_api_pytorch.py::TestQwen3_5_35B_A3B::test_fp8_moe_dflash diff --git a/tests/integration/test_lists/test-db/l0_a10.yml b/tests/integration/test_lists/test-db/l0_a10.yml index dabd43edaaa2..81dc060cd1e9 100644 --- a/tests/integration/test_lists/test-db/l0_a10.yml +++ b/tests/integration/test_lists/test-db/l0_a10.yml @@ -255,7 +255,7 @@ l0_a10: - thirdparty/test_git_modules.py::test_gitmodules # helper-script unit tests (CPU-only, ~3s) - unittest/scripts - - unittest/kv_cache_manager_v2_tests # 4 min + - unittest/kv_cache_manager_v2_tests - unittest/api_stability - unittest/bindings - condition: diff --git a/tests/integration/test_lists/test-db/l0_b200.yml b/tests/integration/test_lists/test-db/l0_b200.yml index 8850cfd301f0..4c8449fdd982 100644 --- a/tests/integration/test_lists/test-db/l0_b200.yml +++ b/tests/integration/test_lists/test-db/l0_b200.yml @@ -156,6 +156,11 @@ l0_b200: - unittest/_torch/modules/test_gate_up_swiglu_quack.py - unittest/_torch/modules/test_multi_stream_utils.py - unittest/_torch/modules/test_megamoe_shared_mlp_scales.py + # Qwen3.5 decode MoE: NVFP4 and BF16 draft engines, CuTe FC2 (decode / route fronts below). + - unittest/_torch/moe/test_moe_nvfp4_engine.py + - unittest/_torch/moe/test_moe_bf16_engine.py + - unittest/_torch/moe/test_moe_lowm_fc2.py + - unittest/_torch/modules/test_expert_l2_prefetch.py # ------------- DeepSeek-V4.1 model, Engram and DSpark --------------- - unittest/_torch/modeling/test_modeling_deepseekv41.py - unittest/_torch/modules/test_engram_decode_hash.py @@ -233,6 +238,9 @@ l0_b200: - unittest/_torch/modules/test_gated_mlp_split.py - unittest/_torch/modules/test_low_m_gemm.py - unittest/_torch/modules/test_low_m_mma_gemm.py + - unittest/_torch/modules/test_resident_fp8_gemm.py + - unittest/_torch/modules/test_inproj_ba_splitk.py + - unittest/_torch/modules/test_gate_add_rmsnorm_fp8.py - unittest/_torch/moe/test_moe_decode_front.py - unittest/_torch/modules/test_embedding_lookup.py - unittest/_torch/moe/test_draft_experts_nvfp4.py @@ -369,7 +377,7 @@ l0_b200: - unittest/tools/test_layer_wise_benchmarks.py::test_qwen3_next_gen_tep[1] - unittest/tools/test_layer_wise_benchmarks.py::test_kimi_k3_gen_dep[1] - unittest/tools/test_layer_wise_benchmarks.py::test_performance_alignment[1] - - unittest/kv_cache_manager_v2_tests + - unittest/kv_cache_manager_v2_tests -k "not RemoteInPlaceOfDisk" - llmapi/test_llm_api_connector.py::test_connector_priorities[kv_cache_manager_v1] - unittest/_torch/pyexecutor/kv_cache/test_mamba_cache_manager.py::test_v2_hybrid_retains_configured_number_of_conversation_turns - unittest/_torch/pyexecutor/kv_cache/test_kvcm2_integration.py::test_helix_retention_uses_rank_local_ranges diff --git a/tests/integration/test_lists/test-db/l0_b300.yml b/tests/integration/test_lists/test-db/l0_b300.yml index d5ba4df428ba..c635313c8ae8 100644 --- a/tests/integration/test_lists/test-db/l0_b300.yml +++ b/tests/integration/test_lists/test-db/l0_b300.yml @@ -76,6 +76,15 @@ l0_b300: - unittest/_torch/modules/test_qwen4_exp_ple_offload.py - unittest/_torch/modules/mamba - unittest/_torch/modules/tests_lora_modules + # Qwen3.5 decode kernels: MoE engines and CuTe FC2; FP8 / BF16 GEMMs with weights loaded before + # the PDL wait (bitwise against SM103 cuBLAS). + - unittest/_torch/moe/test_moe_nvfp4_engine.py + - unittest/_torch/moe/test_moe_bf16_engine.py + - unittest/_torch/moe/test_moe_lowm_fc2.py + - unittest/_torch/modules/test_resident_fp8_gemm.py + - unittest/_torch/modules/test_expert_l2_prefetch.py + - unittest/_torch/modules/test_inproj_ba_splitk.py + - unittest/_torch/modules/test_gate_add_rmsnorm_fp8.py # ------------- MoE components tests --------------- - unittest/_torch/moe/test_moe_load_balancer.py - unittest/_torch/moe/test_moe_routing.py diff --git a/tests/integration/test_lists/test-db/l0_cpu.yml b/tests/integration/test_lists/test-db/l0_cpu.yml index d037225a80ac..7e3603846443 100644 --- a/tests/integration/test_lists/test-db/l0_cpu.yml +++ b/tests/integration/test_lists/test-db/l0_cpu.yml @@ -207,6 +207,9 @@ l0_cpu: - unittest/_torch/modules - unittest/_torch/moe - unittest/_torch/multimodal + # Every test in it is cpu_only, so l0_b200's unittest/_torch/kv_cache_compression entry + # (-m "not cpu_only") runs none of them. + - unittest/_torch/kv_cache_compression/test_quantization_for_cold_page.py - unittest/_torch/ray_orchestrator/single_gpu/test_cache_transceiver_comm.py - unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_capacity_only.py::test_index_mapper_reservation_tracks_confidence_scheduling - unittest/_torch/speculative/hw_agnostic @@ -220,6 +223,7 @@ l0_cpu: - unittest/_torch/test_connector.py - unittest/_torch/test_connector_adp.py - unittest/_torch/models/test_modeling_utils.py::test_tied_embedding_parallel_layout + - unittest/_torch/models/test_qwen3next_moe_input_dual_quant.py - unittest/_torch/models/test_modeling_utils.py::test_tied_embedding_rejects_incompatible_layout - unittest/_torch/models/test_modeling_utils.py::test_quantization_passes_match_declared_fused_checkpoint_names - unittest/_torch/test_connector_shared_pool.py diff --git a/tests/integration/test_lists/test-db/l0_dgx_b200.yml b/tests/integration/test_lists/test-db/l0_dgx_b200.yml index 32924f89db02..9d948e6531fc 100644 --- a/tests/integration/test_lists/test-db/l0_dgx_b200.yml +++ b/tests/integration/test_lists/test-db/l0_dgx_b200.yml @@ -32,6 +32,7 @@ l0_dgx_b200: # vs the single-GPU drafter. - unittest/_torch/multi_gpu/test_dspark_drafter_tp_fusion.py - accuracy/test_llm_api_pytorch.py::TestQwen3_5_35B_A3B::test_bf16[tp2-TRTLLM] + - accuracy/test_llm_api_pytorch.py::TestQwen3_5_35B_A3B::test_bf16_mtp_adp2 - disaggregated/test_disaggregated_beam_search.py::test_disaggregated_beam_search_v2[beam2-reuse] - disaggregated/test_disaggregated_beam_search.py::test_disaggregated_beam_search_v2[beam4-no-reuse] - accuracy/test_disaggregated_serving.py::TestQwen3_8BDFlash::test_gsm8k_1p1d_unified_draft_kv diff --git a/tests/integration/test_lists/test-db/l0_dgx_b300.yml b/tests/integration/test_lists/test-db/l0_dgx_b300.yml index c7cdb79b74c2..2edfefb4bd8e 100644 --- a/tests/integration/test_lists/test-db/l0_dgx_b300.yml +++ b/tests/integration/test_lists/test-db/l0_dgx_b300.yml @@ -23,8 +23,9 @@ l0_dgx_b300: # pre_merge). The GPU cases of kernels/parallel_hw_agnostic/, which do not depend on the # GPU architecture, run on H100 (pre_merge) and GB300 (post_merge). So of attention/, # this 4-GPU stage runs only multi_gpu/, whose cases need >= 2 GPUs; - # test_helix_zero_kv.py runs in this list's pre_merge block instead. - - unittest/_torch/attention/multi_gpu --ignore=unittest/_torch/attention/multi_gpu/test_helix_zero_kv.py + # test_helix_zero_kv.py runs in this list's pre_merge block instead, and + # test_gqa_kv_replica.py in l0_gb300's (same SM103 single-node CUDA-IPC exchange). + - unittest/_torch/attention/multi_gpu --ignore=unittest/_torch/attention/multi_gpu/test_helix_zero_kv.py --ignore=unittest/_torch/attention/multi_gpu/test_gqa_kv_replica.py - unittest/_torch/pyexecutor - unittest/_torch/disaggregation - unittest/_torch/modeling -k "modeling_llama" diff --git a/tests/integration/test_lists/test-db/l0_gb300.yml b/tests/integration/test_lists/test-db/l0_gb300.yml index c65af3a3b310..4a61e957680a 100644 --- a/tests/integration/test_lists/test-db/l0_gb300.yml +++ b/tests/integration/test_lists/test-db/l0_gb300.yml @@ -104,6 +104,12 @@ l0_gb300: - unittest/_torch/modules/test_mxfp8_draft_head.py - unittest/_torch/modules/test_q35_mtp_glue.py - unittest/_torch/pyexecutor/test_steady_spec_prepare.py + # KV cache manager v2 remote cache level: only the fabric transport cases (Grace host memory), which no other + # stage can run. The NIXL cases run with the whole unittest/kv_cache_manager_v2_tests directory in l0_a10 and + # l0_b200 (pre-merge) and l0_h100 (post-merge); the host-only (cpu_only) cases run in l0_cpu. + - unittest/kv_cache_manager_v2_tests/test_remote_fabric_available.py + - unittest/kv_cache_manager_v2_tests/test_remote_level.py -k "fabric" + - unittest/kv_cache_manager_v2_tests/test_remote_capacity.py -k "fabric" # Muse Spark Open decoder fast paths on one GPU: the fused Triton kernels and the # GB300 cluster boundary kernel, against their reference compositions. - unittest/_torch/modeling/test_musespark_open_router_projection.py @@ -150,6 +156,11 @@ l0_gb300: # 3k-6k-token pass keys with their acceptance-length floor. The other layouts and KV dtypes # run post-merge (l0_gb300_multi_gpus). - accuracy/modeling_v2/qwen4_exp/qwen3_8_flash_next_nvfp4__sm_103__default/test_accuracy.py::TestModelingV2Qwen38FlashNextNvfp4Sm103Default::test_mtp3_gsm8k_and_long_context TIMEOUT (60) + # Qwen3.5 TP decode: KV-replica FP8 decode (TP2 / TP4), the MNNVL all-reduce + RMSNorm kernels and the LL TP + # exchanges (sampling, RoPE gather, group merge) at group sizes 2 and 4. + - unittest/_torch/attention/multi_gpu/test_gqa_kv_replica.py + - unittest/_torch/multi_gpu/test_mnnvl_fused_allreduce_norm.py + - unittest/_torch/multi_gpu/test_ll_exchange.py # K3 collectives and decode-path exchanges, four ranks in one NVLink domain. - condition: diff --git a/tests/integration/test_lists/test-db/l0_gb300_multi_gpus.yml b/tests/integration/test_lists/test-db/l0_gb300_multi_gpus.yml index 6283d4b80a49..d25f508c4362 100644 --- a/tests/integration/test_lists/test-db/l0_gb300_multi_gpus.yml +++ b/tests/integration/test_lists/test-db/l0_gb300_multi_gpus.yml @@ -52,8 +52,9 @@ l0_gb300_multi_gpus: # kernels/parallel_hw_agnostic/ run here too, although l0_b200 and l0_b300 ignore that # directory: an --ignore would change this entry's text, which agg_unit_mem_df.csv # matches to set its parallelism. This post_merge stage is the only Blackwell stage that - # runs them. - - unittest/_torch/attention TIMEOUT (120) + # runs them. multi_gpu/test_gqa_kv_replica.py runs in l0_gb300's pre_merge block instead; + # --ignore arguments do not change the CSV key (test_unittests.py _parallel_config_key). + - unittest/_torch/attention --ignore=unittest/_torch/attention/multi_gpu/test_gqa_kv_replica.py TIMEOUT (120) - unittest/_torch/moe/kernels/parallel - unittest/_torch/kernels/parallel - unittest/_torch/visual_gen/kernels/parallel @@ -83,9 +84,6 @@ l0_gb300_multi_gpus: # ------------- MoE components tests --------------- - unittest/_torch/moe/test_moe_load_balancer.py - unittest/_torch/moe/test_moe_routing.py - # MNNVL all-reduce + residual RMSNorm kernels (slot / two-shot / MoE fold / GEMM) and the LL TP exchanges. - - unittest/_torch/multi_gpu/test_mnnvl_fused_allreduce_norm.py - - unittest/_torch/multi_gpu/test_ll_exchange.py - unittest/_torch/modeling -k "modeling_llama" - unittest/_torch/modeling -k "modeling_gpt_oss" # Muse Spark Open's fused expert finalize + TP4 all-reduce over CUDA IPC; each diff --git a/tests/integration/test_lists/test-db/l0_h100.yml b/tests/integration/test_lists/test-db/l0_h100.yml index d56a7a28e104..6eb958ced11f 100644 --- a/tests/integration/test_lists/test-db/l0_h100.yml +++ b/tests/integration/test_lists/test-db/l0_h100.yml @@ -388,7 +388,7 @@ l0_h100: - llmapi/test_llm_api_pytorch_whisper.py::test_whisper_pytorch_feature_combinations[fp16-kv-v2-graphs-off-greedy] - examples/test_gpt.py::test_gpt_oss_20b_lora_torch[gpt-oss-20b-lora-adapter_NIM_r8-gpt-oss-20b] - unittest/bindings # 8 mins on H100 - - unittest/kv_cache_manager_v2_tests # 4 min + - unittest/kv_cache_manager_v2_tests # ------------- KV Cache Iteration Stats --------------- - kv_cache/test_kv_cache_iteration_stats.py::TestKvCacheIterationStats::test_cold_start - kv_cache/test_kv_cache_iteration_stats.py::TestKvCacheIterationStats::test_partial_block_reuse diff --git a/tests/integration/test_lists/waives.txt b/tests/integration/test_lists/waives.txt index e9201ef7f8dc..719ca6a4406b 100644 --- a/tests/integration/test_lists/waives.txt +++ b/tests/integration/test_lists/waives.txt @@ -226,9 +226,6 @@ unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_vocab_size.py::test_branch_ unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_vocab_size.py::test_branch_only_enables_multimodal_keys_when_needed[nemotron_hybrid-encoder_disable_noop] SKIP (https://nvbugs/6818710) unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_vocab_size.py::test_branch_only_enables_multimodal_keys_when_needed[nemotron_hybrid-multimodal] SKIP (https://nvbugs/6818710) unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_vocab_size.py::test_branch_only_enables_multimodal_keys_when_needed[nemotron_hybrid-text_only] SKIP (https://nvbugs/6818710) -unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_vocab_size.py::test_branch_only_enables_multimodal_keys_when_needed[qwen3_5_hybrid-encoder_disable_noop] SKIP (https://nvbugs/6818710) -unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_vocab_size.py::test_branch_only_enables_multimodal_keys_when_needed[qwen3_5_hybrid-multimodal] SKIP (https://nvbugs/6818710) -unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_vocab_size.py::test_branch_only_enables_multimodal_keys_when_needed[qwen3_5_hybrid-text_only] SKIP (https://nvbugs/6818710) unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_vocab_size.py::test_unresolvable_vocab_size_only_warns_when_multimodal_keys_are_needed[False] SKIP (https://nvbugs/6818710) unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_vocab_size.py::test_unresolvable_vocab_size_only_warns_when_multimodal_keys_are_needed[True] SKIP (https://nvbugs/6818710) unittest/_torch/pyexecutor/test_gen_preemption.py::test_forced_resume_accounting_and_drafter_lifecycle[settings0-dflash] SKIP (https://nvbugs/7088349) diff --git a/tests/unittest/_torch/attention/kernels/test_fused_qk_norm_rope_gate.py b/tests/unittest/_torch/attention/kernels/test_fused_qk_norm_rope_gate.py index 3c0a5946238a..232f51fa8446 100644 --- a/tests/unittest/_torch/attention/kernels/test_fused_qk_norm_rope_gate.py +++ b/tests/unittest/_torch/attention/kernels/test_fused_qk_norm_rope_gate.py @@ -24,6 +24,7 @@ from tensorrt_llm._torch.attention.attention import Attention from tensorrt_llm._torch.attention.kernels.fused_qk_norm_rope_gate import ( fused_qkv_gemma_rmsnorm_rope_gate, + fused_sigmoid_mul_fp8, fused_sigmoid_mul_inplace, ) @@ -299,6 +300,32 @@ def test_output_gate_fallback_flattens_fused_gate(): torch.testing.assert_close(actual, expected, atol=0, rtol=0) +# 2e-3 takes most gated values past the E4M3 maximum (448), so the saturation is compared too. +@pytest.mark.parametrize("scale", (0.13, 32.0, 2e-3)) +@pytest.mark.parametrize("num_tokens", (1, 37, 1024, 2049)) +@pytest.mark.parametrize("strided_gate", (False, True)) +def test_fused_sigmoid_mul_fp8_matches_gate_then_static_quantize(scale, num_tokens, strided_gate): + """The FP8-output gate writes the bytes of the in-place gate followed by o_proj's static quantization.""" + torch.manual_seed(num_tokens) + num_heads, head_dim = 8, 256 + attention = torch.randn((num_tokens, num_heads * head_dim), dtype=torch.bfloat16, device="cuda") + if strided_gate: + gate = torch.randn( + (num_tokens, num_heads, 2 * head_dim), dtype=torch.bfloat16, device="cuda" + )[..., :head_dim] + else: + gate = torch.randn_like(attention) + input_scale = torch.tensor([scale], dtype=torch.float32, device="cuda") + + gated = attention.clone() + fused_sigmoid_mul_inplace(gated, gate) + expected, _ = torch.ops.tensorrt_llm.static_quantize_e4m3_per_tensor(gated, input_scale) + actual = fused_sigmoid_mul_fp8(attention, gate, input_scale) + + assert actual.dtype == torch.float8_e4m3fn + assert torch.equal(actual.view(torch.uint8), expected.view(torch.uint8)) + + def test_fused_sigmoid_mul_inplace_supports_flat_gate(): torch.manual_seed(11) attention = torch.randn((9, 512), dtype=torch.float16, device="cuda") @@ -583,3 +610,191 @@ def test_qkv_rope_tiling_batch_boundaries( torch.testing.assert_close( prefix[0][:, v_start:], reference[0][:, v_start:], atol=0, rtol=0 ) + + +# The two output-gate kernels as they were before they became one kernel with an OUT_FP8 flag (verbatim bodies). +import triton # noqa: E402 +import triton.language as tl # noqa: E402 +import triton.language.extra.libdevice as tldevice # noqa: E402 + +from tensorrt_llm._torch.modules.fla.op import gdc_wait_with_memory_clobber # noqa: E402 + + +@triton.jit +def _separate_sigmoid_mul_kernel( + output_ptr, + attention_ptr, + gate_ptr, + output_stride_token, + attention_stride_token, + gate_stride_token, + gate_stride_head, + hidden_size: tl.constexpr, + head_dim: tl.constexpr, + block_size: tl.constexpr, + LAUNCH_WITH_PDL: tl.constexpr = False, +) -> None: + if LAUNCH_WITH_PDL: + tl.extra.cuda.gdc_launch_dependents() + token = tl.program_id(0).to(tl.int64) + block = tl.program_id(1) + offsets = block * block_size + tl.arange(0, block_size) + mask = offsets < hidden_size + head = offsets // head_dim + dim = offsets - head * head_dim + if LAUNCH_WITH_PDL: + gdc_wait_with_memory_clobber() + + attention = tl.load( + attention_ptr + token * attention_stride_token + offsets, + mask=mask, + other=0.0, + ).to(tl.float32) + gate = tl.load( + gate_ptr + token * gate_stride_token + head * gate_stride_head + dim, + mask=mask, + other=0.0, + ).to(tl.float32) + tl.store( + output_ptr + token * output_stride_token + offsets, + attention * tl.sigmoid(gate), + mask=mask, + ) + + +@triton.jit +def _separate_sigmoid_mul_fp8_kernel( + output_ptr, + attention_ptr, + gate_ptr, + scale_ptr, + output_stride_token, + attention_stride_token, + gate_stride_token, + gate_stride_head, + hidden_size: tl.constexpr, + head_dim: tl.constexpr, + block_size: tl.constexpr, + LAUNCH_WITH_PDL: tl.constexpr = False, +) -> None: + if LAUNCH_WITH_PDL: + tl.extra.cuda.gdc_launch_dependents() + token = tl.program_id(0).to(tl.int64) + block = tl.program_id(1) + offsets = block * block_size + tl.arange(0, block_size) + mask = offsets < hidden_size + head = offsets // head_dim + dim = offsets - head * head_dim + if LAUNCH_WITH_PDL: + gdc_wait_with_memory_clobber() + + attention = tl.load( + attention_ptr + token * attention_stride_token + offsets, + mask=mask, + other=0.0, + ).to(tl.float32) + gate = tl.load( + gate_ptr + token * gate_stride_token + head * gate_stride_head + dim, + mask=mask, + other=0.0, + ).to(tl.float32) + y = (attention * tl.sigmoid(gate)).to(attention_ptr.dtype.element_ty).to(tl.float32) + y *= tldevice.rcp_rn(tl.load(scale_ptr).to(tl.float32)) + tl.store( + output_ptr + token * output_stride_token + offsets, + y.to(output_ptr.dtype.element_ty), + mask=mask, + ) + + +def _separate_gate_launch(output, attention, gate, scale): + """The former launch of the two kernels: (grid, num_warps) and the launch itself.""" + num_tokens, hidden_size = attention.shape + if gate.dim() == 3: + head_dim, g_tok, g_head = gate.shape[2], gate.stride(0), gate.stride(1) + else: + head_dim, g_tok, g_head = hidden_size, gate.stride(0), hidden_size + block_size = min(triton.next_power_of_2(hidden_size), 1024 if num_tokens < 1024 else 2048) + grid = (num_tokens, triton.cdiv(hidden_size, block_size)) + pdl = ( + dict(LAUNCH_WITH_PDL=True, launch_pdl=True) + if _kernel_module._sigmoid_mul_pdl(attention.device.index) + else {} + ) + common = dict(hidden_size=hidden_size, head_dim=head_dim, block_size=block_size, num_warps=4) + if scale is None: + _separate_sigmoid_mul_kernel[grid]( + output, + attention, + gate, + output.stride(0), + attention.stride(0), + g_tok, + g_head, + **common, + **pdl, + ) + else: + _separate_sigmoid_mul_fp8_kernel[grid]( + output, + attention, + gate, + scale, + output.stride(0), + attention.stride(0), + g_tok, + g_head, + **common, + **pdl, + ) + return grid, common["block_size"], common["num_warps"] + + +@pytest.mark.parametrize("num_tokens", (1, 37, 1023, 1024, 2049)) +@pytest.mark.parametrize("gate_layout", ("flat", "heads", "strided_heads")) +@pytest.mark.parametrize("fp8", (False, True), ids=("bf16_inplace", "fp8_out")) +def test_one_gate_kernel_matches_the_separate_kernels(num_tokens, gate_layout, fp8): + """The OUT_FP8-flagged gate kernel writes the bytes of the former in-place and FP8-output kernels, with their + grid, block and warp count (the Qwen3.5 context FP8 gate runs from 1024 rows; 2048-wide blocks from there).""" + torch.manual_seed(num_tokens) + num_heads, head_dim = 8, 256 + attention = torch.randn((num_tokens, num_heads * head_dim), dtype=torch.bfloat16, device="cuda") + if gate_layout == "flat": + gate = torch.randn_like(attention) + elif gate_layout == "heads": + gate = torch.randn((num_tokens, num_heads, head_dim), dtype=torch.bfloat16, device="cuda") + else: + gate = torch.randn( + (num_tokens, num_heads, 2 * head_dim), dtype=torch.bfloat16, device="cuda" + )[..., :head_dim] + scale = torch.tensor([0.13], dtype=torch.float32, device="cuda") if fp8 else None + out_dtype = torch.float8_e4m3fn if fp8 else torch.bfloat16 + if fp8: + expected = torch.empty_like(attention, dtype=out_dtype) + ref_launch = _separate_gate_launch(expected, attention, gate, scale) + else: + # The in-place kernel reads and writes the same tensor. + expected = attention.clone() + ref_launch = _separate_gate_launch(expected, expected, gate, None) + + launches = [] + real = _kernel_module._fused_sigmoid_mul_kernel + + class _Recorder: + def __getitem__(self, grid): + def launch(*args, **kwargs): + launches.append((grid, kwargs["block_size"], kwargs["num_warps"])) + return real[grid](*args, **kwargs) + + return launch + + with patch.object(_kernel_module, "_fused_sigmoid_mul_kernel", _Recorder()): + if fp8: + actual = fused_sigmoid_mul_fp8(attention, gate, scale) + else: + actual = attention.clone() + fused_sigmoid_mul_inplace(actual, gate) + torch.cuda.synchronize() + assert launches == [ref_launch] + assert actual.dtype == out_dtype + assert torch.equal(actual.view(torch.uint8), expected.view(torch.uint8)) diff --git a/tests/unittest/_torch/attention/multi_gpu/test_gqa_kv_replica.py b/tests/unittest/_torch/attention/multi_gpu/test_gqa_kv_replica.py index 2e6742be0de6..59d0c07d9a1b 100644 --- a/tests/unittest/_torch/attention/multi_gpu/test_gqa_kv_replica.py +++ b/tests/unittest/_torch/attention/multi_gpu/test_gqa_kv_replica.py @@ -23,12 +23,14 @@ from mpi4py import MPI import tensorrt_llm +from tensorrt_llm._torch.attention.backends.fmha import gqa_kv_replica from tensorrt_llm._torch.attention.backends.fmha.gqa_decode import _kv_replica_exchange_sizes from tensorrt_llm._torch.attention.backends.fmha.gqa_kv_replica import ( kv_replica_decode, kv_replica_fused_decode, ) from tensorrt_llm._torch.attention.backends.fmha.gqa_kv_replica_fused import ( + _plan, kv_replica_fused_state, kv_replica_fused_supported, ) @@ -49,6 +51,10 @@ HQ, D, PAGE = 4, 256, 64 BMM1, BMM2 = 1.0 / 16, 1.0 +_OUT_SCALE = 0.37 +# Largest batch the test runs on the segmented path: its two partials per row fill the merge channel and its counters +# at larger batches, where GqaKvReplicaFmha._takes declines (the push-channel cases only run the fused path). +_SEGMENTED_MAX_REQUESTS = 16 def _inputs(lens, q_len, tp, rank): @@ -85,65 +91,143 @@ def _reference(kv, tables, lens, q, gate, q_len): return gated.to(torch.bfloat16) +def _decode_all(ex, q, kv, tables, seq, lens, q_len, sms, gate, enable_pdl, workspace, counter): + """The outputs of every KV-replica decode path on exchange ``ex``: segmented (up to _SEGMENTED_MAX_REQUESTS + requests), fused (BF16) and fused (E4M3, the merge writing o_proj's input), the last two where the fused partial + kernel takes the shape.""" + out = torch.empty(q.shape, dtype=torch.bfloat16, device="cuda") + outs = {} + if len(lens) <= _SEGMENTED_MAX_REQUESTS: + kv_replica_decode( + ex, + q, + kv, + tables, + seq, + max(lens), + q_len, + 2, + BMM1, + BMM2, + workspace, + counter, + out, + enable_pdl, + gate=gate, + ) + outs["segmented"] = out + if kv_replica_fused_supported(q_len, ex.group_size, HQ, len(lens), sms): + out = torch.empty_like(out) + kv_replica_fused_decode( + ex, + q, + kv, + tables, + seq, + q_len, + BMM1, + BMM2, + out, + kv_replica_fused_state(q.device, sms, len(seq)), + enable_pdl, + gate=gate, + ) + outs["fused"] = out + # The same call with freshly allocated (O, LSE) partial outputs instead of the pushed-mode placeholders: + # the push channel never writes them, so the result is bit-identical. + fresh = torch.empty_like(out) + real_placeholders = gqa_kv_replica._pushed_partial_placeholders + gqa_kv_replica._pushed_partial_placeholders = lambda cp, rows, hq, d, dtype, device: ( + torch.empty(cp, rows, hq, d, dtype=dtype, device=device), + torch.empty(cp, rows, hq, dtype=torch.float32, device=device), + ) + try: + kv_replica_fused_decode( + ex, + q, + kv, + tables, + seq, + q_len, + BMM1, + BMM2, + fresh, + kv_replica_fused_state(q.device, sms, len(seq)), + enable_pdl, + gate=gate, + ) + finally: + gqa_kv_replica._pushed_partial_placeholders = real_placeholders + outs["fused_fresh"] = fresh + out_fp8 = torch.empty(q.shape, dtype=torch.float8_e4m3fn, device="cuda") + kv_replica_fused_decode( + ex, + q, + kv, + tables, + seq, + q_len, + BMM1, + BMM2, + torch.empty_like(out), + kv_replica_fused_state(q.device, sms, len(seq)), + enable_pdl, + gate=gate, + out_fp8=out_fp8, + out_scale=torch.tensor([_OUT_SCALE], dtype=torch.float32, device="cuda"), + ) + outs["fused_fp8"] = out_fp8 + torch.cuda.synchronize() + return outs + + def _kv_replica(tp): rank = tensorrt_llm.mpi_rank() torch.cuda.set_device(rank) MPI.COMM_WORLD.barrier() mapping = Mapping(world_size=tp, tp_size=tp, rank=rank) sms = torch.cuda.get_device_properties(rank).multi_processor_count - max_bytes, max_merge_rows = _kv_replica_exchange_sizes(16, 7, HQ, D) + max_bytes, max_merge_rows = _kv_replica_exchange_sizes(128, 7, HQ, D) ex = TPGroupExchange.create(mapping, tp, max_bytes, max_merge_rows) assert ex is not None, "no peer memory for the exchange" workspace = torch.zeros(128 << 20, dtype=torch.uint8, device="cuda") counter = torch.zeros(128 * 128, dtype=torch.int32, device="cuda") try: - for lens, q_len in (([5000, 70, 1300], 7), ([9000, 64, 130, 4100, 70, 12000], 1)): + plans = set() + for lens, q_len in ( + ([5000, 70, 1300], 7), + ([9000, 64, 130, 4100, 70, 12000], 1), + # The push channel with the wide (33-64 requests) and two-slot (above 64) plans. + ([64 + (i * 97) % 1200 for i in range(40)], 7), + ([7 + (i * 131) % 900 for i in range(100)], 7), + ): + if kv_replica_fused_supported(q_len, tp, HQ, len(lens), sms): + plans.add(_plan(len(lens), sms)) kv, tables, seq, q, gate = _inputs(lens, q_len, tp, rank) ref = _reference(kv, tables, lens, q, gate, q_len) - fused = kv_replica_fused_supported(q_len, tp, HQ, len(lens), sms) for enable_pdl in (False, True): - out = torch.empty(q.shape, dtype=torch.bfloat16, device="cuda") - kv_replica_decode( - ex, - q, - kv, - tables, - seq, - max(lens), - q_len, - 2, - BMM1, - BMM2, - workspace, - counter, - out, - enable_pdl, - gate=gate, - ) - outs = {"segmented": out} - if fused: - out = torch.empty_like(out) - kv_replica_fused_decode( - ex, - q, - kv, - tables, - seq, - q_len, - BMM1, - BMM2, - out, - kv_replica_fused_state(q.device, sms, len(seq)), - enable_pdl, - gate=gate, + args = (q, kv, tables, seq, lens, q_len, sms, gate, enable_pdl, workspace, counter) + outs = _decode_all(ex, *args) + if "fused_fp8" in outs: + # The merge writing o_proj's E4M3 input: the bytes of the BF16 result's static quant. + # static_quantize_e4m3_per_tensor: FP32(BF16) x (1 / s), round to nearest. + out_scale = torch.tensor([_OUT_SCALE], dtype=torch.float32, device="cuda") + expected_fp8 = (outs["fused"].float() * (1.0 / out_scale)).to( + torch.float8_e4m3fn ) - outs["fused"] = out - torch.cuda.synchronize() + assert torch.equal( + outs.pop("fused_fp8").view(torch.uint8), expected_fp8.view(torch.uint8) + ), (lens, q_len, enable_pdl) + if "fused_fresh" in outs: + assert torch.equal( + outs.pop("fused_fresh").view(torch.uint8), outs["fused"].view(torch.uint8) + ), (lens, q_len, enable_pdl) for name, out in outs.items(): # FP8 P / partials: a few percent of the row max per element err = (out.float() - ref.float()).abs().amax(dim=-1) scale = ref.float().abs().amax(dim=-1).clamp_min(1e-3) assert (err / scale).amax().item() < 0.08, (name, lens, q_len, enable_pdl) + assert {"lane", "wide", "two"} <= plans, plans finally: MPI.COMM_WORLD.barrier() ex.close() @@ -166,3 +250,64 @@ def test_kv_replica_decode_matches_reference(mpi_pool_executor): pytest.skip(f"needs {tp} GPUs") results = mpi_pool_executor.map(_worker, [tp] * tp) assert all(results) + + +class _StubExchange: + """The two TPGroupExchange calls kv_replica_fused_decode makes with a gathered q, recorded.""" + + group_size, grank = 2, 0 + + def __init__(self): + self.merged = [] + + def merge_push_args(self, channel, rows, d): + return ("ll", channel, rows, d) + + def alltoall_merge(self, o, lse, out, **kwargs): + self.merged.append((o, lse, kwargs["pushed"])) + + +@pytest.mark.parametrize("rows_seq", [(14, 14, 7), (21, 7, 14)]) +def test_pushed_partials_reuse_placeholder_storage(monkeypatch, rows_seq): + """With the push channel the partial kernel never writes its (O, LSE) outputs and the merge never reads them: + every eager call up to the largest row count seen gets views of the same storage (no two allocations per layer + and step), with the shapes and strides of fresh tensors.""" + partials = [] + monkeypatch.setattr( + gqa_kv_replica, + "kv_replica_fused_partial", + lambda q_all, + kv, + tables, + seq, + q_len, + cp_rank, + cp, + b1, + b2, + o, + lse, + state, + **kw: partials.append((o, lse, kw["ll"])), + ) + ex = _StubExchange() + hq, d = 4, 256 + for rows in rows_seq: + q = torch.zeros(rows, hq, d, dtype=torch.float8_e4m3fn, device="cuda") + out = torch.empty(rows, hq, d, dtype=torch.bfloat16, device="cuda") + q_gathered = torch.zeros(rows, 2 * hq * d, dtype=torch.float8_e4m3fn, device="cuda") + kv_replica_fused_decode( + ex, q, None, None, None, 7, BMM1, BMM2, out, None, False, q_gathered=q_gathered + ) + storages = {o.untyped_storage().data_ptr() for o, _, _ in partials} + lse_storages = {lse.untyped_storage().data_ptr() for _, lse, _ in partials} + # Kept alive by the recorder, fresh allocations would all differ. + assert len(storages) == 1 and len(lse_storages) == 1 + for (o, lse, ll), rows in zip(partials, rows_seq): + ref_o = torch.empty(2, rows, hq, d, dtype=torch.bfloat16, device="cuda") + ref_lse = torch.empty(2, rows, hq, dtype=torch.float32, device="cuda") + assert o.shape == ref_o.shape and o.stride() == ref_o.stride() and o.dtype == ref_o.dtype + assert lse.shape == ref_lse.shape and lse.stride() == ref_lse.stride() + assert o.data_ptr() % 16 == 0 and lse.data_ptr() % 16 == 0 + assert ll == ("ll", 1, rows * hq, d) + assert [m[0] is p[0] and m[2] for m, p in zip(ex.merged, partials)] == [True] * len(rows_seq) diff --git a/tests/unittest/_torch/attention/test_fmha_paged_context_fp8.py b/tests/unittest/_torch/attention/test_fmha_paged_context_fp8.py new file mode 100644 index 000000000000..9065ada40b26 --- /dev/null +++ b/tests/unittest/_torch/attention/test_fmha_paged_context_fp8.py @@ -0,0 +1,601 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""trtllm::fmha_paged_context_fp8: causal FP8 paged-KV context attention through the trtllm-gen runner.""" + +import math +from types import SimpleNamespace + +import pytest +import torch +from utils.util import skip_pre_blackwell + +import tensorrt_llm # noqa: F401 (loads the trtllm ops) + +pytestmark = skip_pre_blackwell + +_TOKENS_PER_PAGE = 64 +_HEAD_DIM = 256 +# The V descale (scale_out / bmm2_scale) of the calls, not 1 so that its application is checked. +_SCALE_OUT = 0.75 +# The FP8 kernel's error against the FP32 reference relative to the output norm (P is rounded to E4M3 for P @ V). +_MAX_REL_ERR = 6e-2 + + +def _make_case(q_lens, kv_lens, num_heads_q, num_heads_kv, seed=0): + torch.manual_seed(seed) + dev = "cuda" + batch = len(q_lens) + max_pages = max(math.ceil(n / _TOKENS_PER_PAGE) for n in kv_lens) + # Separate K and V pages per sequence, shuffled through the pool. + num_pages = 2 * batch * max_pages + pool = (torch.randn(num_pages, num_heads_kv, _TOKENS_PER_PAGE, _HEAD_DIM, device=dev) * 0.5).to( + torch.float8_e4m3fn + ) + perm = torch.randperm(num_pages, device=dev, dtype=torch.int32) + block_tables = perm.view(batch, 2, max_pages).contiguous() + q = (torch.randn(sum(q_lens), num_heads_q, _HEAD_DIM, device=dev) * 0.5).to(torch.float8_e4m3fn) + seq_lens = torch.tensor(kv_lens, dtype=torch.int32, device=dev) + cu_q = torch.zeros(batch + 1, dtype=torch.int32, device=dev) + cu_q[1:] = torch.tensor(q_lens, device=dev).cumsum(0) + cu_kv = torch.zeros(batch + 1, dtype=torch.int32, device=dev) + cu_kv[1:] = seq_lens.cumsum(0) + softmax_scale = 1.0 / math.sqrt(_HEAD_DIM) + scale_bmm1 = torch.tensor( + [softmax_scale, softmax_scale * math.log2(math.e)], dtype=torch.float32, device=dev + ) + return q, pool, block_tables, seq_lens, cu_q, cu_kv, scale_bmm1, softmax_scale + + +def _reference(q, pool, block_tables, q_lens, kv_lens, softmax_scale): + num_heads_q, num_heads_kv = q.shape[1], pool.shape[1] + out = torch.empty(q.shape[0], num_heads_q, _HEAD_DIM, dtype=torch.float32, device=q.device) + q_start = 0 + for b, (q_len, kv_len) in enumerate(zip(q_lens, kv_lens)): + pages = math.ceil(kv_len / _TOKENS_PER_PAGE) + + def gather(kind): + idx = block_tables[b, kind, :pages].long() + x = pool[idx].float() # [pages, Hkv, P, D] + return x.permute(1, 0, 2, 3).reshape(num_heads_kv, -1, _HEAD_DIM)[:, :kv_len] + + k = gather(0).repeat_interleave(num_heads_q // num_heads_kv, 0) + v = gather(1).repeat_interleave(num_heads_q // num_heads_kv, 0) + qb = q[q_start : q_start + q_len].float().transpose(0, 1) + scores = qb @ k.transpose(1, 2) * softmax_scale + pos_q = torch.arange(kv_len - q_len, kv_len, device=q.device)[:, None] + pos_k = torch.arange(kv_len, device=q.device)[None, :] + scores = scores.masked_fill(pos_k > pos_q, float("-inf")) + out[q_start : q_start + q_len] = (scores.softmax(-1) @ v).transpose(0, 1) + q_start += q_len + return out + + +# The K / V stage is always fixed: SM100 / SM103 run the precompiled stage-256 kernels of cubin/kernelMetaInfoStageKv.h, +# every other stage (and arch) is generated with NVRTC (allow_nvrtc). The V descale (scale_out) is not 1. +@pytest.mark.parametrize("head_dim_per_stage_kv", [128, 256]) +@pytest.mark.parametrize( + "q_lens,kv_lens", [([300, 77], [428, 77]), ([1], [130]), ([1024, 64, 513], [1024, 4160, 600])] +) +def test_fmha_paged_context_fp8(head_dim_per_stage_kv, q_lens, kv_lens): + num_heads_q, num_heads_kv = 16, 1 + q, pool, block_tables, seq_lens, cu_q, cu_kv, scale_bmm1, softmax_scale = _make_case( + q_lens, kv_lens, num_heads_q, num_heads_kv + ) + out = torch.empty(q.shape[0], num_heads_q * _HEAD_DIM, dtype=torch.bfloat16, device="cuda") + assert torch.ops.trtllm.fmha_paged_context_fp8( + q, + pool, + block_tables, + seq_lens, + cu_q, + cu_kv, + out, + scale_bmm1, + torch.full((1,), _SCALE_OUT, dtype=torch.float32, device="cuda"), + max(q_lens), + max(kv_lens), + head_dim_per_stage_kv, + True, + ) + ref = _reference(q, pool, block_tables, q_lens, kv_lens, softmax_scale) * _SCALE_OUT + got = out.view(-1, num_heads_q, _HEAD_DIM).float() + torch.testing.assert_close(got, ref, atol=3e-2, rtol=5e-2) + # Relative to the output's norm, which a zero output does not meet at long KV (where atol alone would pass it). + rel = ((got - ref).norm() / ref.norm()).item() + assert rel < _MAX_REL_ERR, rel + + +# Every shape of the FP32-reference test, and one with a 5000-token KV. +@pytest.mark.parametrize( + "q_lens,kv_lens", + [ + ([700, 129, 64], [2048, 129, 5000]), + ([300, 77], [428, 77]), + ([1], [130]), + ([1024, 64, 513], [1024, 4160, 600]), + ], +) +def test_fmha_paged_context_fp8_matches_flashinfer(q_lens, kv_lens): + """The K / V stage size does not change the output bits, and the output matches FlashInfer's prebuilt + trtllm-gen context kernel up to one BF16 ulp in a few elements (the JIT and prebuilt kernels differ there).""" + flashinfer = pytest.importorskip("flashinfer") + num_heads_q, num_heads_kv = 16, 1 + q, pool, block_tables, seq_lens, cu_q, cu_kv, scale_bmm1, softmax_scale = _make_case( + q_lens, kv_lens, num_heads_q, num_heads_kv, seed=1 + ) + + def run_op(head_dim_per_stage_kv): + out = torch.empty(q.shape[0], num_heads_q * _HEAD_DIM, dtype=torch.bfloat16, device="cuda") + assert torch.ops.trtllm.fmha_paged_context_fp8( + q, + pool, + block_tables, + seq_lens, + cu_q, + cu_kv, + out, + scale_bmm1, + torch.full((1,), _SCALE_OUT, dtype=torch.float32, device="cuda"), + max(q_lens), + max(kv_lens), + head_dim_per_stage_kv, + True, + ) + return out + + # On SM100 / SM103, stage 256 is the precompiled E4 kernel and stage 128 the NVRTC one. + out = run_op(_HEAD_DIM) + assert torch.equal(out.view(torch.int16), run_op(_HEAD_DIM // 2).view(torch.int16)) + expected = torch.empty(q.shape[0], num_heads_q, _HEAD_DIM, dtype=torch.bfloat16, device="cuda") + workspace = torch.zeros(128 << 20, dtype=torch.uint8, device="cuda") + flashinfer.prefill.trtllm_batch_context_with_kv_cache( + query=q, + kv_cache=(pool, pool), + workspace_buffer=workspace, + block_tables=block_tables, + seq_lens=seq_lens, + max_q_len=max(q_lens), + max_kv_len=max(kv_lens), + bmm1_scale=scale_bmm1[:1], + bmm2_scale=_SCALE_OUT, + batch_size=len(q_lens), + cum_seq_lens_q=cu_q, + cum_seq_lens_kv=cu_kv, + window_left=-1, + out=expected, + kv_layout="HND", + uses_shared_paged_kv_idx=False, + causal=True, + ) + expected = expected.view(-1, num_heads_q * _HEAD_DIM) + torch.testing.assert_close(out, expected, atol=0.0, rtol=2.0**-7) + assert (out != expected).sum().item() <= out.numel() * 1e-5 + + +@pytest.mark.parametrize("head_dim_per_stage_kv", [128, 256]) +def test_fmha_paged_context_fp8_last_rows_match_full_call(head_dim_per_stage_kv): + """The op's last-row call (one query row per request against its full KV) gives each request's last output row + bit for bit as the full context call does.""" + q_lens, kv_lens = [700, 1, 129, 2048], [5000, 130, 129, 2048] + num_heads_q, num_heads_kv = 16, 1 + q, pool, block_tables, seq_lens, cu_q, cu_kv, scale_bmm1, _ = _make_case( + q_lens, kv_lens, num_heads_q, num_heads_kv, seed=2 + ) + + def run(query, cu, max_q): + out = torch.empty( + query.shape[0], num_heads_q * _HEAD_DIM, dtype=torch.bfloat16, device="cuda" + ) + assert torch.ops.trtllm.fmha_paged_context_fp8( + query, + pool, + block_tables, + seq_lens, + cu, + cu_kv, + out, + scale_bmm1, + torch.ones(1, dtype=torch.float32, device="cuda"), + max_q, + max(kv_lens), + head_dim_per_stage_kv, + True, + ) + return out + + last = (cu_q[1:] - 1).long() + batch = len(q_lens) + full = run(q, cu_q, max(q_lens)) + last_rows = run( + q.index_select(0, last), torch.arange(batch + 1, dtype=torch.int32, device="cuda"), 1 + ) + assert torch.equal(last_rows.view(torch.int16), full[last].view(torch.int16)) + + +class _ContextAttn: + """The layer fields FlashInferTrtllmGenFmha.run_context reads (FP8 KV cache, causal, no RoPE).""" + + def __init__(self, num_heads, head_dim_per_stage_kv, last_rows_only): + from tensorrt_llm.quantization.mode import QuantMode + + self.num_heads, self.num_kv_heads, self.head_dim = num_heads, 1, _HEAD_DIM + self.context_fmha_head_dim_per_stage_kv = head_dim_per_stage_kv + self.context_last_rows_only = last_rows_only + self.quant_mode = int(QuantMode.from_description(use_fp8_kv_cache=True)) + self.q_scaling = 1.0 + self.attention_chunk_size = None + self.rope_params = SimpleNamespace( + dim=0, theta=10000.0, scale_type=0, scale=1.0, max_positions=0 + ) + self.rotary_inv_freq = self.rotary_cos_sin = None + self.local_layer_idx = 0 + self.position_embedding_type = 0 + self.is_mla_enable = False + + def out_head_size(self, is_gen_only): + return self.head_dim + + +@pytest.mark.skipif( + torch.cuda.get_device_capability() not in ((10, 0), (10, 3)), + reason="stage-256 cubins exist for SM100 / SM103", +) +@pytest.mark.parametrize("head_dim_per_stage_kv", [0, _HEAD_DIM], ids=["flashinfer", "paged_fp8"]) +@pytest.mark.parametrize("num_generations", [0, 2], ids=["context_only", "mixed"]) +def test_run_context_last_rows_only(monkeypatch, head_dim_per_stage_kv, num_generations): + """FlashInferTrtllmGenFmha.run_context with context_last_rows_only, on FlashInfer's kernel and on + trtllm::fmha_paged_context_fp8: in a context-only batch each request's last row equals the full call's and the + other rows are zero; in a batch with generation requests the context phase is the full call.""" + pytest.importorskip("flashinfer") + from tensorrt_llm._torch.attention.backends.fmha import flashinfer_trtllm_gen as F + from tensorrt_llm._torch.attention.backends.interface import AttentionInputType + from tensorrt_llm.functional import AttentionMaskType + + q_lens, kv_lens = [700, 1, 129, 64], [2048, 130, 129, 5000] + num_heads_q, num_heads_kv = 16, 1 + q, pool, block_tables, seq_lens, cu_q, cu_kv, scale_bmm1, _ = _make_case( + q_lens, kv_lens, num_heads_q, num_heads_kv, seed=3 + ) + workspace = torch.zeros(128 << 20, dtype=torch.uint8, device="cuda") + preprocessed = ( + q, + pool, + block_tables, + None, + scale_bmm1, + torch.ones(1, dtype=torch.float32, device="cuda"), + workspace, + cu_q, + cu_kv, + max(q_lens), + max(kv_lens), + -1, + ) + # The preprocess (K / V append, Q quant) is given; the test drives the FMHA calls around it. + monkeypatch.setattr( + F, + "thop", + SimpleNamespace( + trtllm_gen_context_preprocess=lambda *args: preprocessed, + trtllm_gen_context_postprocess=lambda *args: None, + ), + ) + + def run(last_rows_only): + attn = _ContextAttn(num_heads_q, head_dim_per_stage_kv, last_rows_only) + fmha = F.FlashInferTrtllmGenFmha(attn) + fmha._multi_processor_count = torch.cuda.get_device_properties(0).multi_processor_count + fmha._multi_ctas_kv_counter_buffer = torch.zeros(1 << 20, dtype=torch.uint8, device="cuda") + out = torch.full( + (q.shape[0], num_heads_q, _HEAD_DIM), 7.0, dtype=torch.bfloat16, device="cuda" + ) + input_type = ( + AttentionInputType.mixed if num_generations else AttentionInputType.context_only + ) + params = SimpleNamespace( + qkv_input=q, + query_input=None, + attn=attn, + meta=SimpleNamespace( + num_generations=num_generations, + kv_cache_block_offsets=None, + host_kv_cache_pool_pointers=None, + host_kv_cache_pool_mapping=None, + use_paged_context_fmha=True, + ), + fwd=SimpleNamespace( + output=out, + attention_input_type=input_type, + kv_scale_orig_quant=None, + kv_scale_quant_orig=None, + out_scale=None, + mrope_rotary_cos_sin=None, + mask_type=int(AttentionMaskType.causal), + attention_sinks=None, + cross_kv=None, + ), + workspace=workspace, + sequence_lengths=seq_lens, + context_lengths=None, + tokens_per_block=_TOKENS_PER_PAGE, + max_attention_window_size=max(kv_lens), + cyclic_attention_window_size=max(kv_lens), + num_tokens=q.shape[0], + batch_size=len(q_lens), + input_seq_length=max(q_lens), + max_past_kv_length=max(kv_lens), + total_num_blocks=pool.shape[0], + kv_factor=2, + is_cross=False, + output=out, + ) + with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CUDA]) as prof: + fmha.run_context(params) + torch.cuda.synchronize() + names = {e.key for e in prof.key_averages()} + paged = any(n.endswith("ContextStageKv256E4") for n in names) + assert paged == bool(head_dim_per_stage_kv), names + return out + + full = run(False) + got = run(True) + if num_generations: + assert torch.equal(got.view(torch.int16), full.view(torch.int16)) + return + last = (cu_q[1:] - 1).long() + assert torch.equal(got[last].view(torch.int16), full[last].view(torch.int16)) + others = torch.ones(q.shape[0], dtype=torch.bool, device="cuda") + others[last] = False + assert not got[others].any() + + +@pytest.mark.skipif( + torch.cuda.get_device_capability() not in ((10, 0), (10, 3)), + reason="stage-256 cubins exist for SM100 / SM103", +) +def test_fmha_paged_context_fp8_stage256_runs_precompiled_kernel(): + """A stage-256 call runs the precompiled E4 kernel instead of generating one.""" + q_lens, kv_lens = [300, 77], [428, 77] + num_heads_q, num_heads_kv = 16, 1 + q, pool, block_tables, seq_lens, cu_q, cu_kv, scale_bmm1, _ = _make_case( + q_lens, kv_lens, num_heads_q, num_heads_kv + ) + out = torch.empty(q.shape[0], num_heads_q * _HEAD_DIM, dtype=torch.bfloat16, device="cuda") + with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CUDA]) as prof: + assert torch.ops.trtllm.fmha_paged_context_fp8( + q, + pool, + block_tables, + seq_lens, + cu_q, + cu_kv, + out, + scale_bmm1, + torch.ones(1, dtype=torch.float32, device="cuda"), + max(q_lens), + max(kv_lens), + _HEAD_DIM, + ) + torch.cuda.synchronize() + names = {e.key for e in prof.key_averages()} + assert any(n.endswith("ContextStageKv256E4") for n in names), names + + +@pytest.mark.skipif( + torch.cuda.get_device_capability() not in ((10, 0), (10, 3)), + reason="stage-256 cubins exist for SM100 / SM103", +) +@pytest.mark.parametrize( + "tokens_per_page,head_dim_per_stage_kv,ran", + [(_TOKENS_PER_PAGE, _HEAD_DIM, True), (32, _HEAD_DIM, False), (_TOKENS_PER_PAGE, 128, False)], +) +def test_fmha_paged_context_fp8_declines_without_a_precompiled_kernel( + tokens_per_page, head_dim_per_stage_kv, ran +): + """Without allow_nvrtc the op runs only a precompiled kernel: for a call whose selected kernel has none (another + page size or stage) it returns False and writes nothing, and FlashInferTrtllmGenFmha then runs FlashInfer's.""" + q_lens, kv_lens = [300, 77], [428, 77] + num_heads_q, num_heads_kv = 16, 1 + q, pool, block_tables, seq_lens, cu_q, cu_kv, scale_bmm1, _ = _make_case( + q_lens, kv_lens, num_heads_q, num_heads_kv + ) + # The same KV bytes in pages of tokens_per_page tokens. + pages_per_page = _TOKENS_PER_PAGE // tokens_per_page + pool = pool.view(pool.shape[0], num_heads_kv, pages_per_page, tokens_per_page, _HEAD_DIM) + pool = pool.permute(0, 2, 1, 3, 4).reshape(-1, num_heads_kv, tokens_per_page, _HEAD_DIM) + block_tables = ( + block_tables[..., None] * pages_per_page + + torch.arange(pages_per_page, dtype=torch.int32, device="cuda") + ).flatten(2) + out = torch.full( + (q.shape[0], num_heads_q * _HEAD_DIM), 7.0, dtype=torch.bfloat16, device="cuda" + ) + assert ( + torch.ops.trtllm.fmha_paged_context_fp8( + q, + pool.contiguous(), + block_tables.contiguous(), + seq_lens, + cu_q, + cu_kv, + out, + scale_bmm1, + torch.ones(1, dtype=torch.float32, device="cuda"), + max(q_lens), + max(kv_lens), + head_dim_per_stage_kv, + ) + is ran + ) + torch.cuda.synchronize() + assert bool((out == 7.0).all()) is not ran + + +def test_fmha_paged_context_fp8_needs_a_fixed_stage(): + q, pool, block_tables, seq_lens, cu_q, cu_kv, scale_bmm1, _ = _make_case([1], [130], 16, 1) + out = torch.empty(1, 16 * _HEAD_DIM, dtype=torch.bfloat16, device="cuda") + with pytest.raises(RuntimeError, match="head_dim_per_stage_kv must be > 0"): + torch.ops.trtllm.fmha_paged_context_fp8( + q, + pool, + block_tables, + seq_lens, + cu_q, + cu_kv, + out, + scale_bmm1, + torch.ones(1, dtype=torch.float32, device="cuda"), + 1, + 130, + 0, + ) + + +def _stage_kv_generator(): + """scripts/trtllm_gen_fmha_stage_kv/gen_stage_kv_cubins.py as a module (stdlib imports only at module level).""" + import importlib.util + from pathlib import Path + + path = ( + Path(__file__).resolve().parents[4] + / "scripts/trtllm_gen_fmha_stage_kv/gen_stage_kv_cubins.py" + ) + if not path.is_file(): + pytest.skip("needs the repository sources") + spec = importlib.util.spec_from_file_location("gen_stage_kv_cubins", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_stage_kv_cubins_match_the_kernel_inputs_they_were_built_against(): + """The stage-KV cubins are compiled against the trtllm-gen kernel headers and launched with parameters the + runner sets up from KernelParams / KernelTraits / FmhaOptions: a change to any of them needs a regeneration + (scripts/trtllm_gen_fmha_stage_kv/gen_stage_kv_cubins.py), which records their hash in every header block.""" + import re + + gen = _stage_kv_generator() + names = {p.relative_to(gen.EXPORT_DIR).as_posix() for p in gen.kernel_input_files()} + assert {"KernelParams.h", "KernelParamsDecl.h", "KernelTraits.h", "FmhaOptions.h"} <= names + assert any(name.startswith("trtllm/dev/") for name in names) + recorded = re.findall(r"// Kernel inputs sha256: ([0-9a-f]{64})", gen.META_HEADER.read_text()) + assert recorded and set(recorded) == {gen.kernel_inputs_sha256()} + + +@pytest.mark.parametrize("touched", ["KernelTraits.h", "FmhaOptions.h", "trtllm/dev/Utils.h"]) +def test_stage_kv_kernel_inputs_hash_covers_the_parameter_setup(tmp_path, touched): + """Editing KernelTraits.h, FmhaOptions.h or a device header changes the recorded hash (not only KernelParams).""" + import shutil + + gen = _stage_kv_generator() + export = tmp_path / "export" + for path in gen.kernel_input_files(): + dst = export / path.relative_to(gen.EXPORT_DIR) + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, dst) + before = gen.kernel_inputs_sha256(export) + assert before == gen.kernel_inputs_sha256() + with open(export / touched, "a") as f: + f.write("\n") + assert gen.kernel_inputs_sha256(export) != before + + +def test_stage_kv_regeneration_keeps_other_page_sizes_and_drops_stale_archives( + tmp_path, monkeypatch +): + """A regeneration for one page size replaces only that configuration's header blocks of its SM, and deletes + the SM's archives no entry references any more (CMake links every archive in cubin/).""" + gen = _stage_kv_generator() + cubin = tmp_path / "cubin" + cubin.mkdir() + monkeypatch.setattr(gen, "CUBIN_DIR", cubin) + monkeypatch.setattr(gen, "META_HEADER", cubin / "kernelMetaInfoStageKv.h") + monkeypatch.setattr(gen, "kernel_inputs_sha256", lambda: "0" * 64) + + def kernel(sm, page, sched): + stem = ( + f"FmhaSm{sm}aKernel_QkvE4m3OBfloat16H256PagedKvCausalP{page}{sched}ContextStageKv256E4" + ) + (cubin / f"{stem}.cubin.tar.zst").write_bytes(b"x") + decl = f"extern unsigned char const {stem}_cubin[];\nextern unsigned int const {stem}_cubin_len;\n" + return stem, decl, f"{{ 256, {{ /* {stem} */ }} }},\n" + + p64 = gen.config_key(256, 64, 256) + p32 = gen.config_key(256, 32, 256) + persistent64, d1, e1 = kernel(103, 64, "Persistent") + static64, d2, e2 = kernel(103, 64, "Static") + gen.write_header(103, p64, d1 + d2, e1 + e2) + other_sm, d3, e3 = kernel(100, 64, "Static") + gen.write_header(100, p64, d3, e3) + static32, d4, e4 = kernel(103, 32, "Static") + keep = gen.write_header(103, p32, d4, e4) + assert keep == {persistent64, static64, static32} + assert gen.remove_stale_archives(103, keep) == [] + text = gen.META_HEADER.read_text() + for stem in (persistent64, static64, static32, other_sm): + assert f"{stem}_cubin[]" in text and f"/* {stem} */" in text + + # Regenerate page size 64 on SM103: only the persistent kernel is selected now. + keep = gen.write_header(103, p64, d1, e1) + assert keep == {persistent64, static32} + assert gen.remove_stale_archives(103, keep) == [cubin / f"{static64}.cubin.tar.zst"] + text = gen.META_HEADER.read_text() + assert static64 not in text and static32 in text and other_sm in text + assert sorted(p.name for p in cubin.glob("*.tar.zst")) == sorted( + f"{s}.cubin.tar.zst" for s in (persistent64, static32, other_sm) + ) + + +def test_fmha_paged_context_fp8_rejects_a_pool_without_kv_heads(): + """The Q / KV head ratio check runs after the KV-head count check (no integer division by zero).""" + q, pool, block_tables, seq_lens, cu_q, cu_kv, scale_bmm1, _ = _make_case([1], [130], 16, 1) + empty_pool = torch.empty( + (pool.shape[0], 0, pool.shape[2], pool.shape[3]), dtype=pool.dtype, device="cuda" + ) + out = torch.empty(1, 16 * _HEAD_DIM, dtype=torch.bfloat16, device="cuda") + with pytest.raises(RuntimeError, match="kv_pool must have KV heads"): + torch.ops.trtllm.fmha_paged_context_fp8( + q, + empty_pool, + block_tables, + seq_lens, + cu_q, + cu_kv, + out, + scale_bmm1, + torch.ones(1, dtype=torch.float32, device="cuda"), + 1, + 130, + _HEAD_DIM, + ) + + +def test_fmha_paged_context_fp8_fake_declines(): + """Traced, the op answers False (whether a cubin exists is known only at run time): a trace keeps the FlashInfer + kernel the caller runs on False, which is always valid.""" + from torch._subclasses.fake_tensor import FakeTensorMode + + with FakeTensorMode(): + q = torch.empty((8, 4, 256), dtype=torch.float8_e4m3fn, device="cuda") + kv_pool = torch.empty((4, 2, 1, 32, 256), dtype=torch.float8_e4m3fn, device="cuda") + block_tables = torch.zeros((1, 4), dtype=torch.int32, device="cuda") + seq_lens = torch.full((1,), 8, dtype=torch.int32, device="cuda") + cu = torch.tensor([0, 8], dtype=torch.int32, device="cuda") + out = torch.empty((8, 4, 256), dtype=torch.bfloat16, device="cuda") + scale = torch.ones(1, dtype=torch.float32, device="cuda") + took = torch.ops.trtllm.fmha_paged_context_fp8( + q, kv_pool, block_tables, seq_lens, cu, cu, out, scale, scale, 8, 8, 256 + ) + assert took is False diff --git a/tests/unittest/_torch/attention/test_gqa_decode_fmha.py b/tests/unittest/_torch/attention/test_gqa_decode_fmha.py index 62ad15ffcfea..9ef6253b6ebe 100644 --- a/tests/unittest/_torch/attention/test_gqa_decode_fmha.py +++ b/tests/unittest/_torch/attention/test_gqa_decode_fmha.py @@ -13,7 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. +import copy import functools +import weakref from types import SimpleNamespace from typing import Optional @@ -29,13 +31,19 @@ from tensorrt_llm._torch.attention.backends.fmha.flashinfer_trtllm_gen import ( FlashInferTrtllmGenFmha, _get_generation_workspace_layout, + trtllm_gen_paged_decode, + trtllm_gen_paged_decode_supported, ) from tensorrt_llm._torch.attention.backends.fmha.gqa_decode import ( + FoldInputs, GqaDecodeFmha, GqaDecodeSetup, GqaKvReplicaFmha, + GqaKvReplicaFusedFmha, GqaSegmentedFmha, GqaSplitKvFmha, + KvAppendPlan, + min_kv_split_scratch_bytes, ) from tensorrt_llm._torch.attention.backends.fmha.gqa_kv_replica import kv_replica_partial_merge_free from tensorrt_llm._torch.attention.backends.fmha.phased import FmhaParams @@ -130,6 +138,51 @@ def spy(self, *args, _run=cls._run_dedicated, _name=cls.__name__, **kwargs): assert taken and all(t == (library, True) for t in taken) +def test_generation_call_loads_trtllm_gen_decode_module(monkeypatch: pytest.MonkeyPatch) -> None: + """A generation call served by a dedicated kernel (the warmup's) loads FlashInfer's trtllm-gen decode module, so + the first segmented or trtllm-gen decode does not JIT-build it.""" + import flashinfer + + loads = [] + load = flashinfer.decode.get_trtllm_gen_fmha_module + + def spy(): + loads.append(True) + return load() + + monkeypatch.setattr(flashinfer.decode, "get_trtllm_gen_fmha_module", spy) + monkeypatch.setattr( + backend_case, + "create_attention", + functools.partial(backend_case.create_attention, gqa_decode=GqaDecodeSetup()), + ) + monkeypatch.setattr(backend_case, "BACKENDS_UNDER_TEST", ("TRTLLM",)) + taken = [] + run_split_kv = GqaSplitKvFmha._run_dedicated + + def spy_split_kv(self, *args, **kwargs): + taken.append(run_split_kv(self, *args, **kwargs)) + return taken[-1] + + monkeypatch.setattr(GqaSplitKvFmha, "_run_dedicated", spy_split_kv) + run_case( + BackendCase( + num_heads=4, + num_kv_heads=1, + head_dim=HEAD_DIM, + seq_lens=[1], + num_cached_tokens=[300], + num_contexts=0, + dtype="bfloat16", + kv_dtype="fp8", + page_size=PAGE, + kv_layout="HND", + ) + ) + assert taken and all(taken) + assert loads + + def _qwen3_next_attention(use_gqa_decode_fmha: bool) -> Qwen3Attention: config = transformers.Qwen3NextConfig( hidden_size=HIDDEN, @@ -351,6 +404,80 @@ def _assert_partial_matches(o: torch.Tensor, ref_o: torch.Tensor) -> None: ids=["balanced", "wide", "two_slot", "two_slot_uniform"], ) def test_kv_replica_fused_partial_matches_reference(q_len: int, lens: list) -> None: + _check_kv_replica_fused_partial(q_len, lens) + + +@pytest.mark.parametrize("q_len", [7, 1]) +def test_kv_replica_fused_two_slot_plan_up_to_64_requests(q_len: int) -> None: + """At most 64 requests take the two-slot plan where a whole-CTA plan would leave CTAs idle; its partials match + the reference as the plan of larger batches does.""" + sms = torch.cuda.get_device_properties(0).multi_processor_count + n_ctas = F._num_ctas(sms) + batches = [b for b in range(F._LANE_PLAN_MAX_BATCH + 1, 65) if F._plan(b, n_ctas) == "two"] + if not batches: + pytest.skip(f"no batch of at most 64 requests takes the two-slot plan on {sms} SMs") + b = batches[-1] + _check_kv_replica_fused_partial(q_len, [1 + (i * 7919) % 50000 for i in range(b - 1)] + [90000]) + + +@pytest.mark.parametrize("q_len", [7, 1]) +@pytest.mark.parametrize( + "lens", + [ + [7, 9000, 33000, 64, 130, 21000, 1, 4000], + [1 + (i * 7919) % 50000 for i in range(40)] + [120000], + [1 + (i * 7919) % 50000 for i in range(100)] + [120000], + ], + ids=["lane", "wide", "two_slot"], +) +def test_kv_replica_fused_partial_softmax_v2_is_bitwise(q_len: int, lens: list) -> None: + """softmax_v2 (row maxima by tcgen05.ld.red.max) and the default softmax write the same bits, on every plan.""" + device = torch.device("cuda", 0) + if not F.ld_red_max_supported(device): + pytest.skip("softmax_v2 needs tcgen05.ld.red.max") + lens = [max(L, q_len) for L in lens] + b = len(lens) + sms = torch.cuda.get_device_properties(0).multi_processor_count + if not F.kv_replica_fused_supported(q_len, CP, HEADS, b, sms): + pytest.skip("shape outside the fused KV-replica split partial kernel's limits") + state = F.kv_replica_fused_state(device, sms, b) + assert state.softmax_v2 + v1 = copy.copy(state) + v1.softmax_v2 = False + g = torch.Generator(device="cuda").manual_seed(b * 10 + q_len + 1) + max_pages = max((max(lens) + PAGE - 1) // PAGE, CP) + nblocks = b * 2 * max_pages + 8 + kv = (torch.randn(nblocks, 1, PAGE, HEAD_DIM, device="cuda", generator=g) * 0.6).to( + torch.float8_e4m3fn + ) + tables = torch.randperm(nblocks, device="cuda", generator=g)[: b * 2 * max_pages] + tables = tables.to(torch.int32).view(b, 2, max_pages).contiguous() + seq = torch.tensor(lens, dtype=torch.int32, device="cuda") + q_all = ( + torch.randn(b * q_len, CP, HEADS, HEAD_DIM, device="cuda", generator=g) + .to(torch.float8_e4m3fn) + .permute(1, 0, 2, 3) + ) + for rank in range(CP): + outs = [] + for st in (state, v1): + o = torch.full( + (CP, b * q_len, HEADS, HEAD_DIM), float("nan"), dtype=torch.bfloat16, device="cuda" + ) + lse = torch.full( + (CP, b * q_len, HEADS), float("nan"), dtype=torch.float32, device="cuda" + ) + F.kv_replica_fused_partial( + q_all, kv, tables, seq, q_len, rank, CP, 1.0 / 16, 1.0, o, lse, st + ) + outs.append((o, lse)) + torch.cuda.synchronize() + (o2, lse2), (o1, lse1) = outs + assert torch.equal(o2.view(torch.int16), o1.view(torch.int16)), rank + assert torch.equal(lse2.view(torch.int32), lse1.view(torch.int32)), rank + + +def _check_kv_replica_fused_partial(q_len: int, lens: list) -> None: hq, d = HEADS, HEAD_DIM lens = [max(L, q_len) for L in lens] b = len(lens) @@ -597,6 +724,7 @@ def _generation_call( max_context_length=1, num_ctx_tokens=0, num_contexts=0, + num_generations=num_requests, is_cuda_graph=False, ) workspace = torch.empty(0, dtype=torch.int8, device=dev) @@ -733,3 +861,368 @@ def test_disabled_segment_libraries_do_not_extend_workspace( ) library.prepare_workspace(call.qkv, None, None, call.metadata, call.fwd, call.workspace) assert call.workspace.numel() == reference.numel() + + +@pytest.mark.parametrize( + "num_heads,num_kv_heads,tokens_per_gen_step,splits", + [ + (32, 2, 7, 8), # Qwen3.5-397B under attention DP, MTP draft length 6 + (32, 2, 9, 0), # 144 rows: more than one Q tile + (8, 2, 1, 0), # 8 splits x 2 KV heads exceed the counters of 8 heads + ], +) +def test_min_kv_splits_need_one_q_tile_and_the_counters( + num_heads: int, num_kv_heads: int, tokens_per_gen_step: int, splits: int +) -> None: + assert GqaDecodeFmha._min_kv_splits_for(num_heads, num_kv_heads, tokens_per_gen_step) == splits + + +def test_min_kv_split_stops_above_the_largest_graph_batch() -> None: + """Batches above the largest CUDA-graph decode batch keep FlashInfer's split, so the forced split's scratch is + bounded by that batch.""" + q_len, kv_heads, sms = 7, 2, 148 + fmha = SimpleNamespace( + _min_kv_splits=8, + _multi_processor_count=sms, + _min_kv_split_batch=16, + attn=SimpleNamespace(num_kv_heads=kv_heads), + ) + batch = fmha._min_kv_split_batch + 1 + assert 8 * kv_heads * batch > sms + q = torch.empty(batch * q_len, 32, HEAD_DIM, dtype=torch.float8_e4m3fn) + kv_pool = torch.empty(1, kv_heads, PAGE, HEAD_DIM, dtype=torch.float8_e4m3fn) + assert not GqaDecodeFmha._run_min_kv_split( + fmha, None, q, kv_pool, None, 0, -1, q_len, None, None, 1.0, 1.0 + ) + + +def test_min_kv_split_batch_is_the_largest_captured_graph_batch() -> None: + """ModelConfig.cuda_graph_batch_sizes (whose largest size bounds the forced split's scratch) holds the decode graph + sizes the engine captures: none above max_batch_size or max_num_tokens // tokens per request (plan_cuda_graphs).""" + from tensorrt_llm._torch.pyexecutor.engine.cuda_graph import plan_cuda_graphs + from tensorrt_llm._torch.pyexecutor.model_loader import captured_cuda_graph_batch_sizes + from tensorrt_llm.llmapi.llm_args import CudaGraphConfig + + spec = SimpleNamespace(tokens_per_gen_step=7) + for graphs, max_batch_size, max_num_tokens, largest in ( + (CudaGraphConfig(), 32, 8192, 32), # default sizes up to 128 + (CudaGraphConfig(max_batch_size=512), 64, 8192, 64), + (CudaGraphConfig(max_batch_size=64), 128, 336, 32), # 336 tokens: 48 requests of 7 + (CudaGraphConfig(batch_sizes=[1, 2, 40], enable_padding=True), 32, 8192, 32), + ): + args = SimpleNamespace(cuda_graph_config=graphs, max_batch_size=max_batch_size) + sizes = captured_cuda_graph_batch_sizes(args, max_num_tokens, spec) + plan = plan_cuda_graphs( + graphs, + None, + max_batch_size=max_batch_size, + max_num_tokens=max_num_tokens, + max_seq_len=4096, + decode_tokens_per_request=7, + ) + assert list(sizes) == plan.batch_sizes and max(sizes) == largest, (graphs, sizes) + assert max(graphs.batch_sizes) > largest + no_graphs = SimpleNamespace(cuda_graph_config=None, max_batch_size=32) + assert captured_cuda_graph_batch_sizes(no_graphs, 8192, spec) == () + + +def test_min_kv_split_decode_is_flashinfer_decode_at_that_sm_count( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The forced-split decode (trtllm_gen_paged_decode with splits x KV heads x batch SMs) writes exactly what + FlashInfer's public decode writes on a device of that many SMs: same kernel, same split.""" + import flashinfer + + hq, hkv, q_len, b, splits = 32, 2, 7, 52, 8 + g = torch.Generator(device="cuda").manual_seed(0) + lens = torch.randint(6000, 9000, (b,), device="cuda", generator=g).to(torch.int32) + pages = (int(lens.max()) + PAGE - 1) // PAGE + nblocks = b * 2 * pages + kv = (torch.randn(nblocks, hkv, PAGE, HEAD_DIM, device="cuda", generator=g) * 0.6).to( + torch.float8_e4m3fn + ) + tables = torch.randperm(nblocks, device="cuda", generator=g).to(torch.int32).view(b, 2, pages) + q = torch.randn(b * q_len, hq, HEAD_DIM, device="cuda", generator=g).to(torch.float8_e4m3fn) + sm_count = splits * hkv * b + assert sm_count > torch.cuda.get_device_properties(0).multi_processor_count + assert trtllm_gen_paged_decode_supported() + # The library's scratch size, checked by the kernel's writes rather than by restating its formula: the scratch + # is the front of a buffer whose tail is a canary that must come back untouched. + nbytes = min_kv_split_scratch_bytes(sm_count, HEAD_DIM) + guarded = torch.full((nbytes + (4 << 20),), 0xA5, dtype=torch.uint8, device="cuda") + workspace = guarded[:nbytes] + counter = torch.zeros(max(b * hq, sm_count) * 4, dtype=torch.uint8, device="cuda") + max_kv_len = int(lens.max()) + + out = torch.empty(b * q_len, hq, HEAD_DIM, dtype=torch.bfloat16, device="cuda") + trtllm_gen_paged_decode( + out, q, kv, workspace, counter, tables, lens, q_len, max_kv_len, 1.0 / 16, 1.0, b, -1, + sm_count, False, + ) # fmt: skip + + def public(sms: int) -> torch.Tensor: + monkeypatch.setattr(flashinfer.decode, "get_device_sm_count", lambda *_: sms) + ref = torch.empty_like(out) + flashinfer.decode.trtllm_batch_decode_with_kv_cache( + query=q, + kv_cache=(kv, kv), + workspace_buffer=workspace, + block_tables=tables, + seq_lens=lens, + max_seq_len=max_kv_len, + bmm1_scale=1.0 / 16, + bmm2_scale=1.0, + out=ref, + kv_layout="HND", + enable_pdl=False, + backend="trtllm-gen", + q_len_per_req=q_len, + uses_shared_paged_kv_idx=False, + multi_ctas_kv_counter_buffer=counter, + ) + return ref + + torch.cuda.synchronize() + assert bool((guarded[nbytes:] == 0xA5).all()), "the forced-split decode wrote past its scratch" + assert bool((workspace != 0xA5).any()), "the forced split must keep its partials in the scratch" + assert torch.equal(out, public(sm_count)) + # The device's own SM count splits less, which only reorders the FP32 sums. + heuristic = public(torch.cuda.get_device_properties(0).multi_processor_count) + torch.testing.assert_close(out, heuristic, atol=2e-2, rtol=2e-2) + + +def test_rope_gather_grid_residency_comes_from_the_compiled_kernel( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The fused q all-gather takes a grid only while all of it stays resident: at most min(occupancy of the compiled + kernel, GATHER_MAX_PROGRAMS_PER_SM) programs per SM. At a TEP8 Qwen3.5 layer (4 q heads, 1 KV head, group of 4) + the occupancy is above the cap, so the cap decides the token bound. Every member of the group compiles the same + kernel, so every member takes the same bound.""" + from tensorrt_llm._torch.attention.kernels import fused_qk_norm_rope_gate as K + + hq, hkv, d, rot, q_len, group = 4, 1, HEAD_DIM, 64, 7, 4 + sms = torch.cuda.get_device_properties(0).multi_processor_count + occupancy = [] + kernels = [] + resident = K._resident_programs_per_sm + + def spy(kernel): + kernels.append(kernel) + occupancy.append(resident(kernel)) + return occupancy[-1] + + monkeypatch.setattr(K, "_resident_programs_per_sm", spy) + + def resident_tokens(num_tokens: int, grank: int = 0) -> int: + b = num_tokens // q_len + dev = "cuda" + plan = KvAppendPlan( + 0, + num_tokens, + b, + q_len, + torch.zeros(8, hkv, PAGE, d, dtype=torch.float8_e4m3fn, device=dev), + torch.zeros(b, 2, 4, dtype=torch.int32, device=dev), + torch.full((b,), q_len, dtype=torch.int32, device=dev), + torch.ones(1, dtype=torch.float32, device=dev), + torch.ones(1, dtype=torch.float32, device=dev), + 1.0 / 16, + ) + return K.rope_gather_max_tokens( + torch.zeros(num_tokens, (2 * hq + 2 * hkv) * d, dtype=torch.bfloat16, device=dev), + torch.zeros(d, dtype=torch.bfloat16, device=dev), + torch.zeros(d, dtype=torch.bfloat16, device=dev), + torch.zeros(4096, 2, rot // 2, dtype=torch.float32, device=dev), + torch.zeros(num_tokens, dtype=torch.int32, device=dev), + 1e-6, + hq, + hkv, + d, + rot, + None, + plan, + ( + torch.zeros(group, dtype=torch.int64, device=dev), + torch.zeros(num_tokens * hq, dtype=torch.int32, device=dev), + grank, + group, + 1 << 16, + True, + ), + ) + + bound = K.GATHER_MAX_PROGRAMS_PER_SM * sms // (hq + 2 * hkv) + assert resident_tokens(q_len) == bound + assert resident_tokens(16 * q_len) == bound + assert occupancy and min(occupancy) >= K.GATHER_MAX_PROGRAMS_PER_SM + kernels.clear() + assert [resident_tokens(q_len, grank) for grank in range(group)] == [bound] * group + assert all(k is kernels[0] for k in kernels) + + +@pytest.mark.parametrize("folded", [False, True]) +def test_rope_gather_launches_only_with_a_resident_grid( + monkeypatch: pytest.MonkeyPatch, folded: bool +) -> None: + """GqaKvReplicaFusedFmha's prologue (the module's unfolded one, and the folded call's fallback) all-gathers q in + the RoPE kernel only for token counts within rope_gather_max_tokens, taken once per shape; otherwise, and + without the plan's gather arguments, the plain kernel runs and plan.q_gathered stays None.""" + from tensorrt_llm._torch.attention.kernels import fused_qk_norm_rope_gate as K + + bound = 21 + calls = [] + + def max_tokens(qkv, *args): + calls.append(("bound", qkv.shape[0])) + return bound + + def gather(qkv, *args): + calls.append(("gather", qkv.shape[0])) + return qkv, qkv, qkv, qkv, qkv + + def plain(qkv, *args): + calls.append(("plain", qkv.shape[0])) + return qkv, qkv, qkv, qkv + + monkeypatch.setattr(K, "rope_gather_max_tokens", max_tokens) + monkeypatch.setattr(K, "fused_qkv_rope_gate_fp8_append_gather", gather) + monkeypatch.setattr(K, "fused_qkv_rope_gate_fp8_append", plain) + + class _Attn: + num_heads, num_kv_heads, head_dim = HEADS, 1, HEAD_DIM + + attn = _Attn() + lib = GqaKvReplicaFusedFmha.__new__(GqaKvReplicaFusedFmha) + lib._attn_ref = weakref.ref(attn) + lib._rope_gather_resident = {} + x = torch.zeros(1) + + def prologue(num_tokens: int, offered: bool) -> Optional[torch.Tensor]: + qkv = torch.zeros(num_tokens, 8) + plan = KvAppendPlan(0, num_tokens, num_tokens // 7, 7, x, x, x, x, x, 1.0) + plan.rope_gather = (x, x, 0, CP, 1, True) if offered else None + f = FoldInputs(qkv, x, x, x, x, 1e-6, 64, None) + if folded: + plan.fold = f + params = SimpleNamespace(num_tokens=num_tokens, fwd=SimpleNamespace(output_gate=None)) + lib._run_fold_prologue(params, plan) + assert params.qkv_input.shape[0] == num_tokens + else: + lib.run_prologue(plan, f.qkv, x, x, x, x, 1e-6, 64, None) + return plan.q_gathered + + assert prologue(21, True) is not None + assert prologue(28, True) is None + assert prologue(21, True) is not None + assert prologue(14, False) is None + assert calls == [ + ("bound", 21), + ("gather", 21), + ("bound", 28), + ("plain", 28), + ("gather", 21), + ("plain", 14), + ] + + +@pytest.mark.parametrize("q_len, armed", [(1, True), (7, True), (8, True), (9, False), (16, False)]) +def test_rope_gather_is_armed_only_where_the_fused_library_is_selected( + monkeypatch: pytest.MonkeyPatch, q_len: int, armed: bool +) -> None: + """kv_append_plan arms the RoPE kernel's q all-gather on the selection-cache cell bound that _is_supported uses: + q_len 9..16 share the cell up to 31 > MAX_Q_LEN, which another library serves, so no gather runs there.""" + from tensorrt_llm._torch.attention.backends.fmha.manager import generation_cell_bound + + class _Attn: + num_heads, num_kv_heads, head_dim = 4, 1, F.HEAD_DIM + + attn = _Attn() + lib = GqaKvReplicaFusedFmha.__new__(GqaKvReplicaFusedFmha) + lib._attn_ref = weakref.ref(attn) + lib._kv_replicas = 2 + lib._multi_processor_count = 148 + x = torch.zeros(1) + batch = 2 + plan = KvAppendPlan(0, batch * q_len, batch, q_len, x, x, x, x, x, 1.0) + monkeypatch.setattr(GqaDecodeFmha, "kv_append_plan", lambda self, metadata, num_tokens: plan) + monkeypatch.setattr( + GqaKvReplicaFusedFmha, "_rope_gather", lambda self, attn, num_tokens: "gather" + ) + metadata = SimpleNamespace(tokens_per_block=F.PAGE) + got = lib.kv_append_plan(metadata, batch * q_len) + assert (got.rope_gather == "gather") is armed + # The library's selection (_is_supported) at this call's cell agrees. + assert lib._takes(*generation_cell_bound(batch, q_len), metadata) is armed + + +def test_trtllm_gen_paged_decode_checks_flashinfers_signature( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The direct call of FlashInfer's private positional decode op is taken only while the op has the signature it + was written for: another signature, another error, or a module that does not load decline.""" + import flashinfer + + from tensorrt_llm._torch.attention.backends.fmha import flashinfer_trtllm_gen as fi + + fi.trtllm_gen_paged_decode_supported.cache_clear() + try: + assert fi.trtllm_gen_paged_decode_supported() + + def module_with(error: Exception): + def op(*args): + raise error + + return lambda: SimpleNamespace(trtllm_paged_attention_decode=op) + + other = fi._PAGED_DECODE_SIGNATURE.replace( + "35: Optional", "35: Optional, 36: int" + ) + for loader in ( + module_with( + TypeError(f"Mismatched number of arguments when calling: `{other}`. Expected 37") + ), + module_with(TypeError("missing 36 required positional arguments")), + module_with(RuntimeError("no such kernel")), + ): + monkeypatch.setattr(flashinfer.decode, "get_trtllm_gen_fmha_module", loader) + fi.trtllm_gen_paged_decode_supported.cache_clear() + assert not fi.trtllm_gen_paged_decode_supported() + + def broken(): + raise RuntimeError("JIT build failed") + + monkeypatch.setattr(flashinfer.decode, "get_trtllm_gen_fmha_module", broken) + fi.trtllm_gen_paged_decode_supported.cache_clear() + assert not fi.trtllm_gen_paged_decode_supported() + finally: + monkeypatch.undo() + fi.trtllm_gen_paged_decode_supported.cache_clear() + + +def test_direct_decode_callers_decline_on_another_flashinfer_signature( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """With the signature check failing, the forced-split decode returns False before any launch (the stock + FlashInfer call runs) and the segmented KV-replica library takes no call.""" + monkeypatch.setattr(gqa_decode, "trtllm_gen_paged_decode_supported", lambda: False) + q_len, kv_heads, sms = 7, 2, 148 + fmha = SimpleNamespace( + _min_kv_splits=8, + _multi_processor_count=sms, + _min_kv_split_batch=16, + attn=SimpleNamespace(num_kv_heads=kv_heads), + ) + batch = 16 + assert 8 * kv_heads * batch > sms + q = torch.empty(batch * q_len, 32, HEAD_DIM, dtype=torch.float8_e4m3fn) + kv_pool = torch.empty(1, kv_heads, PAGE, HEAD_DIM, dtype=torch.float8_e4m3fn) + assert not GqaDecodeFmha._run_min_kv_split( + fmha, None, q, kv_pool, None, 0, -1, q_len, None, None, 1.0, 1.0 + ) + library = SimpleNamespace( + _kv_replicas=4, + attn=SimpleNamespace(num_heads=4), + _largest_segment_rows=GqaKvReplicaFmha._largest_segment_rows, + _counter_slots=GqaKvReplicaFmha._counter_slots, + ) + assert not GqaKvReplicaFmha._takes(library, 2, 7, SimpleNamespace(max_num_requests=512)) diff --git a/tests/unittest/_torch/attention/test_mixed_precision_backends.py b/tests/unittest/_torch/attention/test_mixed_precision_backends.py index 9607192419c7..726750866b94 100644 --- a/tests/unittest/_torch/attention/test_mixed_precision_backends.py +++ b/tests/unittest/_torch/attention/test_mixed_precision_backends.py @@ -116,6 +116,7 @@ def test_optimized_two_pool_prefill_and_decode( register_to_config=False, use_gqa_decode_fmha=False, cache_context_plan=False, + offers_gated_fp8_out=False, _output_quant_flags=None, _use_quantize_output=lambda: False, ) diff --git a/tests/unittest/_torch/disaggregation/test_disagg_idle_cancellation.py b/tests/unittest/_torch/disaggregation/test_disagg_idle_cancellation.py index 3c8b764ed7ae..b9d70e6f6950 100644 --- a/tests/unittest/_torch/disaggregation/test_disagg_idle_cancellation.py +++ b/tests/unittest/_torch/disaggregation/test_disagg_idle_cancellation.py @@ -741,6 +741,8 @@ def test_deferred_lora_generation_resumes_from_harvested_host_token(executor: Py executor.scheduler.schedule_request.side_effect = lambda requests, _: SchedulerOutput( [], [], list(requests), [], [], len(requests) ) + # As the base scheduler: no request lost its KV pages to a failed remote cache level. + executor.scheduler.take_lost_kv_requests.return_value = [] _abort(executor, held) current_batch, _, _ = executor._schedule() diff --git a/tests/unittest/_torch/disaggregation/test_disagg_loop_transcript.py b/tests/unittest/_torch/disaggregation/test_disagg_loop_transcript.py index 3db8b26e7a41..cfa6cc67951c 100644 --- a/tests/unittest/_torch/disaggregation/test_disagg_loop_transcript.py +++ b/tests/unittest/_torch/disaggregation/test_disagg_loop_transcript.py @@ -269,6 +269,76 @@ def test_executor_loop_overlap_transcript(monkeypatch) -> None: assert calls == idle_pass + _SHUTDOWN_PASS +def _deferred_close_executor(monkeypatch, calls: list) -> PyExecutor: + """Idle overlap executor with kv_cache_config.defer_generation_only_release, recording the manager's + deferred-close calls among the coordinator calls.""" + executor = _idle_executor(monkeypatch, calls) + executor.dist = Mock(tp_size=1, world_size=1) + executor._defer_generation_only_release = True + executor.kv_cache_manager = SimpleNamespace( + enable_deferred_close=lambda enabled: calls.append(("enable_deferred_close", enabled)), + flush_deferred_closes=lambda: calls.append(("flush_deferred_closes",)), + ) + return executor + + +def test_executor_loop_overlap_flushes_deferred_closes(monkeypatch) -> None: + """The overlap loop turns the deferred close on before its first iteration. An idle iteration closes what + earlier iterations left, then again once no request is active, and again after the timeout checks, so an idle + server holds no deferred pages while its next fetch may block.""" + calls = [] + PyExecutor._executor_loop_overlap(_deferred_close_executor(monkeypatch, calls)) + + idle_pass = _SCHEDULE_HEAD + [ + ("flush_deferred_closes",), + ("flush_pending_transfer_responses",), + ("flush_deferred_closes",), + ("handle_timeouts_synced",), + ("check_transfer_timeouts", "only_with_context_sends=True"), + ("flush_deferred_closes",), + ("pace_idle",), + ] + assert calls == [("enable_deferred_close", True)] + idle_pass + _SHUTDOWN_PASS + + +def test_executor_loop_overlap_flushes_deferred_closes_on_a_retried_iteration(monkeypatch) -> None: + """An iteration the benchmark gate retries skips the forward and the flushes after it, so it closes the + deferred caches before it starts over.""" + calls = [] + executor = _deferred_close_executor(monkeypatch, calls) + executor._check_benchmark_disagg_gate = Mock(return_value=(True, True)) + executor._release_unused_connector_reservations = Mock() + + PyExecutor._executor_loop_overlap(executor) + + retried_pass = _SCHEDULE_HEAD + [ + ("flush_pending_transfer_responses",), + ("flush_deferred_closes",), + ] + assert calls == [("enable_deferred_close", True)] + retried_pass + _SHUTDOWN_PASS + + +@pytest.mark.parametrize("defer", [False, True], ids=["release_now", "defer_release"]) +def test_kv_pool_rebalance_flushes_deferred_closes_before_adjust(defer: bool) -> None: + """adjust() moves pages, so a deferred close must not hold any: the rebalance closes them before it suspends + the active requests and adjusts.""" + executor = object.__new__(PyExecutor) + executor._defer_generation_only_release = defer + manager = Mock() + manager.is_request_active.return_value = True + executor.kv_cache_manager = manager + executor.active_requests = [SimpleNamespace(py_request_id=3)] + executor._suspend_padding_dummies_for_rebalance = Mock(return_value=[]) + executor._resume_padding_dummies_after_rebalance = Mock() + executor._read_kv_cache_capacity = Mock(return_value=0) + + PyExecutor._rebalance_kv_pools_now(executor) + + names = [name for name, _, _ in manager.mock_calls] + head = ["is_request_active", "suspend_request", "impl.adjust", "resume_request"] + assert names == (["flush_deferred_closes"] if defer else []) + head + + @pytest.mark.parametrize( "states", [("absent", "processed"), ("processed", "deferred"), ("deferred", "absent")], diff --git a/tests/unittest/_torch/distributed/test_mnnvl_fused_allreduce_dispatch.py b/tests/unittest/_torch/distributed/test_mnnvl_fused_allreduce_dispatch.py index 36cab1386b09..e6be3fea0d3f 100644 --- a/tests/unittest/_torch/distributed/test_mnnvl_fused_allreduce_dispatch.py +++ b/tests/unittest/_torch/distributed/test_mnnvl_fused_allreduce_dispatch.py @@ -38,16 +38,19 @@ def test_shared_memory_limit( [ (8192, 264, True), (16384, 64, True), - (16384, 67, False), - (32768, 63, True), - (32768, 64, False), - (65536, 63, True), - (65536, 64, False), + (16384, 67, True), # slot transport (up to SLOT_MAX_ROWS) + (16384, 129, True), # two CTAs of 1024 threads per token + (32768, 64, True), + (65536, 64, True), + (65536, 129, True), # eight CTAs of 1024 threads per token + (131072, 129, False), # eight CTAs of 2048 threads per token ], ) def test_thread_limit( fused_norm: MnnvlAllReduceNorm, hidden: int, rows: int, supported: bool ) -> None: + """Above SLOT_MAX_ROWS a token's CTAs shrink to fit the SMs only while each stays within 1024 threads; a hidden + size whose eight CTAs per token still exceed them is not taken.""" fused_norm.hidden = hidden assert fused_norm.supports_rows(rows) is supported @@ -74,3 +77,38 @@ def test_two_cta_residency( @pytest.mark.parametrize("rows", [0, -1]) def test_nonpositive_rows(fused_norm: MnnvlAllReduceNorm, rows: int) -> None: assert not fused_norm.supports_rows(rows) + + +# (m, hidden, sms, access group) -> (block, cluster, loads per thread) of twoshotAllreduceFusionOp's rmsNormLamport +# launch, from mnnvlAllreduceKernels.cu's adjustGridConfig / compiled on the host (getMultiProcessorCount +# replaced by sms): every step of it (cluster shrink and regrowth, the SM cap, the non-CGA fallback, loads > 1). +_LIB_NORM_LAUNCHES = [ + ((1, 4096, 148, 1), (64, 8, 1)), + ((18, 4096, 148, 1), (64, 8, 1)), + ((19, 4096, 148, 1), (128, 4, 1)), + ((64, 4096, 148, 1), (256, 2, 1)), + ((75, 4096, 148, 1), (512, 1, 1)), + ((200, 4096, 148, 1), (512, 1, 1)), + ((128, 16384, 148, 1), (1024, 2, 1)), + ((128, 65536, 148, 1), (1024, 8, 1)), + ((1, 2560, 148, 1), (80, 4, 1)), + ((40, 2560, 148, 1), (160, 2, 1)), + ((1, 131072, 148, 1), (2048, 1, 8)), + ((1, 6144, 132, 2), (96, 8, 1)), + ((17, 7168, 132, 2), (224, 4, 1)), + ((1, 1000, 160, 1), (125, 1, 1)), +] + + +@pytest.mark.parametrize(("args", "launch"), _LIB_NORM_LAUNCHES) +def test_lib_norm_tree_matches_the_library_launch( + args: tuple[int, int, int, int], launch: tuple[int, int, int] +) -> None: + """The one Python port of the library's norm launch shape, which both the slot / two-shot all-reduce kernels + (``_ctas_per_token``) and the GEMM + two-shot kernel replay.""" + from tensorrt_llm._torch.distributed.mnnvl_fused_allreduce import _ctas_per_token, lib_norm_tree + + m, hidden, sms, group = args + assert lib_norm_tree(m, hidden, sms, group=group) == launch + if group == 1: + assert _ctas_per_token(m, hidden, sms) == launch[1] diff --git a/tests/unittest/_torch/distributed/test_torchdist_object_collectives.py b/tests/unittest/_torch/distributed/test_torchdist_object_collectives.py index 0a17b64c3dc9..9e656de5a4bb 100644 --- a/tests/unittest/_torch/distributed/test_torchdist_object_collectives.py +++ b/tests/unittest/_torch/distributed/test_torchdist_object_collectives.py @@ -298,6 +298,31 @@ def rec_bc(tensor, *args, **kwargs): assert len(shapes) == 2, shapes +def test_broadcast_or_none_with_header_rides_in_the_size_word(td, world): + """The header (rank 0's clock in the request fetch) costs no extra round: one collective for nothing, two for a + payload, as without it; the single-word size exchange is left as it was.""" + rank, _, _ = world + shapes = [] + orig_bc = dist.broadcast + + def rec_bc(tensor, *args, **kwargs): + shapes.append(tuple(tensor.shape)) + return orig_bc(tensor, *args, **kwargs) + + header = [123_456_789, -1] if rank == 0 else [0, -1] + with mock.patch.object(dist, "broadcast", rec_bc): + assert td.broadcast_or_none_with_header(None, header, root=0) == ([123_456_789, -1], None) + assert shapes == [(3,)], shapes + shapes.clear() + obj = {"payload": list(range(50))} + got = td.broadcast_or_none_with_header(obj if rank == 0 else None, header, root=0) + assert got == ([123_456_789, -1], obj) + assert len(shapes) == 2 and shapes[0] == (3,), shapes + shapes.clear() + assert td.broadcast_or_none(None, root=0) is None + assert shapes == [(1,)], shapes + + def test_broadcast_root_stages_asynchronously_through_fenced_pinned_buffers(td, world): rank, _, _ = world pg = td._cuda_obj_pg("world") diff --git a/tests/unittest/_torch/helpers.py b/tests/unittest/_torch/helpers.py index 9e2f0e8f909d..4e6054b0d09d 100644 --- a/tests/unittest/_torch/helpers.py +++ b/tests/unittest/_torch/helpers.py @@ -351,6 +351,56 @@ def gumbel_max_reference(logits: torch.Tensor, temperatures: torch.Tensor, logits.float().argmax(-1)).to(torch.int32) +@triton.jit +def _fast_gumbel_score(logits_ptr, out_ptr, row, vocab, cols, u, inv_t): + ok = cols < vocab + x = tl.load(logits_ptr + row * vocab + cols, mask=ok, + other=0.0).to(tl.float32) + u = tl.minimum(tl.maximum(u, 1e-12), 0.99999994) + tl.store(out_ptr + row * vocab + cols, + x * inv_t - tl.log(-tl.log(u)), + mask=ok) + + +@triton.jit +def _fast_gumbel_scores_kernel(logits_ptr, temp_ptr, seed_ptr, out_ptr, vocab, + BLOCK: tl.constexpr): + row = tl.program_id(0) + n = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK) + u0, u1, u2, u3 = tl.rand4x(tl.load(seed_ptr), row * (vocab // 4) + n) + inv_t = 1.0 / tl.load(temp_ptr + row).to(tl.float32) + # Entry 4 * n + j takes Philox word (0, 2, 1, 3)[j]. + _fast_gumbel_score(logits_ptr, out_ptr, row, vocab, 4 * n, u0, inv_t) + _fast_gumbel_score(logits_ptr, out_ptr, row, vocab, 4 * n + 1, u2, inv_t) + _fast_gumbel_score(logits_ptr, out_ptr, row, vocab, 4 * n + 2, u1, inv_t) + _fast_gumbel_score(logits_ptr, out_ptr, row, vocab, 4 * n + 3, u3, inv_t) + + +def fast_gumbel_max_reference(logits: torch.Tensor, temperatures: torch.Tensor, + seed: torch.Tensor, + greedy_threshold: float) -> torch.Tensor: + """As ``gumbel_max_reference`` with the noise of ``TPKeyExchange``'s + ``fast_gumbel`` kernel: entry ``4 * n + j`` of ``row`` takes word + ``(0, 2, 1, 3)[j]`` of ``philox(seed, row * vocab / 4 + n)``, scaled logits + ``x * (1 / T)``.""" + rows, vocab = logits.shape + assert vocab % 4 == 0 + scores = torch.empty((rows, vocab), + dtype=torch.float32, + device=logits.device) + block = 256 + grid = (rows, triton.cdiv(vocab // 4, block)) + _fast_gumbel_scores_kernel[grid](logits.contiguous(), + temperatures, + seed, + scores, + vocab, + BLOCK=block) + sampled = temperatures >= greedy_threshold + return torch.where(sampled, scores.argmax(-1), + logits.float().argmax(-1)).to(torch.int32) + + def triton_num_compiled(kernel) -> int: """Specializations of a ``triton.jit`` kernel compiled in this process. @@ -361,3 +411,38 @@ def triton_num_compiled(kernel) -> int: if caches is None: pytest.skip("this Triton has no JITFunction.device_caches") return sum(len(cache[0]) for cache in caches.values()) + + +@triton.jit +def _late_copy_kernel(src_ptr, dst_ptr, n, delay_ns, BLOCK: tl.constexpr): + # Releases its PDL dependents at entry, then copies after ~delay_ns. + tl.extra.cuda.gdc_launch_dependents() + t0 = tl.inline_asm_elementwise("mov.u64 $0, %globaltimer;", + "=l", [], + dtype=tl.int64, + is_pure=False, + pack=1) + t = t0 + while t - t0 < delay_ns: + t = tl.inline_asm_elementwise("mov.u64 $0, %globaltimer;", + "=l", [], + dtype=tl.int64, + is_pure=False, + pack=1) + offs = tl.arange(0, BLOCK) + mask = offs < n + tl.store(dst_ptr + offs, tl.load(src_ptr + offs, mask=mask), mask=mask) + + +def late_copy(src: torch.Tensor, dst: torch.Tensor, delay_ns: int) -> None: + """``dst.copy_(src)`` by a one-program kernel that releases a PDL-launched + successor at entry and stores ``dst`` only ~``delay_ns`` later: a + successor that reads ``dst`` before its griddepcontrol.wait sees the old + values.""" + assert src.is_contiguous() and dst.is_contiguous() + assert src.dtype == dst.dtype and src.numel() == dst.numel() + _late_copy_kernel[(1, )](src, + dst, + src.numel(), + delay_ns, + BLOCK=triton.next_power_of_2(src.numel())) diff --git a/tests/unittest/_torch/kernels/parallel/test_nvfp4_quant.py b/tests/unittest/_torch/kernels/parallel/test_nvfp4_quant.py index 99d4bcde345f..f6dc1ee0440c 100644 --- a/tests/unittest/_torch/kernels/parallel/test_nvfp4_quant.py +++ b/tests/unittest/_torch/kernels/parallel/test_nvfp4_quant.py @@ -21,7 +21,11 @@ from utils.util import skip_pre_blackwell from tensorrt_llm._torch.flashinfer_utils import get_env_enable_pdl -from tensorrt_llm._torch.kernels.nvfp4_quant import can_use_nvfp4_quant, nvfp4_quant +from tensorrt_llm._torch.kernels.nvfp4_quant import ( + can_use_nvfp4_quant, + nvfp4_fp8_dual_quant, + nvfp4_quant, +) pytestmark = skip_pre_blackwell @@ -128,6 +132,29 @@ def test_nvfp4_quant_all_nan_position_masks(global_scale: float) -> None: _check(x.reshape(1024, 1024), torch.tensor([global_scale], device="cuda", dtype=torch.float32)) +@pytest.mark.parametrize("rows", [1, 5, 1025, 4097]) +@pytest.mark.parametrize("hidden", [1024, 4096]) +@pytest.mark.parametrize("global_scale", [1e-6, 1.0, 1e6]) +@pytest.mark.parametrize("fp8_scale", [1e-3, 0.05, 1.0, 100.0]) +def test_nvfp4_fp8_dual_quant_parity( + rows: int, hidden: int, global_scale: float, fp8_scale: float +) -> None: + torch.manual_seed(42) + x = torch.randn(rows, hidden, device="cuda", dtype=torch.bfloat16) * 8 + x[0, :16] = 0.0 + scale = torch.tensor([global_scale], device="cuda", dtype=torch.float32) + fp8_scale_t = torch.tensor([fp8_scale], device="cuda", dtype=torch.float32) + q, sf, fp8 = nvfp4_fp8_dual_quant(x, scale, fp8_scale_t) + expected = torch.ops.trtllm.fp4_quantize(x, scale, 16, False, False) + for result, reference in zip((q, sf), expected): + torch.testing.assert_close(result, reference, rtol=0, atol=0) + expected_fp8, _ = torch.ops.tensorrt_llm.static_quantize_e4m3_per_tensor(x, fp8_scale_t) + assert fp8.dtype == expected_fp8.dtype == torch.float8_e4m3fn + torch.testing.assert_close( + fp8.view(torch.uint8), expected_fp8.view(torch.uint8), rtol=0, atol=0 + ) + + @triton.jit def _producer(src, dst, count: tl.constexpr, pdl: tl.constexpr) -> None: if pdl: diff --git a/tests/unittest/_torch/kv_cache_compression/test_quantization_for_cold_page.py b/tests/unittest/_torch/kv_cache_compression/test_quantization_for_cold_page.py index a174b47e8ef5..f24944442219 100644 --- a/tests/unittest/_torch/kv_cache_compression/test_quantization_for_cold_page.py +++ b/tests/unittest/_torch/kv_cache_compression/test_quantization_for_cold_page.py @@ -1328,6 +1328,7 @@ def _build_cold_creator( creator._kv_cache_config = SimpleNamespace( host_cache_size=None, disk_cache_size=None, + remote_cache_config=None, enable_block_reuse=False, ) creator._llm_args = SimpleNamespace(kv_cache_compression_config=compression_config) diff --git a/tests/unittest/_torch/misc/test_autotuner.py b/tests/unittest/_torch/misc/test_autotuner.py index 73990a1ab83e..07f8ab4c9085 100644 --- a/tests/unittest/_torch/misc/test_autotuner.py +++ b/tests/unittest/_torch/misc/test_autotuner.py @@ -1761,7 +1761,12 @@ def fake_choose_one(self, custom_op, runners, tuning_config, inputs, seen["tuner"] = list(inputs) return runners[0], -1 - def fake_forward(self, inputs, tactic, output=None, prerouted=None): + def fake_forward(self, + inputs, + tactic, + output=None, + prerouted=None, + lamport_out=None): seen["kernel"] = list(inputs) return [torch.zeros(1, device="cuda")] diff --git a/tests/unittest/_torch/modeling_v2/models/glm5_next/glm_5_3_flash_nvfp4__sm_100__default_mtp_fused/spec/test_modeling_v2_mtp_step.py b/tests/unittest/_torch/modeling_v2/models/glm5_next/glm_5_3_flash_nvfp4__sm_100__default_mtp_fused/spec/test_modeling_v2_mtp_step.py index 1bd3425c6853..897b61857a1e 100644 --- a/tests/unittest/_torch/modeling_v2/models/glm5_next/glm_5_3_flash_nvfp4__sm_100__default_mtp_fused/spec/test_modeling_v2_mtp_step.py +++ b/tests/unittest/_torch/modeling_v2/models/glm5_next/glm_5_3_flash_nvfp4__sm_100__default_mtp_fused/spec/test_modeling_v2_mtp_step.py @@ -216,7 +216,9 @@ def _batch(seed, ctx_lens, num_gens, draft_len, accept_depths, greedy=True): def _run_stock(batch, draft_len): spec_config = MTPDecodingConfig(max_draft_len=draft_len) - worker = get_spec_worker(spec_config, SimpleNamespace(mapping=Mapping()), Mapping()) + worker = get_spec_worker( + spec_config, SimpleNamespace(mapping=Mapping(), extra_attrs={}), Mapping() + ) return worker(resource_manager=None, **batch) diff --git a/tests/unittest/_torch/modeling_v2/models/glm_moe_dsa/glm_5_2_nvfp4__sm_103__tep4/test_modeling_v2_draft_loop.py b/tests/unittest/_torch/modeling_v2/models/glm_moe_dsa/glm_5_2_nvfp4__sm_103__tep4/test_modeling_v2_draft_loop.py index b2be4af51e0f..a12278432770 100644 --- a/tests/unittest/_torch/modeling_v2/models/glm_moe_dsa/glm_5_2_nvfp4__sm_103__tep4/test_modeling_v2_draft_loop.py +++ b/tests/unittest/_torch/modeling_v2/models/glm_moe_dsa/glm_5_2_nvfp4__sm_103__tep4/test_modeling_v2_draft_loop.py @@ -53,6 +53,7 @@ class _Worker: _sample_and_accept_draft_tokens_base = SpecWorkerBase._sample_and_accept_draft_tokens_base _fused_force_params = SpecWorkerBase._fused_force_params _prepare_next_new_tokens = SpecWorkerBase._prepare_next_new_tokens + fused_sample_accept = SpecWorkerBase.fused_sample_accept def __init__(self, target: torch.Tensor, force: float) -> None: self._target = target @@ -417,3 +418,36 @@ def test_worker_overrides_are_model_local() -> None: assert name in vars(op.Glm52MTPEagleWorker), name assert vars(op.MTPEagleWorker).get(name) is None assert getattr(op.MTPEagleWorker, name) is getattr(Eagle3OneModelWorker, name) + + +# ---- the greedy draft pick through the engine's entry ----------------------------------- + + +@pytest.mark.parametrize("argmax_on", [True, False]) +def test_greedy_draft_pick_through_the_engine_entry(argmax_on) -> None: + """`SpecWorkerBase.sample_draft_tokens` reaches the override (CuTe DSL argmax, or the + built-in argmax when it is off) with and without the step's `out` row.""" + from tensorrt_llm._torch._experimental.modeling_v2.models.glm_moe_dsa.glm_5_2_nvfp4__sm_103__tep4.ops.sampling import ( # noqa: E501 + cute_dsl_argmax as argmax_entry, + ) + + worker = op.Glm52MTPEagleWorker.__new__(op.Glm52MTPEagleWorker) + torch.nn.Module.__init__(worker) # attribute storage only; the init needs the model + worker.mapping = SimpleNamespace(tp_size=1, tp_rank=0, enable_attention_dp=False) + worker._d2t = None + counts: dict = {} + worker._glm_count = lambda route, hit: counts.__setitem__( + (route, hit), counts.get((route, hit), 0) + 1 + ) + compiled = argmax_entry.compile() if argmax_on else None + worker._glm_argmax_rows = lambda: compiled + worker._glm_argmax_on = argmax_on + spec = SimpleNamespace(wants_advanced_draft_sampling=False, is_cuda_graph=False) + logits = torch.randn(5, argmax_entry.VOCAB, device=DEV) + want = logits.argmax(dim=-1).to(torch.int32) + assert torch.equal(worker.sample_draft_tokens(logits, spec, 5, draft_step=0), want) + out = torch.full((5,), -1, dtype=torch.int32, device=DEV) + tokens = worker.sample_draft_tokens(logits, spec, 5, draft_step=0, out=out) + assert tokens.data_ptr() == out.data_ptr() # the tokens are out's storage + assert torch.equal(out, want) + assert counts == ({("greedy_draft", True): 2} if argmax_on else {}) diff --git a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_103__tp4/spec/test_modeling_v2_m3_exact_numerics.py b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_103__tp4/spec/test_modeling_v2_m3_exact_numerics.py index 05512cb07ac8..a8d8e689dac5 100644 --- a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_103__tp4/spec/test_modeling_v2_m3_exact_numerics.py +++ b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_103__tp4/spec/test_modeling_v2_m3_exact_numerics.py @@ -72,7 +72,7 @@ def _stock_accept(logits: torch.Tensor, draft: torch.Tensor): is_cuda_graph=False, sharded_target_logits=False, ) - worker = SimpleNamespace(force_num_accepted_tokens=0.0) + worker = SimpleNamespace(force_num_accepted_tokens=0.0, fused_sample_accept=False) worker._sample_tokens_for_batch = lambda *a: Eagle3OneModelWorker._sample_tokens_for_batch( worker, *a ) diff --git a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_103__tp8/spec/test_modeling_v2_m3_exact_numerics.py b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_103__tp8/spec/test_modeling_v2_m3_exact_numerics.py index 07a2027b274b..cef192babe71 100644 --- a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_103__tp8/spec/test_modeling_v2_m3_exact_numerics.py +++ b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_103__tp8/spec/test_modeling_v2_m3_exact_numerics.py @@ -74,7 +74,7 @@ def _stock_accept(logits: torch.Tensor, draft: torch.Tensor): is_cuda_graph=False, sharded_target_logits=False, ) - worker = SimpleNamespace(force_num_accepted_tokens=0.0) + worker = SimpleNamespace(force_num_accepted_tokens=0.0, fused_sample_accept=False) worker._sample_tokens_for_batch = lambda *a: Eagle3OneModelWorker._sample_tokens_for_batch( worker, *a ) diff --git a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/spec/test_modeling_v2_m3_wide_draft_logits.py b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/spec/test_modeling_v2_m3_wide_draft_logits.py index f89a2ddde2e6..967ab9b01ee3 100644 --- a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/spec/test_modeling_v2_m3_wide_draft_logits.py +++ b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp2/spec/test_modeling_v2_m3_wide_draft_logits.py @@ -130,3 +130,20 @@ def apply_linear(self, x, bias): tokens = w.sample_draft_tokens(logits, meta, rows, draft_step=0) assert calls == [((rows, shard), torch.bfloat16, shard, (rows, 0))] assert torch.equal(tokens, torch.arange(rows, dtype=torch.int32) + 7) + + +def test_the_greedy_draft_override_fills_out() -> None: + """SpecWorkerBase.sample_draft_tokens passes ``tokens_out`` to greedy_sample_draft_with_tp_gather; the M3 override + hands it on, and the step's ``out`` row holds the tokens on every path. (Its signature is checked with every + other override's in hw_agnostic/test_draft_sampler_overrides.py.)""" + w = _worker() + w.mapping.tp_size = 1 # replicated logits: the base sampler's plain argmax + w._d2t = None + meta = SimpleNamespace(wants_advanced_draft_sampling=False, is_cuda_graph=False) + logits = torch.randn(5, 64) + out = torch.full((5,), -1, dtype=torch.int32) + tokens = w.sample_draft_tokens(logits, meta, 5, draft_step=0, out=out) + expected = logits.argmax(dim=-1).to(torch.int32) + assert torch.equal(out, expected) + assert torch.equal(tokens, expected) + assert torch.equal(w.sample_draft_tokens(logits, meta, 5, draft_step=0), expected) diff --git a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp4/spec/test_modeling_v2_m3_exact_numerics.py b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp4/spec/test_modeling_v2_m3_exact_numerics.py index dd876b9a2b39..8bdf578d5943 100644 --- a/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp4/spec/test_modeling_v2_m3_exact_numerics.py +++ b/tests/unittest/_torch/modeling_v2/models/minimax_m3/minimax_m3_nvfp4__sm_107__tp4/spec/test_modeling_v2_m3_exact_numerics.py @@ -73,7 +73,7 @@ def _stock_accept(logits: torch.Tensor, draft: torch.Tensor): is_cuda_graph=False, sharded_target_logits=False, ) - worker = SimpleNamespace(force_num_accepted_tokens=0.0) + worker = SimpleNamespace(force_num_accepted_tokens=0.0, fused_sample_accept=False) worker._sample_tokens_for_batch = lambda *a: Eagle3OneModelWorker._sample_tokens_for_batch( worker, *a ) diff --git a/tests/unittest/_torch/modeling_v2/models/minimax_m3/test_modeling_v2_eagle3_worker_api.py b/tests/unittest/_torch/modeling_v2/models/minimax_m3/test_modeling_v2_eagle3_worker_api.py index 71473270866a..df1fe5a8cb8c 100644 --- a/tests/unittest/_torch/modeling_v2/models/minimax_m3/test_modeling_v2_eagle3_worker_api.py +++ b/tests/unittest/_torch/modeling_v2/models/minimax_m3/test_modeling_v2_eagle3_worker_api.py @@ -131,10 +131,11 @@ def _forward_external_shared_target_kv_draft_loop(self, **kwargs): forward = next( n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "_forward_impl" ) + # ast.walk: the parent nests the branch in a try / finally (the side-stream join). branch = copy.deepcopy( next( n - for n in forward.body + for n in ast.walk(forward) if isinstance(n, ast.If) and ast.unparse(n.test) == "self._uses_external_shared_target_kv" ) diff --git a/tests/unittest/_torch/models/test_qwen3_next_decode_gates.py b/tests/unittest/_torch/models/test_qwen3_next_decode_gates.py new file mode 100644 index 000000000000..63169491797f --- /dev/null +++ b/tests/unittest/_torch/models/test_qwen3_next_decode_gates.py @@ -0,0 +1,540 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Where the Qwen3.5 prefill / decode kernels engage, decided on the host (no GPU): the architecture and layout +gates, the resident band, the shared expert's low-M path and its tuning, the expert prefetch's layers, the row +gates under torch.compile, the drafter's view of the target's declarations and the fast paths' runtime hooks. +Each reference layout (GB300 NVL72: CTX TEP2 / DEP4, GEN TEP8 / TEP16 / DEP4, MTP 6) keeps its decisions.""" + +from types import SimpleNamespace + +import pytest +import torch +from torch import nn + +from tensorrt_llm._torch.models import modeling_qwen3_next as m +from tensorrt_llm._torch.models.modeling_qwen3_5 import Qwen3_5ForCausalLM, Qwen3_5MoeForCausalLM +from tensorrt_llm._torch.models.modeling_qwen3_next import ( + Qwen3NextForCausalLM, + Qwen3NextLinearDecoderLayer, + Qwen3NextModel, + Qwen3NextSparseMoeBlock, +) +from tensorrt_llm._torch.moe.fused_moe.impl_contract import MOE_DECODE_OPTIONS, MoEDecodeOptions +from tensorrt_llm.mapping import Mapping + +pytestmark = pytest.mark.cpu_only + + +class _StopInit(Exception): + pass + + +def _stop(model_config) -> None: + raise _StopInit + + +def _config(mapping: Mapping, extra_attrs=None, spec_rows=None, batch_sizes=(1, 2)): + return SimpleNamespace( + pretrained_config=SimpleNamespace( + model_type="qwen3_5_moe_text", torch_dtype=torch.bfloat16 + ), + extra_attrs={} if extra_attrs is None else extra_attrs, + spec_config=None if spec_rows is None else SimpleNamespace(tokens_per_gen_step=spec_rows), + cuda_graph_batch_sizes=list(batch_sizes), + mapping=mapping, + ) + + +# Qwen3.5's declarations on the shared class (the Qwen3.5 classes' own __init__ only normalizes the quant config). +_Q35 = type("_Q35", (Qwen3NextForCausalLM,), {"decode_kernels": True, "prefill_kernels": True}) + + +def _build(model_cls: type, config) -> None: + """Run the model class's __init__ up to the decoder model (what it declares in ``extra_attrs``).""" + with pytest.raises(_StopInit): + model_cls(config) + + +# (name, mapping, aarch64): GB300 / GB200 NVL racks are aarch64 with an NVLink fabric, HGX nodes x86. +_GB300_TEP8 = Mapping(world_size=8, tp_size=8, moe_ep_size=8, gpus_per_node=4) +_GB300_TEP16 = Mapping(world_size=16, tp_size=16, moe_ep_size=16, gpus_per_node=4) +_GB300_CTX_TEP2 = Mapping(world_size=2, tp_size=2, moe_ep_size=2, gpus_per_node=4) +_DEP4 = Mapping(world_size=4, tp_size=4, moe_ep_size=4, gpus_per_node=4, enable_attention_dp=True) +_HGX_TEP8 = Mapping(world_size=8, tp_size=8, moe_ep_size=8, gpus_per_node=8) +_HGX_TP2 = Mapping(world_size=2, tp_size=2, gpus_per_node=8) +_TP1 = Mapping(world_size=1, tp_size=1) + + +@pytest.fixture +def blackwell(monkeypatch) -> None: + monkeypatch.setattr(m, "is_blackwell_datacenter", lambda: True) + monkeypatch.setattr(m, "Qwen3NextModel", _stop) + + +def _fabric(monkeypatch, aarch64: bool) -> None: + """The MNNVL hardware check of MNNVLAllReduce.is_mnnvl: an NVLink fabric on an aarch64 (Grace) node.""" + from tensorrt_llm._torch.distributed import mnnvl_memory, ops + + monkeypatch.delenv("TLLM_TEST_MNNVL", raising=False) + monkeypatch.setattr(mnnvl_memory.MnnvlMemory, "supports_mnnvl", staticmethod(lambda: True)) + monkeypatch.setattr(ops.platform, "machine", lambda: "aarch64" if aarch64 else "x86_64") + + +@pytest.mark.parametrize( + "mapping,aarch64,expected", + [ + (_GB300_TEP8, True, True), # GEN TEP8 (reference) + (_GB300_TEP16, True, True), # GEN TEP16 (reference) + (_GB300_CTX_TEP2, True, True), # CTX TEP2 (reference; its TWOSHOT strategy does not matter) + (_DEP4, True, True), # GEN / CTX DEP4 (reference) + (_DEP4, False, True), # attention DP on an HGX node + (_HGX_TEP8, False, False), # TEP8 on 8x B200 HGX: no MNNVL + (_HGX_TP2, False, False), # Qwen3.6 TP2 on B200 HGX + (_TP1, False, False), # Qwen3.6 TP1 on B200 HGX + (_TP1, True, True), # TP1 on a GB300 node (as before) + ], + ids=[ + "gb300_tep8", + "gb300_tep16", + "gb300_ctx_tep2", + "gb300_dep4", + "hgx_dep4", + "hgx_tep8", + "hgx_tp2", + "hgx_tp1", + "gb300_tp1", + ], +) +def test_decode_kernels_follow_the_layout( + monkeypatch, blackwell, mapping, aarch64, expected +) -> None: + """The declared decode kernels (and the fused-norm all-reduces, the MoE decode options, the fast paths) engage + under attention DP or in a TP layout with MNNVL, where they were tuned; a TP layout without one (an HGX node) + keeps the stock paths. Every GB300 reference layout keeps them.""" + _fabric(monkeypatch, aarch64) + config = _config(mapping) + _build(_Q35, config) + assert m._uses_decode_kernels(config) is expected + assert _Q35.supports_spec_decode_fast_paths(config) is expected + assert MoEDecodeOptions.of(config.extra_attrs).tuning is expected + assert config.extra_attrs.get("allreduce_mnnvl_fused_norm", False) is expected + assert config.extra_attrs.get("allreduce_tp2_fused_norm", False) is expected + assert m._uses_tp_decode_kernels(config) is (expected and not mapping.enable_attention_dp) + + +@pytest.mark.parametrize("sm", [90, 100, 103, 107, 120]) +@pytest.mark.parametrize("declared", [True, False]) +def test_prefill_kernels_need_blackwell_datacenter(monkeypatch, sm, declared) -> None: + """The declared prefill kernels (fused GDN prefill conv and splits, MoE input dual quant, FP8 output gate, + staged-KV FP8 context attention) run on SM 10.0 / 10.3 only, as the decode kernels.""" + import tensorrt_llm._utils as utils + + monkeypatch.setattr(utils, "get_sm_version", lambda: sm) + monkeypatch.setattr(m, "Qwen3NextModel", _stop) + monkeypatch.setattr(m, "_decode_kernels_layout", lambda model_config: True) + config = _config(_GB300_CTX_TEP2) + assert Qwen3_5MoeForCausalLM.prefill_kernels and not Qwen3_5ForCausalLM.prefill_kernels + _build(type("_Declared", (Qwen3NextForCausalLM,), {"prefill_kernels": declared}), config) + assert m._uses_prefill_kernels(config) is (declared and sm in (100, 103)) + + +def _layer_with_projection(n: int, k: int) -> Qwen3NextLinearDecoderLayer: + layer = Qwen3NextLinearDecoderLayer.__new__(Qwen3NextLinearDecoderLayer) + nn.Module.__init__(layer) + projection = SimpleNamespace( + weight=torch.empty((n, k), dtype=torch.float8_e4m3fn, device="meta"), + _weights_removed=False, + resident_fp8_min_rows=0, + ) + layer.linear_attn = SimpleNamespace(in_proj_qkvz=projection) + return layer + + +def _feeding_layer(tp_size: int, post_moe_fusion: bool, scale) -> SimpleNamespace: + return SimpleNamespace( + next_layer_input_scale=scale, + fusion_config=SimpleNamespace(POST_MOE_FUSION=post_moe_fusion), + mapping=SimpleNamespace(tp_size=tp_size), + allreduce=SimpleNamespace(mnnvl_allreduce=None), + next_layer_resident_rows=(1, 0), + ) + + +@pytest.mark.parametrize( + "tp_size,post_moe_fusion,scale,n,k,band", + [ + # TEP8: GDN in_proj_qkvz (20480 / 8) and attention qkv_proj + (8, True, True, 2560, 4096, True), + (16, True, True, 1280, 4096, True), # TEP16: GDN in_proj_qkvz + (16, True, True, 1536, 4096, True), # TEP16: attention qkv_proj (q 1024 + replicated k / v) + (1, True, True, 2560, 4096, False), # TP1: no all-reduce hands over E4M3 + # no POST_MOE_FUSION: the next layer quantizes its own input + (8, False, True, 2560, 4096, False), + (8, True, False, 2560, 4096, False), # BF16 next projection + (8, True, True, 2624, 4096, False), # N not in whole 128-feature CTA pairs + (8, True, True, 2560, 4608, False), # K not in whole x TMA boxes + ], +) +def test_resident_band_needs_an_e4m3_handover_and_a_covered_shape( + tp_size, post_moe_fusion, scale, n, k, band +) -> None: + """The input projection after a MoE-output all-reduce takes the resident-weight GEMM from its resident rows only + where that all-reduce hands it an E4M3 input and resident_fp8_gemm covers (K, N) at every row of the band; the + reference TEP8 / TEP16 shapes keep the band.""" + from tensorrt_llm._torch.kernels.blackwell.resident_fp8_gemm import MAX_ROWS + + layer = _feeding_layer(tp_size, post_moe_fusion, torch.ones(1) if scale else None) + next_layer = _layer_with_projection(n, k) + model = SimpleNamespace( + model_config=SimpleNamespace( + extra_attrs={"qwen3_next_decode_kernels": True}, + mapping=SimpleNamespace(enable_attention_dp=False), + spec_config=SimpleNamespace(tokens_per_gen_step=7), + ) + ) + Qwen3NextModel._cache_tp_decode_gates(model, [layer, next_layer]) + projection = next_layer.linear_attn.in_proj_qkvz + assert projection.resident_fp8_min_rows == (14 if band else 0) + assert layer.next_layer_resident_rows == ((14, MAX_ROWS) if band else (1, 0)) + + +@pytest.mark.parametrize("attention_dp,rows", [(False, 14), (True, 0)]) +def test_resident_rows_come_from_one_helper(monkeypatch, attention_dp, rows) -> None: + """The GDN layer's resident rows and the model's resident band derive from _resident_min_rows.""" + config = SimpleNamespace( + extra_attrs={"qwen3_next_decode_kernels": True}, + mapping=SimpleNamespace(enable_attention_dp=attention_dp), + spec_config=SimpleNamespace(tokens_per_gen_step=7), + cuda_graph_batch_sizes=[1, 2, 4, 8], + ) + assert m._resident_min_rows(config) == rows + built = {} + + def record(self, model_config, aux_stream, layer_idx, **kwargs) -> None: + nn.Module.__init__(self) + built.update(kwargs) + raise _StopInit + + monkeypatch.setattr(m.Qwen3NextGatedDeltaNet, "__init__", record) + with pytest.raises(_StopInit): + Qwen3NextLinearDecoderLayer(config, 0, None) + assert built["resident_min_rows"] == rows + assert built["resident_ba_min_rows"] == (rows + 1 if rows else 0) + + +class _Dispatcher: + """A low-M dispatcher that records its FP8 race calls.""" + + def __init__(self) -> None: + self.calls = [] + + def takes_rows(self, module, rows: int) -> bool: + return True + + def apply_fp8(self, x, weight, weight_scale, input_scale, out_dtype): + self.calls.append((tuple(x.shape), x.dtype, weight)) + + +def _shared_expert_block(raced_rows: int, hidden: int = 256, inter: int = 64): + dispatcher = _Dispatcher() + scale = torch.ones(()) + + def projection(n: int, k: int) -> SimpleNamespace: + return SimpleNamespace( + weight=torch.zeros((n, k), dtype=torch.float8_e4m3fn), + weight_scale=scale, + quant_method=SimpleNamespace(get_static_input_scale=lambda proj: scale), + _low_m_gemm_dispatcher=dispatcher, + ) + + block = Qwen3NextSparseMoeBlock.__new__(Qwen3NextSparseMoeBlock) + nn.Module.__init__(block) + block._shared_expert_low_m = (torch.zeros(1), torch.zeros(1)) + block._shared_expert_raced_rows = raced_rows + block.shared_expert = SimpleNamespace( + gate_up_proj=projection(2 * inter, hidden), down_proj=projection(hidden, inter) + ) + return block, dispatcher + + +@pytest.mark.parametrize( + "raced_rows,tunes", + [ + # MTP 3, CUDA graphs up to 4 requests: eager 17..32-row steps take fused_shared_expert + (16, True), + # TEP16 b1 (reference): its steps never pass 7 rows, so nothing reads these races + (7, True), + (32, False), # the raced path covers every low-M row count + (56, False), # TEP2 / TEP8 with 8+ requests at MTP 6 (reference) + (0, False), # attention DP (reference DEP4): the stock calls tune the races + ], +) +def test_shared_expert_tuning_also_tunes_the_fused_path(monkeypatch, raced_rows, tunes) -> None: + """In tuning mode the raced path takes every call, so the low-M races that fused_shared_expert reads for the + rows above the raced ones (gate_up_proj with a BF16 input, down_proj with an E4M3 input) are timed beside it.""" + from tensorrt_llm._torch.autotuner import AutoTuner + + block, dispatcher = _shared_expert_block(raced_rows) + monkeypatch.setattr(m, "raced_shared_expert", lambda x, weights, **kwargs: "raced") + monkeypatch.setattr(m, "fused_shared_expert", lambda dispatcher, x, weights, **kwargs: "fused") + monkeypatch.setattr(AutoTuner.get(), "is_tuning_mode", True) + x = torch.zeros((64, 256), dtype=torch.bfloat16) + out = block._shared_expert_low_m_forward(x) + assert out == ("raced" if raced_rows else "fused") + mlp = block.shared_expert + if tunes: + assert dispatcher.calls == [ + ((32, 256), torch.bfloat16, mlp.gate_up_proj.weight), + ((32, 64), torch.float8_e4m3fn, mlp.down_proj.weight), + ] + else: + assert dispatcher.calls == [] + # Outside tuning nothing extra runs. + dispatcher.calls.clear() + monkeypatch.setattr(AutoTuner.get(), "is_tuning_mode", False) + block._shared_expert_low_m_forward(x[: max(raced_rows, 1)]) + assert dispatcher.calls == [] + + +@pytest.mark.parametrize( + "gate_up,down,qualifies", + [ + ((256, 4096), (4096, 128), True), # TEP8 shared expert (I 1024 / 8) + ((128, 4096), (4096, 64), True), # TEP16 + ((2048, 4096), (4096, 1024), True), # attention DP (whole shared expert) + ((256, 1088), (1088, 128), False), # K of 17 64-wide chunks: no default gate_up tactic + ], +) +def test_shared_expert_low_m_declines_shapes_without_a_default_tactic( + monkeypatch, gate_up, down, qualifies +) -> None: + """An untuned launch of the shared expert's low-M path runs low_m_mma_gemm.default_tactic, which raises for + some shapes: the path declines them when its weights are built.""" + assert ( + m._shared_expert_default_tactics_exist(torch.empty(gate_up), torch.empty(down)) is qualifies + ) + + class _Fp8: + def get_static_input_scale(self, proj): + return torch.ones(()) + + def projection(shape): + # BF16 stands in for the E4M3 weights: only their shapes decide (CPU tensor ops). + return SimpleNamespace( + weight=torch.zeros(shape, dtype=torch.bfloat16), bias=None, quant_method=_Fp8() + ) + + monkeypatch.setattr(m, "FP8QDQLinearMethod", _Fp8) + monkeypatch.setattr(m, "warp_mma_supported", lambda: True) + monkeypatch.setattr(m, "low_m_gemm_dispatcher", lambda module: object()) + block = Qwen3NextSparseMoeBlock.__new__(Qwen3NextSparseMoeBlock) + nn.Module.__init__(block) + block._shared_expert_low_m = None + block.shared_expert = SimpleNamespace( + gate_up_proj=projection(gate_up), + down_proj=projection(down), + activation=torch.nn.functional.silu, + _is_plain_swiglu=lambda: True, + swiglu_limit=None, + ) + block.shared_expert_gate = SimpleNamespace( + weight=torch.zeros((1, gate_up[1]), dtype=torch.bfloat16), bias=None + ) + weights = block._shared_expert_low_m_weights() + assert (weights is not None) is qualifies + + +def _moe_layer(idx: int, post_moe_fusion: bool, defers: bool, fold_rows) -> SimpleNamespace: + mlp = Qwen3NextSparseMoeBlock.__new__(Qwen3NextSparseMoeBlock) + nn.Module.__init__(mlp) + mlp._experts_defer_finalize = lambda: defers + return SimpleNamespace( + layer_idx=idx, + mlp=mlp, + hidden_size=4096, + fusion_config=SimpleNamespace(POST_MOE_FUSION=post_moe_fusion), + allreduce=SimpleNamespace(supports_moe_fold=lambda rows, hidden: rows in fold_rows), + ) + + +def test_expert_prefetch_keeps_only_layers_whose_front_records() -> None: + """The decode front records a layer's experts only in an un-finalized MoE call (the MoE-output all-reduce folds + and finalizes it): a layer that never takes one is unregistered, so it launches no prefetch on an empty or stale + selection. The reference TEP layouts (MNNVL fold at every prefetched row count) keep every layer.""" + from tensorrt_llm._torch.modules.expert_l2_prefetch import ExpertL2Prefetch + + prefetch = ExpertL2Prefetch(6, min_rows=14, max_rows=63, top_k=10, stream=None) + every_row = range(1, 129) + layers = [ + _moe_layer(0, True, True, every_row), # reference TEP8 / TEP16 layer + _moe_layer(1, True, True, range(64, 129)), # folds only above the prefetched rows + _moe_layer(2, True, True, ()), # no MNNVL all-reduce (e.g. AUTO TEP4 within one tray) + _moe_layer(3, True, False, every_row), # experts that cannot defer their finalize + _moe_layer(4, False, True, every_row), # no POST_MOE_FUSION + _moe_layer(5, True, True, range(30, 31)), # folds at one prefetched row count + ] + for layer in layers: + prefetch.register(layer.layer_idx, object(), 0) + Qwen3NextModel._drop_expert_prefetch_without_record( + SimpleNamespace(expert_prefetch=prefetch), layers + ) + assert [prefetch.registered(i) for i in range(6)] == [True, False, False, False, False, True] + # An unregistered layer launches nothing (the backend lookup returns first, before any device work). + prefetch.prefetch(2, 20) + assert not prefetch._forked + + +def _compile_count(fn, rows) -> int: + from torch._dynamo.testing import CompileCounter + + counter = CompileCounter() + compiled = torch.compile(fn, backend=counter, dynamic=True) + for n in rows: + compiled(torch.zeros((n, 8))) + return counter.frame_count + + +def test_expert_prefetch_rows_do_not_guard_under_torch_compile() -> None: + """Under torch.compile the prefetch row check tests is_compiling() first, so a symbolic row count crossing its + bounds compiles once.""" + from tensorrt_llm._torch.modules.expert_l2_prefetch import ExpertL2Prefetch + + torch._dynamo.reset() + prefetch = ExpertL2Prefetch(4, min_rows=14, max_rows=63, top_k=10, stream=None) + + def fn(x): + return x * 2 if prefetch.takes_rows(x.shape[0]) else x + 1 + + assert _compile_count(fn, (2, 3, 20, 40, 100, 300)) == 1 + + +def test_moe_input_dual_quant_rows_do_not_guard_under_torch_compile() -> None: + """The MoE input dual quant tests is_compiling() before its 1024-row bound: a symbolic row count crossing it + compiles once.""" + torch._dynamo.reset() + block = Qwen3NextSparseMoeBlock.__new__(Qwen3NextSparseMoeBlock) + nn.Module.__init__(block) + block._dual_quant_input = True + + def fn(x): + return x * 2 if block._moe_input_dual_quant(x, None) is None else x + 1 + + assert _compile_count(fn, (2, 3, 900, 1100, 2000)) == 1 + + +def _spec_config(kind: str) -> SimpleNamespace: + mode = SimpleNamespace( + use_one_engine=lambda: True, + is_sa=lambda: False, + is_eagle3_one_model=lambda: False, + is_external_drafter=lambda: kind == "pard", + is_parallel_draft=lambda: False, + ) + return SimpleNamespace( + spec_dec_mode=mode, + uses_external_draft_model=kind == "external_mtp", + uses_replacement_heads=False, + speculative_model="drafter", + tokens_per_gen_step=7, + ) + + +@pytest.mark.parametrize("kind", ["external_mtp", "pard", "own_mtp"]) +def test_drafters_of_another_checkpoint_do_not_take_the_target_decode_options( + monkeypatch, kind +) -> None: + """The target's MoE decode options and fused-norm all-reduce declarations stay out of a drafter built from + another checkpoint (external MTP, PARD / draft-target), whose config shares the target's extra_attrs; Qwen3.5's + own MTP layer (the reference) keeps them, and the target's dict is unchanged afterwards.""" + from tensorrt_llm._torch.models import modeling_speculative as ms + from tensorrt_llm._torch.models.modeling_utils import DecoderModelForCausalLM + + def base_init(self, model, *, config, hidden_size, vocab_size) -> None: + nn.Module.__init__(self) + self.model = model + self.lm_head = None + self.epilogue = [] + + seen = {} + + def get_draft_model(model_config, draft_config, lm_head, model): + attrs = model_config.extra_attrs + seen["options"] = MoEDecodeOptions.of(attrs) + seen["fused_norm"] = attrs.get("allreduce_mnnvl_fused_norm", False) + seen["layers"] = "attn_layers" in attrs + seen["shared"] = draft_config is None or draft_config.extra_attrs is attrs + return None + + monkeypatch.setattr(DecoderModelForCausalLM, "__init__", base_init) + monkeypatch.setattr(ms, "_get_requested_draft_moe_backend", lambda *args: "TRTLLM") + monkeypatch.setattr(ms, "_set_draft_kv_cache_quant_algo", lambda *args: None) + monkeypatch.setattr(ms, "external_drafter_config_kwargs", lambda *args: {}) + monkeypatch.setattr(ms, "should_use_separate_draft_kv_cache", lambda *args: False) + monkeypatch.setattr(ms, "get_draft_model", get_draft_model) + monkeypatch.setattr(ms, "get_spec_worker", lambda *args, **kwargs: None) + monkeypatch.setattr( + ms.ModelConfig, "from_pretrained", classmethod(lambda cls, *a, **k: SimpleNamespace()) + ) + + options = MoEDecodeOptions(tuning=True, fc2_weights_evict_first_rows=1344) + extra_attrs = { + MOE_DECODE_OPTIONS: options, + "allreduce_mnnvl_fused_norm": True, + "allreduce_tp2_fused_norm": True, + "attn_layers": {}, + } + config = SimpleNamespace( + spec_config=_spec_config(kind), + extra_attrs=extra_attrs, + attn_backend="TRTLLM", + mapping=SimpleNamespace(mapping_for_full_rows=lambda: None), + max_num_tokens=8, + moe_max_num_tokens=8, + pretrained_config=SimpleNamespace(hidden_size=8, vocab_size=8), + ) + target = Qwen3_5MoeForCausalLM.__new__(Qwen3_5MoeForCausalLM) + ms.SpecDecOneEngineForCausalLM.__init__(target, None, config) + + own = kind == "own_mtp" + assert seen["shared"] and seen["layers"] + assert seen["options"] == (options if own else MoEDecodeOptions()) + assert seen["fused_norm"] is own + assert extra_attrs[MOE_DECODE_OPTIONS] is options + assert extra_attrs["allreduce_mnnvl_fused_norm"] and extra_attrs["allreduce_tp2_fused_norm"] + + +def test_fast_path_runtime_hooks_are_declared_by_the_model() -> None: + """Qwen3Next declares its fast paths' step-loop hooks; another fast-path model gets none from the base class.""" + from tensorrt_llm._torch.models.modeling_speculative import SpecDecOneEngineForCausalLM + from tensorrt_llm._torch.pyexecutor.runtime_hooks import RuntimeHooks + + expected = RuntimeHooks( + loop_on_execution_stream=True, + pack_spec_rng_uploads=True, + iteration_timing_one_event=True, + perf_metrics_timing_side_stream=True, + ) + for cls in (Qwen3NextForCausalLM, Qwen3_5MoeForCausalLM, Qwen3_5ForCausalLM): + model = cls.__new__(cls) + nn.Module.__init__(model) + model.spec_decode_fast_paths = True + assert model.runtime_hooks == expected + model.spec_decode_fast_paths = False + assert model.runtime_hooks is None + other_cls = type("_OtherFastPathModel", (SpecDecOneEngineForCausalLM,), {}) + other = other_cls.__new__(other_cls) + nn.Module.__init__(other) + other.spec_decode_fast_paths = True + assert other.runtime_hooks is None diff --git a/tests/unittest/_torch/models/test_qwen3_next_eager_fusion.py b/tests/unittest/_torch/models/test_qwen3_next_eager_fusion.py index 835fa3257cdf..d81eb795b147 100644 --- a/tests/unittest/_torch/models/test_qwen3_next_eager_fusion.py +++ b/tests/unittest/_torch/models/test_qwen3_next_eager_fusion.py @@ -31,7 +31,8 @@ _Qwen3NextDecoderLayerBase, ) from tensorrt_llm._torch.modules.rms_norm import RMSNorm -from tensorrt_llm._torch.utils import EventType +from tensorrt_llm._torch.moe.fused_moe.impl_contract import MoEDecodeOptions +from tensorrt_llm._torch.utils import AuxStreamType, EventType def _new_causal_lm() -> Qwen3NextForCausalLM: @@ -250,6 +251,8 @@ def test_pre_moe_allreduce_runs_in_mixer_output_projection() -> None: next_layer_layernorm=next_layer_norm, next_layer_input_scale=None, next_layer_reads_bf16=False, + next_layer_prefetch_weight=None, + post_moe_norm_fold=False, allreduce_fp8_payload=False, fusion_config=SimpleNamespace(PRE_MOE_FUSION=True, POST_MOE_FUSION=True), disable_attn_allreduce=True, @@ -293,20 +296,12 @@ def test_pre_moe_allreduce_runs_in_mixer_output_projection() -> None: assert mlp.call_args.kwargs["do_finalize"] -@pytest.mark.parametrize( - "model_type,sm,enabled", - [ - ("qwen3_5_moe", 103, True), - ("qwen3_5_moe", 100, True), - ("qwen3_next", 103, False), - ("qwen3_5_moe", 107, False), - ("qwen3_5_moe", 90, False), - ], -) -def test_attention_takes_the_gqa_decode_kernel_on_qwen3_5_sm100_and_sm103( - monkeypatch, model_type, sm, enabled +@pytest.mark.parametrize("enabled", [False, True]) +def test_attention_takes_the_gqa_decode_kernel_where_the_model_declares_it( + monkeypatch, enabled ) -> None: - from tensorrt_llm import _utils + """The decode kernels the model class declares (test_decode_kernels_follow_the_model_declaration) reach the + attention module as constructor arguments.""" from tensorrt_llm._torch.models import modeling_qwen3_next from tensorrt_llm._torch.models.modeling_qwen3 import Qwen3Attention @@ -316,17 +311,152 @@ def record_init(self, *args, **kwargs) -> None: nn.Module.__init__(self) built.update(kwargs) - monkeypatch.setattr(_utils, "get_sm_version", lambda: sm) monkeypatch.setattr(Qwen3Attention, "__init__", record_init) config = SimpleNamespace( - pretrained_config=SimpleNamespace(model_type=model_type), + pretrained_config=SimpleNamespace(model_type="qwen3_5_moe_text"), mapping=SimpleNamespace(enable_attention_dp=False), + extra_attrs={"qwen3_next_decode_kernels": True} if enabled else {}, ) modeling_qwen3_next.Qwen3NextAttention(config, layer_idx=0, fuse_qk_norm_rope=True) assert built["use_gqa_decode_fmha"] is enabled assert built["cache_context_plan"] is enabled + assert built["fp8_output_gate"] is False + assert built["context_fmha_head_dim_per_stage_kv"] == 0 + + +@pytest.mark.parametrize("declared", [False, True]) +def test_attention_takes_the_prefill_kernels_where_the_model_declares_them( + monkeypatch, declared +) -> None: + """Qwen3_5MoeForCausalLM.prefill_kernels reaches the attention module as constructor arguments.""" + from tensorrt_llm._torch.models import modeling_qwen3_next + from tensorrt_llm._torch.models.modeling_qwen3 import Qwen3Attention + + built = {} + + def record_init(self, *args, **kwargs) -> None: + nn.Module.__init__(self) + built.update(kwargs) + + monkeypatch.setattr(Qwen3Attention, "__init__", record_init) + config = SimpleNamespace( + pretrained_config=SimpleNamespace(model_type="qwen3_5_moe_text", head_dim=256), + mapping=SimpleNamespace(enable_attention_dp=False), + extra_attrs={"qwen3_next_prefill_kernels": True} if declared else {}, + ) + + modeling_qwen3_next.Qwen3NextAttention(config, layer_idx=0, fuse_qk_norm_rope=True) + + assert built["fp8_output_gate"] is declared + assert built["context_fmha_head_dim_per_stage_kv"] == (256 if declared else 0) + assert built["context_last_rows_only"] is False + + +class _StopInit(Exception): + pass + + +@pytest.mark.parametrize("declared", [False, True]) +def test_mtp_attention_computes_only_last_context_rows_with_the_prefill_kernels( + monkeypatch, declared +) -> None: + """Only each context request's last MTP row feeds the draft token: with the prefill kernels the MTP layer + builds its attention to compute only those rows.""" + built = {} + + def record_init(self, *args, **kwargs) -> None: + built.update(kwargs) + raise _StopInit + + monkeypatch.setattr(Qwen3NextFullAttentionDecoderLayer, "__init__", record_init) + config = SimpleNamespace( + extra_attrs={"qwen3_next_prefill_kernels": True} if declared else {}, + ) + with pytest.raises(_StopInit): + Qwen3NextMTP(config, layer_idx=60, aux_stream_dict={AuxStreamType.Attention: None}) + + assert built["context_last_rows_only"] is declared + + +@pytest.mark.parametrize("declared,blackwell", [(False, True), (True, False), (True, True)]) +def test_decode_kernels_follow_the_model_declaration(monkeypatch, declared, blackwell) -> None: + """The decode paths follow the model class's ``decode_kernels`` declaration (on SM 10.0 / 10.3), not the + checkpoint's model type; both Qwen3.5 classes declare them.""" + from tensorrt_llm._torch.models import modeling_qwen3_next as m + from tensorrt_llm._torch.models.modeling_qwen3_5 import ( + Qwen3_5ForCausalLM, + Qwen3_5MoeForCausalLM, + ) + + assert Qwen3_5MoeForCausalLM.decode_kernels and Qwen3_5ForCausalLM.decode_kernels + assert not Qwen3NextForCausalLM.decode_kernels + + def stop(model_config): + raise _StopInit + + monkeypatch.setattr(m, "Qwen3NextModel", stop) + monkeypatch.setattr(m, "is_blackwell_datacenter", lambda: blackwell) + # A layout the decode kernels were tuned for (test_qwen3_next_decode_gates.py covers the layouts). + monkeypatch.setattr(m, "_decode_kernels_layout", lambda model_config: True) + model_cls = type("_Declared", (Qwen3NextForCausalLM,), {"decode_kernels": declared}) + config = SimpleNamespace( + pretrained_config=SimpleNamespace(model_type="qwen3_next"), + extra_attrs={}, + spec_config=None, + cuda_graph_batch_sizes=[1, 2], + mapping=SimpleNamespace(enable_attention_dp=False, dp_size=1), + ) + with pytest.raises(_StopInit): + model_cls(config) + assert m._uses_decode_kernels(config) is (declared and blackwell) + assert MoEDecodeOptions.of(config.extra_attrs).tuning is (declared and blackwell) + + +@pytest.mark.parametrize("sm", [90, 100, 103, 107, 120]) +def test_decode_kernels_need_blackwell_datacenter(monkeypatch, sm) -> None: + """The declared decode paths run on SM 10.0 / 10.3 only (not SM 10.7, 12.x or Hopper).""" + import tensorrt_llm._utils as utils + from tensorrt_llm._torch.models import modeling_qwen3_next as m + + def stop(model_config): + raise _StopInit + + monkeypatch.setattr(utils, "get_sm_version", lambda: sm) + monkeypatch.setattr(m, "Qwen3NextModel", stop) + monkeypatch.setattr(m, "_decode_kernels_layout", lambda model_config: True) + model_cls = type("_Declared", (Qwen3NextForCausalLM,), {"decode_kernels": True}) + config = SimpleNamespace( + pretrained_config=SimpleNamespace(model_type="qwen3_next"), + extra_attrs={}, + spec_config=None, + cuda_graph_batch_sizes=[1, 2], + mapping=SimpleNamespace(enable_attention_dp=False, dp_size=1), + ) + with pytest.raises(_StopInit): + model_cls(config) + assert utils.is_blackwell_datacenter() is (sm in (100, 103)) + assert m._uses_decode_kernels(config) is (sm in (100, 103)) + + +def test_next_layer_l2_prefetch_rows() -> None: + """The MoE-output all-reduce prefetches the next projection's weight from l2_prefetch_min_rows rows, except in + the rows the resident-weight GEMM takes it.""" + from tensorrt_llm._torch.models import modeling_qwen3_next as m + + weight = torch.zeros(8, 4) + layer = SimpleNamespace( + next_layer_prefetch_weight=weight, + l2_prefetch_min_rows=14, + next_layer_resident_rows=(14, 64), + ) + assert m._next_layer_l2_prefetch(layer, 7) is None + assert m._next_layer_l2_prefetch(layer, 14) is None + assert m._next_layer_l2_prefetch(layer, 64) is None + assert m._next_layer_l2_prefetch(layer, 65) is weight + layer.next_layer_resident_rows = (1, 0) + assert m._next_layer_l2_prefetch(layer, 14) is weight @pytest.mark.parametrize("can_defer_finalize", [False, True]) @@ -375,6 +505,8 @@ def mlp_forward(hidden_states, *args, do_finalize, fold_shared_expert, **kwargs) next_layer_layernorm=next_layer_norm, next_layer_input_scale=None, next_layer_reads_bf16=False, + next_layer_prefetch_weight=None, + post_moe_norm_fold=False, allreduce_fp8_payload=False, fusion_config=SimpleNamespace(PRE_MOE_FUSION=True, POST_MOE_FUSION=True), disable_attn_allreduce=True, @@ -405,3 +537,219 @@ def mlp_forward(hidden_states, *args, do_finalize, fold_shared_expert, **kwargs) assert ar_input is routed assert params.expanded_idx_to_permuted_idx is None assert params.expert_scale_factor is None + + +@pytest.mark.parametrize("fold", [False, True]) +def test_attention_dp_post_moe_chain_takes_the_norm_fold(monkeypatch, fold) -> None: + """Under attention DP a layer with ``post_moe_norm_fold`` asks the MoE block to defer its shared-expert + finalize and hands the deferred output to _post_moe_norm_fold instead of next_layer_layernorm.""" + from tensorrt_llm._torch.models import modeling_qwen3_next + + rows, hidden = 3, 4 + hidden_states = torch.randn(rows, hidden, dtype=torch.bfloat16) + residual = torch.randn_like(hidden_states) + deferred = _DeferredSharedExpertFinalize( + torch.randn_like(hidden_states), torch.randn_like(hidden_states), torch.randn(rows, 1) + ) + mlp_out = torch.randn_like(hidden_states) + + def mlp_forward(hidden_states, *args, defer_shared_expert_finalize, fold_shared_expert, **kw): + assert not fold_shared_expert + assert defer_shared_expert_finalize is fold + return deferred if defer_shared_expert_finalize else mlp_out + + folded = (torch.empty(rows, hidden, dtype=torch.float8_e4m3fn), residual) + fold_calls = [] + + def post_moe_norm_fold(layer, mlp_output, residual): + fold_calls.append(mlp_output) + return folded + + monkeypatch.setattr(modeling_qwen3_next, "_post_moe_norm_fold", post_moe_norm_fold) + next_layer_norm = MagicMock(side_effect=lambda h, r: (h, r)) + layer = SimpleNamespace( + layer_idx=0, + hidden_size=hidden, + post_moe_norm_fold=fold, + mixer_forward=MagicMock( + side_effect=lambda pos, h, md, sm, lora, all_reduce_params, **kw: h + ), + post_attention_layernorm=MagicMock(side_effect=lambda h, r: (h, r)), + next_layer_layernorm=next_layer_norm, + fusion_config=SimpleNamespace(PRE_MOE_FUSION=False, POST_MOE_FUSION=False), + disable_attn_allreduce=True, + mlp=MagicMock(side_effect=mlp_forward), + mapping=SimpleNamespace(tp_size=4), + ) + + out = _Qwen3NextDecoderLayerBase.forward( + layer, + position_ids=torch.arange(rows), + hidden_states=hidden_states, + attn_metadata=SimpleNamespace(), + residual=residual, + ) + + if fold: + assert fold_calls == [deferred] + assert out[0] is folded[0] and out[1] is folded[1] + next_layer_norm.assert_not_called() + else: + assert not fold_calls + assert out[0] is mlp_out + next_layer_norm.assert_called_once() + + +def _kept_rows_layer(rows, hidden, norm_fold=False): + """A decoder layer stub whose MLP is row-wise (its kept rows equal the full pass's rows) and records its input. + ``norm_fold``: the MLP defers its shared-expert finalize to the post-MoE norm fold (attention DP).""" + seen = {} + + def mlp_forward(hidden_states, attn_metadata, **kwargs): + seen["rows"] = hidden_states.shape[0] + seen["counts"] = attn_metadata.all_rank_num_tokens + if kwargs["defer_shared_expert_finalize"]: + return _DeferredSharedExpertFinalize( + hidden_states * 2, hidden_states - 1, hidden_states * 0.5 + ) + return hidden_states * 2 + + mlp = MagicMock(side_effect=mlp_forward) + mlp.can_defer_finalize = False + mlp.has_shared_expert = False + layer = SimpleNamespace( + layer_idx=0, + hidden_size=hidden, + input_layernorm=MagicMock(), + mixer_forward=MagicMock(side_effect=lambda pos, h, md, sm, lora, arp, **kw: h + 1), + post_attention_layernorm=MagicMock(side_effect=lambda h, r: (h, r + h)), + next_layer_layernorm=MagicMock(side_effect=lambda h, r: (h + r, r)), + fusion_config=SimpleNamespace(PRE_MOE_FUSION=False, POST_MOE_FUSION=False), + disable_attn_allreduce=True, + mlp=mlp, + mapping=SimpleNamespace(tp_size=1), + post_moe_norm_fold=norm_fold, + ) + return layer, seen + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="the row gather is a Triton kernel") +@pytest.mark.parametrize("norm_fold", [False, True], ids=["norm", "norm_fold"]) +@pytest.mark.parametrize("counts", [None, [3, 2]]) +@torch.no_grad() +def test_kept_rows_run_the_mlp_tail_on_those_rows_only(monkeypatch, counts, norm_fold) -> None: + """With ``kept_rows`` the layer runs its MLP and tail on the kept rows (under attention DP with every rank's + kept-row count installed), also through the post-MoE norm fold: the result is the full pass's rows at those + ids.""" + from tensorrt_llm._torch.models import modeling_qwen3_next as m + from tensorrt_llm._torch.speculative.kept_rows import DraftKeptRows + + def fold(layer, mlp_output, residual): + # row-wise stand-in for gate_add_rmsnorm_fp8: gate * shared + routed + residual + h = mlp_output.routed_output + torch.sigmoid(mlp_output.shared_gate_logits) * ( + mlp_output.shared_output + ) + return h + residual, residual + h + + monkeypatch.setattr(m, "_post_moe_norm_fold", fold) + + rows, hidden = 7, 4 + hidden_states = torch.randn(rows, hidden, device="cuda") + residual = torch.randn(rows, hidden, device="cuda") + ids = torch.tensor([6, 2, 3], device="cuda") + + def run(kept_rows): + layer, seen = _kept_rows_layer(rows, hidden, norm_fold) + md = SimpleNamespace(all_rank_num_tokens=[rows, rows]) + out = _Qwen3NextDecoderLayerBase.forward( + layer, + position_ids=torch.arange(rows, device="cuda"), + hidden_states=hidden_states.clone(), + attn_metadata=md, + residual=residual.clone(), + kept_rows=kept_rows, + ) + return out, seen + + (full_h, full_r), full_seen = run(None) + (kept_h, kept_r), kept_seen = run(DraftKeptRows(ids, counts, compact=True)) + assert full_seen["rows"] == rows and kept_seen["rows"] == ids.numel() + assert kept_seen["counts"] == (counts if counts is not None else [rows, rows]) + assert torch.equal(kept_h, full_h[ids]) and torch.equal(kept_r, full_r[ids]) + + +@pytest.mark.parametrize("compact", [True, False]) +@torch.no_grad() +def test_mtp_forward_returns_the_kept_rows(monkeypatch, compact) -> None: + """The MTP layer hands ``kept_rows`` to the decoder forward and returns its rows compact, or scattered back to + their positions (other rows zero); the rank token counts are restored either way.""" + from tensorrt_llm._torch.speculative.kept_rows import DraftKeptRows + + model = _new_mtp() + rows = 5 + ids = torch.tensor([4, 1]) + kept = DraftKeptRows(ids, [2, 2], compact=compact) + target_rank_tokens = [rows, rows] + attn_metadata = SimpleNamespace(all_rank_num_tokens=target_rank_tokens) + + def decoder_forward(self, **kwargs): + assert kwargs["kept_rows"] is kept + kwargs["attn_metadata"].all_rank_num_tokens = kept.all_rank_counts + return kwargs["hidden_states"].index_select(0, ids), None + + monkeypatch.setattr(Qwen3NextFullAttentionDecoderLayer, "forward", decoder_forward) + hidden_in = torch.randn(rows, 2) + embed = nn.Embedding(1, 2) + out = model( + input_ids=torch.zeros(rows, dtype=torch.long), + position_ids=torch.arange(rows), + hidden_states=hidden_in, + embed_tokens=embed, + attn_metadata=attn_metadata, + kept_rows=kept, + ) + # identity norms and fc: the layer input is concat(embedding, hidden) + expected = torch.cat([embed(torch.zeros(rows, dtype=torch.long)), hidden_in], dim=-1)[ids] + if compact: + assert torch.equal(out, expected) + else: + assert out.shape == (rows, 4) and torch.equal(out[ids], expected) + assert not out[[0, 2, 3]].any() + assert attn_metadata.all_rank_num_tokens is target_rank_tokens + + +@pytest.mark.parametrize( + "batch,attention_dp,large_rows,kept_rows", + [ + # (largest CUDA-graph decode batch, attention DP): reference GEN layouts at 7 rows per request + (1, False, 448, False), # TEP16 b1 + (2, False, 448, True), # TEP8 b2 + (5, False, 448, True), # TEP8 b5 + (8, False, 448, True), # TEP8 b8 + (16, False, 448, True), # TEP8 b16 + (64, False, 448, True), # TEP8 b64: 448 rows from full steps + (128, False, 448, True), + (52, True, 448, True), # DEP4 b52: 364 rows per rank, below 448 + ], +) +def test_decode_layout_decisions(monkeypatch, batch, attention_dp, large_rows, kept_rows) -> None: + """Where the Qwen3.5 decode paths engage, derived from the layout (MTP rows per request, CUDA-graph batch + sizes, attention DP): the large-step rows (tcgen05 GDN verify, the MoE engine's spare SMs), pass 0's kept rows, + the state promotion beside the draft loop (TP decode kernels, every layout) and the expert prefetch's budgeted + steps.""" + from tensorrt_llm._torch.models import modeling_qwen3_next as m + + monkeypatch.setattr(m, "_uses_decode_kernels", lambda model_config: True) + model_config = SimpleNamespace( + spec_config=SimpleNamespace(tokens_per_gen_step=7), + cuda_graph_batch_sizes=list(range(1, batch + 1)), + mapping=SimpleNamespace(enable_attention_dp=attention_dp), + ) + assert m._large_step_rows(model_config) == large_rows + # tcgen05 GDN verify: every step under attention DP, large steps with TP attention + assert m._verify_tcgen05_min_rows(model_config) == (7 if attention_dp else large_rows) + assert m.Qwen3NextMTP.takes_kept_rows(model_config) == kept_rows + assert m.Qwen3NextMTP.promotes_target_state_beside(model_config) == (not attention_dp) + # Expert prefetch rank + issue budget per step: 3..5 requests (TEP8 b5's steady step, not b2's or b8's) + lo, hi = m._expert_prefetch_budget_rows(model_config) + assert [r for r in range(1, 10) if lo < 7 * r <= hi] == [3, 4, 5] diff --git a/tests/unittest/_torch/models/test_qwen3_next_moe_sm_reserve.py b/tests/unittest/_torch/models/test_qwen3_next_moe_sm_reserve.py new file mode 100644 index 000000000000..e8fb4f9270ea --- /dev/null +++ b/tests/unittest/_torch/models/test_qwen3_next_moe_sm_reserve.py @@ -0,0 +1,79 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Qwen3.5's MoE block asks the routed experts' backend for the shared expert's SMs per forward, through +MoEImplBase.reserve_sms_for_concurrent_kernels.""" + +from types import SimpleNamespace + +import pytest + +from tensorrt_llm._torch.models.modeling_qwen3_next import Qwen3NextSparseMoeBlock +from tensorrt_llm._torch.modules.multi_stream_utils import with_multi_stream +from tensorrt_llm._torch.moe.fused_moe.configurable_moe import ConfigurableMoE + +CEILING = 8 +# 64 requests of an MTP 6 decode step (7 rows each): _large_step_rows. +RESERVE_ROWS = 64 * 7 + + +class _Backend: + def __init__(self) -> None: + self.asked: list[int] = [] + + def sm_reserve_ceiling(self) -> int: + return CEILING + + def reserve_sms_for_concurrent_kernels(self, num_sms: int) -> int: + self.asked.append(num_sms) + return num_sms + + +def _block(reserve_rows: int, aux_stream: object = object()) -> SimpleNamespace: + experts = ConfigurableMoE.__new__(ConfigurableMoE) + object.__setattr__(experts, "backend", _Backend()) + return SimpleNamespace( + experts=experts, aux_stream=aux_stream, _shared_expert_reserve_rows=reserve_rows + ) + + +@pytest.mark.parametrize( + "multi_stream,rows,expect", + [ + (True, RESERVE_ROWS, CEILING), + (True, RESERVE_ROWS + 70, CEILING), + (True, RESERVE_ROWS - 1, 0), + (False, RESERVE_ROWS, 0), + ], +) +def test_shared_expert_sms_are_asked_per_forward(multi_stream, rows, expect) -> None: + """The backend's ceiling where the shared expert runs beside the routed experts (multi-stream) on a step of at + least _shared_expert_reserve_rows rows; 0 for smaller or in-order steps, so the grid keeps every SM.""" + block = _block(RESERVE_ROWS) + with with_multi_stream(multi_stream): + Qwen3NextSparseMoeBlock._reserve_sms_for_shared_expert(block, rows) + assert block.experts.backend.asked == [expect] + + +def test_no_reserve_without_the_declared_rows_or_an_aux_stream() -> None: + """Without the decode kernels' rows (no MTP, or another model) nothing is asked; without an aux stream the shared + expert runs in order, so the grid keeps every SM.""" + block = _block(0) + with with_multi_stream(True): + Qwen3NextSparseMoeBlock._reserve_sms_for_shared_expert(block, RESERVE_ROWS) + assert block.experts.backend.asked == [] + block = _block(RESERVE_ROWS, aux_stream=None) + with with_multi_stream(True): + Qwen3NextSparseMoeBlock._reserve_sms_for_shared_expert(block, RESERVE_ROWS) + assert block.experts.backend.asked == [0] diff --git a/tests/unittest/_torch/models/test_qwen3next_moe_allreduce_guard.py b/tests/unittest/_torch/models/test_qwen3next_moe_allreduce_guard.py index 7016e61d7000..695bdae217b6 100644 --- a/tests/unittest/_torch/models/test_qwen3next_moe_allreduce_guard.py +++ b/tests/unittest/_torch/models/test_qwen3next_moe_allreduce_guard.py @@ -46,6 +46,7 @@ def _fake_model_config(mapping: _FakeMapping) -> SimpleNamespace: mapping=mapping, allreduce_strategy=None, mnnvl_allreduce_fp8_payload=False, + extra_attrs={}, ) diff --git a/tests/unittest/_torch/models/test_qwen3next_moe_input_dual_quant.py b/tests/unittest/_torch/models/test_qwen3next_moe_input_dual_quant.py new file mode 100644 index 000000000000..975b085473e6 --- /dev/null +++ b/tests/unittest/_torch/models/test_qwen3next_moe_input_dual_quant.py @@ -0,0 +1,101 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Which Qwen3Next MoE blocks quantize a context-sized input once for both expert paths. + +The routed experts must take an NVFP4 input quantized ahead of them (``ConfigurableMoE.nvfp4_input_scale``) +and the shared expert's fused gate_up must be an FP8 projection with a static input scale. The blocks and +backends are built without ``__init__``; no GPU is needed. +""" + +from types import SimpleNamespace + +import pytest +import torch +from torch import nn + +from tensorrt_llm._torch.models.modeling_qwen3_next import Qwen3NextSparseMoeBlock +from tensorrt_llm._torch.modules.linear import FP8QDQLinearMethod +from tensorrt_llm._torch.moe.fused_moe.configurable_moe import ConfigurableMoE +from tensorrt_llm._torch.moe.fused_moe.cutedsl.grouped_gemm.nvfp4 import ( + TrtllmCutedslGroupedGemmNvfp4Impl, +) +from tensorrt_llm._torch.moe.fused_moe.impl_base import MoEImplBase + +pytestmark = pytest.mark.cpu_only + + +def _bare(cls): + module = cls.__new__(cls) + nn.Module.__init__(module) + return module + + +def _nvfp4_grouped_gemm_backend() -> TrtllmCutedslGroupedGemmNvfp4Impl: + backend = _bare(TrtllmCutedslGroupedGemmNvfp4Impl) + backend.fc31_input_scale = torch.tensor([448.0 * 6.0], dtype=torch.float32) + return backend + + +def _block(backend, *, declared: bool = True, comm=None) -> Qwen3NextSparseMoeBlock: + experts = _bare(ConfigurableMoE) + experts.backend = backend + experts.comm = comm + experts.apply_router_weight_on_input = False + experts.layer_load_balancer = None + experts.moe_max_num_tokens = 16384 + gate_up = SimpleNamespace( + quant_method=FP8QDQLinearMethod(), + dtype=torch.bfloat16, + input_scale=torch.tensor([0.5], dtype=torch.float32), + force_dynamic_quantization=False, + _locality_domain_weight_shards=None, + ) + block = _bare(Qwen3NextSparseMoeBlock) + block.moe_input_dual_quant = declared + block.experts = experts + block.shared_expert = SimpleNamespace( + split_gate_up=False, _can_fuse_gate_up_swiglu=lambda: False, gate_up_proj=gate_up + ) + return block + + +def test_dual_quant_with_nvfp4_grouped_gemm_experts(): + assert _block(_nvfp4_grouped_gemm_backend())._moe_input_dual_quant_supported() + + +@pytest.mark.parametrize("blocker", ["not_declared", "backend_quantizes_itself", "comm"]) +def test_dual_quant_declined(blocker): + backend = _nvfp4_grouped_gemm_backend() + if blocker == "backend_quantizes_itself": + # MoEImplBase's default: the backend takes no pre-quantized NVFP4 input. + backend.prequantized_nvfp4_input_scale = lambda: MoEImplBase.prequantized_nvfp4_input_scale( + backend + ) + block = _block( + backend, + declared=blocker != "not_declared", + comm=object() if blocker == "comm" else None, + ) + assert not block._moe_input_dual_quant_supported() + + +def test_prefill_kernels_declared_by_qwen3_5_moe_only(): + """Only the Qwen3.5 MoE class declares the prefill-sized kernels (dual quant included); dense Qwen3.5 (also + MiniCPM-V 4.6's inner LM) and Qwen3Next keep the stock paths.""" + from tensorrt_llm._torch.model_config import ModelConfig + from tensorrt_llm._torch.models.modeling_qwen3_5 import ( + Qwen3_5ForCausalLM, + Qwen3_5MoeForCausalLM, + ) + from tensorrt_llm._torch.models.modeling_qwen3_next import ( + Qwen3NextForCausalLM, + _uses_prefill_kernels, + ) + + assert Qwen3_5MoeForCausalLM.prefill_kernels + assert not Qwen3_5ForCausalLM.prefill_kernels + assert not Qwen3NextForCausalLM.prefill_kernels + config = ModelConfig() + assert not _uses_prefill_kernels(config) + config.extra_attrs["qwen3_next_prefill_kernels"] = True + assert _uses_prefill_kernels(config) diff --git a/tests/unittest/_torch/modules/mamba/test_gdn_direct_launch.py b/tests/unittest/_torch/modules/mamba/test_gdn_direct_launch.py index 80e08fe92291..5f3383d31da2 100644 --- a/tests/unittest/_torch/modules/mamba/test_gdn_direct_launch.py +++ b/tests/unittest/_torch/modules/mamba/test_gdn_direct_launch.py @@ -147,3 +147,139 @@ def run(direct): assert launched["decode"] == ( 1 if fsg.flashinfer_gdn_decode_direct_available(torch.bfloat16, 128, 128) else 0 ) + + +def _make_fused_prefill_mixer() -> Qwen3NextGatedDeltaNet: + """A mixer whose shapes take the fused prefill conv (q / k and v channels in whole 1024-channel programs).""" + config = Qwen3NextConfig( + hidden_size=256, + intermediate_size=512, + num_hidden_layers=1, + num_attention_heads=4, + num_key_value_heads=2, + linear_num_key_heads=4, + linear_num_value_heads=8, + linear_key_head_dim=128, + linear_value_head_dim=128, + linear_conv_kernel_dim=4, + vocab_size=1024, + torch_dtype=torch.bfloat16, + ) + mixer = Qwen3NextGatedDeltaNet( + ModelConfig(pretrained_config=config), + aux_stream=torch.cuda.Stream(), + layer_idx=0, + fused_prefill=True, + ).cuda() + torch.manual_seed(2) + with torch.no_grad(): + for p in mixer.parameters(): + if p.dim() == 2: + p.copy_(torch.randn_like(p, dtype=torch.float32) * 0.02) + mixer.post_load_weights() + return mixer + + +@pytest.mark.skipif(not _sm100(), reason="FlashInfer GDN prefill kernels (SM100/SM103)") +@pytest.mark.parametrize("ctx_lens", [[70, 45], [130, 1, 300]]) +@torch.no_grad() +def test_fused_prefill_conv_takes_the_direct_scan_launch(monkeypatch, ctx_lens): + """A context-only batch on the fused prefill conv writes the shared scratch and launches FlashInfer's scan + straight from its packed views: the launcher gets bit-identical q / k / v / alpha / beta, slots and lengths as + through the public adapter, and the output and states are bitwise the adapter's.""" + monkeypatch.setenv("FORCE_DETERMINISTIC", "0") + if not gm._gdn_prefill_uses_flashinfer(): + pytest.skip("FlashInfer GDN prefill is unavailable") + dev = "cuda" + mixer = _make_fused_prefill_mixer() + assert mixer.fused_prefill_conv + conv_dim = mixer.conv_dim_per_tp + width = mixer.conv_kernel_size - 1 + batch = len(ctx_lens) + slots = [3, 1, 4][:batch] + seq_lens = torch.tensor(ctx_lens, dtype=torch.int) + total = sum(ctx_lens) + x = torch.randn(total, mixer.hidden_size, dtype=torch.bfloat16, device=dev) + conv0 = torch.randn(batch + 8, conv_dim, width, dtype=torch.bfloat16, device=dev) + ssm0 = ( + torch.randn(batch + 8, mixer.num_v_heads_per_tp, 128, 128, dtype=torch.bfloat16, device=dev) + * 0.01 + ) + real_launcher = fc._sm100_direct_launcher() + if real_launcher is None: + pytest.skip("FlashInfer's direct GDN launcher is unavailable") + real_scan = gm.chunk_gated_delta_rule_indexed_direct + + def run(direct): + launched = {"direct": 0, "inputs": None} + + def recording_launcher(q, k, v, gate, beta, out, cu, init, final, scale, state_indices): + launched["inputs"] = [t.clone() for t in (q, k, v, gate, beta, cu, state_indices)] + [ + scale + ] + return real_launcher( + q, k, v, gate, beta, out, cu, init, final, scale, state_indices=state_indices + ) + + def counting_scan(*a, **k): + r = real_scan(*a, **k) + launched["direct"] += int(bool(r)) + return r + + conv, ssm = conv0.clone(), ssm0.clone() + layer_cache = SimpleNamespace( + conv=conv, temporal=ssm, intermediate_conv_window=None, intermediate_ssm=None + ) + manager = _CacheManager(slots) + manager.mamba_layer_cache = lambda layer_idx: layer_cache + manager.is_speculative = lambda: False + md = Mamba2Metadata(max_batch_size=128, chunk_size=64) + attn = SimpleNamespace( + seq_lens=seq_lens, + seq_lens_cuda=seq_lens.cuda(), + num_contexts=batch, + num_ctx_tokens=total, + num_tokens=total, + kv_cache_manager=manager, + request_ids=list(range(100, 100 + batch)), + kv_cache_params=SimpleNamespace( + num_cached_tokens_per_seq=torch.tensor([0, 9, 0][:batch], dtype=torch.int) + ), + ) + md.prepare(attn) + out = torch.empty(1, total, mixer.num_v_heads_per_tp, 128, dtype=torch.bfloat16, device=dev) + with monkeypatch.context() as m: + m.setattr(fc, "_sm100_direct_launcher", lambda: recording_launcher) + if direct: + m.setattr(gm, "chunk_gated_delta_rule_indexed_direct", counting_scan) + else: + m.setattr(gm, "chunk_gated_delta_rule_indexed_direct", lambda *a, **k: False) + fused_calls = [] + real_fused = gm.gdn_prefill_conv_post + m.setattr( + gm, + "gdn_prefill_conv_post", + lambda *a, **k: fused_calls.append(1) or real_fused(*a, **k), + ) + mixed_qkv, z, a, b, _ = mixer._compute_tokenwise_inputs(x) + mixer.forward_core(mixed_qkv, a, b, attn, md, output=out) + torch.cuda.synchronize() + assert fused_calls == [1], "the batch must take the fused prefill conv" + return out.clone(), conv, ssm, launched + + out_ref, conv_ref, ssm_ref, via_adapter = run(False) + out_got, conv_got, ssm_got, direct = run(True) + assert direct["direct"] == 1, "the fused branch must hand FlashInfer its packed scratch views" + assert via_adapter["inputs"] is not None and direct["inputs"] is not None + for name, a, b in zip( + ("q", "k", "v", "alpha", "beta", "cu_seqlens", "slots", "scale"), + direct["inputs"], + via_adapter["inputs"], + ): + if isinstance(a, torch.Tensor): + assert a.shape == b.shape and a.dtype == b.dtype, name + assert torch.equal(a.view(torch.uint8), b.view(torch.uint8)), name + else: + assert a == b, name + assert torch.equal(out_got, out_ref) + assert torch.equal(conv_got, conv_ref) and torch.equal(ssm_got, ssm_ref) diff --git a/tests/unittest/_torch/modules/mamba/test_gdn_inforward_snapshot.py b/tests/unittest/_torch/modules/mamba/test_gdn_inforward_snapshot.py index 4250a9a56085..042eb61b377c 100644 --- a/tests/unittest/_torch/modules/mamba/test_gdn_inforward_snapshot.py +++ b/tests/unittest/_torch/modules/mamba/test_gdn_inforward_snapshot.py @@ -19,6 +19,7 @@ import pytest import torch +from tensorrt_llm._torch.modules.mamba import gdn_inforward_split from tensorrt_llm._torch.modules.mamba.causal_conv1d import causal_conv1d_fn from tensorrt_llm._torch.modules.mamba.gdn_mixer import ( _gdn_prefill_uses_flashinfer, @@ -203,3 +204,221 @@ def test_split_conv_states_match_two_iterations(): assert torch.equal(conv_states, expected_live) assert torch.equal(stage, expected_stage) assert torch.equal(out, expected_out) + + +def _random_states(rows, seed): + torch.manual_seed(seed) + return torch.randn(rows, NUM_V_HEADS, HEAD_DIM, HEAD_DIM, device="cuda").to(torch.bfloat16) + + +def test_split_kernels_match_index_ops(): + """Each gdn_inforward_split launch writes exactly the bytes of the index ops it replaces.""" + split = _split() + total = sum(length for _, _, length, _ in _BATCH) + q, k, v, g, beta = _inputs(total, seed=2) + # One final state per chunked-prefill sequence: a split request runs as two. + final = _random_states(split.gather.numel(), seed=3) + ssm_states = _random_states(NUM_SLOTS, seed=4) + assert gdn_inforward_split.split_core_ok( + q, + k, + v, + g, + beta, + final, + ssm_states, + ssm_states[:4], + q.new_empty(1, total, NUM_V_HEADS, HEAD_DIM), + ) + + # Final states into the live slots, and the tails' initial states. + expected_ssm = ssm_states.clone() + expected_ssm.index_copy_(0, split.live, final.index_select(0, split.main_rows)) + tail_init = gdn_inforward_split.split_state_rows(final, ssm_states, split) + assert torch.equal(ssm_states, expected_ssm) + assert torch.equal(tail_init, final.index_select(0, split.split_rows)) + + # Tail tokens. + gathered = gdn_inforward_split.gather_tail_tokens(q, k, v, g, beta, split) + for got, x in zip(gathered, (q, k, v, g, beta)): + assert torch.equal(got, x.index_select(1, split.tail_tok)) + + # Tail final states into the staging rows, tail outputs into the output. + tail_final = _random_states(split.k, seed=5) + tail_out = torch.randn(1, split.num_tail_tokens, NUM_V_HEADS, HEAD_DIM, device="cuda").to( + torch.bfloat16 + ) + stage = _random_states(4, seed=6) + core_out = torch.randn(1, total, NUM_V_HEADS, HEAD_DIM, device="cuda").to(torch.bfloat16) + expected_stage, expected_out = stage.clone(), core_out.clone() + expected_stage.index_copy_(0, split.stage_rows, tail_final) + expected_out[0].index_copy_(0, split.tail_tok, tail_out[0]) + # Rows whose inner dims are not packed are refused, with nothing written. + wide = torch.zeros(1, total, NUM_V_HEADS, 2 * HEAD_DIM, dtype=core_out.dtype, device="cuda") + assert not gdn_inforward_split.scatter_tail( + tail_final, stage, tail_out, wide[..., :HEAD_DIM], split + ) + strided_stage = stage.transpose(2, 3) + assert not gdn_inforward_split.scatter_tail( + tail_final, strided_stage, tail_out, core_out, split + ) + assert not wide.any() + assert gdn_inforward_split.scatter_tail(tail_final, stage, tail_out, core_out, split) + assert torch.equal(stage, expected_stage) + assert torch.equal(core_out, expected_out) + + +def test_split_conv_states_kernel_matches_index_ops(): + split = _split() + total = sum(length for _, _, length, _ in _BATCH) + torch.manual_seed(7) + mixed_qkv = torch.randn(total, CONV_DIM, device="cuda").to(torch.bfloat16) + conv_states = torch.randn(NUM_SLOTS, CONV_DIM, D_CONV - 1, device="cuda").to(torch.bfloat16) + stage = torch.randn(4, CONV_DIM, D_CONV - 1, device="cuda").to(torch.bfloat16) + expected_states, expected_stage = conv_states.clone(), stage.clone() + _inforward_split_conv_states( + expected_states, mixed_qkv.index_select(0, split.conv_win), split, expected_stage + ) + assert gdn_inforward_split.split_conv_states_ok(conv_states, mixed_qkv, stage) + gdn_inforward_split.split_conv_states(conv_states, mixed_qkv, split, stage) + assert torch.equal(conv_states, expected_states) + assert torch.equal(stage, expected_stage) + + +def test_split_prefill_core_fused_copies_bitwise(): + """fused_copies only changes how the states and tokens move: outputs and states are bit-identical.""" + split = _split() + total = sum(length for _, _, length, _ in _BATCH) + q, k, v, g, beta = _inputs(total, seed=8) + results = [] + for fused_copies in (False, True): + ssm_states = _random_states(NUM_SLOTS, seed=9) * 0.01 + stage = torch.zeros(4, NUM_V_HEADS, HEAD_DIM, HEAD_DIM, dtype=torch.bfloat16, device="cuda") + out = _inforward_split_prefill_core( + q, + k, + v, + g, + beta, + ssm_states, + split, + stage, + None, + g_is_linear=False, + fused_copies=fused_copies, + ) + results.append((out, ssm_states, stage)) + for reference, fused in zip(*results): + assert torch.equal(reference, fused) + + +@pytest.mark.parametrize("fused_copies", [False, True]) +def test_split_prefill_core_alpha_bitwise(fused_copies): + """alpha = exp(g) as the gate (g_is_linear; the tails gather it in place of g) gives the bits of g alone.""" + if not _gdn_prefill_uses_flashinfer(): + pytest.skip("only the FlashInfer scan takes the linear-space gate") + split = _split() + total = sum(length for _, _, length, _ in _BATCH) + q, k, v, g, beta = _inputs(total, seed=10) + results = [] + for linear_gate in (False, True): + ssm_states = _random_states(NUM_SLOTS, seed=11) * 0.01 + stage = torch.zeros(4, NUM_V_HEADS, HEAD_DIM, HEAD_DIM, dtype=torch.bfloat16, device="cuda") + out = _inforward_split_prefill_core( + q, + k, + v, + torch.exp(g) if linear_gate else g, + beta, + ssm_states, + split, + stage, + None, + g_is_linear=linear_gate, + fused_copies=fused_copies, + ) + results.append((out, ssm_states, stage)) + for reference, with_alpha in zip(*results): + assert torch.equal(reference, with_alpha) + + +def test_split_kernels_compile_once_for_every_batch(): + """The state-row split and the tail scatter take the batch's live / split counts at run time: one compiled + variant each serves counts of 1, 2, 16 and 3 (no in-step compile for a new count class).""" + from _torch.helpers import triton_num_compiled + + def states(rows, seed): + return _random_states(rows, seed) + + def run(n_live, k): + cuda = torch.device("cuda") + split = types.SimpleNamespace( + live=torch.arange(n_live, dtype=torch.int32, device=cuda) % NUM_SLOTS, + main_rows=torch.arange(n_live, dtype=torch.int32, device=cuda), + split_rows=torch.arange(k, dtype=torch.int32, device=cuda), + k=k, + stage_rows=torch.arange(k, dtype=torch.int32, device=cuda), + tail_tok=torch.arange(2, dtype=torch.int32, device=cuda), + ) + final = states(max(n_live, k), seed=n_live) + ssm = states(NUM_SLOTS, seed=k) + expected_ssm = ssm.clone() + expected_ssm.index_copy_(0, split.live.long(), final.index_select(0, split.main_rows)) + tail_init = gdn_inforward_split.split_state_rows(final, ssm, split) + if n_live <= NUM_SLOTS: # distinct live slots + assert torch.equal(ssm, expected_ssm) + assert torch.equal(tail_init, final.index_select(0, split.split_rows)) + stage = states(k, seed=7) + tail_final = states(k, seed=8) + tail_out = torch.randn(1, 2, NUM_V_HEADS, HEAD_DIM, device=cuda).to(torch.bfloat16) + core_out = torch.zeros(1, 4, NUM_V_HEADS, HEAD_DIM, dtype=torch.bfloat16, device=cuda) + assert gdn_inforward_split.scatter_tail(tail_final, stage, tail_out, core_out, split) + assert torch.equal(stage, tail_final) + + run(3, 3) + before = ( + triton_num_compiled(gdn_inforward_split._split_state_rows_kernel), + triton_num_compiled(gdn_inforward_split._tail_scatter_kernel), + ) + for n_live, k in ((1, 1), (2, 2), (16, 16), (8, 3)): + run(n_live, k) + assert ( + triton_num_compiled(gdn_inforward_split._split_state_rows_kernel), + triton_num_compiled(gdn_inforward_split._tail_scatter_kernel), + ) == before + + +def test_conv_state_and_tail_gather_kernels_compile_once_for_every_batch(): + """The conv-state split and the tail-token gather take their counts as grid sizes and their strides from the + model's fixed widths: the variant compiled for the first split batch (the startup warmup's) serves every later + split count, so serving compiles none of the four split kernels.""" + from _torch.helpers import triton_num_compiled + + cuda = torch.device("cuda") + q, k, v, g, beta = _inputs(64, seed=3) + + def run(num_splits, num_tail): + split = types.SimpleNamespace( + k=num_splits, + tail_slots=torch.arange(num_splits, dtype=torch.long, device=cuda) % NUM_SLOTS, + stage_rows=torch.arange(num_splits, dtype=torch.long, device=cuda), + conv_win=torch.arange(num_splits * (D_CONV - 1), dtype=torch.long, device=cuda) % 64, + tail_tok=torch.arange(num_tail, dtype=torch.long, device=cuda), + ) + mixed_qkv = torch.randn(64, CONV_DIM, device=cuda).to(torch.bfloat16) + conv_states = torch.randn(NUM_SLOTS, CONV_DIM, D_CONV - 1, device=cuda).to(torch.bfloat16) + stage = torch.zeros(NUM_SLOTS, CONV_DIM, D_CONV - 1, dtype=torch.bfloat16, device=cuda) + gdn_inforward_split.split_conv_states(conv_states, mixed_qkv, split, stage) + outs = gdn_inforward_split.gather_tail_tokens(q, k, v, g, beta, split) + for x, o in zip((q, k, v, g, beta), outs): + assert torch.equal(o, x.index_select(1, split.tail_tok)) + + kernels = ( + gdn_inforward_split._split_conv_state_kernel, + gdn_inforward_split._tail_token_gather_kernel, + ) + run(2, 4) + before = tuple(triton_num_compiled(kernel) for kernel in kernels) + for num_splits, num_tail in ((1, 1), (3, 17), (8, 64), (5, 2)): + run(num_splits, num_tail) + assert tuple(triton_num_compiled(kernel) for kernel in kernels) == before diff --git a/tests/unittest/_torch/modules/mamba/test_gdn_mixed_decode.py b/tests/unittest/_torch/modules/mamba/test_gdn_mixed_decode.py index 431212d281a7..e0967fe248a0 100644 --- a/tests/unittest/_torch/modules/mamba/test_gdn_mixed_decode.py +++ b/tests/unittest/_torch/modules/mamba/test_gdn_mixed_decode.py @@ -201,6 +201,87 @@ def observe_direct(*args, **kwargs): torch.testing.assert_close(actual_conv, expected_conv, rtol=0, atol=0) +@pytest.mark.parametrize("deterministic", [True, False]) +@pytest.mark.parametrize("use_flashinfer", [False, True]) +@pytest.mark.parametrize("prefill_lengths", [(127,), (7, 129)]) +def test_fused_prefill_conv_under_force_deterministic( + monkeypatch: pytest.MonkeyPatch, + request: pytest.FixtureRequest, + deterministic: bool, + use_flashinfer: bool, + prefill_lengths: tuple[int, ...], +) -> None: + """FORCE_DETERMINISTIC=1 skips the fused prefill conv, so a prompt prefilled alone gets the GDN state it + gets next to decodes; without it a context-only batch keeps the fused path.""" + monkeypatch.setenv("FORCE_DETERMINISTIC", "1" if deterministic else "0") + monkeypatch.setenv("TLLM_USE_FLASHINFER_GDN_PREFILL", "1" if use_flashinfer else "0") + if use_flashinfer and not gdn_mixer._use_flashinfer_gdn_prefill(): + pytest.skip("FlashInfer GDN prefill is unavailable on this GPU") + gdn_mixer._resolve_chunk_gated_delta_rule.cache_clear() + request.addfinalizer(gdn_mixer._resolve_chunk_gated_delta_rule.cache_clear) + torch.manual_seed(42) + layer = _make_layer() + layer.conv_kernel_size, layer.conv_dim_per_tp = 4, 2048 + assert gdn_mixer.gdn_prefill_conv_supported(128, 128, 4, "silu", 2048, 4) + layer.fused_prefill_conv = True + num_decodes, num_slots = 3, 7 + num_prefills, prefill_length = len(prefill_lengths), sum(prefill_lengths) + num_tokens = prefill_length + num_decodes + projected = torch.randn(num_tokens, 3072, device="cuda", dtype=torch.bfloat16) * 0.1 + gates = torch.randn(num_tokens, 16, device="cuda", dtype=torch.bfloat16) * 0.1 + conv = torch.randn(num_slots, 2048, 3, device="cuda", dtype=torch.bfloat16) * 0.1 + state = torch.randn(num_slots, 8, 128, 128, device="cuda", dtype=torch.float32) * 0.1 + indices = torch.tensor([5, 4][:num_prefills] + [3, 0, 6], device="cuda", dtype=torch.int32) + lengths = [0, *prefill_lengths, *([1] * num_decodes)] + positions = torch.tensor(lengths, device="cuda", dtype=torch.int32).cumsum(0, dtype=torch.int32) + + def run(batch_decodes: int): + tokens = prefill_length + batch_decodes + batch = num_prefills + batch_decodes + conv_states, ssm_states = conv.clone(), state.clone() + # The decode convolution writes into its input, so each run gets fresh inputs. + mixed_qkv = projected.clone()[:tokens, :2048] + b, a = gates[:tokens, :8].clone(), gates[:tokens, 8:].clone() + with patch.object( + gdn_mixer, "gdn_prefill_conv_post", wraps=gdn_mixer.gdn_prefill_conv_post + ) as fused_call: + out = layer.forward_extend( + conv_states, + ssm_states, + mixed_qkv=mixed_qkv, + a=a, + b=b, + batch_size=batch, + has_initial_states=torch.ones(batch, device="cuda", dtype=torch.bool), + cache_indices=indices[:batch], + query_start_loc=positions[: batch + 1], + query_start_loc_long=positions[: batch + 1].long(), + num_prefill_tokens=prefill_length, + num_decode_tokens=batch_decodes, + state_indices_p=indices[:num_prefills], + state_indices_d=indices[num_prefills:batch], + num_prefill=num_prefills, + num_decodes=batch_decodes, + ) + return out[:, :prefill_length], conv_states, ssm_states, fused_call.call_count + + # Warm chunk tuning with disposable state, as in the mixed-batch test above. + run(0) + alone, alone_conv, alone_state, alone_fused = run(0) + if not deterministic: + assert alone_fused == 1 + return + assert alone_fused == 0 + mixed, mixed_conv, mixed_state, mixed_fused = run(num_decodes) + assert mixed_fused == 0 + prefill_slots = indices[:num_prefills] + torch.testing.assert_close(mixed, alone, rtol=0, atol=0) + torch.testing.assert_close( + mixed_state[prefill_slots], alone_state[prefill_slots], rtol=0, atol=0 + ) + torch.testing.assert_close(mixed_conv[prefill_slots], alone_conv[prefill_slots], rtol=0, atol=0) + + def test_forward_core_runs_prefill_groups_from_host_offsets( request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tests/unittest/_torch/modules/mamba/test_gdn_prefill_conv.py b/tests/unittest/_torch/modules/mamba/test_gdn_prefill_conv.py new file mode 100644 index 000000000000..b8d403ae87e5 --- /dev/null +++ b/tests/unittest/_torch/modules/mamba/test_gdn_prefill_conv.py @@ -0,0 +1,231 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""gdn_prefill_conv_post against the stock GDN prefill pipeline. + +extract_transpose_prefill_slice + causal_conv1d_fn + fused_gdn_post_conv: g, beta and the new conv states are +bitwise equal; q / k differ in the FP32 summation order of their L2 norms, and q / k / v in the SiLU, which the +stock CUDA conv takes through tanh.approx above -7 (causalConv1d.cu) and the fused kernel exactly. The linear-space +gate alpha = exp(g) is libdevice expf (torch.exp's bits), a few FP32 ulp from the stock kernel's tl.exp +(fused_gdn_post_conv(g_linear=True)). The value-head counts include ones that are not powers of two (24 / 48 per +rank). +""" + +import pytest +import torch + +from tensorrt_llm._torch.modules.mamba.causal_conv1d import causal_conv1d_fn +from tensorrt_llm._torch.modules.mamba.fuse_elementwise_ops import ( + extract_transpose_prefill_slice, + fused_gdn_post_conv, +) +from tensorrt_llm._torch.modules.mamba.gdn_prefill_conv import ( + gdn_prefill_conv_post, + gdn_prefill_conv_supported, +) + +pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required") + +HEAD_DIM = 128 + + +def _inputs(lens, num_k_heads, num_v_heads, *, pad_seqs=(), extra_tokens=0, seed=0): + g = torch.Generator(device="cuda").manual_seed(seed) + conv_dim = (2 * num_k_heads + num_v_heads) * HEAD_DIM + num_tokens = sum(lens) + extra_tokens + num_seqs = len(lens) + num_slots = 2 * num_seqs + 1 + ab = torch.randn(num_tokens, 2 * num_v_heads, device="cuda", generator=g).to(torch.bfloat16) + return dict( + mixed_qkv=torch.randn(num_tokens, conv_dim, device="cuda", generator=g).to(torch.bfloat16), + weight=(torch.randn(conv_dim, 1, 4, device="cuda", generator=g) * 0.5).to(torch.bfloat16), + conv_states=torch.randn(num_slots, conv_dim, 3, device="cuda", generator=g).to( + torch.bfloat16 + ), + query_start_loc=torch.tensor( + [0] + torch.tensor(lens).cumsum(0).tolist(), device="cuda", dtype=torch.int32 + ), + cache_indices=torch.tensor( + [-1 if i in pad_seqs else 2 * i + 1 for i in range(num_seqs)], + device="cuda", + dtype=torch.int32, + ), + has_initial_state=torch.rand(num_seqs, device="cuda", generator=g) < 0.5, + a=ab[:, :num_v_heads], + b=ab[:, num_v_heads:], + A_log=torch.randn(num_v_heads, device="cuda", generator=g), + dt_bias=torch.randn(num_v_heads, device="cuda", generator=g), + ) + + +def _stock(x, num_k_heads, num_v_heads): + conv_states = x["conv_states"].clone() + mixed = x["mixed_qkv"] + mixed_t = extract_transpose_prefill_slice(mixed, mixed.shape[0], 0, mixed.shape[1]) + mixed_t = causal_conv1d_fn( + mixed_t, + x["weight"].squeeze(1), + None, + activation="silu", + conv_states=conv_states, + has_initial_state=x["has_initial_state"], + cache_indices=x["cache_indices"], + query_start_loc=x["query_start_loc"], + ) + q, k, v, g, beta = fused_gdn_post_conv( + mixed_t, + None, + x["a"], + x["b"], + x["A_log"], + x["dt_bias"], + num_k_heads, + HEAD_DIM, + num_v_heads, + HEAD_DIM, + ) + return q, k, v, g, beta, conv_states + + +def _stock_alpha(x, num_k_heads, num_v_heads): + """alpha of the stock pipeline with the FlashInfer gate convention: fused_gdn_post_conv(g_linear=True).""" + conv_states = x["conv_states"].clone() + mixed = x["mixed_qkv"] + mixed_t = extract_transpose_prefill_slice(mixed, mixed.shape[0], 0, mixed.shape[1]) + mixed_t = causal_conv1d_fn( + mixed_t, + x["weight"].squeeze(1), + None, + activation="silu", + conv_states=conv_states, + has_initial_state=x["has_initial_state"], + cache_indices=x["cache_indices"], + query_start_loc=x["query_start_loc"], + ) + return fused_gdn_post_conv( + mixed_t, + None, + x["a"], + x["b"], + x["A_log"], + x["dt_bias"], + num_k_heads, + HEAD_DIM, + num_v_heads, + HEAD_DIM, + g_linear=True, + )[3] + + +def _fused(x, num_k_heads, num_v_heads, out=None): + conv_states = x["conv_states"].clone() + alpha = torch.empty((1, x["mixed_qkv"].shape[0], num_v_heads), device="cuda") + q, k, v, g, beta = gdn_prefill_conv_post( + x["mixed_qkv"], + x["weight"], + None, + conv_states, + x["query_start_loc"], + x["cache_indices"], + x["has_initial_state"], + x["a"], + x["b"], + x["A_log"], + x["dt_bias"], + num_k_heads, + HEAD_DIM, + num_v_heads, + HEAD_DIM, + alpha_out=alpha, + out=out, + ) + return q, k, v, g, beta, conv_states, alpha + + +@pytest.mark.parametrize( + "num_k_heads,num_v_heads", + [(8, 32), (16, 64), (8, 24), (16, 48)], + ids=["tp2_397b", "tp1_397b", "48v_tp2", "48v_tp1"], +) +@pytest.mark.parametrize( + "lens,pad_seqs,extra_tokens", + [ + ([4096], (), 0), + ([700, 3, 0, 1, 1300], (2,), 0), + ([1, 2, 65, 64, 130], (0, 3), 7), + ], + ids=["one", "mixed_pad", "short_tail"], +) +def test_matches_stock_pipeline(num_k_heads, num_v_heads, lens, pad_seqs, extra_tokens): + conv_dim = (2 * num_k_heads + num_v_heads) * HEAD_DIM + assert gdn_prefill_conv_supported(HEAD_DIM, HEAD_DIM, 4, "silu", conv_dim, num_k_heads) + x = _inputs(lens, num_k_heads, num_v_heads, pad_seqs=pad_seqs, extra_tokens=extra_tokens) + q_ref, k_ref, v_ref, g_ref, beta_ref, cs_ref = _stock(x, num_k_heads, num_v_heads) + q, k, v, g, beta, cs, alpha = _fused(x, num_k_heads, num_v_heads) + # tanh.approx (max relative error 2^-11) in the stock SiLU: |error| <= |pre-activation| / 2 * 2^-11 on top of + # the bf16 rounding. + torch.testing.assert_close(v.float(), v_ref.float(), atol=4e-3, rtol=2**-7) + assert torch.equal(g, g_ref) + assert torch.equal(beta, beta_ref) + assert torch.equal(cs, cs_ref) + assert torch.equal(alpha, torch.exp(g)) + # alpha in (0, 1]: the int32 bit patterns of two such floats differ by their ulp distance. + alpha_ref = _stock_alpha(x, num_k_heads, num_v_heads) + ulps = (alpha.view(torch.int32) - alpha_ref.view(torch.int32)).abs().max().item() + assert ulps <= _ALPHA_MAX_ULPS, ulps + torch.testing.assert_close(q.float(), q_ref.float(), atol=8e-3, rtol=0) + torch.testing.assert_close(k.float(), k_ref.float(), atol=8e-3, rtol=0) + + +# libdevice expf vs the stock kernel's tl.exp (ex2.approx of g * log2(e), whose error grows with |g|) on the gates +# of these inputs: at most 25 ulp measured on GB300, a relative difference below 3e-6. +_ALPHA_MAX_ULPS = 32 + + +@pytest.mark.parametrize("lens,pad_seqs", [([700, 3, 0, 1, 1300], (2,)), ([1, 65], ())]) +def test_out_buffers_take_the_same_values(lens, pad_seqs): + """``out=`` (the mixer's shared scratch views) is the buffers the kernel writes and returns: the same launches + give bit-identical q / k / v / g / beta, alpha and conv states as freshly allocated outputs.""" + num_k_heads, num_v_heads = 8, 32 + x = _inputs(lens, num_k_heads, num_v_heads, pad_seqs=pad_seqs) + ref = _fused(x, num_k_heads, num_v_heads) + T = x["mixed_qkv"].shape[0] + # Prefix views of larger flat buffers filled with NaN, as the scratch hands them out. + out = ( + torch.full((2 * T * num_k_heads * HEAD_DIM,), float("nan"), device="cuda") + .to(torch.bfloat16)[: T * num_k_heads * HEAD_DIM] + .view(1, T, num_k_heads, HEAD_DIM), + torch.full((T * num_k_heads * HEAD_DIM,), float("nan"), device="cuda") + .to(torch.bfloat16) + .view(1, T, num_k_heads, HEAD_DIM), + torch.full((T * num_v_heads * HEAD_DIM,), float("nan"), device="cuda") + .to(torch.bfloat16) + .view(1, T, num_v_heads, HEAD_DIM), + torch.full((3 * T * num_v_heads,), float("nan"), device="cuda")[: T * num_v_heads].view( + 1, T, num_v_heads + ), + torch.full((T, num_v_heads), float("nan"), device="cuda").view(1, T, num_v_heads), + ) + got = _fused(x, num_k_heads, num_v_heads, out=out) + torch.cuda.synchronize() + for t, o in zip(got[:5], out): + assert t.data_ptr() == o.data_ptr() + for name, a, b in zip(("q", "k", "v", "g", "beta", "conv_states", "alpha"), got, ref): + assert torch.equal(a.view(torch.uint8), b.view(torch.uint8)), name + + +def test_out_buffers_are_checked(): + num_k_heads, num_v_heads = 8, 32 + x = _inputs([5], num_k_heads, num_v_heads) + T = x["mixed_qkv"].shape[0] + q = torch.empty((1, T, num_k_heads, HEAD_DIM), dtype=torch.bfloat16, device="cuda") + v = torch.empty((1, T, num_v_heads, HEAD_DIM), dtype=torch.bfloat16, device="cuda") + g = torch.empty((1, T, num_v_heads), device="cuda") + with pytest.raises(ValueError, match="out must be"): + _fused(x, num_k_heads, num_v_heads, out=(q, q.clone(), v, g, g.to(torch.bfloat16))) + + +@pytest.mark.parametrize("num_k_heads,num_v_heads", [(2, 6), (4, 12)]) +def test_partial_program_head_counts_unsupported(num_k_heads, num_v_heads): + """Head counts whose q / k or v channels do not fill whole programs keep the stock kernels.""" + conv_dim = (2 * num_k_heads + num_v_heads) * HEAD_DIM + assert not gdn_prefill_conv_supported(HEAD_DIM, HEAD_DIM, 4, "silu", conv_dim, num_k_heads) diff --git a/tests/unittest/_torch/modules/mamba/test_gdn_verify_tcgen05.py b/tests/unittest/_torch/modules/mamba/test_gdn_verify_tcgen05.py new file mode 100644 index 000000000000..314a67a54fae --- /dev/null +++ b/tests/unittest/_torch/modules/mamba/test_gdn_verify_tcgen05.py @@ -0,0 +1,446 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""gdn_verify_tcgen05 (the tcgen05 GDN MTP target-verify kernel) against trtllm::gdn_verify with FP8 output. + +The two differ only in the MMA accumulation order and the gated norm's sum order: y agrees up to FP8 rounding flips, +the committed state and the histories to bf16 rounding. A replay from the same inputs is bitwise identical. +""" + +import pytest +import torch + +from tensorrt_llm._torch.kernels.blackwell import gdn_verify_tcgen05 as gdn_verify_module +from tensorrt_llm._torch.kernels.blackwell.gdn_verify_tcgen05 import ( + compile_gdn_verify_tcgen05, + gdn_verify_tcgen05, + gdn_verify_tcgen05_supported, +) + +skip_no_sm100f = pytest.mark.skipif( + not torch.cuda.is_available() or torch.cuda.get_device_capability() not in ((10, 0), (10, 3)), + reason="needs SM100/SM103", +) +_DIM, _HIST, _SLOTS = 128, 16, 256 +_T = 7 + + +def _verify_case(heads, n, t, pnat, seed=1000): + """Per-rank shapes of a 16 k-head / 64 v-head GDN layer: heads = (k heads, v heads).""" + K = V = _DIM + H, HV = heads + g = torch.Generator(device="cuda").manual_seed(seed) + cd = 2 * H * K + HV * V + proj = (torch.randn(n * t, cd + HV * V, generator=g, device="cuda") * 0.7).to(torch.bfloat16) + ba = torch.randn(n * t, 2 * HV, generator=g, device="cuda").to(torch.bfloat16) + st = dict( + a_log=torch.log(torch.rand(HV, generator=g, device="cuda") * 7 + 1).float(), + dt_bias=(torch.rand(HV, generator=g, device="cuda") * 2 - 1).float(), + norm_w=(torch.rand(V, generator=g, device="cuda") + 0.5).to(torch.bfloat16), + fp8_scale=torch.tensor(0.02, dtype=torch.float32, device="cuda"), + state_indices=torch.randperm(_SLOTS, generator=g, device="cuda")[:n].to(torch.int32), + pnat=torch.full((_SLOTS,), pnat, dtype=torch.int32, device="cuda"), + buf=torch.zeros(_SLOTS, dtype=torch.int32, device="cuda"), + ) + st["buf"][2::3] = 1 + kh = torch.randn(_SLOTS, 2, _HIST, H, K, generator=g, device="cuda") + dec = torch.rand(_SLOTS, 2, HV, _HIST, generator=g, device="cuda") * 0.49 + 0.01 + mut = dict( + ssm=(torch.randn(_SLOTS, HV, V, K, generator=g, device="cuda") * 0.05).to(torch.bfloat16), + old_k=(kh / kh.norm(dim=-1, keepdim=True)).to(torch.bfloat16), + old_u=(torch.randn(_SLOTS, 2, _HIST, HV, V, generator=g, device="cuda") * 0.5).to( + torch.bfloat16 + ), + old_g=(-torch.cumsum(dec, dim=-1)).float().contiguous(), + ) + return HV, cd, proj, ba, st, mut + + +def _verify_op(op, HV, cd, n, t, proj, ba, st, mut): + """Run op (trtllm::gdn_verify's argument list, FP8 output) on clones of the mutable state.""" + m = {k: v.clone() for k, v in mut.items()} + y = op( + proj[:, :cd], + proj[:, cd:].view(n * t, HV, _DIM), + ba[:, HV:], + ba[:, :HV], + st["a_log"], + st["dt_bias"], + st["norm_w"], + st["fp8_scale"], + 1e-6, + m["ssm"], + st["state_indices"], + m["old_u"], + m["old_k"], + m["old_g"], + st["buf"], + st["pnat"], + ) + return y, m + + +def _rel(a, b): + a, b = a.float(), b.float() + return ((a - b).norm() / b.norm().clamp_min(1e-30)).item() + + +def _check_matches_reference(y, m, y_ref, m_ref, mut, state_indices): + """y up to FP8 rounding flips; the state and histories of the requests' slots up to bf16 rounding (errors + relative to those slots only), and every other slot left untouched by both ops.""" + assert y.dtype == torch.float8_e4m3fn and y.shape == y_ref.shape + assert _rel(y, y_ref) < 5e-2 + assert (y.view(torch.uint8) != y_ref.view(torch.uint8)).float().mean().item() < 0.2 + slots = state_indices[state_indices >= 0].long() + other = torch.ones(_SLOTS, dtype=torch.bool, device=slots.device) + other[slots] = False + for k in mut: + assert torch.equal(m[k][other], mut[k][other]), k + assert torch.equal(m_ref[k][other], mut[k][other]), k + assert _rel(m["old_u"][slots], m_ref["old_u"][slots]) < 1e-3 + assert _rel(m["old_k"][slots], m_ref["old_k"][slots]) < 1e-2 + assert torch.allclose(m["old_g"][slots], m_ref["old_g"][slots], rtol=1e-5, atol=1e-6) + assert _rel(m["ssm"][slots], m_ref["ssm"][slots]) < 1e-3 + + +@pytest.mark.parametrize( + "T,HV,HK,fp8_out,expected", + [ + (7, 8, 2, True, True), + (7, 64, 16, True, True), + (2, 4, 1, True, True), + (8, 8, 2, True, True), + (7, 8, 2, False, False), + (1, 8, 2, True, False), + (9, 8, 2, True, False), + (7, 8, 3, True, False), + (7, 0, 2, True, False), + ], +) +def test_gdn_verify_tcgen05_supported(T, HV, HK, fp8_out, expected): + assert gdn_verify_tcgen05_supported(T, HV, HK, fp8_out) is expected + + +@skip_no_sm100f +@pytest.mark.parametrize( + "heads,n", + [ + ((2, 8), 1), + ((2, 8), 16), + ((2, 8), 64), + ((2, 8), 128), + ((16, 64), 8), + ((16, 64), 52), + # GQA groups HV / HK of 1, 2 and 3 (the cases above are group 4). + ((4, 4), 1), + ((4, 4), 52), + ((4, 8), 1), + ((4, 8), 52), + ((4, 12), 1), + ((4, 12), 52), + ], +) +@pytest.mark.parametrize("pnat", [0, 12]) +def test_gdn_verify_tcgen05_matches_gdn_verify(heads, n, pnat): + HV, cd, proj, ba, st, mut = _verify_case(heads, n, _T, pnat) + y_ref, m_ref = _verify_op(torch.ops.trtllm.gdn_verify, HV, cd, n, _T, proj, ba, st, mut) + y, m = _verify_op(gdn_verify_tcgen05, HV, cd, n, _T, proj, ba, st, mut) + torch.cuda.synchronize() + _check_matches_reference(y, m, y_ref, m_ref, mut, st["state_indices"]) + if pnat + _T > _HIST: + assert not torch.equal(m["ssm"], mut["ssm"]), "commit expected (history full)" + + +@skip_no_sm100f +@pytest.mark.parametrize("heads,n", [((2, 8), 128), ((16, 64), 52)]) +def test_gdn_verify_tcgen05_replay_is_bitwise(heads, n): + """Two runs from the same inputs (one committing slot in three requests) give bitwise-identical results.""" + H, HV = heads + compile_gdn_verify_tcgen05(_T, HV, H, torch.device("cuda")) + HV, cd, proj, ba, st, mut = _verify_case(heads, n, _T, 0) + st["pnat"][st["state_indices"][::3].long()] = 12 + y0, m0 = _verify_op(gdn_verify_tcgen05, HV, cd, n, _T, proj, ba, st, mut) + y1, m1 = _verify_op(gdn_verify_tcgen05, HV, cd, n, _T, proj, ba, st, mut) + torch.cuda.synchronize() + assert torch.equal(y0.view(torch.uint8), y1.view(torch.uint8)) + for k in m0: + assert torch.equal(m0[k], m1[k]), k + assert not torch.equal(m0["ssm"], mut["ssm"]), "commit expected (history full)" + + +@skip_no_sm100f +@pytest.mark.parametrize("t", [2, 4, 7, 8]) +@pytest.mark.parametrize("pnat", ["zero", "offset", "fills", "mixed"]) +@pytest.mark.parametrize("n", [16, 200]) +def test_gdn_verify_tcgen05_matches_gdn_verify_across_draft_lengths(t, pnat, n): + """Every admitted draft length, appends at an offset into the history, a history the step fills exactly + (16 - T), batches mixing appends and commits, and more requests than one CTA wave of 128.""" + heads = (2, 8) + start = {"zero": 0, "offset": 3, "fills": _HIST - t, "mixed": 0}[pnat] + HV, cd, proj, ba, st, mut = _verify_case(heads, n, t, start, seed=2000 + t) + if pnat == "mixed": + # Every third request commits (its history overflows), the others append at offset 3. + st["pnat"].fill_(3) + st["pnat"][st["state_indices"][::3].long()] = 12 + y_ref, m_ref = _verify_op(torch.ops.trtllm.gdn_verify, HV, cd, n, t, proj, ba, st, mut) + y, m = _verify_op(gdn_verify_tcgen05, HV, cd, n, t, proj, ba, st, mut) + torch.cuda.synchronize() + _check_matches_reference(y, m, y_ref, m_ref, mut, st["state_indices"]) + + +@skip_no_sm100f +def test_gdn_verify_tcgen05_honours_enable_pdl(monkeypatch): + """TRTLLM_ENABLE_PDL=0 compiles and launches the kernel without PDL; the results are bitwise those with PDL.""" + H, HV = 2, 8 + n = 52 + compile_pdl = [] + real_compile = gdn_verify_module.cute.compile + + def recording_compile(*args, **kwargs): + compile_pdl.append(kwargs.get("PDL")) + return real_compile(*args, **kwargs) + + monkeypatch.setattr(gdn_verify_module.cute, "compile", recording_compile) + gdn_verify_module._compiled.cache_clear() + HV, cd, proj, ba, st, mut = _verify_case((H, HV), n, _T, 0) + st["pnat"][st["state_indices"][::3].long()] = 12 + results = {} + try: + for env in ("1", "0"): + monkeypatch.setenv("TRTLLM_ENABLE_PDL", env) + compile_gdn_verify_tcgen05(_T, HV, H) + results[env] = _verify_op(gdn_verify_tcgen05, HV, cd, n, _T, proj, ba, st, mut) + torch.cuda.synchronize() + finally: + gdn_verify_module._compiled.cache_clear() + assert compile_pdl == [True, False] + (y_on, m_on), (y_off, m_off) = results["1"], results["0"] + assert torch.equal(y_on.view(torch.uint8), y_off.view(torch.uint8)) + for k in m_on: + assert torch.equal(m_on[k], m_off[k]), k + + +def _page_views(pages, HV, H): + """Views of replay pages laid out as the V2 hybrid manager binds them: per replay slot a [prev_num_accepted, + cache_buf_idx, ., .] int32 row, then the history planes (slot strides of a page).""" + planes = { + "old_u": (torch.bfloat16, (2, _HIST, HV, _DIM)), + "old_k": (torch.bfloat16, (2, _HIST, H, _DIM)), + "old_g": (torch.float32, (2, HV, _HIST)), + } + views, off = {}, 16 + for name, (dtype, shape) in planes.items(): + nbytes = dtype.itemsize * torch.Size(shape).numel() + views[name] = pages[:, off : off + nbytes].view(dtype).unflatten(1, shape) + off += nbytes + meta = pages[:, :16].view(torch.int32) + return views, meta[:, 0], meta[:, 1] + + +def _page_bytes(HV, H): + nbytes = 16 + 2 * _HIST * (HV + H) * _DIM * 2 + 2 * HV * _HIST * 4 + return (nbytes + 48 + 15) // 16 * 16 + + +@skip_no_sm100f +@pytest.mark.parametrize("heads,n", [((2, 8), 52), ((16, 64), 8)]) +def test_gdn_verify_tcgen05_addresses_the_history_by_replay_slot(heads, n): + """History and bookkeeping in replay pages of their own (the KV-cache replay region: slot strides of a page, + replay slots other than the state slots): bitwise the result of the same step on per-state-slot contiguous + history, trtllm::gdn_verify's up to the kernels' rounding, and no write outside the requests' history rows.""" + H, HV = heads + HV, cd, proj, ba, st, mut = _verify_case(heads, n, _T, 0) + st["pnat"][st["state_indices"][::3].long()] = 12 # every third request commits + st["state_indices"][1] = -1 # a padded request + num_replay_slots = _SLOTS + 40 + g = torch.Generator(device="cuda").manual_seed(7) + replay = torch.randperm(num_replay_slots, generator=g, device="cuda")[:n].to(torch.int32) + valid = st["state_indices"] >= 0 + rows, slots = replay[valid].long(), st["state_indices"][valid].long() + + pages = torch.randint( + 0, + 256, + (num_replay_slots, _page_bytes(HV, H)), + dtype=torch.uint8, + device="cuda", + generator=g, + ) + views, pnat, buf = _page_views(pages, HV, H) + # every bookkeeping row valid (a padded request reads replay slot 0's) + pnat.zero_() + buf.zero_() + for name, view in views.items(): + view[rows] = mut[name][slots] + pnat[rows] = st["pnat"][slots] + buf[rows] = st["buf"][slots] + + def run(op): + p = pages.clone() + v, pn, cb = _page_views(p, HV, H) + ssm = mut["ssm"].clone() + y = op( + proj[:, :cd], + proj[:, cd:].view(n * _T, HV, _DIM), + ba[:, HV:], + ba[:, :HV], + st["a_log"], + st["dt_bias"], + st["norm_w"], + st["fp8_scale"], + 1e-6, + ssm, + st["state_indices"], + v["old_u"], + v["old_k"], + v["old_g"], + cb, + pn, + replay, + ) + return y, ssm, p, v + + y_c, m_c = _verify_op(gdn_verify_tcgen05, HV, cd, n, _T, proj, ba, st, mut) + y_p, ssm_p, pages_p, v_p = run(gdn_verify_tcgen05) + y_r, ssm_r, _, v_r = run(torch.ops.trtllm.gdn_verify) + torch.cuda.synchronize() + out = torch.arange(n * _T, device="cuda").view(n, _T)[valid].flatten() + assert torch.equal(y_p.view(torch.uint8)[out], y_c.view(torch.uint8)[out]) + assert torch.equal(ssm_p, m_c["ssm"]) + for name in views: + assert torch.equal(v_p[name][rows], m_c[name][slots]), name + untouched = torch.ones(num_replay_slots, dtype=torch.bool, device="cuda") + untouched[rows] = False + assert torch.equal(pages_p[untouched], pages[untouched]) + assert torch.equal(pages_p[:, :16], pages[:, :16]) # the bookkeeping is the caller's to advance + assert _rel(y_p[out], y_r[out]) < 5e-2 + assert _rel(v_p["old_u"][rows], v_r["old_u"][rows]) < 1e-3 + assert torch.allclose(v_p["old_g"][rows], v_r["old_g"][rows], rtol=1e-5, atol=1e-6) + assert _rel(ssm_p[slots], ssm_r[slots]) < 1e-3 + other = torch.ones(_SLOTS, dtype=torch.bool, device="cuda") + other[slots] = False + assert torch.equal(ssm_p[other], mut["ssm"][other]) + assert torch.equal(ssm_r[other], mut["ssm"][other]) + + +@pytest.mark.parametrize( + "bad", ["z_rows", "z_heads", "a_heads", "b_rows", "old_u_buffers", "old_k_hist"] +) +def test_gdn_verify_tcgen05_checks_the_op_shapes(bad): + """The wrapper refuses, before any launch, the z / a / b and history shapes trtllm::gdn_verify refuses.""" + n = 4 + HV, cd, proj, ba, st, mut = _verify_case((2, 8), n, _T, 0) + z = proj[:, cd:].view(n * _T, HV, _DIM) + a, b = ba[:, HV:], ba[:, :HV] + old_u, old_k = mut["old_u"], mut["old_k"] + if bad == "z_rows": + z = z[:-1] + elif bad == "z_heads": + z = z[:, : HV // 2] + elif bad == "a_heads": + a = ba[:, HV + 1 :] + elif bad == "b_rows": + b = b[:-1] + elif bad == "old_u_buffers": + old_u = old_u[:, :1] + else: + old_k = old_k[:, :, : _HIST // 2] + with pytest.raises(AssertionError): + gdn_verify_tcgen05( + proj[:, :cd], z, a, b, st["a_log"], st["dt_bias"], st["norm_w"], st["fp8_scale"], 1e-6, + mut["ssm"].clone(), st["state_indices"], old_u, old_k, mut["old_g"], st["buf"], st["pnat"], + ) # fmt: skip + + +@pytest.mark.parametrize( + "bad", + [ + "qkv_dtype", + "z_dtype", + "a_dtype", + "b_dtype", + "old_u_dtype", + "old_k_dtype", + "ssm_dtype", + "scale_dtype", + "scale_numel", + "qkv_base", + "ssm_base", + ], +) +def test_gdn_verify_tcgen05_checks_the_op_dtypes_and_alignment(bad): + """The wrapper refuses, before any launch, the dtypes, the FP8 scale and the 16-byte bases trtllm::gdn_verify + refuses (gdnVerifyOp.cpp): the kernel would otherwise read them as BF16 / a FP32 scalar / aligned rows.""" + n = 4 + HV, cd, proj, ba, st, mut = _verify_case((2, 8), n, _T, 0) + x = proj[:, :cd] + z = proj[:, cd:].view(n * _T, HV, _DIM) + a, b = ba[:, HV:], ba[:, :HV] + old_u, old_k, ssm = mut["old_u"], mut["old_k"], mut["ssm"].clone() + scale = st["fp8_scale"] + if bad == "qkv_dtype": + x = x.to(torch.float16) + elif bad == "z_dtype": + z = z.to(torch.float16) + elif bad == "a_dtype": + a = a.float() + elif bad == "b_dtype": + b = b.float() + elif bad == "old_u_dtype": + old_u = old_u.to(torch.float16) + elif bad == "old_k_dtype": + old_k = old_k.to(torch.float16) + elif bad == "ssm_dtype": + ssm = ssm.to(torch.float16) + elif bad == "scale_dtype": + scale = scale.to(torch.bfloat16) + elif bad == "scale_numel": + scale = scale.reshape(1).repeat(2) + elif bad == "qkv_base": + # Rows keep their 16-byte stride; the base moves by 8 elements (16 bytes) minus one. + wide = torch.zeros(x.shape[0], x.shape[1] + 8, dtype=torch.bfloat16, device="cuda") + x = wide.view(-1)[7 : 7 + x.numel()].view(x.shape[0], x.shape[1]) + assert x.stride(0) % 8 == 0 and x.data_ptr() % 16 != 0 + else: + flat = torch.zeros(ssm.numel() + 8, dtype=torch.bfloat16, device="cuda") + ssm = flat[1 : 1 + ssm.numel()].view(ssm.shape) + assert ssm.data_ptr() % 16 != 0 + with pytest.raises(AssertionError): + gdn_verify_tcgen05( + x, z, a, b, st["a_log"], st["dt_bias"], st["norm_w"], scale, 1e-6, + ssm, st["state_indices"], old_u, old_k, mut["old_g"], st["buf"], st["pnat"], + ) # fmt: skip + + +def test_gdn_compiles_the_tcgen05_verify_only_for_an_fp8_out_proj(monkeypatch): + """The tcgen05 verify runs only when the gated norm writes E4M3 (norm.fp8_scale, set for an FP8QDQ out_proj): + cache_derived_state compiles it then, and a BF16 out_proj never compiles it.""" + from types import SimpleNamespace + + from tensorrt_llm._torch.modules.linear import FP8QDQLinearMethod, UnquantizedLinearMethod + from tensorrt_llm._torch.modules.mamba.gdn_mixer import Qwen3NextGatedDeltaNet + from tensorrt_llm._torch.modules.mamba.layernorm_gated import RMSNorm + + compiled = [] + monkeypatch.setattr( + gdn_verify_module, "compile_gdn_verify_tcgen05", lambda *args: compiled.append(args) + ) + + def layer(quant_method): + m = Qwen3NextGatedDeltaNet.__new__(Qwen3NextGatedDeltaNet) + torch.nn.Module.__init__(m) + m.fused_verify = False + m.norm = RMSNorm(8) + m.num_v_heads_per_tp, m.num_k_heads_per_tp = 16, 4 + # What __init__ sets for a supported MTP verify (rows gate, draft rows per request). + m.verify_tcgen05_min_rows, m.verify_tcgen05_tokens = 64, 7 + m.out_proj = SimpleNamespace( + quant_method=quant_method, + input_scale=torch.nn.Parameter(torch.tensor(0.5), requires_grad=False), + force_dynamic_quantization=False, + ) + return m + + layer(UnquantizedLinearMethod()).cache_derived_state() + assert compiled == [] + layer(FP8QDQLinearMethod()).cache_derived_state() + assert compiled == [(7, 16, 4)] diff --git a/tests/unittest/_torch/modules/mamba/test_layernorm_gated.py b/tests/unittest/_torch/modules/mamba/test_layernorm_gated.py index b0ec3ecc5dcf..7b37dc93bc1d 100644 --- a/tests/unittest/_torch/modules/mamba/test_layernorm_gated.py +++ b/tests/unittest/_torch/modules/mamba/test_layernorm_gated.py @@ -307,6 +307,66 @@ def test_token_major_pdl_launch_is_bitwise_invariant( assert torch.equal(outputs[True], outputs[False]) + @pytest.mark.parametrize("gate_activation", ["silu", "sigmoid"]) + @pytest.mark.parametrize("with_fp8", [False, True]) + def test_token_major_groups_launch_is_bitwise_invariant( + self, gate_activation: str, with_fp8: bool + ) -> None: + """From _MULTIROW_GROUPS_MIN_ROWS rows a program runs _MULTIROW_GROUPS + tiles; every output bit must equal the one-tile-per-program launch, + including a partial last group.""" + from tensorrt_llm._torch.modules.mamba.layernorm_gated import rms_norm_gated_token_major + + device = "cuda" + dtype = torch.bfloat16 + heads, N = 24, 128 + rows_per_program = layernorm_gated._MULTIROW_ROWS * layernorm_gated._MULTIROW_GROUPS + num_tokens = ( + triton.cdiv(layernorm_gated._MULTIROW_GROUPS_MIN_ROWS, heads * rows_per_program) + * rows_per_program + + 3 + ) + num_rows = num_tokens * heads + assert layernorm_gated._MULTIROW_GROUPS > 1 + assert num_rows >= layernorm_gated._MULTIROW_GROUPS_MIN_ROWS + assert num_rows % rows_per_program != 0 + torch.manual_seed(5) + x = torch.randn(num_rows, N, device=device, dtype=dtype) + weight = torch.randn(N, device=device, dtype=dtype) * 0.1 + 1.0 + wide = torch.randn(num_tokens, heads * N + 128, device=device, dtype=dtype) + z = wide[:, 128:].view(num_tokens, heads, N) + fp8_scale = torch.tensor(0.13, device=device, dtype=torch.float32) if with_fp8 else None + + actual = rms_norm_gated_token_major( + x, z, weight, 1e-6, fp8_scale=fp8_scale, gate_activation=gate_activation + ) + expected = torch.empty_like(actual) + layernorm_gated._rms_norm_gated_fwd_multirow_kernel[ + (triton.cdiv(num_rows, layernorm_gated._MULTIROW_ROWS),) + ]( + x, + expected, + weight, + z, + None, + fp8_scale, + x.stride(0), + expected.stride(0), + z.stride(0), + num_rows, + 1e-6, + N=N, + ROWS=layernorm_gated._MULTIROW_ROWS, + HEADS_PER_TOK=heads, + GATE_SIGMOID=gate_activation == "sigmoid", + WEIGHT_IS_DELTA=False, + LAUNCH_WITH_PDL=False, + GROUPS=1, + num_warps=layernorm_gated._MULTIROW_NUM_WARPS, + ) + + assert torch.equal(actual.view(torch.uint8), expected.view(torch.uint8)) + @skip_no_cuda class TestRMSNormNVFP4: diff --git a/tests/unittest/_torch/modules/test_expert_l2_prefetch.py b/tests/unittest/_torch/modules/test_expert_l2_prefetch.py new file mode 100644 index 000000000000..ee718912ca8c --- /dev/null +++ b/tests/unittest/_torch/modules/test_expert_l2_prefetch.py @@ -0,0 +1,139 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""ExpertL2Prefetch: the record kernel keeps the experts with the most token tiles (or, in budgeted forwards, routed +rows), only registered layers and forwards in the row range record or prefetch, and the prefetch (with or without an +issue budget) leaves every tensor unchanged.""" + +from types import SimpleNamespace + +import pytest +import torch + +from tensorrt_llm._torch.modules.expert_l2_prefetch import PIECE, ExpertL2Prefetch + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] < 9, + reason="cp.async.bulk.prefetch.L2 needs SM90+", +) + +NUM_LOCAL = 16 +TOP_K = 10 + + +def _selection(prefetch: ExpertL2Prefetch, layer_idx: int) -> list: + torch.cuda.synchronize() + return prefetch._device_state(torch.device("cuda")).sel[layer_idx].tolist() + + +def _backend(num_local: int = NUM_LOCAL) -> SimpleNamespace: + return SimpleNamespace( + has_nvfp4=True, + w3_w1_weight=torch.randint(0, 255, (num_local, 2, PIECE), dtype=torch.uint8, device="cuda"), + w3_w1_weight_scale=torch.randint( + 0, 255, (num_local, PIECE), dtype=torch.uint8, device="cuda" + ), + ) + + +def test_record_keeps_the_experts_with_most_tiles() -> None: + prefetch = ExpertL2Prefetch( + num_layers=2, min_rows=2, max_rows=64, top_k=TOP_K, stream=torch.cuda.Stream() + ) + prefetch.register(0, _backend()) + k = prefetch.num_experts + # Tiles per expert: 5 -> 3, 2 -> 3, 9 -> 1 (ties: lower id first); the entries past num_ctas do not count. + cta_batch = torch.tensor([5, 2, 9, 5, 2, 5, 2, 7, 7, 7, 7], dtype=torch.int32, device="cuda") + num_ctas = torch.tensor([7], dtype=torch.int32, device="cuda") + limit = torch.full_like(cta_batch, 1 << 20) + prefetch.record(0, cta_batch, limit, num_ctas, 8, NUM_LOCAL, cta_batch, rows=8) + prefetch.join() + assert _selection(prefetch, 0) == ([2, 5, 9] + [-1] * k)[:k] + + # Outside the row range, or for an unregistered layer: nothing is recorded. + other = torch.tensor([3, 3], dtype=torch.int32, device="cuda") + two = num_ctas.new_tensor([2]) + prefetch.record(0, other, other, two, 8, NUM_LOCAL, other, rows=1) + prefetch.record(0, other, other, two, 8, NUM_LOCAL, other, rows=65) + prefetch.record(1, other, other, two, 8, NUM_LOCAL, other, rows=8) + prefetch.join() + assert _selection(prefetch, 0) == ([2, 5, 9] + [-1] * k)[:k] + assert _selection(prefetch, 1) == [-1] * k + + +@pytest.mark.parametrize("rows,budgeted", [(16, False), (17, True), (35, True), (36, False)]) +def test_record_by_rows_in_budgeted_forwards(rows, budgeted) -> None: + """A forward of more than budget_rows[0] and at most budget_rows[1] rows ranks by routed rows: row r of the padded + permuted order belongs to tile r // tile and counts while r is below that tile's row limit. Other forwards rank + by tiles.""" + prefetch = ExpertL2Prefetch( + num_layers=1, + min_rows=2, + max_rows=64, + top_k=TOP_K, + stream=torch.cuda.Stream(), + budget_rows=(16, 35), + ) + prefetch.register(0, _backend()) + assert prefetch.budgeted(rows) == budgeted + k, tile = prefetch.num_experts, 4 + # Tiles of 4 rows: expert 3 two tiles of 1 row, expert 6 one full tile, expert 1 one tile of 2 rows. + cta_batch = torch.tensor([3, 3, 6, 1, 9], dtype=torch.int32, device="cuda") + limit = torch.tensor([1, 5, 12, 14, 20], dtype=torch.int32, device="cuda") + num_ctas = torch.tensor([4], dtype=torch.int32, device="cuda") + prefetch.record(0, cta_batch, limit, num_ctas, tile, NUM_LOCAL, cta_batch, rows=rows) + prefetch.join() + expect = ( + [6, 1, 3] if budgeted else [3, 1, 6] + ) # by tiles: 3 -> 2 tiles, then 1 and 6 with one each + assert _selection(prefetch, 0) == (expect + [-1] * k)[:k] + + +@pytest.mark.parametrize("rows", [8, 20]) +@pytest.mark.parametrize("budget_ns", [0, 1, 1 << 30]) +def test_prefetch_changes_no_tensor_and_joins(budget_ns, rows) -> None: + """With and without the issue budget (rows 20 is a budgeted forward, 8 is not).""" + prefetch = ExpertL2Prefetch( + num_layers=1, + min_rows=2, + max_rows=64, + top_k=TOP_K, + stream=torch.cuda.Stream(), + budget_rows=(16, 35), + ) + backend = _backend() + weight, scale = backend.w3_w1_weight.clone(), backend.w3_w1_weight_scale.clone() + prefetch.register(0, backend, issue_budget_ns=budget_ns) + tiles = torch.arange(NUM_LOCAL, dtype=torch.int32, device="cuda") + limit = torch.arange(1, NUM_LOCAL + 1, dtype=torch.int32, device="cuda") * 8 + prefetch.record(0, tiles, limit, tiles.new_tensor([NUM_LOCAL]), 8, NUM_LOCAL, tiles, rows=rows) + prefetch.join() + assert not prefetch._forked + prefetch.prefetch(0, rows=rows) + assert prefetch._forked # forked by prefetch() itself + prefetch.join() + assert not prefetch._forked + torch.cuda.synchronize() + assert torch.equal(backend.w3_w1_weight, weight) + assert torch.equal(backend.w3_w1_weight_scale, scale) + + +def test_prefetch_skips_experts_without_nvfp4_scales() -> None: + """A layer whose experts are not NVFP4 (no FC1 block scales) issues no prefetch and forks nothing.""" + prefetch = ExpertL2Prefetch( + num_layers=1, min_rows=2, max_rows=64, top_k=TOP_K, stream=torch.cuda.Stream() + ) + prefetch.register(0, SimpleNamespace(has_nvfp4=False)) + prefetch.prefetch(0, rows=8) + assert not prefetch._forked diff --git a/tests/unittest/_torch/modules/test_fused_add_rms_norm_quant.py b/tests/unittest/_torch/modules/test_fused_add_rms_norm_quant.py index c68608166a0c..73dbffe9ea1a 100644 --- a/tests/unittest/_torch/modules/test_fused_add_rms_norm_quant.py +++ b/tests/unittest/_torch/modules/test_fused_add_rms_norm_quant.py @@ -12,12 +12,15 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -"""Unit tests for fused_add_rms_norm_quant with/without output_hp_norm support.""" +"""Unit tests for fused_add_rms_norm_quant with/without output_hp_norm support, and for the NCCL allreduce +fallback's fused residual + RMSNorm + FP8 quantize.""" import pytest import torch from utils.util import getSMVersion +from tensorrt_llm._torch.distributed import AllReduceFusionOp, AllReduceStrategy + def fused_add_rms_norm_quant_available(): """Check if the fused_add_rms_norm_quant op is available.""" @@ -377,3 +380,76 @@ def test_fused_add_rms_norm_quant_non_power_of_2_hidden(m, n): sf_out_hp_valid = sf_out_hp[valid_sf_indices] sf_out_no_hp_valid = sf_out_no_hp[valid_sf_indices] torch.testing.assert_close(sf_out_hp_valid, sf_out_no_hp_valid, rtol=0, atol=0) + + +# The NCCL / NCCL_SYMMETRIC allreduce fallback of every model fuses residual + RMSNorm + FP8 quantize after the +# reduce. A one-rank group runs the same post-reduce path in one process, so these run on single-GPU stages, +# Hopper included; they keep their own GPU gate and do not use skip_unsupported (SM100+). +_FP8_FUSION_OPS = [ + pytest.param(AllReduceFusionOp.RESIDUAL_RMS_NORM_QUANT_FP8, id="residual_rms_norm_quant_fp8"), + pytest.param( + AllReduceFusionOp.RESIDUAL_RMS_NORM_OUT_QUANT_FP8, id="residual_rms_norm_out_quant_fp8" + ), +] + + +def _nccl_one_rank_allreduce(x, residual, norm_weight, scale, op): + return torch.ops.trtllm.allreduce( + input=x, + residual=residual, + norm_weight=norm_weight, + scale=scale, + bias=None, + workspace=None, + group=[0], + strategy=AllReduceStrategy.NCCL, + op=op, + eps=1e-5, + trigger_completion_at_end=True, + ) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU") +@pytest.mark.parametrize("seq_len", [1, 7, 300], ids=lambda x: f"seqlen:{x}") +@pytest.mark.parametrize("hidden_size", [128, 256, 4096, 7168, 8192], ids=lambda x: f"hidden:{x}") +@pytest.mark.parametrize("fusion_op", _FP8_FUSION_OPS) +@torch.inference_mode() +def test_nccl_residual_rms_norm_quant_fp8_bitwise(seq_len, hidden_size, fusion_op): + """The NCCL fallback's fused residual + RMSNorm + FP8 quantize (one kernel where the hidden size allows it) is + bit for bit RESIDUAL_RMS_NORM followed by the static per-tensor quantize.""" + torch.manual_seed(0) + x = torch.randn((seq_len, hidden_size), dtype=torch.bfloat16, device="cuda") + residual = torch.randn_like(x) + norm_weight = torch.randn((hidden_size,), dtype=torch.bfloat16, device="cuda") + scale = torch.tensor(0.37, dtype=torch.float32, device="cuda") + + norm, residual_out = _nccl_one_rank_allreduce( + x, residual, norm_weight, scale, AllReduceFusionOp.RESIDUAL_RMS_NORM + ) + ref_quant, _ = torch.ops.tensorrt_llm.static_quantize_e4m3_per_tensor(norm, scale) + outputs = _nccl_one_rank_allreduce(x, residual, norm_weight, scale, fusion_op) + if fusion_op == AllReduceFusionOp.RESIDUAL_RMS_NORM_OUT_QUANT_FP8: + assert torch.equal(outputs[0], norm) + assert torch.equal(outputs[-2].view(torch.uint8), ref_quant.view(torch.uint8)) + assert torch.equal(outputs[-1], residual_out) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU") +@pytest.mark.parametrize("fusion_op", _FP8_FUSION_OPS) +@torch.inference_mode() +def test_nccl_residual_rms_norm_quant_fp8_no_tokens(fusion_op): + """The NCCL fallback's fused residual + RMSNorm + FP8 quantize returns empty outputs for an empty input.""" + hidden_size = 4096 + x = torch.empty((0, hidden_size), dtype=torch.bfloat16, device="cuda") + outputs = _nccl_one_rank_allreduce( + x, + torch.empty_like(x), + torch.ones((hidden_size,), dtype=torch.bfloat16, device="cuda"), + torch.tensor(1.0, dtype=torch.float32, device="cuda"), + fusion_op, + ) + torch.cuda.synchronize() + expected = 3 if fusion_op == AllReduceFusionOp.RESIDUAL_RMS_NORM_OUT_QUANT_FP8 else 2 + assert len(outputs) == expected + assert all(o.shape == (0, hidden_size) for o in outputs) + assert outputs[-2].dtype == torch.float8_e4m3fn diff --git a/tests/unittest/_torch/modules/test_gate_add_rmsnorm_fp8.py b/tests/unittest/_torch/modules/test_gate_add_rmsnorm_fp8.py new file mode 100644 index 000000000000..9662686f7f20 --- /dev/null +++ b/tests/unittest/_torch/modules/test_gate_add_rmsnorm_fp8.py @@ -0,0 +1,79 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Shared-expert gate + residual add + RMSNorm + E4M3 quant in one launch (kernels/blackwell/gate_add_rmsnorm_fp8.py): +bitwise equal to the three launches of the attention-DP post-MoE chain it replaces.""" + +import pytest +import torch + +import tensorrt_llm # noqa: F401 +from tensorrt_llm._torch.moe.fused_shared_expert import fused_sigmoid_gate_mul_add +from tensorrt_llm._utils import is_blackwell_datacenter + +pytestmark = pytest.mark.skipif( + not is_blackwell_datacenter(), reason="the post-MoE fold runs on SM 10.0 / 10.3" +) + + +def _inputs(rows, hidden, seed): + g = torch.Generator(device="cuda").manual_seed(seed) + + def randn(*shape, scale=1.0): + return (torch.randn(*shape, generator=g, device="cuda") * scale).to(torch.bfloat16) + + return dict( + routed=randn(rows, hidden), + shared=randn(rows, hidden, scale=0.5), + gate_logits=randn(rows, 1, scale=2.0), + residual=randn(rows, hidden, scale=4.0), + weight=randn(hidden, scale=0.1), + scale=torch.rand(1, generator=g, device="cuda") * 0.05 + 0.01, + ) + + +def _reference(t, eps): + """fused_sigmoid_gate_mul_add, FlashInfer's gemma fused add + RMSNorm (as RMSNorm runs it), then the next FP8 + projection's static_quantize_e4m3_per_tensor.""" + x = fused_sigmoid_gate_mul_add(t["routed"].clone(), t["gate_logits"], t["shared"]) + residual = t["residual"].clone() + torch.ops.trtllm.flashinfer_gemma_fused_add_rmsnorm(x, residual, t["weight"], eps) + q, _ = torch.ops.tensorrt_llm.static_quantize_e4m3_per_tensor(x, t["scale"]) + return x, residual, q + + +@pytest.mark.parametrize("write_y", [True, False]) +@pytest.mark.parametrize("rows", [1, 7, 48 * 7, 52 * 7, 1001]) +def test_gate_add_rmsnorm_fp8_bitwise(rows, write_y): + from tensorrt_llm._torch.kernels.blackwell.gate_add_rmsnorm_fp8 import gate_add_rmsnorm_fp8 + + hidden, eps = 4096, 1e-6 + t = _inputs(rows, hidden, seed=rows) + y_ref, residual_ref, q_ref = _reference(t, eps) + + routed, residual = t["routed"].clone(), t["residual"].clone() + y, q = gate_add_rmsnorm_fp8( + routed, + t["shared"], + t["gate_logits"], + residual, + t["weight"], + eps, + t["scale"], + write_y=write_y, + ) + torch.cuda.synchronize() + + assert y is routed + assert torch.equal(residual.view(torch.int16), residual_ref.view(torch.int16)) + assert torch.equal(q.view(torch.uint8), q_ref.view(torch.uint8)) + if write_y: + assert torch.equal(y.view(torch.int16), y_ref.view(torch.int16)) + else: + assert torch.equal(routed.view(torch.int16), t["routed"].view(torch.int16)) + + +def test_supports_hidden(): + from tensorrt_llm._torch.kernels.blackwell.gate_add_rmsnorm_fp8 import supports_hidden + + assert supports_hidden(4096) + assert not supports_hidden(4096 + 8) diff --git a/tests/unittest/_torch/modules/test_inproj_ba_splitk.py b/tests/unittest/_torch/modules/test_inproj_ba_splitk.py new file mode 100644 index 000000000000..f27a8802c2a2 --- /dev/null +++ b/tests/unittest/_torch/modules/test_inproj_ba_splitk.py @@ -0,0 +1,105 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""in_proj_ba split-K kernel (kernels/blackwell/inproj_ba_splitk.py): bitwise equal to an in-test reference of +its arithmetic (four FP32 partials over K / 4, summed in order, then BF16) on data whose partials are exact in any +summation order while their serial sum rounds; a pairwise sum of the same partials gives other bits in every call.""" + +import pytest +import torch + +import tensorrt_llm # noqa: F401 +from tensorrt_llm._utils import is_blackwell_datacenter + +pytestmark = pytest.mark.skipif( + not is_blackwell_datacenter(), + reason="the kernel runs on SM 10.0 / 10.3 (bitwise against cuBLAS there)", +) + +K, NB, KC = 4096, 16, 1024 + + +def _gen(seed): + return torch.Generator(device="cuda").manual_seed(seed) + + +def _ordered(m, seed): + """Split 0: +-2^25 at one position plus even-integer noise (every partial sum a multiple of 4 below 2^26), split + 2: its negation, permuted; splits 1 / 3: integers in [-1, 1]. Every split partial is then exact in FP32 whatever + the order of its sums, while (p0 + p1) and (p2 + p3) round to multiples of 4.""" + g = _gen(seed) + + def ints(shape, bound): + return torch.randint(-bound, bound + 1, shape, generator=g, device="cuda").float() + + x = torch.empty(m, K, device="cuda") + w = torch.empty(NB, K, device="cuda") + x[:, :KC] = 2 * ints((m, KC), 4) + w[:, :KC] = 2 * ints((NB, KC), 4) + x[:, 0] = 2.0**13 * torch.where(ints((m,), 1) >= 0, 1.0, -1.0) + w[:, 0] = 2.0**12 + perm = torch.randperm(KC, generator=g, device="cuda") + x[:, 2 * KC : 3 * KC] = -x[:, :KC][:, perm] + w[:, 2 * KC : 3 * KC] = w[:, :KC][:, perm] + for s in (1, 3): + x[:, s * KC : (s + 1) * KC] = ints((m, KC), 1) + w[:, s * KC : (s + 1) * KC] = ints((NB, KC), 1) + return x.to(torch.bfloat16).contiguous(), w.to(torch.bfloat16).contiguous() + + +def _bits(y): + return y.view(torch.int16) + + +def _split_partials(x, w): + """The four split partials, exact (FP64 sums of exact products), as FP32.""" + return [ + (x[:, s * KC : (s + 1) * KC].double() @ w[:, s * KC : (s + 1) * KC].double().t()).float() + for s in range(4) + ] + + +def test_plan(): + from tensorrt_llm._torch.kernels.blackwell import inproj_ba_splitk as R + + assert R.plan(56, K, NB) == 2 and R.plan(77, K, NB) == 3 and R.plan(96, K, NB) == 3 + assert R.plan(32, K, NB) == 1 and R.plan(97, K, NB) is None + # K in whole barrier groups of x boxes per split, N within TMEM sub-partition 0's 16 rows + assert R.plan(56, 2048, NB) == 2 and R.plan(56, 3072, 8) == 2 and R.plan(56, 1536, NB) is None + assert R.plan(56, K, 32) is None and R.plan(56, K, 12) is None + # ~110 KB at the model's shape, so a CTA fits beside the MoE all-reduce's CTAs in the 196 KB shared-memory split + assert R._smem_bytes(K, NB) <= 120 * 1024, R._smem_bytes(K, NB) + + +@pytest.mark.parametrize("m", [1, 33, 56, 77, 96]) +def test_bitwise_vs_serial_reference(m): + from tensorrt_llm._torch.kernels.blackwell import inproj_ba_splitk as R + + calls = 4 + diff = 0 + pairwise_differs = 0 + for c in range(calls): + x, w = _ordered(m, 700 + 10 * c) + p = _split_partials(x, w) + serial = (((p[0] + p[1]) + p[2]) + p[3]).to(torch.bfloat16) + pairwise = ((p[0] + p[1]) + (p[2] + p[3])).to(torch.bfloat16) + y = R.ba_splitk(x, w) + torch.cuda.synchronize() + diff += int(not torch.equal(_bits(y), _bits(serial))) + pairwise_differs += int(not torch.equal(_bits(serial), _bits(pairwise))) + assert diff == 0, diff + assert pairwise_differs == calls, pairwise_differs + + +def test_supports_only_operands_the_kernel_reads(): + """A planned shape of contiguous BF16 operands at the compiled 128-byte alignment; a misaligned or strided view + falls back instead of asserting.""" + from tensorrt_llm._torch.kernels.blackwell.inproj_ba_splitk import supports + + buf = torch.zeros((57 * K,), dtype=torch.bfloat16, device="cuda") + w = torch.zeros((NB, K), dtype=torch.bfloat16, device="cuda") + x = buf[: 56 * K].view(56, K) + assert supports(x, w) + assert supports(buf[K : 57 * K].view(56, K), w) + assert not supports(buf[8 : 8 + 56 * K].view(56, K), w) # 16-byte aligned only + assert not supports(x.t().contiguous().t(), w) + assert not supports(x.float(), w) diff --git a/tests/unittest/_torch/modules/test_low_m_gemm.py b/tests/unittest/_torch/modules/test_low_m_gemm.py index dbc46f56d3a9..677fd698f090 100644 --- a/tests/unittest/_torch/modules/test_low_m_gemm.py +++ b/tests/unittest/_torch/modules/test_low_m_gemm.py @@ -96,6 +96,20 @@ def test_attach_reaches_the_router_gate(monkeypatch) -> None: assert root.gate._low_m_gemm_name == "gate" +def test_a_later_attach_keeps_the_models_own_dispatcher(monkeypatch) -> None: + """The loader's prepare_low_m_gemm after load must not replace a dispatcher the model attached itself + (Qwen3.5: limit_rows, whole_bucket_direct_tiles, per_rank_tuning); new modules still get the later one.""" + monkeypatch.setattr(_mod, "LOW_M_GEMM_ACTIVE", True) + root = torch.nn.Module() + root.own = torch.nn.Linear(8, 8) + model_dispatcher = _mod.prepare_low_m_gemm(root, force=True, whole_bucket_direct_tiles=True) + root.later = torch.nn.Linear(8, 8) + loader_dispatcher = _mod.prepare_low_m_gemm(root) + + assert root.own._low_m_gemm_dispatcher is model_dispatcher + assert root.later._low_m_gemm_dispatcher is loader_dispatcher + + # --------------------------------------------------------------------------- # linear.py fast pre-filter # --------------------------------------------------------------------------- @@ -108,6 +122,52 @@ def test_linear_fast_rejects_m_above_max_m(monkeypatch) -> None: assert not _mod._should_apply_low_m_gemm(torch.empty((33, 128))) +def test_takes_rows_follows_the_module_ceiling(monkeypatch) -> None: + monkeypatch.setattr(_mod, "LOW_M_GEMM_ACTIVE", False) + dispatcher = LowMGemmDispatcher() + plain, limited = torch.nn.Linear(8, 8), torch.nn.Linear(8, 8) + for module in (plain, limited): + module._low_m_gemm_dispatcher = dispatcher + dispatcher.limit_rows(limited, 14) + + assert not _mod.low_m_gemm_takes_rows(torch.nn.Linear(8, 8), 4) + assert _mod.low_m_gemm_takes_rows(plain, _mod._MAX_M) + assert not _mod.low_m_gemm_takes_rows(plain, _mod._MAX_M + 1) + assert _mod.low_m_gemm_takes_rows(limited, 14) + assert not _mod.low_m_gemm_takes_rows(limited, 15) + + +def test_static_fp8_input_scale_is_one_decision(monkeypatch) -> None: + """Linear.static_fp8_input_scale: the scale where an FP8 QDQ layer takes an E4M3 input at these rows, else + None (another quantization, LoRA, bias, a non-scalar scale, or rows on the low-M path).""" + from tensorrt_llm._torch.modules.linear import FP8QDQLinearMethod, Linear, W8A16FP8LinearMethod + + monkeypatch.setattr(_mod, "LOW_M_GEMM_ACTIVE", True) + scale = torch.tensor([0.5], dtype=torch.float32) + + def layer(**overrides): + fields = dict( + quant_method=FP8QDQLinearMethod(), + lora=None, + bias=None, + input_scale=scale, + force_dynamic_quantization=False, + ) + fields.update(overrides) + return MagicMock( + spec=[*fields, "_low_m_gemm_dispatcher"], _low_m_gemm_dispatcher=None, **fields + ) + + rows = _mod._MAX_M + 1 + assert Linear.static_fp8_input_scale(layer(), rows) is scale + assert Linear.static_fp8_input_scale(layer(), _mod._MAX_M) is None + assert Linear.static_fp8_input_scale(layer(quant_method=W8A16FP8LinearMethod()), rows) is None + assert Linear.static_fp8_input_scale(layer(lora=object()), rows) is None + assert Linear.static_fp8_input_scale(layer(bias=torch.zeros(4)), rows) is None + assert Linear.static_fp8_input_scale(layer(force_dynamic_quantization=True), rows) is None + assert Linear.static_fp8_input_scale(layer(input_scale=scale.half()), rows) is None + + # --------------------------------------------------------------------------- # apply() — shape routing and weight transpose # --------------------------------------------------------------------------- diff --git a/tests/unittest/_torch/modules/test_low_m_mma_gemm.py b/tests/unittest/_torch/modules/test_low_m_mma_gemm.py index b9a5233799e2..784af3865af7 100644 --- a/tests/unittest/_torch/modules/test_low_m_mma_gemm.py +++ b/tests/unittest/_torch/modules/test_low_m_mma_gemm.py @@ -49,6 +49,24 @@ def _assert_close(y, ref, tol=1.6e-2): assert err <= tol * ref.float().abs().max().item(), err +def _cublas_fp8(x8, w, s_in, s_w): + """The stock FP8 projection (FP8QDQLinearMethod.apply's cuBLAS call), BF16 out.""" + return torch.ops.trtllm.cublas_scaled_mm( + x8, + w.t(), + scale_a=s_in.reshape(1), + scale_b=s_w.reshape(1), + bias=None, + out_dtype=torch.bfloat16, + ) + + +def _assert_e4m3_near(h8, ref_h8, tag=None): + """E4M3 codes at most one apart (the FP32 sums' order differs from cuBLAS's), almost all equal.""" + codes = (h8.view(torch.uint8).int() - ref_h8.view(torch.uint8).int()).abs() + assert (codes == 0).float().mean().item() > 0.97 and codes.max().item() <= 1, tag + + @pytest.mark.parametrize("m", [1, 9, 28]) @pytest.mark.parametrize( "n,k,tactic", @@ -114,7 +132,7 @@ def test_bf16_segments_and_mixed_launch(m): assert torch.equal(b, L.low_m_mma_gemm(x16=x, w_bf16=wba, tactic_bf16=(16, 1))) -@pytest.mark.parametrize("m", [1, 7, 28]) +@pytest.mark.parametrize("m", [1, 7, 28, 33, 64, 128]) def test_shared_expert_launch(m): """Shared expert as two launches (gate_up + SwiGLU -> E4M3 with the BF16 gate as an n_valid segment, then down) against the stock quantize / cuBLAS FP8 / silu_and_mul / F.linear kernels.""" @@ -127,14 +145,7 @@ def test_shared_expert_launch(m): s_in = _scale(x) gate_w = torch.zeros(8, k, dtype=torch.bfloat16, device="cuda") gate_w[:1] = _bf16_weight(1, k, 12) - gu = torch.ops.trtllm.cublas_scaled_mm( - _squant(x, s_in), - w_gu.t(), - scale_a=s_in.reshape(1), - scale_b=s_gu.reshape(1), - bias=None, - out_dtype=torch.bfloat16, - ) + gu = _cublas_fp8(_squant(x, s_in), w_gu, s_in, s_gu) ref_h8 = torch.ops.trtllm.silu_and_mul(gu, scale=s_dn_in.reshape(1), dtype=torch.float8_e4m3fn) h8, gate = L.low_m_mma_gemm( x16=x, @@ -148,13 +159,12 @@ def test_shared_expert_launch(m): out_scale=s_dn_in, ) assert h8.dtype == torch.float8_e4m3fn and gate.shape == (m, 1) and gate.is_contiguous() - codes = (h8.view(torch.uint8).int() - ref_h8.view(torch.uint8).int()).abs() - assert (codes == 0).float().mean().item() > 0.97 and codes.max().item() <= 1 - _assert_close(gate, x.float() @ gate_w[:1].float().t()) + _assert_e4m3_near(h8, ref_h8) + _assert_close(gate, F.linear(x, gate_w[:1])) out = L.low_m_mma_gemm( x8=h8, w_fp8=w_dn, weight_scale=s_dn_w, input_scale=s_dn_in, fp8_act="fp8" ) - _assert_close(out, (h8.float() @ w_dn.float().t()) * (s_dn_in * s_dn_w)) + _assert_close(out, _cublas_fp8(h8, w_dn, s_dn_in, s_dn_w)) @pytest.mark.parametrize("m", [1, 28]) @@ -254,6 +264,45 @@ def warp_mma_tactic(self, rows, weight, *args, quantize=True, **kwargs): _assert_close(out, ref_out) _assert_close(logits, ref_gate) assert looked_up == plain_fp8_input + # 0 rows (the warp-MMA GEMM refuses M = 0) stay on the stock shared expert, raced rows or not. + for raced_rows in (0, 8): + blk._shared_expert_raced_rows = raced_rows + assert blk._shared_expert_low_m_forward(x[:0]) is None + + +@pytest.mark.parametrize("inter", [512, 64]) # TP2 / TP16 shards of a 1024-wide shared expert +def test_shared_expert_race_candidates_launch(inter, m=128): + """Every tactic the shared expert's two races offer at the row ceiling fits the shard and the kernel's shared + memory, and launches with the stock kernels' outputs (quantize + cuBLAS FP8 + silu_and_mul, F.linear for the + gate, cuBLAS FP8 down) as the heuristic tactic does.""" + k = 4096 + w_gu, s_gu = _fp8_weight(2 * inter, k, 50) + w_dn, s_dn = _fp8_weight(k, inter, 51) + gate_w = torch.zeros(8, k, dtype=torch.bfloat16, device="cuda") + gate_w[:1] = _bf16_weight(1, k, 52) + x = _act(m, k, 53) + s_in = _scale(x) + s_dn_in = torch.tensor(0.05, device="cuda") + gu = _cublas_fp8(_squant(x, s_in), w_gu, s_in, s_gu) + stock_h8 = torch.ops.trtllm.silu_and_mul( + gu, scale=s_dn_in.reshape(1), dtype=torch.float8_e4m3fn + ) + stock_gate = F.linear(x, gate_w[:1]) + up_inputs = [x, L.swiglu_pairs(w_gu), gate_w, s_gu, s_in, s_dn_in] + up = L._SharedExpertLaunchRunner(swiglu=True) + tactics = up.get_valid_tactics(up_inputs, None) + assert tactics + for tactic in (-1, *tactics): + h8, gate = up(up_inputs, tactic=tactic) + _assert_e4m3_near(h8, stock_h8, tactic) + _assert_close(gate, stock_gate) + down_inputs = [stock_h8, w_dn, s_dn, s_dn_in] + stock_out = _cublas_fp8(stock_h8, w_dn, s_dn_in, s_dn) + down = L._SharedExpertLaunchRunner(swiglu=False) + tactics = down.get_valid_tactics(down_inputs, None) + assert tactics + for tactic in (-1, *tactics): + _assert_close(down(down_inputs, tactic=tactic), stock_out) @pytest.mark.parametrize("tp16,n,pad", [(False, 1, False), (True, 4, False), (False, 2, True)]) diff --git a/tests/unittest/_torch/modules/test_resident_fp8_gemm.py b/tests/unittest/_torch/modules/test_resident_fp8_gemm.py new file mode 100644 index 000000000000..a0a6c326655d --- /dev/null +++ b/tests/unittest/_torch/modules/test_resident_fp8_gemm.py @@ -0,0 +1,278 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Decode FP8 projection with its weights loaded before the PDL wait (kernels/blackwell/resident_fp8_gemm.py): bitwise +equal to cuBLAS' nvjet (``torch.ops.trtllm.cublas_scaled_mm``) at the decode target-verify shapes, and in conv mode +to nvjet followed by Triton's causal_conv1d_update. Control: an FP32 GEMM of the same operands (another accumulation +order) must differ from nvjet on the test data, so equality is not a property of the data alone.""" + +import pytest +import torch + +import tensorrt_llm # noqa: F401 (registers torch.ops.trtllm) +from tensorrt_llm._utils import is_blackwell_datacenter + +pytestmark = pytest.mark.skipif( + not is_blackwell_datacenter(), + reason="the kernel runs on SM 10.0 / 10.3 (bitwise against nvjet there)", +) + +N, K = 2560, 4096 + + +def _gen(seed): + return torch.Generator(device="cuda").manual_seed(seed) + + +def _scales(): + return torch.tensor([4.0 / 448.0], device="cuda"), torch.tensor([0.08 / 448.0], device="cuda") + + +def _weight(seed, sb, scale): + g = _gen(seed) + w = torch.randn(N, K, generator=g, device="cuda") * scale + w[:, torch.randint(0, K, (64,), generator=g, device="cuda")] *= 20.0 # outlier columns + return (w / sb).clamp(-448, 448).to(torch.float8_e4m3fn) + + +def _act(m, seed, sa): + g = _gen(seed) + x = torch.randn(m, K, generator=g, device="cuda") + x = ( + x * x * x * torch.exp(torch.randn(m, 1, generator=g, device="cuda")) + ) # heavy tails, per-row scales + x[:, torch.randint(0, K, (8,), generator=g, device="cuda")] *= 30.0 # hot columns + return (x / sa).clamp(-448, 448).to(torch.float8_e4m3fn) + + +def _bits(y): + return y.view(torch.int16) + + +def _fp32_gemm(x, w, sa, sb): + """The GEMM in FP32 (another K order than nvjet's), rounded like the kernel's epilogue.""" + prev = torch.backends.cuda.matmul.allow_tf32 + torch.backends.cuda.matmul.allow_tf32 = False + try: + return ((x.float() @ w.float().t()) * (sa * sb)).to(torch.bfloat16) + finally: + torch.backends.cuda.matmul.allow_tf32 = prev + + +def test_plan(): + from tensorrt_llm._torch.kernels.blackwell import resident_fp8_gemm as R + + assert R.plan(56, K, N) == ( + 2, + 28, + 32, + 15, + ) # 15 resident slots, 17 streamed tiles: the slot ring wraps + assert R.plan(77, K, N) == (3, 26, 32, 15) + assert R.plan(96, K, N) == (3, 32, 32, 15) + assert R.plan(112, K, N) == (3, 38, 48, 11) + assert R.plan(128, K, N) == (3, 43, 48, 11) + assert R.plan(129, K, N) is None + # K in whole x boxes of 8 K tiles, N in whole 128-feature pairs + assert R.plan(56, 2048, N) == (2, 28, 32, 16) and R.plan(56, 1536, N) is None + assert R.plan(56, K, 2500) is None + assert R.plan(56, K, N, 216 * 1024) == (2, 28, 32, 18) + # small budgets shrink the slot ring down to 1 slot; below that the plan falls back + assert R.plan(56, K, N, 100 * 1024) == (2, 28, 32, 4) and R.plan(56, K, N, 90 * 1024) == ( + 2, + 28, + 32, + 3, + ) + assert ( + R.plan(56, K, N, 65536 + 2048 + 8192) == (2, 28, 32, 1) + and R.plan(56, K, N, 65536 + 2048 + 4096) is None + ) + assert R.plan_conv(56, 7, K, N) == (2, 28, 32, 15, 14) + assert R.plan_conv(77, 7, K, N) == (3, 28, 32, 15, 14) + assert R.plan_conv(13 * 7, 7, K, N) == ( + 3, + 42, + 48, + 11, + 21, + ) # 13-18 requests: 3 per CTA half at TN 48 + assert R.plan_conv(19 * 7, 7, K, N) is None + # x + weight slots + barriers within the budget, and the budget within the 196 KB split beside three 512 B CTAs + # (200,704 B - 3 x (512 B + 1 KB reserved) - this CTA's 1 KB reserved = 195,072 B) + for m in (56, 112): + _, _, tn, r = R.plan(m, K, N) + assert r * R.W_TILE + (K // R.K_BOX) * (tn // 2) * R.K_BOX + 2048 <= R.SMEM_BUDGET <= 195072 + + +def test_bitwise_smallest_ring(): + """1 resident slot (the minimum): all 31 other K tiles stream through it, one after the other.""" + from tensorrt_llm._torch.kernels.blackwell import resident_fp8_gemm as R + + sa, sb = _scales() + bud = 65536 + 2048 + 8192 + assert R.plan(56, K, N, bud)[3] == 1 + for c in range(3): + w = _weight(600 + c, sb, 0.02) + x = _act(56, 700 + c, sa) + ref = torch.ops.trtllm.cublas_scaled_mm(x, w.t(), sa, sb, None, torch.bfloat16) + y = R.resident_fp8_gemm(x, w, sa, sb, budget=bud) + torch.cuda.synchronize() + assert torch.equal(_bits(y), _bits(ref)), c + assert not torch.equal(_bits(_fp32_gemm(x, w, sa, sb)), _bits(ref)), c + + +@pytest.mark.parametrize("budget", [None, 216 * 1024], ids=["default", "b216"]) +@pytest.mark.parametrize("m", [33, 56, 77, 96, 112, 128]) +def test_bitwise_vs_nvjet(m, budget): + from tensorrt_llm._torch.kernels.blackwell import resident_fp8_gemm as R + + bud = R.SMEM_BUDGET if budget is None else budget + sa, sb = _scales() + calls = 6 + diff = other_order = 0 + for c in range(calls): + w = _weight(100 + c, sb, 0.02 if c % 2 == 0 else 0.05) + x = _act(m, 200 + c, sa) + ref = torch.ops.trtllm.cublas_scaled_mm(x, w.t(), sa, sb, None, torch.bfloat16) + y = R.resident_fp8_gemm(x, w, sa, sb, budget=bud) + torch.cuda.synchronize() + diff += int(not torch.equal(_bits(y), _bits(ref))) + other_order += int(not torch.equal(_bits(_fp32_gemm(x, w, sa, sb)), _bits(ref))) + assert diff == 0, f"{diff} of {calls} calls differ from nvjet" + # Without this the check could not tell a changed accumulation order from nvjet's. + assert other_order == calls, f"the FP32 GEMM differs in only {other_order} of {calls}" + + +@pytest.mark.parametrize( + "case", + [ + (8, "dim_last"), + (8, "dim_first"), + (11, "dim_last"), + (11, "dim_first"), + (16, "dim_last"), + (16, "dim_first"), + ], +) +def test_conv_bitwise_vs_nvjet_and_triton_conv(case): + """Conv mode (GDN MTP target-verify, 7 tokens per request): the convolved q|k|v columns, the raw z columns, the + conv state of every slot and the per-token windows equal cuBLAS followed by Triton's causal_conv1d_update with + the model's arguments (gdn_mixer._fused_verify), with a padded request in odd calls.""" + from tensorrt_llm._torch.kernels.blackwell import resident_fp8_gemm as R + from tensorrt_llm._torch.modules.mamba.causal_conv1d_triton import causal_conv1d_update + + nreq, layout = case + qt, c_dim, slots_n = 7, 1536, 32 + m = nreq * qt + sa, sb = _scales() + calls = 4 + diff = {"qkv": 0, "z": 0, "state": 0, "windows": 0} + other_order = 0 + for c in range(calls): + gen = _gen(300 + c) + w = _weight(400 + c, sb, 0.02) + x = _act(m, 500 + c, sa) + cw = (torch.randn(c_dim, 4, generator=gen, device="cuda") * 0.5).to(torch.bfloat16) + if layout == "dim_last": + st0 = torch.randn(slots_n, c_dim, 3, generator=gen, device="cuda").to(torch.bfloat16) + else: + st0 = ( + torch.randn(slots_n, 3, c_dim, generator=gen, device="cuda") + .to(torch.bfloat16) + .permute(0, 2, 1) + ) + slots = torch.randperm(slots_n, generator=gen, device="cuda")[:nreq].to(torch.int32) + if c % 2: + slots[nreq // 2] = -1 # padding: no outputs compared, no state / window writes + win0 = torch.zeros(16, qt, c_dim, 3, dtype=torch.bfloat16, device="cuda") + keep = slots >= 0 + rows = keep.repeat_interleave(qt) + raw = torch.ops.trtllm.cublas_scaled_mm(x, w.t(), sa, sb, None, torch.bfloat16) + st_r, win_r = st0.clone(), win0.clone() + ref = causal_conv1d_update( + raw[:, :c_dim].reshape(nreq, qt, c_dim).transpose(1, 2), + st_r, + cw, + None, + "silu", + conv_state_indices=slots, + intermediate_conv_window=win_r, + intermediate_state_indices=torch.arange(nreq, dtype=torch.int32, device="cuda"), + hoist_x=True, + ) + ref = ref.transpose(1, 2).reshape(m, c_dim) + st, win = st0.clone(), win0.clone() + y = R.resident_fp8_gemm( + x, + w, + sa, + sb, + conv=R.ConvUpdate(weight=cw, state=st, slots=slots, windows=win, tokens=qt), + ) + ctl = causal_conv1d_update( + _fp32_gemm(x, w, sa, sb)[:, :c_dim].reshape(nreq, qt, c_dim).transpose(1, 2), + st0.clone(), + cw, + None, + "silu", + conv_state_indices=slots, + intermediate_conv_window=win0.clone(), + intermediate_state_indices=torch.arange(nreq, dtype=torch.int32, device="cuda"), + hoist_x=True, + ) + ctl = ctl.transpose(1, 2).reshape(m, c_dim) + torch.cuda.synchronize() + diff["qkv"] += int( + not torch.equal(_bits(y[rows, :c_dim].contiguous()), _bits(ref[rows].contiguous())) + ) + diff["z"] += int( + not torch.equal(_bits(y[:, c_dim:].contiguous()), _bits(raw[:, c_dim:].contiguous())) + ) + diff["state"] += int(not torch.equal(_bits(st.contiguous()), _bits(st_r.contiguous()))) + diff["windows"] += int( + not torch.equal( + _bits(win[:nreq][keep].contiguous()), _bits(win_r[:nreq][keep].contiguous()) + ) + ) + other_order += int( + not torch.equal(_bits(ctl[rows].contiguous()), _bits(ref[rows].contiguous())) + ) + assert all(v == 0 for v in diff.values()), diff + # A K-order change can leave every convolved output of a call unchanged after the BF16 roundings, so the + # control must fire in most calls, not all. + assert other_order >= calls - 1, other_order + + +def test_supports_only_operands_the_kernel_reads(): + """The FP8 linear's gate (``supports``): a planned shape of contiguous E4M3 operands at the compiled 128-byte + alignment; a misaligned or strided view or a BF16 input falls back to cuBLAS instead of asserting.""" + from tensorrt_llm._torch.kernels.blackwell.resident_fp8_gemm import supports + + buf = torch.zeros((17 * K,), dtype=torch.float8_e4m3fn, device="cuda") + w = torch.zeros((N, K), dtype=torch.float8_e4m3fn, device="cuda") + x = buf[: 16 * K].view(16, K) + assert supports(x, w) + assert supports(buf[K : 17 * K].view(16, K), w) # a whole-row offset keeps the alignment + assert not supports(buf[16 : 16 + 16 * K].view(16, K), w) # 16-byte aligned only + assert not supports(x.t().contiguous().t(), w) + assert not supports(x.to(torch.bfloat16), w) + + +def test_supports_conv_rejects_strided_slots(): + """Conv mode reads the slots as one contiguous int32 row (``torch.as_strided(slots, (1,), (1,))``): a strided + slot view falls back to the unfused path instead of reading the wrong slots.""" + from tensorrt_llm._torch.kernels.blackwell import resident_fp8_gemm as R + + qt, c_dim, nreq = 7, 1536, 8 + x = torch.zeros((nreq * qt, K), dtype=torch.float8_e4m3fn, device="cuda") + w = torch.zeros((N, K), dtype=torch.float8_e4m3fn, device="cuda") + cw = torch.zeros((c_dim, 4), dtype=torch.bfloat16, device="cuda") + st = torch.zeros((32, c_dim, 3), dtype=torch.bfloat16, device="cuda") + win = torch.zeros((16, qt, c_dim, 3), dtype=torch.bfloat16, device="cuda") + slots = torch.arange(2 * nreq, dtype=torch.int32, device="cuda") + + def conv(s: torch.Tensor) -> "R.ConvUpdate": + return R.ConvUpdate(weight=cw, state=st, slots=s, windows=win, tokens=qt) + + assert R.supports_conv(x, w, conv(slots[:nreq])) + assert not R.supports_conv(x, w, conv(slots[::2])) diff --git a/tests/unittest/_torch/moe/fused_moe/test_cutedsl_evict_first_tuning.py b/tests/unittest/_torch/moe/fused_moe/test_cutedsl_evict_first_tuning.py new file mode 100644 index 000000000000..5fddb7951cd9 --- /dev/null +++ b/tests/unittest/_torch/moe/fused_moe/test_cutedsl_evict_first_tuning.py @@ -0,0 +1,124 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""The CuTe DSL evict-first FC2 finalize runner tunes up to the token bound its caller selects it for +(``MoEDecodeOptions.fc2_weights_evict_first_rows``), not only up to the tuning call's tokens; where the tuning call +is at that bound (the Qwen3.5 DEP4 GEN reference) the tuned profiles and every cache key are unchanged.""" + +import pytest +import torch + +import tensorrt_llm._torch.custom_ops.cute_dsl_custom_ops as cute_dsl_custom_ops +from tensorrt_llm._torch.autotuner import AutoTuner +from tensorrt_llm._torch.cute_dsl_utils import IS_CUTLASS_DSL_AVAILABLE + +pytestmark = [ + pytest.mark.cpu_only, + pytest.mark.skipif(not IS_CUTLASS_DSL_AVAILABLE, reason="Requires CUTLASS DSL"), +] + +# Qwen3.5-397B NVFP4 under DEP4: 512 experts, top-10, EP4 (128 local experts), hidden 4096, expert I 1024. +_EXPERTS, _TOP_K, _LOCAL, _HIDDEN, _INTER = 512, 10, 128, 4096, 1024 +# DEP4 GEN reference: CUDA graphs up to 48 requests x 7 rows (MTP 6) per rank. The evict-first bound is +# those rows x dp_size; the generation-only autotuner warmup runs 48 x 7 rows per rank, which the EP4 +# dispatch receives from every rank. +_DEP4_BOUND = 48 * 7 * 4 +_DEP4_TUNING_TOKENS = 4 * 48 * 7 + + +def _runner(monkeypatch, tile_size: int, evict_first: bool, max_tokens: int): + monkeypatch.setattr(cute_dsl_custom_ops, "get_sm_version", lambda: 103) + return cute_dsl_custom_ops.Sm100BlockScaledContiguousGroupedGemmFinalizeFusionRunner( + _EXPERTS, + _TOP_K, + _LOCAL, + 0, + tile_size, + torch.bfloat16, + weights_evict_first=evict_first, + weights_evict_first_max_tokens=max_tokens, + ) + + +def _helper(tile_size: int): + return cute_dsl_custom_ops.GroupedGemmInputsHelper(_EXPERTS, _TOP_K, _LOCAL, 0, tile_size) + + +def _inputs(tokens: int, tile_size: int) -> list: + """Shapes of the finalize op's inputs for a call of ``tokens`` tokens (meta tensors: only shapes matter).""" + rows = _helper(tile_size).get_max_num_permuted_tokens(tokens) + meta = dict(device="meta") + return [ + torch.empty((rows, _INTER // 2), **meta), + torch.empty((_LOCAL, _HIDDEN, _INTER // 2), **meta), + torch.empty((rows * _INTER // 16,), **meta), + torch.empty((_LOCAL, _HIDDEN, _INTER // 16), **meta), + torch.empty((_LOCAL,), **meta), + torch.empty((tokens, _HIDDEN), **meta), + torch.empty((rows // tile_size,), **meta), + torch.empty((rows // tile_size,), **meta), + torch.empty((rows,), **meta), + torch.empty((1,), **meta), + torch.empty((tokens, _TOP_K), **meta), + ] + + +def _profiles(config, inputs) -> list: + return [p.get_opt_shapes() for p in AutoTuner.get()._optimization_profiles(config, inputs)] + + +@pytest.mark.parametrize("tile_size", [128, 256]) +def test_evict_first_runner_tunes_up_to_its_bound(monkeypatch, tile_size) -> None: + helper = _helper(tile_size) + evict = _runner(monkeypatch, tile_size, True, _DEP4_BOUND).get_tuning_config() + assert evict.tune_max_num_tokens == helper.get_max_num_permuted_tokens(_DEP4_BOUND) + # Without the evict-first policy (or a bound) the runner keeps tuning up to the tuning call. + assert ( + _runner(monkeypatch, tile_size, False, _DEP4_BOUND).get_tuning_config().tune_max_num_tokens + is None + ) + assert _runner(monkeypatch, tile_size, True, 0).get_tuning_config().tune_max_num_tokens is None + # A tuning call below the bound (e.g. fewer warmup tokens than the evict-first rows) still tunes every + # bucket that a call the runner serves (1..bound tokens) looks up; without the bound the larger ones are + # missing, so those calls ran the default tactic. + small = _inputs(_DEP4_BOUND // 4, tile_size) + untuned = _runner(monkeypatch, tile_size, True, 0).get_tuning_config() + looked_up = { + helper.map_to_tuning_buckets(helper.get_max_num_permuted_tokens(t)) + for t in range(1, _DEP4_BOUND + 1) + } + tuned = lambda config: {p[0][0] for p in _profiles(config, small)} # noqa: E731 + assert looked_up <= tuned(evict) + assert not looked_up <= tuned(untuned) + + +@pytest.mark.parametrize("tile_size", [128, 256]) +def test_dep4_reference_tuning_is_unchanged(monkeypatch, tile_size) -> None: + """DEP4 GEN reference: the tuning call is at the evict-first bound, so the bound adds no profile, and every + runtime call the evict-first runner serves (1..bound tokens) reads the same cache key.""" + assert _DEP4_TUNING_TOKENS == _DEP4_BOUND + with_bound = _runner(monkeypatch, tile_size, True, _DEP4_BOUND).get_tuning_config() + without = _runner(monkeypatch, tile_size, True, 0).get_tuning_config() + tuning_inputs = _inputs(_DEP4_TUNING_TOKENS, tile_size) + assert _profiles(with_bound, tuning_inputs) == _profiles(without, tuning_inputs) + + def key(config, shapes: tuple, at_runtime: bool) -> tuple: + return AutoTuner._find_nearest_profile( + tuple(torch.Size(s) for s in shapes), + config.dynamic_tensor_specs, + config.constraint_specs, + config.tune_max_num_tokens, + at_runtime, + ) + + # Lookups at runtime (bucketed) ... + for tokens in range(1, _DEP4_BOUND + 1): + shapes = tuple(tuple(t.shape) for t in _inputs(tokens, tile_size)) + assert key(with_bound, shapes, True) == key(without, shapes, True), tokens + # ... and the keys the tuned profiles are stored under. + for profile in _profiles(without, tuning_inputs): + assert key(with_bound, profile, False) == key(without, profile, False), profile + + +def test_finalize_op_takes_the_bound() -> None: + schema = torch.ops.trtllm.cute_dsl_nvfp4_grouped_gemm_finalize_inplace_blackwell.default._schema + assert "weights_evict_first_max_tokens" in [a.name for a in schema.arguments] diff --git a/tests/unittest/_torch/moe/kernels/parallel/test_cute_dsl_moe.py b/tests/unittest/_torch/moe/kernels/parallel/test_cute_dsl_moe.py index 44ae7440d93c..f7ccd3ca7b65 100644 --- a/tests/unittest/_torch/moe/kernels/parallel/test_cute_dsl_moe.py +++ b/tests/unittest/_torch/moe/kernels/parallel/test_cute_dsl_moe.py @@ -1047,6 +1047,81 @@ def test_nvfp4_grouped_gemm_finalize_blackwell( assert match_ratio > 0.99 +@pytest.mark.skipif( + get_sm_version() not in (100, 103), + reason="This test is only supported on SM 100 and SM 103 GPUs", +) +@pytest.mark.skipif(not IS_CUTLASS_DSL_AVAILABLE, reason="cutlass-dsl is not available") +@pytest.mark.parametrize("top_k", [1, 2]) +@pytest.mark.parametrize("num_tokens", [7, 48 * 7, 4 * 52 * 7]) +def test_nvfp4_grouped_gemm_finalize_weights_evict_first_bitwise(num_tokens: int, top_k: int): + """The L2 evict_first policy on the FC2 weight loads leaves every output bit unchanged (top-k <= 2: the + finalize's scatter-add is order-independent).""" + sf_vec_size, tile_size = 16, 128 + hidden_size, interm_size = 4096, 1024 + num_experts, num_local_experts = 512, 128 + + torch.manual_seed(0) + routing_logits = torch.randn(num_tokens, num_experts, device="cuda") + # Token 0 picks local expert 0 first, so the output is never all zero (no local pick at all). + routing_logits[0, 0] = routing_logits.max() + 1 + token_final_scales, token_selected_experts = routing_logits.topk(top_k, dim=-1) + token_selected_experts = token_selected_experts.to(torch.int32) + token_final_scales = token_final_scales.softmax(dim=-1).to(torch.float32) + ( + tile_idx_to_group_idx, + tile_idx_to_mn_limit, + _, + permuted_idx_to_expanded_idx, + _, + num_non_exiting_tiles, + ) = torch.ops.trtllm.moe_sort( + token_selected_experts=token_selected_experts, + token_final_scales=token_final_scales, + num_experts=num_experts, + top_k=top_k, + local_expert_offset=0, + local_num_experts=num_local_experts, + tile_tokens_dim=tile_size, + ) + a = torch.randn(permuted_idx_to_expanded_idx.size(0), interm_size, device="cuda").bfloat16() + b = torch.randn(num_local_experts, hidden_size, interm_size, device="cuda").bfloat16() + a_global_sf = a.abs().max().float() / (448 * 6) + b_global_sf = b.abs().amax(dim=(1, 2)).float() / (448 * 6) + a, a_sf = torch.ops.trtllm.fp4_quantize(a, 1 / a_global_sf, sf_vec_size, False) + b, b_sf = torch.ops.trtllm.fp4_quantize(b, 1 / b_global_sf, sf_vec_size, False) + b_sf = b_sf.view(num_local_experts, hidden_size, interm_size // sf_vec_size) + + def run(weights_evict_first): + out = torch.zeros(num_tokens, hidden_size, dtype=torch.bfloat16, device="cuda") + torch.ops.trtllm.cute_dsl_nvfp4_grouped_gemm_finalize_inplace_blackwell( + a.view(torch.float4_e2m1fn_x2), + b.view(torch.float4_e2m1fn_x2), + a_sf, + b_sf, + a_global_sf * b_global_sf, + out, + tile_idx_to_group_idx, + tile_idx_to_mn_limit, + permuted_idx_to_expanded_idx, + num_non_exiting_tiles, + token_final_scales, + num_experts=num_experts, + top_k=top_k, + num_local_experts=num_local_experts, + local_expert_offset=0, + tile_size=tile_size, + output_dtype=torch.bfloat16, + scaling_vector_size=sf_vec_size, + weights_evict_first=weights_evict_first, + ) + return out + + expected = run(False) + assert expected.abs().sum().item() > 0 + assert torch.equal(run(True).view(torch.int16), expected.view(torch.int16)) + + @pytest.mark.skipif( get_sm_version() not in (100, 103), reason="This test is only supported on SM 100 and SM 103 GPUs", diff --git a/tests/unittest/_torch/moe/test_moe_backend.py b/tests/unittest/_torch/moe/test_moe_backend.py index 141ec515ad9f..3ddf148131f2 100644 --- a/tests/unittest/_torch/moe/test_moe_backend.py +++ b/tests/unittest/_torch/moe/test_moe_backend.py @@ -614,6 +614,7 @@ def test_cutedsl_direct_metadata_tuning_buckets_capacity_and_legacy_uses_tokens( assert legacy_dynamic_spec.map_to_tuning_buckets(expert_capacity_rows) == 512 +@pytest.mark.cpu_only @pytest.mark.parametrize("decode_tuning", [False, True]) def test_fp4_block_scale_moe_decode_tuning(decode_tuning: bool) -> None: """Only a model that declares decode tuning gets the decode-step buckets and rank 0's tactic on every @@ -636,6 +637,175 @@ def test_fp4_block_scale_moe_decode_tuning(decode_tuning: bool) -> None: assert set(spec.gen_tuning_buckets) & set(range(1, 129)) == set(pow2) assert [spec.map_to_tuning_buckets(m) for m in (7, 14, 28, 130)] == [4, 8, 16, 128] + # Only the declaring model's tuning cache key carries the flag, and with it do_finalize (finalized and + # un-finalized calls run different kernels). + for do_finalize in (False, True): + runner = FP4BlockScaleMoERunner( + 512, 10, None, None, 512, 0, 64, None, 1, do_finalize, 0, decode_tuning=decode_tuning + ) + assert runner.unique_id() == (10, 512, 64, 0) + ( + (True, do_finalize) if decode_tuning else () + ) + + +@pytest.mark.cpu_only +@pytest.mark.parametrize("do_finalize", [False, True]) +def test_fp4_block_scale_decode_tactic_key_matches_tuning( + monkeypatch: pytest.MonkeyPatch, do_finalize: bool +) -> None: + """``decode_tactic`` finds the entry the MoE op's own lookup finds for a call of that ``do_finalize``: the + entry is stored under the runner, tuning config and shapes that ``_run_fp4_block_scale_moe`` builds. A + mismatch leaves every decode front without a tactic, so it falls back to the stock MoE.""" + from tensorrt_llm._torch.autotuner import AutoTunerProfilingCache + from tensorrt_llm._torch.custom_ops.trtllm_gen_custom_ops import _run_fp4_block_scale_moe + from tensorrt_llm._torch.moe.fused_moe.routing import RenormalizeMoeRoutingMethod + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.fp4_block_scale import ( + TRTLLMGenFp4BlockScaleBase, + ) + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.kernel_inputs import to_trtllm_gen_act_type + from tensorrt_llm._torch.utils import ActivationType + + tuned_tactic = [8, 3] + # Bypasses __init__, which queries the device. + cache = AutoTunerProfilingCache.__new__(AutoTunerProfilingCache) + cache.cache = {} + + class _OpLookedUp(Exception): + pass + + class _Tuner: + """Stores the op's tactic where the op's runtime lookup searches, then stops the op before its kernel.""" + + is_tuning_mode = False + profiling_cache = cache + _find_nearest_profile = AutoTuner._find_nearest_profile + + def choose_one(self, custom_op, runners, tuning_config, inputs, **kwargs): + shapes = tuple(AutoTuner._get_input_sizes(self, inputs)) + key = cache.get_cache_key(custom_op, runners[0], shapes, tuning_config) + cache[key] = (0, tuned_tactic, 1.0) + raise _OpLookedUp + + tuner = _Tuner() + monkeypatch.setattr(AutoTuner, "get", classmethod(lambda cls: tuner)) + num_slots, top_k, num_local, inter, hidden, m = 512, 10, 64, 512, 4096, 14 + + def meta(*shape): + return torch.empty(shape, dtype=torch.uint8, device="meta") + + backend = SimpleNamespace( + routing_method=RenormalizeMoeRoutingMethod(top_k=top_k), + num_slots=num_slots, + slot_start=0, + expert_size_per_partition=num_local, + _intermediate_size_padded=lambda: inter, + activation_type=ActivationType.Swiglu, + max_num_tokens=8192, + use_dp=False, + decode_tuning=True, + bias=False, + act_alpha=None, + act_beta=None, + act_clamp=None, + w3_w1_weight=meta(num_local, 2 * inter, hidden // 2), + w3_w1_weight_scale=meta(num_local, 2 * inter, hidden // 16), + w2_weight=meta(num_local, hidden, inter // 2), + w2_weight_scale=meta(num_local, hidden, inter // 16), + ) + # Not tuned yet. + assert TRTLLMGenFp4BlockScaleBase.decode_tactic(backend, m, do_finalize) is None + # The op call TRTLLMGenFp4BlockScaleBase.run_moe makes for m router-logit rows. + with pytest.raises(_OpLookedUp): + _run_fp4_block_scale_moe( + meta(m, num_slots), + None, + meta(m, hidden // 2), + meta(m * hidden // 16), + backend.w3_w1_weight, + backend.w3_w1_weight_scale, + None, + None, + None, + None, + backend.w2_weight, + backend.w2_weight_scale, + None, + None, + None, + None, + num_slots, + top_k, + None, + None, + inter, + backend.slot_start, + num_local, + None, + int(backend.routing_method.routing_method_type), + do_finalize, + to_trtllm_gen_act_type(backend.activation_type), + tune_max_num_tokens=backend.max_num_tokens, + use_dp=backend.use_dp, + decode_tuning=backend.decode_tuning, + ) + assert TRTLLMGenFp4BlockScaleBase.decode_tactic(backend, m, do_finalize) == tuned_tactic + # The other do_finalize runs other kernels and is tuned apart. + assert TRTLLMGenFp4BlockScaleBase.decode_tactic(backend, m, not do_finalize) is None + + +@pytest.mark.cpu_only +def test_decode_front_tactics_per_do_finalize() -> None: + """The decode front looks the MoE tactic and its front race up and caches them per (rows, do_finalize), the + key the MoE op tunes them under: an un-finalized call never takes a finalized call's tactic or its miss.""" + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen import decode_front as df + + num_experts, top_k = 512, 10 + asked = [] + + def decode_tactic(m: int, do_finalize: bool): + asked.append((m, do_finalize)) + return None if do_finalize else [8, 0] + + backend = SimpleNamespace(decode_tactic=decode_tactic) + front = df.DecodeFront(frozenset()) + assert front._moe_tactic(backend, 14, True) is None + assert front._moe_tactic(backend, 14, False) == [8, 0] + assert front._moe_tactic(backend, 14, False) == [8, 0] # cached + assert asked == [(14, True), (14, False)] + + moe = SimpleNamespace( + backend=SimpleNamespace( + decode_tactic=decode_tactic, expert_size_per_partition=num_experts, slot_start=0 + ), + routing_method=SimpleNamespace(experts_per_token=top_k), + ) + gate = SimpleNamespace(weight=torch.empty(num_experts, 16)) + unfinalized = front._front_runner(gate, moe, False) + finalized = front._front_runner(gate, moe, True) + assert unfinalized.tile_of(7) == 8 and finalized.tile_of(7) is None + assert unfinalized.unique_id() != finalized.unique_id() + + +@pytest.mark.cpu_only +def test_fp4_block_scale_moe_op_mutability() -> None: + """The NVFP4 MoE op every model reaches is functional (torch.compile can trace it); the decode kernels' op + declares the buffers its engine writes.""" + import tensorrt_llm._torch.custom_ops.trtllm_gen_custom_ops # noqa: F401 + + def written(op): + return { + a.name for a in op.default._schema.arguments if a.alias_info and a.alias_info.is_write + } + + assert written(torch.ops.trtllm.fp4_block_scale_moe_runner) == set() + assert written(torch.ops.trtllm.fp4_block_scale_moe_decode_runner) == { + "decode_engine_state", + "lamport_fc2_out", + "prerouted_tables", + "prerouted_ids", + "prerouted_weights", + } + @pytest.mark.cpu_only @pytest.mark.parametrize( @@ -7073,6 +7243,26 @@ def route(router_logits, input_ids=None): ) +@pytest.mark.cpu_only +@pytest.mark.parametrize( + "comm,dp_padding", [(object(), False), (None, True)], ids=["comm", "dp_padding"] +) +def test_lamport_fc2_out_rejects_communication_and_padding(comm, dp_padding): + """The MoE-output all-reduce polls the Lamport FC2 rows of this rank's tokens only, as prerouted routing.""" + moe = _chunking_moe(SimpleNamespace(takes_lamport_fc2_out=True), num_chunks=1) + moe.comm = comm + with pytest.raises(ValueError, match="without communication or padding"): + ExternalCommMoEScheduler(moe).forward( + torch.zeros((4, 8), dtype=torch.bfloat16), + torch.zeros((4, 4)), + do_finalize=False, + output_dtype=torch.bfloat16, + all_rank_num_tokens=None, + use_dp_padding=dp_padding, + lamport_fc2_out=torch.empty((8, 8), dtype=torch.bfloat16), + ) + + def _forward_in_two_chunks(backend) -> Tuple[torch.Tensor, torch.Tensor]: """Eight tokens through the external-comm scheduler, split into two chunks of four. Integer-valued, so the expected ``x * 2`` is exact in bfloat16.""" diff --git a/tests/unittest/_torch/moe/test_moe_bf16_engine.py b/tests/unittest/_torch/moe/test_moe_bf16_engine.py new file mode 100644 index 000000000000..709b1487b4aa --- /dev/null +++ b/tests/unittest/_torch/moe/test_moe_bf16_engine.py @@ -0,0 +1,269 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""The BF16 decode MoE engine (kernels/blackwell/moe_bf16_engine.py) against trtllm::bf16_moe_runner routed from +the router logits, un-finalized: per (token, k) the same pick and gemm2 row bit for bit and the BF16 top-k weight +within 1 ulp (the engine's softmax is ex2.approx / rcp.approx, the runner's expf / IEEE divide), through each op's own +expanded -> permuted index (the engine packs the local picks' rows), at the Qwen3.5 MTP draft layer's shapes (512 +experts, top-10, hidden 4096, intermediate 512 per rank, 128 / 64 local experts) and at 256 experts, top-8.""" + +from types import SimpleNamespace + +import pytest +import torch + +from tensorrt_llm._utils import is_blackwell_datacenter + +pytestmark = pytest.mark.skipif(not is_blackwell_datacenter(), reason="needs SM 10.0 / 10.3") + +H, E, TOPK, INTER = 4096, 512, 10, 512 + + +def _assert_within_one_ulp(got: torch.Tensor, ref: torch.Tensor) -> None: + """Positive BF16 weights at most one ulp apart (as int16 bit patterns, adjacent values differ by 1).""" + assert (got > 0).all() and (ref > 0).all() + ulps = (got.view(torch.int16).int() - ref.view(torch.int16).int()).abs() + assert int(ulps.max()) <= 1, f"top-k weights {int(ulps.max())} ulp apart" + + +def _gen(seed): + return torch.Generator(device="cuda").manual_seed(seed) + + +def _experts(e_local, seed): + """BF16 experts in the trtllm-gen BlockMajorK layout both kernels read.""" + g = _gen(seed) + w31 = (torch.randn((e_local, H // 64, 2 * INTER, 64), generator=g, device="cuda") * 0.02).to( + torch.bfloat16 + ) + w2 = (torch.randn((e_local, INTER // 64, H, 64), generator=g, device="cuda") * 0.02).to( + torch.bfloat16 + ) + return w31, w2 + + +def _inputs(m, num_experts, local_start, e_local, seed): + g = _gen(seed) + x = torch.randn(m, H, generator=g, device="cuda").to(torch.bfloat16) + lg = torch.randn(m, num_experts, generator=g, device="cuda") + lg[:, local_start : local_start + e_local] += 1.0 # most picks local + return x, lg.to(torch.bfloat16) + + +def _reference(x, lg, w31, w2, top_k, local_start, e_local): + from tensorrt_llm._torch.moe.fused_moe.moe_op_backend import TRTLLMOpBackend + from tensorrt_llm._torch.moe.fused_moe.routing import RoutingMethodType + from tensorrt_llm._torch.utils import ActType_TrtllmGen + + return TRTLLMOpBackend().run_bf16_moe( + lg, + None, + x, + w31, + w2, + lg.shape[1], + top_k, + None, + None, + INTER, + local_start, + e_local, + None, + RoutingMethodType.Renormalize, + gated_act_type=int(ActType_TrtllmGen.SwiGlu), + do_finalize=False, + ) + + +# 512 / 256 local experts: the draft experts with no or 2-way expert parallelism. +@pytest.mark.parametrize( + "num_experts,top_k,e_local", + [(E, TOPK, 512), (E, TOPK, 256), (E, TOPK, 128), (E, TOPK, 64), (256, 8, 64)], +) +@pytest.mark.parametrize("m", [1, 2, 7, 14, 16, 17, 32]) +def test_engine_matches_bf16_moe_runner(m, num_experts, top_k, e_local): + from tensorrt_llm._torch.kernels.blackwell import moe_bf16_engine as eng + + local_start = 64 + w31, w2 = _experts(e_local, 9) + state = eng.new_state(torch.device("cuda")) + for seed in (51 + m, 53 + m): # consecutive calls on one state (both counter parities) + x, lg = _inputs(m, num_experts, local_start, e_local, seed) + h = torch.empty((m * top_k, INTER), dtype=torch.bfloat16, device="cuda") + out = torch.full((m * top_k + 4, H), -1, dtype=torch.int16, device="cuda") + wts = torch.empty((m, top_k), dtype=torch.bfloat16, device="cuda") + e2p = torch.empty((m, top_k), dtype=torch.int32, device="cuda") + eng.moe_bf16_engine( + x, + lg, + w31, + w2, + h, + out[: m * top_k].view(torch.bfloat16), + wts, + e2p, + state, + top_k=top_k, + local_start=local_start, + ) + ref = _reference(x, lg, w31, w2, top_k, local_start, e_local) + torch.cuda.synchronize() + r_rows, r_wts, r_e2p = ref[0], ref[1], ref[2].reshape(m, top_k) + _assert_within_one_ulp(wts, r_wts) + valid = e2p >= 0 + assert torch.equal(valid, r_e2p >= 0), "local picks" + rows = torch.sort(e2p[valid]).values + assert torch.equal( + rows, torch.arange(rows.numel(), dtype=rows.dtype, device=rows.device) + ), "one packed row per local pick" + assert int(valid.sum()) > 0 + got = out[e2p[valid].long()] + assert torch.equal(got, r_rows[r_e2p[valid].long()].view(torch.int16)), "gemm2 rows" + assert (out[m * top_k :] == -1).all(), "wrote past the pair rows" + + +def test_engine_takes_the_layer_shapes(): + from tensorrt_llm._torch.kernels.blackwell.moe_bf16_engine import ( + supports_local_experts, + supports_routing, + ) + + assert supports_routing(512, 10) and supports_routing(256, 8) and supports_routing(512, 16) + assert ( + not supports_routing(512, 17) + and not supports_routing(128, 4) + and not supports_routing(1024, 8) + ) + assert ( + supports_local_experts(E, 128) + and supports_local_experts(E, 64) + and supports_local_experts(E, 32) + ) + assert not supports_local_experts(E, 48) and not supports_local_experts(256, 512) + + +def _leaf_and_inputs(m, e_local, local_start, seed, **overrides): + """A BF16 leaf's attributes that ``decode_moe_bf16`` reads, and its kernel inputs.""" + from tensorrt_llm._torch.moe.fused_moe.quantization import ( + TRTLLM_GEN_WEIGHT_LAYOUT_BLOCK_MAJOR_K, + ) + from tensorrt_llm._torch.moe.fused_moe.routing import RoutingMethodType + from tensorrt_llm._torch.utils import ActivationType + + w31, w2 = _experts(e_local, 9) + x, lg = _inputs(m, E, local_start, e_local, seed) + leaf = dict( + activation_type=ActivationType.Swiglu, + bias=False, + act_alpha=None, + act_beta=None, + act_clamp=None, + routing_method=SimpleNamespace(routing_method_type=RoutingMethodType.Renormalize), + num_slots=E, + expert_size_per_partition=e_local, + slot_start=local_start, + quant_method=SimpleNamespace( + use_shuffled_weight=True, weight_layout=TRTLLM_GEN_WEIGHT_LAYOUT_BLOCK_MAJOR_K + ), + w3_w1_weight=w31, + w2_weight=w2, + ) + k = dict(do_finalize=False, router_logits=lg, routing_bias=None, top_k=TOPK, x=x) + for name, value in overrides.items(): + (leaf if name in leaf else k)[name] = value + return SimpleNamespace(**leaf), SimpleNamespace(**k) + + +def test_decode_moe_bf16_applies_to_the_engine_shapes(): + """``decode_moe_bf16.applies``: an un-finalized logits-routed Renormalize SwiGLU run of 1..M_MAX rows on the + BlockMajorK weights; any other run keeps bf16_moe_runner.""" + from tensorrt_llm._torch.kernels.blackwell.moe_bf16_engine import M_MAX + from tensorrt_llm._torch.moe.fused_moe.routing import RoutingMethodType + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen import decode_moe_bf16 + from tensorrt_llm._torch.utils import ActivationType + + assert decode_moe_bf16.applies(*_leaf_and_inputs(7, 128, 64, 1)) + assert decode_moe_bf16.applies(*_leaf_and_inputs(M_MAX, 64, 0, 1)) + assert not decode_moe_bf16.applies(*_leaf_and_inputs(M_MAX + 1, 128, 64, 1)) + x, lg = _inputs(7, E, 64, 128, 1) + # 16-byte row strides on an 8-byte-offset start: the kernel's 16-byte loads would be misaligned. + hidden = x.shape[1] + x_pad = torch.zeros((7, hidden + 8), dtype=x.dtype, device=x.device) + x_pad[:, 4 : 4 + hidden] = x + lg_pad = torch.zeros(lg.numel() + 4, dtype=lg.dtype, device=lg.device) + lg_pad[4:] = lg.reshape(-1) + for overrides in ( + dict(x=x_pad[:, 4 : 4 + hidden]), + dict(router_logits=lg_pad[4:].view(lg.shape)), + dict(do_finalize=True), + dict(router_logits=None), + dict(routing_bias=torch.zeros(E, device="cuda")), + dict(activation_type=ActivationType.Geglu), + dict(act_clamp=torch.ones(128, device="cuda")), + dict(routing_method=SimpleNamespace(routing_method_type=RoutingMethodType.DeepSeekV3)), + dict(quant_method=SimpleNamespace(use_shuffled_weight=False, weight_layout=None)), + dict(router_logits=lg.t().contiguous().t()), + dict(router_logits=lg.float()), + dict(expert_size_per_partition=48), + ): + assert not decode_moe_bf16.applies(*_leaf_and_inputs(7, 128, 64, 1, **overrides)), overrides + + +@pytest.mark.parametrize("m", [1, 7, 32]) +def test_decode_moe_bf16_run_matches_bf16_moe_runner(m): + """``decode_moe_bf16.run``: the un-finalized (rows, top-k weights, expanded -> permuted index) of bf16_moe_runner, + per (token, k).""" + from tensorrt_llm._torch.kernels.blackwell import moe_bf16_engine as eng + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen import decode_moe_bf16 + + e_local, local_start = 128, 64 + leaf, k = _leaf_and_inputs(m, e_local, local_start, 70 + m) + assert decode_moe_bf16.applies(leaf, k) + rows, wts, e2p = decode_moe_bf16.run(leaf, k, eng.new_state(torch.device("cuda"))) + ref = _reference( + k.x, k.router_logits, leaf.w3_w1_weight, leaf.w2_weight, TOPK, local_start, e_local + ) + torch.cuda.synchronize() + r_rows, r_wts, r_e2p = ref[0], ref[1], ref[2].reshape(m, TOPK) + _assert_within_one_ulp(wts, r_wts) + valid = e2p >= 0 + assert torch.equal(valid, r_e2p >= 0) and int(valid.sum()) > 0 + assert torch.equal( + rows[e2p[valid].long()].view(torch.int16), + r_rows[r_e2p[valid].long()].view(torch.int16), + ) + + +def test_leaf_returns_the_index_tokens_by_top_k(monkeypatch): + """The BF16 leaf's un-finalized output has the expanded -> permuted index [tokens, top_k], like the top-k + weights.""" + from tensorrt_llm._torch.moe.fused_moe.moe_op_backend import TRTLLMOpBackend + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen import trtllm_bf16 + + m, e_local, local_start = 7, 128, 64 + leaf, k = _leaf_and_inputs(m, e_local, local_start, 90) + k = SimpleNamespace( + **vars(k), + n_group=None, + topk_group=None, + routed_scaling_factor=None, + token_final_scales=None, + token_selected_experts=None, + moe_output=None, + ) + monkeypatch.setattr(trtllm_bf16, "prepare_kernel_inputs", lambda impl, ctx: k) + impl = SimpleNamespace( + **vars(leaf), + _decode_engine_state=None, + op_backend=TRTLLMOpBackend(), + intermediate_size_per_partition=INTER, + max_num_tokens=8192, + use_dp=False, + _unfinalized=lambda outputs: outputs, + ) + rows, wts, e2p = trtllm_bf16.TrtllmTrtllmGenBf16Impl.run_moe(impl, None) + ref = _reference( + k.x, k.router_logits, leaf.w3_w1_weight, leaf.w2_weight, TOPK, local_start, e_local + ) + torch.cuda.synchronize() + assert wts.shape == (m, TOPK) and e2p.shape == (m, TOPK) + assert torch.equal(e2p, ref[2]) diff --git a/tests/unittest/_torch/moe/test_moe_decode_front.py b/tests/unittest/_torch/moe/test_moe_decode_front.py index 43c608cf1308..06fccabf2d9f 100644 --- a/tests/unittest/_torch/moe/test_moe_decode_front.py +++ b/tests/unittest/_torch/moe/test_moe_decode_front.py @@ -15,13 +15,15 @@ """TRTLLM-gen NVFP4 MoE decode front (trtllm_gen/decode_front.py): router GEMM, route + tables, the one-launch fused front and the route front against reference routing, and the pre-routed MoE output.""" +from types import SimpleNamespace + import pytest import torch import triton import triton.language as tl from tensorrt_llm._torch.modules.low_m_mma_gemm import default_tactic, low_m_mma_gemm -from tensorrt_llm._torch.moe.fused_moe.impl_contract import PreroutedRouting +from tensorrt_llm._torch.moe.fused_moe.impl_contract import EngineRouting, PreroutedRouting from tensorrt_llm._torch.moe.fused_moe.trtllm_gen import decode_front as df E, K, H = 512, 10, 4096 @@ -121,8 +123,8 @@ def _two_launch(x, w, gs, ls, nl, tile): return logits, out[8], out[9], out[0], out[1], flat -def _route_front(x, w, gs, flat, ls, nl, tile): - front = df.RouteFront() +def _route_front(x, w, gs, flat, ls, nl, tile, lean=False): + front = df.RouteFront(lean=lean) fn = front.compiled(x, E, tile, nl, K) assert fn is not None, "route front does not apply" logits = _cublas(x, w) @@ -201,6 +203,120 @@ def _configs(runner, m, nl, inter): return {t: sorted(c) for t, c in by_tile.items()} +@pytest.mark.parametrize("m", [33, 40, 77, 96, 97, 128]) +def test_route_front_router_gemm(m): + """The route front steps' CuTe router GEMM (moe_router_gemm): as accurate as cuBLAS, and a token's logits do + not depend on the batch it runs in (fixed split-K order); declined above ROUTER_GEMM_MAX_TOKENS rows.""" + x, w, _ = _inputs(m, seed=21 + m) + rg = df.RouteFrontRouterGemm() + a = rg(x, w) + assert a is not None and torch.equal(a, rg(x, w)) + exact = x.float() @ w.float().t() + err = (a.float() - exact).abs().max().item() + err_ref = (_cublas(x, w).float() - exact).abs().max().item() + assert err <= 2 * err_ref + 1e-3, (err, err_ref) + head = rg(x[:33].contiguous(), w) + assert torch.equal(head, a[:33]) + big, _, _ = _inputs(df.ROUTER_GEMM_MAX_TOKENS + 1, seed=21) + assert rg(big, w) is None + + +def _ref_candidates(logits: torch.Tensor, top_k: int = K) -> torch.Tensor: + """trtllm-gen reduceTopK keys (twiddled BF16 << 16 | 65535 - expert) of each 128-expert tile, top ``top_k`` + descending: equal logits go to the smaller expert.""" + m, e = logits.shape + bits = logits.view(torch.int16).to(torch.int64) & 0xFFFF + tw = torch.where((bits & 0x8000) != 0, bits ^ 0xFFFF, bits | 0x8000) + keys = (tw << 16) | (65535 - torch.arange(e, device=logits.device)) + top = keys.view(m, e // 128, 128).sort(dim=-1, descending=True).values[..., :top_k] + return torch.where(top >= 2**31, top - 2**32, top).to(torch.int32) + + +def _engine_route_gemm(x, w, gs, poison: int, top_k: int = K): + """The engine-route router GEMM into outputs filled with ``poison`` (a missing store keeps it).""" + import cuda.bindings.driver as cuda + import cutlass + import cutlass.cute as cute + + from tensorrt_llm._torch.flashinfer_utils import get_env_enable_pdl + from tensorrt_llm._torch.kernels.blackwell.utils import make_ptr + + m, h = x.shape + fn = df._router_gemm_compile(m, h, E, x.stride(0), get_env_enable_pdl(), route_top_k=top_k) + assert fn is not None, "the engine-route router GEMM declined" + dev = x.device + logits = torch.full((m, E), poison, dtype=torch.int16, device=dev).view(torch.bfloat16) + cand = torch.full((m, E // 128, top_k), poison, dtype=torch.int32, device=dev) + xq = torch.full((m, h // 2), poison & 0xFF, dtype=torch.uint8, device=dev) + xsf = torch.full((m, h // 16), poison & 0xFF, dtype=torch.uint8, device=dev) + + def bf(t): + return make_ptr(cutlass.BFloat16, t.data_ptr(), cute.AddressSpace.gmem, assumed_align=16) + + p64 = lambda t: cutlass.Int64(t.data_ptr()) # noqa: E731 + stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream) + fn(bf(x), bf(w), p64(logits), stream, p64(cand), p64(gs), p64(xq), p64(xsf)) + return logits, cand, xq, xsf + + +# Steps the MoE engine routes (above the router GEMM's 32 rows, up to the engine's 64): MTP-6 decode at CUDA-graph +# batches 5..9 (35..63 rows) and the bounds. +@pytest.mark.parametrize( + "m,dup", [(33, False), (35, False), (42, True), (49, False), (56, False), (63, False)] +) +def test_engine_route_router_gemm(m, dup): + """The router GEMM with the engine-route epilogue: logits bitwise the plain kernel's, each token's top-10 keys per + 128-expert tile equal to reduceTopK's (tie order included), x bytes equal to fp4_quantize; every output written + (two runs over different poison).""" + x, w, gs = _inputs(m, seed=1900 + m, dup=dup) + plain = df.RouteFrontRouterGemm()(x, w) + assert plain is not None + q_ref, sf_ref = torch.ops.trtllm.fp4_quantize(x, gs, 16, False, False) + q_ref = q_ref.view(torch.uint8).view(m, H // 2) + sf_ref = sf_ref.view(torch.uint8).flatten()[: m * H // 16].view(m, H // 16) + cand_ref = _ref_candidates(plain) + for poison in (-1, 0x2AAA): + logits, cand, xq, xsf = _engine_route_gemm(x, w, gs, poison) + tag = (m, dup, poison) + assert torch.equal(_bits(logits), _bits(plain)), (tag, "logits") + assert torch.equal(cand, cand_ref), (tag, "candidates") + assert torch.equal(xq, q_ref) and torch.equal(xsf, sf_ref), (tag, "x quant") + out = df.RouteFrontRouterGemm(engine_route=True)(x, w, gs, K) + assert out is not None + for name, a, b in zip(("logits", "cand", "xq", "xsf"), out, (plain, cand_ref, q_ref, sf_ref)): + assert torch.equal(_bits(a), _bits(b)), (m, name) + + +@pytest.mark.parametrize("m,top_k", [(35, 8), (56, 4)]) +def test_engine_route_router_gemm_top_k(m, top_k): + """The routing epilogue for another top-k: each token's top-``top_k`` keys per expert tile equal to reduceTopK's, + logits and x bytes as at top-10.""" + x, w, gs = _inputs(m, seed=1950 + m) + plain = df.RouteFrontRouterGemm()(x, w) + ref = df.RouteFrontRouterGemm(engine_route=True)(x, w, gs, K) + logits, cand, xq, xsf = _engine_route_gemm(x, w, gs, -1, top_k) + assert torch.equal(_bits(logits), _bits(plain)) + assert torch.equal(cand, _ref_candidates(plain, top_k)) + assert torch.equal(xq, ref[2]) and torch.equal(xsf, ref[3]) + + +def test_engine_route_router_gemm_rejects(): + """The routing epilogue takes 1..32 keys per tile and 8 token rows per expert tile in a 32- or 64-token tile: + 256 experts (a 16-token tile) and 33 keys are declined (the caller keeps the route front).""" + from tensorrt_llm._torch.flashinfer_utils import get_env_enable_pdl + from tensorrt_llm._torch.kernels.blackwell.moe_router_gemm import MoeRouterGemmKernel + + pdl = get_env_enable_pdl() + assert df._router_gemm_compile(35, H, 256, H, pdl, route_top_k=K) is None + assert df._router_gemm_compile(35, H, E, H, pdl, route_top_k=33) is None + shape = dict(num_rows=35, k_extent=H, num_experts=E, a_stride=H, token_tile=32) + assert MoeRouterGemmKernel.supports(**shape, route_top_k=K) + assert not MoeRouterGemmKernel.supports(**dict(shape, token_tile=64), route_top_k=K) + assert MoeRouterGemmKernel.supports( + **dict(shape, num_experts=1024, token_tile=64), route_top_k=K + ) + + @pytest.mark.parametrize("m", [1, 7, 32]) def test_router_gemm(m): """Triton router GEMM: deterministic, as accurate as cuBLAS; its fused and the standalone NVFP4 quant are @@ -296,29 +412,42 @@ def test_fused_front_parity(m, nl, ls, tile, dup): # M = 40 (odd split over the 8 routing CTAs), 112 / 224 (MTP-6 verify at batch 16 / 32), 256 (clusters of 8); # 257..1024 run on clusters of 16, above 512 with two-word token masks. +_ROUTE_FRONT_CASES = [ + (21, 64, 448, 8, False, False), + (40, 128, 0, 8, False, False), + (56, 512, 0, 16, False, False), + (224, 128, 384, 32, False, False), + (256, 256, 256, 8, False, False), + (112, 128, 128, 8, True, False), + (224, 128, 0, 8, False, True), + (280, 128, 128, 16, False, False), + (448, 64, 448, 16, False, False), + (448, 128, 0, 16, True, False), + (448, 128, 0, 16, False, True), + (513, 128, 0, 16, False, False), + (896, 256, 256, 32, True, False), + (1024, 128, 0, 16, False, True), +] +# The lean table build runs on clusters of 8 only; above 256 rows the route front takes the default kernel. +_LEAN_MAX_M = 256 + + @pytest.mark.parametrize( - "m,nl,ls,tile,dup,crowd", + "m,nl,ls,tile,dup,crowd,lean", [ - (40, 128, 0, 8, False, False), - (224, 128, 384, 32, False, False), - (256, 256, 256, 8, False, False), - (112, 128, 128, 8, True, False), - (224, 128, 0, 8, False, True), - (280, 128, 128, 16, False, False), - (448, 64, 448, 16, False, False), - (448, 128, 0, 16, True, False), - (448, 128, 0, 16, False, True), - (513, 128, 0, 16, False, False), - (896, 256, 256, 32, True, False), - (1024, 128, 0, 16, False, True), + pytest.param(*c, lean, id="-".join(map(str, ("lean" if lean else "default", *c)))) + for lean in (False, True) + for c in _ROUTE_FRONT_CASES + if not lean or c[0] <= _LEAN_MAX_M ], ) -def test_route_front_parity(m, nl, ls, tile, dup, crowd): +def test_route_front_parity(m, nl, ls, tile, dup, crowd, lean): """The route front after the stock router GEMM equals the Triton route kernel and fp4_quantize bitwise, - tables in token order; a repeated launch gives the same result.""" + tables in token order; a repeated launch gives the same result. ``lean`` (the decode kernels' table build, up + to 256 rows) gives the same bits.""" x, w, gs = _inputs(m, seed=100 + m + nl + tile, dup=dup, crowd=crowd) flat = _flat(m, nl, tile) - lg, xq, xsf, ids, wts = _route_front(x, w, gs, flat, ls, nl, tile) + lg, xq, xsf, ids, wts = _route_front(x, w, gs, flat, ls, nl, tile, lean) ids_r, wts_r, flat_r, xq_r, xsf_r = _ref_route(_cublas(x, w), x, gs, ls, nl, tile) q_ref, sf_ref = torch.ops.trtllm.fp4_quantize(x, gs, 16, False, False) tag = (m, nl, ls, tile, dup, crowd) @@ -335,7 +464,7 @@ def test_route_front_parity(m, nl, ls, tile, dup, crowd): if dup: _check_dup_ties(ids, tag) flat2 = torch.full_like(flat, -7) - again = _route_front(x, w, gs, flat2, ls, nl, tile) + again = _route_front(x, w, gs, flat2, ls, nl, tile, lean) for a, b in zip(again, (lg, xq, xsf, ids, wts)): assert torch.equal(_bits(a), _bits(b)), (tag, "repeat") _check_tables(_tables(flat2, m, nl, tile), _tables(flat, m, nl, tile), tile, (tag, "repeat")) @@ -370,8 +499,9 @@ def __call__(self, x): return _cublas(x, self.weight) -def _front_runner(w, nl, ls, tile): - return df.FrontRunner(df.DecodeFront(frozenset()), _Gate(w), nl, ls, K, lambda m: tile) +def _front_runner(w, nl, ls, tile, decode_kernels=False): + front = df.DecodeFront(frozenset(), decode_kernels=decode_kernels) + return df.FrontRunner(front, _Gate(w), nl, ls, K, lambda m: tile) @pytest.mark.parametrize("m,nl,ls", [(1, 64, 448), (7, 64, 448), (14, 128, 128)]) @@ -419,6 +549,34 @@ def test_front_runner_race(): tuner.clear_cache() +@pytest.mark.parametrize("nl,ls", [(32, 224), (64, 192)]) +def test_front_runner_fused_only(nl, ls, tile=8): + """A front declared with the decode kernels races only the one-launch front's warp splits wherever one takes + the step, so the AutoTuner caches the one-launch front at every row count; the two launches stay the only + tactic where none does (rows not 16-byte aligned). Undeclared fronts keep both.""" + from tensorrt_llm._torch.autotuner import AutoTuner, autotune + + x, w, gs = _inputs(df.FUSED_FRONT_MAX_TOKENS, seed=1650 + nl) + runner = _front_runner(w, nl, ls, tile, decode_kernels=True) + stock = _front_runner(w, nl, ls, tile) + for m in range(1, df.FUSED_FRONT_MAX_TOKENS + 1): + tactics = runner.get_valid_tactics([x[:m], gs], None) + assert tactics and 0 not in tactics, (m, tactics) + assert stock.get_valid_tactics([x[:m], gs], None) == [0, *tactics], m + padded = torch.zeros((7, H + 4), dtype=x.dtype, device=x.device)[:, :H] + assert runner.get_valid_tactics([padded, gs], None) == [0] + tuner = AutoTuner.get() + tuner.clear_cache() + with autotune(): + tuner.choose_one(df.FrontRunner.OP, [runner], df.FrontRunner.TUNING_CONFIG, [x[:7], gs]) + for m in range(1, df.FUSED_FRONT_MAX_TOKENS + 1): + _, tactic = tuner.choose_one( + df.FrontRunner.OP, [runner], df.FrontRunner.TUNING_CONFIG, [x[:m], gs] + ) + assert tactic > 0, (m, tactic) + tuner.clear_cache() + + # front: tables = Triton router GEMM + RouteTables, fused = FusedFront, route = cuBLAS router + RouteFront. # tile None: every tile the runner offers at m; "min": its smallest (above 512 tokens it drops the small tiles). # cfg None: first and last config of the tile; an int forces it (m 448 tile 16 config 0 is what the autotuner @@ -636,7 +794,7 @@ def __init__(self, calls: list[str]) -> None: "Backend", (), dict( - decode_tactic=lambda _, m: [8, 0], + decode_tactic=lambda _, m, do_finalize: [8, 0], slot_start=0, expert_size_per_partition=E, fc31_input_scale=torch.ones(1), @@ -755,3 +913,166 @@ def route( assert out is None and calls == [], calls else: assert out == "front" and calls == path, calls + + +def _engine_backend( + decode_tuning: bool = True, engine_state: bool = True, num_local: int = 128, inter: int = 512 +) -> SimpleNamespace: + """An NVFP4 TRTLLM-gen backend as ``decode_moe.engine_routes`` reads it (meta weights).""" + from tensorrt_llm._torch.utils import ActivationType + + def meta(*shape, dtype=torch.uint8): + return torch.empty(shape, dtype=dtype, device="meta") + + return SimpleNamespace( + decode_tactic=lambda m, do_finalize: [8, 0], + slot_start=0, + expert_size_per_partition=num_local, + fc31_input_scale=torch.ones(1), + decode_tuning=decode_tuning, + decode_engine_state=torch.zeros(1, dtype=torch.int32) if engine_state else None, + activation_type=ActivationType.Swiglu, + bias=False, + w3_w1_bias=None, + w2_bias=None, + act_alpha=None, + act_beta=None, + act_clamp=None, + w3_w1_weight=meta(num_local, 2 * inter, H // 2), + w2_weight=meta(num_local, H, inter // 2), + fc31_scale_c=meta(num_local, dtype=torch.float32), + fc31_alpha=meta(num_local, dtype=torch.float32), + fc2_alpha=meta(num_local, dtype=torch.float32), + ) + + +_TODAY = ["router_gemm", "route_front", "moe"] + + +@pytest.mark.parametrize( + "top_k,num_experts,routes", + [ + (10, 512, True), + (8, 512, True), + (9, 512, True), + (6, 1024, True), + (13, 512, False), # 64 tokens x 52 keys: more than two 16-byte loads per engine thread + (7, 128, False), # 7 keys of one list: not whole 16-byte vectors + (10, 1024, False), # 80 keys per token: more than two loads per thread + (10, 256, False), # two lists: the router epilogue's 16-token tile does not exist + (33, 512, False), # the router epilogue stores at most 32 keys per tile + ], +) +def test_engine_routes_top_k_and_lists(top_k: int, num_experts: int, routes: bool) -> None: + """The routing engine and its router epilogue take top-k and the number of 128-expert lists as compile-time + parameters; ``engine_routes`` declines what either kernel cannot run.""" + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen import decode_moe as dm + + assert dm.engine_routes(_engine_backend(), 35, top_k, num_experts) == routes + assert not dm.engine_routes(_engine_backend(), 65, top_k, num_experts) + + +@pytest.mark.parametrize( + "engine_route,finalize,backend_kw,path", + [ + (True, False, {}, ["engine_router", "moe"]), + (True, True, {}, _TODAY), + (False, False, {}, _TODAY), + (True, False, dict(engine_state=False), _TODAY), + (True, False, dict(decode_tuning=False), _TODAY), + (True, False, dict(num_local=256), _TODAY), + ], + ids=["engine", "finalized", "not_declared", "no_engine_state", "no_decode_tuning", "256_local"], +) +def test_decode_front_engine_route_gate( + monkeypatch: pytest.MonkeyPatch, + engine_route: bool, + finalize: bool, + backend_kw: dict, + path: list[str], +) -> None: + """A step of 35 rows routes in the MoE engine (the epilogue router GEMM, then the MoE with the candidates and no + route launch) only where the front declares ``engine_route`` and the call is un-finalized and runs the engine; + otherwise the route front steps' CuTe router GEMM and the route front, without candidates.""" + m = 35 + calls: list[str] = [] + seen: list[PreroutedRouting] = [] + xq = torch.zeros((m, H // 2), dtype=torch.uint8) + xsf = torch.zeros((m, H // 16), dtype=torch.uint8) + ids, wts = torch.zeros((m, K), dtype=torch.int32), torch.zeros((m, K), dtype=torch.bfloat16) + logits = torch.zeros((m, E), dtype=torch.bfloat16) + cand = torch.zeros((m, E // 128, K), dtype=torch.int32) + + class Gate: + out_dtype = torch.bfloat16 + weight = torch.zeros((E, H), dtype=torch.bfloat16) + + def __call__(self, x: torch.Tensor) -> torch.Tensor: + calls.append("gate") + return logits + + class RouteFront: + def compiled(self, x, n, tile, num_local, top_k): + return "compiled" + + def __call__(self, fn, lg, x, gs, flat, tile, local_start, num_local, top_k): + calls.append("route_front") + return xq, xsf, ids, wts + + def launch(name: str, out): + def run(*args, **kwargs): + calls.append(name) + return out + + return run + + class Moe: + backend = _engine_backend(**backend_kw) + routing_method = SimpleNamespace(experts_per_token=K) + + def __call__(self, x, lg, output_dtype, prerouted=None, **kwargs) -> str: + calls.append("moe") + seen.append(prerouted) + return "front" + + monkeypatch.setattr(df, "front_eligible", lambda moe, x, max_tokens: True) + front = df.DecodeFront(frozenset({35, 42}), decode_kernels=True, engine_route=engine_route) + front.route_front = RouteFront() + front.route_front_router = launch("router_gemm", logits) + if engine_route: + front.engine_router = launch("engine_router", (logits, cand, xq, xsf)) + x = torch.zeros((m, H), dtype=torch.bfloat16) + out = front(Gate(), Moe(), x, do_finalize=finalize) + assert out == "front" and calls == path, calls + engine = path[0] == "engine_router" + # The engine's hand-off is an EngineRouting carrying the candidates; otherwise a plain PreroutedRouting. + assert isinstance(seen[0], EngineRouting) == engine + assert not engine or seen[0].candidates is cand + + +def test_engine_route_decision_is_kept_per_token_count(monkeypatch: pytest.MonkeyPatch) -> None: + """``DecodeFront._engine_routes`` evaluates ``decode_moe.engine_routes`` once per token count after the backend's + engine state exists (everything else it reads is fixed per layer), and every call before that.""" + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen import decode_moe as dm + + evaluated: list[int] = [] + real = dm.engine_routes + + def counted(backend, m, top_k, num_experts): + evaluated.append(m) + return real(backend, m, top_k, num_experts) + + monkeypatch.setattr(dm, "engine_routes", counted) + front = df.DecodeFront(frozenset({35, 42}), decode_kernels=True, engine_route=True) + front.engine_router = object() + unfinalized = {"do_finalize": False} + backend = _engine_backend(engine_state=False) + assert not front._engine_routes(backend, 35, K, E, unfinalized) + assert not front._engine_routes(backend, 35, K, E, unfinalized) + assert evaluated == [35, 35] + backend.decode_engine_state = torch.zeros(1, dtype=torch.int32) + for _ in range(3): + assert front._engine_routes(backend, 35, K, E, unfinalized) + assert not front._engine_routes(backend, 65, K, E, unfinalized) + assert not front._engine_routes(backend, 35, K, E, {"do_finalize": True}) + assert evaluated == [35, 35, 35, 65] diff --git a/tests/unittest/_torch/moe/test_moe_lowm_fc2.py b/tests/unittest/_torch/moe/test_moe_lowm_fc2.py new file mode 100644 index 000000000000..024894f528a9 --- /dev/null +++ b/tests/unittest/_torch/moe/test_moe_lowm_fc2.py @@ -0,0 +1,393 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""The decode-sized CuTe DSL FC2 (decode_moe CUTE_FC2) after the FC1-only trtllm-gen runner vs the runner's own FC2 +cubin: bit-identical un-finalized outputs (gemm2 rows, expert weights, expanded -> permuted index).""" + +from types import SimpleNamespace +from typing import NamedTuple + +import pytest +import torch + +import tensorrt_llm # noqa: F401 (registers torch.ops.trtllm) +from tensorrt_llm._utils import is_blackwell_datacenter + +pytestmark = pytest.mark.skipif(not is_blackwell_datacenter(), reason="needs SM 10.0 / 10.3") + +_TILE = 8 + + +class _Shape(NamedTuple): + """An MoE layer as one rank runs it: ``local_picks`` of a token's ``top_k`` experts are among the rank's + ``local`` experts (ids 0 .. local - 1), the others are another rank's (ids >= local, ignored).""" + + num_experts: int + local: int + hidden: int + inter: int + top_k: int + local_picks: int + + +_ALL_LOCAL = _Shape(384, 384, 5120, 576, 6, 6) +# An expert-parallel rank of a 512-expert top-10 layer (128 local experts), with all or some picks local. +_EP_LOCAL = _Shape(128, 128, 4096, 512, 10, 10) +_EP_REMOTE = _Shape(512, 128, 4096, 512, 10, 3) + + +def _runner(): + return torch.classes.trtllm.FP4BlockScaleMoERunner(0) + + +def _inputs(m, shape, kind): + torch.manual_seed(11 + m) + dev = "cuda" + e, hidden, inter, top_k = shape.local, shape.hidden, shape.inter, shape.top_k + x = torch.randn(m, hidden, device=dev, dtype=torch.bfloat16) + gs = (448.0 * 6.0 / x.float().abs().amax()).reshape(1).float() + xq, xsf = torch.ops.trtllm.fp4_quantize(x, gs, 16, False, False) + ids = [] + for _ in range(m): + loc = torch.randperm(e, device=dev)[: shape.local_picks] + rest = e + torch.randperm(shape.num_experts - e, device=dev)[: top_k - shape.local_picks] + ids.append(torch.cat([loc, rest])[torch.randperm(top_k, device=dev)]) + ids = torch.stack(ids).int() + w = torch.softmax(torch.randn(m, top_k, device=dev), -1).to(torch.bfloat16) + + def u8(*s): + b = torch.randint(0, 256, s, dtype=torch.uint8, device=dev) + return b & 0x88 if kind == "signed_zeros" else b + + def sf(lo, hi, *s): + return torch.randint(lo, hi, s, dtype=torch.uint8, device=dev).view(torch.float8_e4m3fn) + + lo, hi = (0x00, 0x7F) if kind == "full_sf" else (0x28, 0x41) + w13, w13s = u8(e, 2 * inter, hidden // 2), sf(0x28, 0x41, e, 2 * inter, hidden // 16) + w2, w2s = u8(e, hidden, inter // 2), sf(lo, hi, e, hidden, inter // 16) + one = torch.full((e,), 1e-4, device=dev) + alpha2 = torch.rand(e, device=dev) * 1e-3 + 1e-4 + clamp = torch.full((e,), 1e5, device=dev) + return ( + ids, + w, + (xq, xsf.flatten().view(torch.float8_e4m3fn), w13, w13s, clamp, w2, w2s, one, alpha2), + ) + + +def _common(shape, ins, ids, w, tactic): + xq, xsf, w13, w13s, clamp, w2, w2s, one, alpha2 = ins + return ( + None, + None, + xq, + xsf, + w13, + w13s, + None, + None, + None, + clamp, + w2, + w2s, + None, + one, + one, + alpha2, + shape.num_experts, + shape.top_k, + None, + None, + shape.inter, + 0, + shape.local, + None, + 1, + False, + tactic, + w, + ids, + None, + ) + + +def _assert_same_expert_rows(got, ref): + """Same expert row per (token, k), each gathered through its own run's permutation (the routing kernel's + permuted order may differ between runs). The returned expert weights are the runner's scratch when topk_weights + are passed in, so they are not compared.""" + pg, pr = got[2].flatten(), ref[2].flatten() + assert torch.equal(pg >= 0, pr >= 0) + valid = pr >= 0 + assert int(valid.sum()) > 0 + assert torch.equal( + got[0][pg[valid].long()].view(torch.int16), ref[0][pr[valid].long()].view(torch.int16) + ) + + +def _bitwise_tactics(runner, m, shape): + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import cute_fc2_reproduces + + cfg = runner.get_valid_configs(shape.top_k, shape.hidden, shape.inter, shape.local, m) + tactics = [ + t + for t in cfg + if t[0] == _TILE and cute_fc2_reproduces(runner.get_gemm2_kernel_options(t[0], t[1])) + ] + assert tactics, "no tile-8 tactic whose FC2 cubin the CuTe FC2 reproduces" + return tactics + + +def test_fc2_cubin_selection_is_structural(): + """The CuTe FC2 takes the tile-8 FC2 cubins with M128 N8 K64 MMAs on one CTA per tile, whatever their tile K, + stages, unrolling or scheduler, and no split-K or other MMA shape or dtype; decided from the cubin's options as + the C++ runner reports them, not from its name.""" + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import cute_fc2_reproduces + + def options(**over): + base = dict( + dtypeA="E2m1", + dtypeB="E2m1", + dtypeC="Bfloat16", + dtypeAcc="Fp32", + tileM="128", + tileN="8", + tileK="256", + mmaM="128", + mmaN="8", + mmaK="64", + clusterDimX="1", + clusterDimY="1", + clusterDimZ="1", + numSlicesForSplitK="1", + ) + return {**base, **over} + + assert cute_fc2_reproduces(options()) + assert cute_fc2_reproduces(options(tileK="512")) + assert not cute_fc2_reproduces(options(clusterDimZ="2", numSlicesForSplitK="2")) + assert not cute_fc2_reproduces(options(numSlicesForSplitK="2")) + assert not cute_fc2_reproduces(options(mmaK="128")) + assert not cute_fc2_reproduces(options(tileN="16", mmaN="16")) + assert not cute_fc2_reproduces(options(dtypeA="E4m3")) + assert not cute_fc2_reproduces({}) + + +def test_fc2_cubin_options_match_the_cubin_names(): + """Every FC2 cubin the runner offers reports the options its name encodes (tile, MMA shape, cluster, split-K, + dtypes), so the options-based selection takes exactly the tile-8 M128 N8 K64 single-CTA cubins.""" + import re + + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import cute_fc2_reproduces + from tensorrt_llm._torch.utils import ActType_TrtllmGen + + old_name = re.compile( + r"^bmm_(?P[A-Za-z0-9]+)_(?P[A-Za-z0-9]+)_(?P[A-Za-z0-9]+)_Ab\d+_Bb\d+" + r"_t(?P\d+x\d+)x\d+(?:u2)?_s\d+_et\d+x\d+_m(?P\d+x\d+x\d+)_c(?P\d+x\d+x\d+)" + r"_r[MN]_(?PsplitK\d+_)?TN_transOut_" + ) + runner = torch.classes.trtllm.FP4BlockScaleMoERunner(int(ActType_TrtllmGen.SwiGlu)) + picked = 0 + # (local experts, intermediate): this file's EP shape and Qwen3.5-397B's TEP8 / TEP16 experts (hidden 4096, top-10). + for local, inter in ((_EP_LOCAL.local, _EP_LOCAL.inter), (64, 1024), (32, 1024)): + for m in (1, 8, 32, 128): + configs = runner.get_valid_configs(_EP_LOCAL.top_k, _EP_LOCAL.hidden, inter, local, m) + for tile, config in configs: + opts = runner.get_gemm2_kernel_options(tile, config) + name = runner.get_gemm2_kernel_name(tile, config) + assert f"_t{opts['tileM']}x{opts['tileN']}x{opts['tileK']}" in name, (name, opts) + assert f"_m{opts['mmaM']}x{opts['mmaN']}x{opts['mmaK']}_" in name, (name, opts) + cluster = f"_c{opts['clusterDimX']}x{opts['clusterDimY']}x{opts['clusterDimZ']}_" + assert cluster in name, (name, opts) + split = re.search(r"_splitK(\d+)_", name) + assert opts["numSlicesForSplitK"] == (split.group(1) if split else "1"), ( + name, + opts, + ) + assert name.startswith( + f"bmm_{opts['dtypeC']}_{opts['dtypeA']}{opts['dtypeB']}_{opts['dtypeAcc']}_" + ) + picked += cute_fc2_reproduces(opts) + # The name-parsing selection this replaced (d7b87c20fc) picks the same cubins. + m_old = old_name.match(name) + by_name = ( + m_old is not None + and (m_old["out"], m_old["ab"], m_old["acc"]) + == ("Bfloat16", "E2m1E2m1", "Fp32") + and m_old["tile"] == "128x8" + and m_old["mma"] == "128x8x64" + and m_old["cluster"] == "1x1x1" + and m_old["split"] is None + ) + assert cute_fc2_reproduces(opts) == by_name, (name, opts) + assert picked + + +@pytest.mark.parametrize("kind", ["random", "signed_zeros", "full_sf"]) +@pytest.mark.parametrize( + "m,shape", + [(m, _ALL_LOCAL) for m in (1, 6, 8, 16)] + + [(m, _ALL_LOCAL._replace(num_experts=192, local=192)) for m in (1, 6, 8, 16)] + + [(m, s) for s in (_EP_LOCAL, _EP_REMOTE) for m in (56, 77, 112, 126)], +) +def test_fc1_only_then_cute_fc2_is_bitwise(m, shape, kind): + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import fc1_only_args, run_cute_fc2 + + runner = _runner() + ids, w, ins = _inputs(m, shape, kind) + fc2_args = SimpleNamespace( + gemm2_weights=ins[5], gemm2_weights_scale=ins[6], output2_scale_scalar=ins[8] + ) + for tactic in _bitwise_tactics(runner, m, shape): + common = _common(shape, ins, ids, w, list(tactic)) + ref = runner.run_moe(*common) + got = run_cute_fc2(runner.run_moe_fc1(*fc1_only_args(common)), fc2_args, None) + torch.cuda.synchronize() + _assert_same_expert_rows(got, ref) + + +def test_fc1_only_requires_unfinalized(): + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import fc1_only_args + + runner = _runner() + ids, w, ins = _inputs(6, _ALL_LOCAL, "random") + tactic = _bitwise_tactics(runner, 6, _ALL_LOCAL)[0] + common = list(_common(_ALL_LOCAL, ins, ids, w, tactic)) + assert len(fc1_only_args(common)) == len(common) - 3 + common[25] = True # do_finalize + with pytest.raises(ValueError): + fc1_only_args(common) + + +@pytest.mark.parametrize("decode_tuning", [True, False]) +def test_runner_forward_dispatch(decode_tuning, monkeypatch): + """FP4BlockScaleMoERunner.forward with a tile-8 tactic: the CuTe FC2 where the model declares its decode kernels, + the cubin otherwise; same bits either way.""" + from tensorrt_llm._torch.custom_ops.trtllm_gen_custom_ops import FP4BlockScaleMoERunner + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen import decode_moe + + runner = _runner() + m, shape = 6, _ALL_LOCAL + ids, w, (xq, xsf, w13, w13s, clamp, w2, w2s, one, alpha2) = _inputs(m, shape, "random") + tactic = list(_bitwise_tactics(runner, m, shape)[0]) + args = ( + shape.num_experts, + shape.top_k, + None, + None, + shape.inter, + 0, + shape.local, + None, + 1, + False, + 0, + ) + inputs = [ + None, + None, + xq, + xsf, + w13, + w13s, + None, + None, + None, + clamp, + w2, + w2s, + None, + one, + one, + alpha2, + w, + ids, + ] + ref = FP4BlockScaleMoERunner(*args).forward(inputs, tactic=tactic) + called = [] + orig = decode_moe.run_cute_fc2 + monkeypatch.setattr(decode_moe, "run_cute_fc2", lambda *a: called.append(1) or orig(*a)) + got = FP4BlockScaleMoERunner(*args, decode_tuning=decode_tuning).forward(inputs, tactic=tactic) + torch.cuda.synchronize() + assert bool(called) == decode_tuning + _assert_same_expert_rows(got, ref) + + +@pytest.mark.parametrize("prerouted", [False, True]) +def test_fc1_only_args_drop_exactly_the_fc2_arguments(prerouted): + """The FC1-only entries take run_moe's / run_moe_prerouted's arguments without gemm2_bias, do_finalize and + output; the pre-routed tables and tile that follow output stay in order.""" + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import ( + DO_FINALIZE_ARG, + GEMM2_BIAS_ARG, + OUTPUT_ARG, + fc1_only_args, + ) + + # run_moe: 30 arguments; run_moe_prerouted adds 6 routing tables and the routing tile. + run_args = [f"arg{i}" for i in range(30 + (7 if prerouted else 0))] + run_args[GEMM2_BIAS_ARG], run_args[DO_FINALIZE_ARG], run_args[OUTPUT_ARG] = None, False, None + dropped = {GEMM2_BIAS_ARG, DO_FINALIZE_ARG, OUTPUT_ARG} + assert fc1_only_args(run_args) == tuple(a for i, a in enumerate(run_args) if i not in dropped) + for i, value in ((GEMM2_BIAS_ARG, "bias"), (DO_FINALIZE_ARG, True), (OUTPUT_ARG, "out")): + bad = list(run_args) + bad[i] = value + with pytest.raises(ValueError): + fc1_only_args(bad) + + +def test_fp4_moe_fake_refuses_the_lamport_output(): + """The ops' fake fails closed with a Lamport buffer: whether the rows come back in it depends on the kernel the + host picks per call, which a trace cannot know.""" + import inspect + + from tensorrt_llm._torch.custom_ops.trtllm_gen_custom_ops import _fp4_block_scale_moe_fake + + params = inspect.signature(_fp4_block_scale_moe_fake).parameters + kwargs = {name: None for name, p in params.items() if p.default is inspect.Parameter.empty} + kwargs.update( + hidden_states=torch.empty((4, 64), dtype=torch.uint8, device="meta"), + num_experts=8, + top_k=2, + do_finalize=False, + lamport_fc2_out=torch.empty((16, 128), dtype=torch.bfloat16, device="meta"), + ) + with pytest.raises(NotImplementedError, match="eager-only"): + _fp4_block_scale_moe_fake(**kwargs) + kwargs["lamport_fc2_out"] = None + assert ( + len(_fp4_block_scale_moe_fake(**kwargs)) == 3 + ) # rows, top-k weights, expanded -> permuted + + +def test_both_fp4_ops_trace_through_the_one_fake(): + """The plain and the decode FP4 MoE ops register the one fake, which takes each op's own arguments (the decode + op's state arguments included) and shapes the finalized output from the hidden states.""" + from torch._subclasses.fake_tensor import FakeTensorMode + + from tensorrt_llm._torch.custom_ops import trtllm_gen_custom_ops as G + + decode_only = {"decode_spare_sms": 8, "decode_early_release_rows": 4, "decode_tuning": True} + for op, extra in ( + (torch.ops.trtllm.fp4_block_scale_moe_runner, {}), + (torch.ops.trtllm.fp4_block_scale_moe_decode_runner, decode_only), + ): + with FakeTensorMode(): + kwargs = {} + for arg in op.default._schema.arguments: + text = str(arg.type) + if text == "Tensor": + kwargs[arg.name] = torch.empty((1,), dtype=torch.uint8, device="cuda") + elif text in ("int", "bool"): + kwargs[arg.name] = 1 if text == "int" else False + elif arg.has_default_value(): + continue + else: + kwargs[arg.name] = None + kwargs.update( + hidden_states=torch.empty((4, 64), dtype=torch.uint8, device="cuda"), + do_finalize=True, + **extra, + ) + (out,) = op(**kwargs) + assert out.shape == (4, 128) and out.dtype == torch.bfloat16, op + assert G.fp4_block_scale_moe_runner._abstract_fn is G._fp4_block_scale_moe_fake + assert G.fp4_block_scale_moe_decode_runner._abstract_fn is G._fp4_block_scale_moe_fake diff --git a/tests/unittest/_torch/moe/test_moe_nvfp4_engine.py b/tests/unittest/_torch/moe/test_moe_nvfp4_engine.py new file mode 100644 index 000000000000..2a5330f7b91e --- /dev/null +++ b/tests/unittest/_torch/moe/test_moe_nvfp4_engine.py @@ -0,0 +1,1247 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""The NVFP4 decode MoE engine (one persistent launch: FC1 -> SwiGLU -> NVFP4 -> FC2) against the trtllm-gen FP4 MoE +runner's pre-routed un-finalized run on the same routing: every (token, k) gemm2 row bit for bit. + +One TEP8 rank's shapes: 128 local experts of 512, hidden 4096, intermediate 512 per rank, top-10. Random +checkpoint-format NVFP4 experts through the loader's own shuffle; block scales over 2^-6..2^6 so FP32 sums round.""" + +import functools +import sys +from types import SimpleNamespace + +import pytest +import torch + +from tensorrt_llm._utils import is_blackwell_datacenter + +pytestmark = pytest.mark.skipif(not is_blackwell_datacenter(), reason="needs SM 10.0 / 10.3") + +H, INTER, E, E_LOCAL, TOPK = 4096, 512, 512, 128, 10 +LAMPORT_MAX_ROWS = 128 # the model's (the slot all-reduce's rows) + + +def _experts(seed=20261106, w2_identity=False): + from tensorrt_llm._torch.moe.fused_moe.quantization import NVFP4TRTLLMGenFusedMoEMethod + + gen = torch.Generator(device="cuda").manual_seed(seed) + + def sf(*shape): + return torch.randint( + 0x08, 0x70, shape, dtype=torch.uint8, device="cuda", generator=gen + ).view(torch.float8_e4m3fn) + + w31 = torch.randint( + 0, 256, (E_LOCAL, 2 * INTER, H // 2), dtype=torch.uint8, device="cuda", generator=gen + ) + w31s = sf(E_LOCAL, 2 * INTER, H // 16) + if w2_identity: + w2 = torch.zeros((E_LOCAL, H, INTER // 2), dtype=torch.uint8, device="cuda") + n = torch.arange(INTER, device="cuda") + w2[:, n, n // 2] = torch.where(n % 2 == 0, 0x02, 0x20).to(torch.uint8) + w2s = torch.full((E_LOCAL, H, INTER // 16), 0x38, dtype=torch.uint8, device="cuda").view( + torch.float8_e4m3fn + ) + else: + w2 = torch.randint( + 0, 256, (E_LOCAL, H, INTER // 2), dtype=torch.uint8, device="cuda", generator=gen + ) + w2s = sf(E_LOCAL, H, INTER // 16) + module = SimpleNamespace( + w3_w1_weight=w31, + w2_weight=w2, + w3_w1_weight_scale=w31s, + w2_weight_scale=w2s, + is_gated_activation=True, + bias=False, + ) + NVFP4TRTLLMGenFusedMoEMethod()._shuffle_all_experts(module) + x_scale, h_scale = 448.0 * 6.0 / 8.0, 448.0 * 6.0 / 24.0 + a = ( + 1.5 + / (x_scale * 2.93 * 1.3 * H**0.5) + * (0.8 + 0.4 * torch.rand(E_LOCAL, device="cuda", generator=gen)) + ) + a2 = ( + torch.ones(E_LOCAL, device="cuda") + if w2_identity + else ( + (0.8 + 0.4 * torch.rand(E_LOCAL, device="cuda", generator=gen)) + / (h_scale * 2.93 * 1.3 * INTER**0.5) + ) + ) + return SimpleNamespace( + w31=w31, + w31s=w31s, + w2=w2, + w2s=w2s, + scale_c=(h_scale * a).float().contiguous(), + alpha1=a.float().contiguous(), + alpha2=a2.float().contiguous(), + x_scale=x_scale, + ) + + +def _inputs(m, ex, seed): + gen = torch.Generator(device="cuda").manual_seed(seed) + x = torch.randn(m, H, device="cuda", generator=gen).to(torch.bfloat16) + xq, xsf = torch.ops.trtllm.fp4_quantize( + x, torch.tensor([ex.x_scale], device="cuda"), 16, False, False + ) + w = torch.full((E,), 0.5 / (E - E_LOCAL), device="cuda") + w[:E_LOCAL] = 0.5 / E_LOCAL + ids = ( + torch.multinomial(w.unsqueeze(0).repeat(m, 1), TOPK, replacement=False, generator=gen) + .int() + .contiguous() + ) + wts = torch.softmax(torch.randn(m, TOPK, device="cuda", generator=gen), -1).to(torch.bfloat16) + return xq, xsf.view(torch.uint8).reshape(m, -1), ids, wts + + +def _tables(ids, tile): + """trtllm-gen's routing tables (decode_front.prerouted_table_sizes order) built on the host.""" + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_front import ( + max_num_tiles, + prerouted_table_sizes, + ) + + m, k = ids.shape + lid = ids.flatten().cpu().long() + local = (lid >= 0) & (lid < E_LOCAL) + counts = torch.bincount(lid[local], minlength=E_LOCAL) + ncta = (counts + tile - 1) // tile + offs = torch.cumsum(ncta, 0) - ncta + sizes = prerouted_table_sizes(m, k, E_LOCAL, tile) + flat = torch.zeros(sum(sizes), dtype=torch.int32) + e2p, p2t, batch, limit, nct, npad = torch.split(flat, sizes) + for e in range(E_LOCAL): + for c in range(int(ncta[e])): + cta = int(offs[e]) + c + batch[cta] = e + limit[cta] = min((cta + 1) * tile, int(offs[e]) * tile + int(counts[e])) + rank = torch.zeros(E_LOCAL, dtype=torch.long) + e2p.fill_(-1) + for i in range(m * k): + if local[i]: + e = int(lid[i]) + p = int(offs[e]) * tile + int(rank[e]) + rank[e] += 1 + e2p[i] = p + p2t[p] = i // k + nct[0] = int(ncta.sum()) + npad[0] = int(ncta.sum()) * tile + return list(torch.split(flat.cuda(), sizes)), max_num_tiles(m, k, E_LOCAL, tile) * tile + + +def _stock(ex, xq, xsf, ids, wts): + from tensorrt_llm._torch.custom_ops import trtllm_gen_custom_ops as G + + m = xq.shape[0] + r = G.FP4BlockScaleMoERunner( + E, TOPK, None, None, INTER, 0, E_LOCAL, None, 1, False, G.ActType_TrtllmGen.SwiGlu.value + ) + tactics = [ + list(map(int, t)) for t in r.get_runner().get_valid_configs(TOPK, H, INTER, E_LOCAL, m) + ] + tile = min(t[0] for t in tactics) + tac = next(t for t in tactics if t[0] == tile) + views, _ = _tables(ids, tile) + inputs = [ + None, + None, + xq, + xsf.view(torch.float8_e4m3fn).flatten(), + ex.w31, + ex.w31s, + None, + None, + None, + None, + ex.w2, + ex.w2s, + None, + ex.scale_c, + ex.alpha1, + ex.alpha2, + wts, + ids, + ] + out = r.forward(inputs, tactic=tac, prerouted=(views, ids, wts)) + e2p = views[0] + valid = e2p >= 0 + return out[0][e2p[valid].long()], valid + + +def _engine( + ex, + xq, + xsf, + ids, + tile, + n_max, + state, + out=None, + tile_k=256, + release_after_wait=False, + spare_sms=0, +): + from tensorrt_llm._torch.kernels.blackwell.moe_nvfp4_engine import moe_nvfp4_engine + + views, cap = _tables(ids, tile) + e2p, p2t, batch, limit, nct, _ = views + h = torch.zeros((cap, INTER // 2), dtype=torch.uint8, device="cuda") + hsf = torch.zeros((cap * INTER // 16,), dtype=torch.uint8, device="cuda") + if out is None: + out = torch.zeros((cap, H), dtype=torch.bfloat16, device="cuda") + moe_nvfp4_engine( + xq, + xsf, + p2t, + batch, + limit, + nct, + ex.w31, + ex.w31s.view(torch.uint8), + ex.w2, + ex.w2s.view(torch.uint8), + ex.scale_c, + ex.alpha1, + ex.alpha2, + h, + hsf, + out, + state, + tile=tile, + n_max=n_max, + tile_k=tile_k, + release_after_wait=release_after_wait, + spare_sms=spare_sms, + ) + torch.cuda.synchronize() + return out, h, hsf, e2p + + +@pytest.fixture(scope="module") +def state(): + from tensorrt_llm._torch.kernels.blackwell.moe_nvfp4_engine import new_state + + return new_state(torch.device("cuda")) + + +@pytest.mark.parametrize( + "m,n_max,tile", + [ + (8, 16, 8), + (56, 64, 8), + (112, 64, 8), + (224, 64, 8), + (224, 16, 16), + (896, 64, 8), + (896, 32, 64), + ], +) +def test_engine_rows_are_trtllm_gen_bit_for_bit(m, n_max, tile, state): + import tensorrt_llm # noqa: F401 + + ex = _experts() + xq, xsf, ids, wts = _inputs(m, ex, seed=11 + m) + ref, valid = _stock(ex, xq, xsf, ids, wts) + out, _, _, e2p = _engine(ex, xq, xsf, ids, tile, n_max, state) + got = out[e2p[valid].long()] + assert torch.equal(got.view(torch.int16), ref.view(torch.int16)) + again, _, _, _ = _engine(ex, xq, xsf, ids, tile, n_max, state) + assert torch.equal(again[e2p[valid].long()].view(torch.int16), got.view(torch.int16)) + + +@pytest.mark.parametrize("release_after_wait", [False, True]) +@pytest.mark.parametrize("m", [56, 63, 64, 112]) +def test_engine_hook_tiles_bit_for_bit(m, release_after_wait, state): + """The hook's n_max / K tile per row count, with either PDL release point, leave the rows unchanged.""" + import tensorrt_llm # noqa: F401 + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import n_max_for, tile_k_for + + ex = _experts() + xq, xsf, ids, wts = _inputs(m, ex, seed=13 + m) + ref, valid = _stock(ex, xq, xsf, ids, wts) + n_max = n_max_for(m) + out, _, _, e2p = _engine( + ex, + xq, + xsf, + ids, + 8, + n_max, + state, + tile_k=tile_k_for(n_max, H, INTER), + release_after_wait=release_after_wait, + ) + assert torch.equal(out[e2p[valid].long()].view(torch.int16), ref.view(torch.int16)) + + +@pytest.mark.parametrize("m", [448, 896]) +def test_engine_rows_do_not_depend_on_the_grid(m, state): + """Beside a shared expert the engine leaves SMs free (decode_moe.ENGINE_SPARE_SMS): its rows are the full grid's, + bit for bit (the FC1 units balance over the grid, the FC2 units are claimed as tickets).""" + import tensorrt_llm # noqa: F401 + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import ( + ENGINE_SPARE_SMS, + n_max_for, + tile_k_for, + ) + + ex = _experts() + xq, xsf, ids, _ = _inputs(m, ex, seed=29 + m) + n_max = n_max_for(m) + opts = dict(tile_k=tile_k_for(n_max, H, INTER), release_after_wait=True) + full, _, _, e2p = _engine(ex, xq, xsf, ids, 8, n_max, state, **opts) + valid = e2p[e2p >= 0].long() + for spare in (ENGINE_SPARE_SMS, 2 * ENGINE_SPARE_SMS): + out, _, _, _ = _engine(ex, xq, xsf, ids, 8, n_max, state, spare_sms=spare, **opts) + assert torch.equal(out[valid].view(torch.int16), full[valid].view(torch.int16)), spare + + +@pytest.mark.parametrize( + "m,tile,release_after_wait", + [ + (7, 8, False), + (28, 8, False), + (56, 8, False), + (63, 16, False), + (64, 8, True), + (112, 16, True), + ], +) +def test_engine_writes_only_real_rows_of_a_sentinel_buffer(m, tile, release_after_wait, state): + """Lamport FC2 (decode_moe.LamportFc2Buffer) hands the engine a persistent buffer that holds 0xFFFFFFFF + wherever no row is written; the MoE-output all-reduce's fold polls each word of the e2p-valid rows until it is not + 0xFFFFFFFF, then writes it back. So the engine must write exactly those rows, bit for bit its default output and + never a 0xFFFFFFFF word, and leave every other word alone (padded rows, rows past the call's). Two calls in a row + with the fold's reset between them, as consecutive layers share the buffer; the hook's n_max and tile_k.""" + import tensorrt_llm # noqa: F401 + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_front import max_num_tiles + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import n_max_for, tile_k_for + + ex = _experts() + n_max = n_max_for(m) + opts = dict(tile_k=tile_k_for(n_max, H, INTER), release_after_wait=release_after_wait) + cap = max_num_tiles(m, TOPK, E_LOCAL, tile) * tile + buf = torch.full((cap + 64, H), -1, dtype=torch.int16, device="cuda") + for seed in (19 + m, 23 + m): + xq, xsf, ids, _ = _inputs(m, ex, seed=seed) + ref, _, _, e2p = _engine(ex, xq, xsf, ids, tile, n_max, state, **opts) + rows = e2p[e2p >= 0].long() + _engine(ex, xq, xsf, ids, tile, n_max, state, out=buf[:cap].view(torch.bfloat16), **opts) + assert torch.equal(buf[rows], ref.view(torch.int16)[rows]) + assert not (buf[rows].view(torch.int32) == -1).any() + rest = torch.ones(buf.shape[0], dtype=torch.bool, device="cuda") + rest[rows] = False + assert (buf[rest] == -1).all() + buf[rows] = -1 # the fold's write-back + + +def _op_inputs(ex, xq, xsf): + """The FP4 runner's inputs without router logits / top-k (FP4BlockScaleMoEInputs order).""" + return [ + None, + None, + xq, + xsf.view(torch.float8_e4m3fn).flatten(), + ex.w31, + ex.w31s, + None, + None, + None, + None, + ex.w2, + ex.w2s, + None, + ex.scale_c, + ex.alpha1, + ex.alpha2, + None, + None, + ] + + +def _decode_runner(decode_tuning=True, decode_spare_sms=0): + from tensorrt_llm._torch.custom_ops import trtllm_gen_custom_ops as G + + return G.FP4BlockScaleMoERunner( + E, + TOPK, + None, + None, + INTER, + 0, + E_LOCAL, + None, + 1, + False, + G.ActType_TrtllmGen.SwiGlu.value, + decode_tuning=decode_tuning, + decode_spare_sms=decode_spare_sms, + ) + + +def _tile8_tactics(runner, m): + """(a tile-8 tactic, a tile-8 tactic whose FC2 cubin the CuTe FC2 reproduces); the runner offers one.""" + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import cute_fc2_reproduces + + cr = runner.get_runner() + tactics = [list(map(int, t)) for t in cr.get_valid_configs(TOPK, H, INTER, E_LOCAL, m)] + tile8 = [t for t in tactics if t[0] == 8] + bitwise = [t for t in tile8 if cute_fc2_reproduces(cr.get_gemm2_kernel_options(t[0], t[1]))] + assert bitwise, [cr.get_gemm2_kernel_name(t[0], t[1]) for t in tile8] + return tile8[0], bitwise[0] + + +def _spy_select(monkeypatch): + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen import decode_moe + + picked, orig = [], decode_moe.select + + def spy(*args, **kwargs): + picked.append(orig(*args, **kwargs)) + return picked[-1] + + monkeypatch.setattr(decode_moe, "select", spy) + return picked + + +def test_decode_kernels_select_the_engine_with_the_runner_abi(monkeypatch): + """A pre-routed un-finalized call of a runner that declares the decode kernels takes the engine when its backend + hands in the engine state, and otherwise the FC1-only runner + CuTe FC2 or the cubins; the rows reached through + the expanded -> permuted index are the stock runner's bit for bit either way, and the (rows, weights [m, k], + index [m, k] int32) triple is what the MoE-output all-reduce's in-kernel finalize accepts.""" + import tensorrt_llm # noqa: F401 + from tensorrt_llm._torch.distributed.mnnvl_fused_allreduce import MnnvlAllReduceNorm + from tensorrt_llm._torch.kernels.blackwell.moe_persistent_engine import new_state + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import DecodeKernel + + ex = _experts() + m = 56 + xq, xsf, ids, wts = _inputs(m, ex, seed=17) + ref, valid = _stock(ex, xq, xsf, ids, wts) + runner = _decode_runner() + any8, bitwise8 = _tile8_tactics(runner, m) + views, _ = _tables(ids, 8) + e2p = views[0].view(m, TOPK) + state = new_state(torch.device("cuda")) + picked = _spy_select(monkeypatch) + cases = [ + (any8, state, DecodeKernel.ENGINE), + (any8, None, None), + (bitwise8, None, DecodeKernel.CUTE_FC2), + ] + for tactic, engine_state, expect in cases: + picked.clear() + out = runner.forward( + _op_inputs(ex, xq, xsf), + tactic=tactic, + prerouted=(views, ids, wts), + engine_state=engine_state, + )[0] + torch.cuda.synchronize() + assert len(picked) == 1, picked + if expect is None: + assert picked[0] != DecodeKernel.ENGINE, picked + else: + assert picked[0] == expect, (picked, expect) + assert MnnvlAllReduceNorm.moe_fold_supported(out, wts.view(m, TOPK), e2p, H) + got = out[e2p.flatten()[valid].long()] + assert torch.equal(got.view(torch.int16), ref.view(torch.int16)), (tactic, picked) + picked.clear() + _decode_runner(decode_tuning=False).forward( + _op_inputs(ex, xq, xsf), tactic=any8, prerouted=(views, ids, wts), engine_state=state + ) + assert not picked + + +@pytest.mark.parametrize( + "e_local,inter", + # Qwen3.5-397B-A17B experts (512, intermediate 1024, top-10) at EP4 / EP8, layouts that take the engine in + # production (TP4/EP4, TEP8); the 56-row comparison needs a tile-8 tactic, which 32 local experts do not offer. + [(128, 1024), (64, 1024)], +) +def test_engine_rows_match_the_runner_at_the_qwen35_layouts(monkeypatch, e_local, inter): + """The runner-ABI engine / CuTe FC2 / cubin comparison of + ``test_decode_kernels_select_the_engine_with_the_runner_abi`` at the production expert layouts, not only this + file's 128 x 512 one.""" + module = sys.modules[__name__] + monkeypatch.setattr(module, "E_LOCAL", e_local) + monkeypatch.setattr(module, "INTER", inter) + test_decode_kernels_select_the_engine_with_the_runner_abi(monkeypatch) + + +def test_engine_leaves_the_reserved_sms_free(monkeypatch): + """The runner hands the engine its ``decode_spare_sms`` (the backend's reserve for this call); the rows stay the + stock runner's.""" + import tensorrt_llm # noqa: F401 + from tensorrt_llm._torch.kernels.blackwell.moe_persistent_engine import new_state + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen import decode_moe + + ex = _experts() + m = 56 + xq, xsf, ids, wts = _inputs(m, ex, seed=31) + ref, valid = _stock(ex, xq, xsf, ids, wts) + views, _ = _tables(ids, 8) + e2p = views[0].view(m, TOPK) + state = new_state(torch.device("cuda")) + seen, orig = [], decode_moe.run_engine + + def spy(*args, **kwargs): + seen.append(kwargs["spare_sms"]) + return orig(*args, **kwargs) + + monkeypatch.setattr(decode_moe, "run_engine", spy) + for spare in (0, decode_moe.ENGINE_SPARE_SMS): + runner = _decode_runner(decode_spare_sms=spare) + any8, _ = _tile8_tactics(runner, m) + seen.clear() + out = runner.forward( + _op_inputs(ex, xq, xsf), tactic=any8, prerouted=(views, ids, wts), engine_state=state + )[0] + torch.cuda.synchronize() + assert seen == [spare], (spare, seen) + got = out[e2p.flatten()[valid].long()] + assert torch.equal(got.view(torch.int16), ref.view(torch.int16)), spare + + +def test_engine_reserve_is_the_moe_sm_reserve_hook(): + """The NVFP4 TRTLLM-Gen leaf takes the shared expert's SMs through MoEImplBase's hooks: a ceiling of + ENGINE_SPARE_SMS only where the model declares the decode kernels of a pre-routed call, and the per-forward + reserve bounded by it (the model hands 0 for an in-order step).""" + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import ENGINE_SPARE_SMS + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.fp4_block_scale import ( + TRTLLMGenFp4BlockScaleBase, + ) + + def leaf(decode_tuning, prerouted): + obj = SimpleNamespace(decode_tuning=decode_tuning, supports_prerouted_routing=prerouted) + obj.sm_reserve_ceiling = functools.partial( + TRTLLMGenFp4BlockScaleBase.sm_reserve_ceiling, obj + ) + obj.reserve = functools.partial( + TRTLLMGenFp4BlockScaleBase.reserve_sms_for_concurrent_kernels, obj + ) + return obj + + declared = leaf(True, True) + assert declared.sm_reserve_ceiling() == ENGINE_SPARE_SMS + assert declared.reserve(ENGINE_SPARE_SMS) == ENGINE_SPARE_SMS + assert declared._concurrent_sm_reserve == ENGINE_SPARE_SMS + assert declared.reserve(4 * ENGINE_SPARE_SMS) == ENGINE_SPARE_SMS + assert declared.reserve(0) == 0 and declared._concurrent_sm_reserve == 0 + with pytest.raises(ValueError): + declared.reserve(-1) + for decode_tuning, prerouted in ((False, True), (True, False)): + other = leaf(decode_tuning, prerouted) + assert other.sm_reserve_ceiling() == 0 + assert other.reserve(ENGINE_SPARE_SMS) == 0 + + +def test_engine_grid_leaves_the_global_sm_reserve(monkeypatch): + """The persistent MoE grids also keep out the SMs ``cute_dsl_utils.sm_reserve()`` reserves (DWDP), on top of + the per-call spare SMs.""" + import tensorrt_llm._torch.cute_dsl_utils as cdu + from tensorrt_llm._torch.kernels.blackwell import moe_lowm_fc2 + + sms = torch.cuda.get_device_properties(torch.device("cuda")).multi_processor_count + assert moe_lowm_fc2.num_sms(torch.device("cuda")) == sms + monkeypatch.setattr(cdu, "_sm_reserve", 4) + assert moe_lowm_fc2.num_sms(torch.device("cuda")) == sms - 4 + + +def test_lamport_out_takes_the_decode_kernels_rows(monkeypatch): + """With a Lamport FC2 buffer the engine and the CuTe FC2 write their rows there, bit for bit the plain call's, + leaving the rest of the buffer sentinel; a call of the cubins returns its own rows and leaves the buffer untouched + (no copy). Through the custom op the Lamport rows come back as an empty placeholder (an op output may not alias + an input) that the op backend replaces with the buffer.""" + import tensorrt_llm # noqa: F401 + from tensorrt_llm._torch.kernels.blackwell.moe_persistent_engine import new_state + from tensorrt_llm._torch.moe.fused_moe.impl_contract import PreroutedRouting + from tensorrt_llm._torch.moe.fused_moe.moe_op_backend import TRTLLMOpBackend + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import ( + DecodeKernel, + LamportFc2Buffer, + ) + from tensorrt_llm._torch.utils import ActType_TrtllmGen + + ex = _experts() + dev = torch.device("cuda", torch.cuda.current_device()) + lamport = LamportFc2Buffer(LAMPORT_MAX_ROWS).get(H, INTER, TOPK, E_LOCAL, dev) + words = lamport.view(torch.int16) + assert (words == -1).all() + state = new_state(dev) + picked = _spy_select(monkeypatch) + m = 56 + xq, xsf, ids, wts = _inputs(m, ex, seed=29) + runner = _decode_runner() + any8, bitwise8 = _tile8_tactics(runner, m) + views, _ = _tables(ids, 8) + rows = views[0][views[0] >= 0].long() + rest = torch.ones(words.shape[0], dtype=torch.bool, device="cuda") + rest[rows] = False + cases = [ + (runner, any8, state, DecodeKernel.ENGINE), + (runner, bitwise8, None, DecodeKernel.CUTE_FC2), + (_decode_runner(decode_tuning=False), any8, state, None), + ] + for op_runner, tactic, engine_state, expect in cases: + kw = dict(tactic=tactic, prerouted=(views, ids, wts), engine_state=engine_state) + plain = op_runner.forward(_op_inputs(ex, xq, xsf), **kw)[0] + picked.clear() + out = op_runner.forward(_op_inputs(ex, xq, xsf), lamport_out=lamport, **kw)[0] + torch.cuda.synchronize() + assert picked == ([] if expect is None else [expect]) + assert torch.equal(out[rows].view(torch.int16), plain[rows].view(torch.int16)) + if expect is None: # the cubins: their own rows, the buffer untouched + assert out.data_ptr() != lamport.data_ptr() and (words == -1).all() + continue + assert out.data_ptr() == lamport.data_ptr() + assert not (words[rows].view(torch.int32) == -1).any() + assert (words[rest] == -1).all() + words[rows] = -1 # the fold's write-back + backend = TRTLLMOpBackend() + + def run(lamport_fc2_out, decode_tuning=True): + return backend.run_fp4_block_scale_moe( + None, + None, + xq, + xsf, + ex.w31, + ex.w31s, + None, + None, + None, + None, + ex.w2, + ex.w2s, + None, + ex.scale_c, + ex.alpha1, + ex.alpha2, + E, + TOPK, + None, + None, + INTER, + 0, + E_LOCAL, + None, + 1, + do_finalize=False, + topk_weights=None, + topk_ids=None, + gated_act_type=int(ActType_TrtllmGen.SwiGlu), + prerouted=PreroutedRouting(torch.cat(views), any8, ids, wts), + decode_tuning=decode_tuning, + decode_engine_state=state, + lamport_fc2_out=lamport_fc2_out, + ) + + plain = run(None) + out = run(lamport) + torch.cuda.synchronize() + assert out[0] is lamport + assert torch.equal(out[0][rows].view(torch.int16), plain[0][rows].view(torch.int16)) + words[rows] = -1 + out = run(lamport, decode_tuning=False) + torch.cuda.synchronize() + assert out[0] is not lamport and (words == -1).all() + assert torch.equal(out[0][rows].view(torch.int16), plain[0][rows].view(torch.int16)) + + +def test_lamport_buffer_holds_every_tile_the_runner_can_tune(): + """One Lamport buffer serves every Lamport call of the model: every token count up to its max rows at every tile + the FP4 runner offers for it, which bounds the engine's rows and the FC1-only runner's gemm2 rows (at least + 128 KiB of them) the CuTe FC2 writes.""" + import tensorrt_llm # noqa: F401 + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen import decode_moe as dm + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_front import max_num_tiles + from tensorrt_llm._torch.utils import ActType_TrtllmGen + + runner = torch.classes.trtllm.FP4BlockScaleMoERunner(int(ActType_TrtllmGen.SwiGlu)) + calls = [] + for m in range(1, LAMPORT_MAX_ROWS + 1): + tiles = {int(t[0]) for t in runner.get_valid_configs(TOPK, H, INTER, E_LOCAL, m)} + assert tiles + calls += [max(max_num_tiles(m, TOPK, E_LOCAL, t) * t, 128 * 1024 // (H * 2)) for t in tiles] + rows = dm.lamport_buffer_rows(runner, LAMPORT_MAX_ROWS, H, INTER, TOPK, E_LOCAL) + assert max(calls) <= rows + dev = torch.device("cuda", torch.cuda.current_device()) + owner = dm.LamportFc2Buffer(LAMPORT_MAX_ROWS) + buf = owner.get(H, INTER, TOPK, E_LOCAL, dev) + assert buf.shape == (rows, H) and buf.dtype == torch.bfloat16 + assert (buf.view(torch.int16) == -1).all() + assert owner.get(H, INTER, TOPK, E_LOCAL, dev).data_ptr() == buf.data_ptr() + + +def test_fc1_intermediate_matches_identity_w2(state): + """With W2[n][n] = 1 (scales 1, alpha2 1) the runner's gemm2 columns < I are the dequantized FC1 intermediate.""" + import tensorrt_llm # noqa: F401 + + ex = _experts(w2_identity=True) + m = 224 + xq, xsf, ids, wts = _inputs(m, ex, seed=5) + ref, valid = _stock(ex, xq, xsf, ids, wts) + _, h, hsf, e2p = _engine(ex, xq, xsf, ids, 8, 64, state) + rows = e2p[valid].long() + lut = torch.tensor( + [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0], + device="cuda", + ) + hb = h[rows].long() + vals = torch.stack((lut[hb & 0xF], lut[hb >> 4]), dim=-1).flatten(-2) + r = rows.view(-1, 1) + b = torch.arange(INTER // 16, device="cuda").view(1, -1) + sf = hsf.view(torch.float8_e4m3fn)[ + ((r // 8) * (INTER // 64) + b // 4) * 32 + (r % 8) * 4 + b % 4 + ].float() + got = vals * sf.repeat_interleave(16, dim=1) + assert torch.equal(got, ref[:, :INTER].float()) + + +@pytest.mark.parametrize("inter", [256, 512, 768, 1024]) +@pytest.mark.parametrize("m", [7, 16, 17, 224, 225, 896]) +def test_engine_gate_matches_the_engine_shapes(m, inter): + """``select``'s engine gate holds exactly where the engine compiles for the K tile ``run_engine`` passes (e.g. + MoE TP4's intermediate 256 per rank takes K tiles of 256 at every row count).""" + from tensorrt_llm._torch.kernels.blackwell.moe_nvfp4_engine import MoeNvfp4Engine + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen import decode_moe as dm + from tensorrt_llm._torch.utils import ActType_TrtllmGen + + def t(*shape): + return torch.empty(shape, dtype=torch.uint8, device="meta") + + args = SimpleNamespace( + hidden_states=t(m, H // 2), + hidden_states_scale=t(m, H // 16), + gemm1_weights=t(E_LOCAL, 2 * inter, H // 2), + gemm2_weights=t(E_LOCAL, H, inter // 2), + gemm1_bias=None, + gemm1_alpha=None, + gemm1_beta=None, + gemm1_clamp_limit=None, + output1_scale_scalar=t(E_LOCAL), + output1_scale_gate_scalar=t(E_LOCAL), + output2_scale_scalar=t(E_LOCAL), + ) + assert dm._engine_fits(args, ActType_TrtllmGen.SwiGlu, TOPK) + n_max = dm.n_max_for(m) + tile_k = dm.tile_k_for(n_max, H, inter) + MoeNvfp4Engine(H, inter, n_max, 4, 8, tile_k, False) # asserts the shapes it compiles for + assert tile_k == (256 if inter % 512 or n_max > 32 else 512) + + +@pytest.mark.parametrize("m,top_k,fits", [(1024, TOPK, True), (1024, 32, False), (64, 32, True)]) +def test_engine_gate_bounds_the_segment_table(m, top_k, fits): + """The engine gate refuses a call whose worst-case (expert, row chunk) segment count exceeds ``SEG_CAP``.""" + from tensorrt_llm._torch.kernels.blackwell.moe_nvfp4_engine import SEG_CAP + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen import decode_moe as dm + from tensorrt_llm._torch.utils import ActType_TrtllmGen + + def t(*shape): + return torch.empty(shape, dtype=torch.uint8, device="meta") + + args = SimpleNamespace( + hidden_states=t(m, H // 2), + hidden_states_scale=t(m, H // 16), + gemm1_weights=t(E_LOCAL, 2 * INTER, H // 2), + gemm2_weights=t(E_LOCAL, H, INTER // 2), + gemm1_bias=None, + gemm1_alpha=None, + gemm1_beta=None, + gemm1_clamp_limit=None, + output1_scale_scalar=t(E_LOCAL), + output1_scale_gate_scalar=t(E_LOCAL), + output2_scale_scalar=t(E_LOCAL), + ) + assert (E_LOCAL + -(-m * top_k // dm.n_max_for(m)) <= SEG_CAP) == fits + assert dm._engine_fits(args, ActType_TrtllmGen.SwiGlu, top_k) == fits + + +def test_fine_grained_sync_keeps_the_runner_fc2(): + """A call keeps the runner's FC2 only where the runner runs its fine-grained-sync pair (the FC1-only entry points + refuse it), as the runner reports for the call's tile and shape; the FC2 cubin's options are asked once per + (act type, tactic).""" + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen import decode_moe as dm + from tensorrt_llm._torch.utils import ActType_TrtllmGen + + options = dict(dm._CUTE_FC2_OPTIONS, tileK="256") + asked, fg_calls = [], [] + + def runner(fine_grained): + def uses_fine_grained_sync(*shape): + fg_calls.append(shape) + return fine_grained + + return SimpleNamespace( + get_gemm2_kernel_options=lambda tile, config: asked.append((tile, config)) or options, + uses_fine_grained_sync=uses_fine_grained_sync, + ) + + args = SimpleNamespace( + hidden_states=torch.empty((7, H // 2), dtype=torch.uint8, device="meta"), + gemm2_weights=torch.empty((E_LOCAL, H, INTER // 2), dtype=torch.uint8, device="meta"), + gemm2_weights_scale=torch.empty( + (E_LOCAL, H, INTER // 16), dtype=torch.uint8, device="meta" + ), + gemm2_bias=None, + ) + kw = dict( + top_k=TOPK, + do_finalize=False, + output=None, + intermediate_size=INTER, + prerouted=False, + engine_state=None, + ) + act = int(ActType_TrtllmGen.SwiGlu) + dm._FC2_REPRODUCED.clear() + assert dm.cute_fc2_reproduces(options) + assert dm.select(runner(False), act, [8, 0], args, **kw) == dm.DecodeKernel.CUTE_FC2 + assert dm.select(runner(True), act, [8, 0], args, **kw) == dm.DecodeKernel.CUBIN + assert dm.select(runner(False), act, [8, 0], args, **kw) == dm.DecodeKernel.CUTE_FC2 + assert asked == [(8, 0)] + # (tile, top_k, hidden, intermediate, local experts, tokens), as the runner's own call resolves it. + assert fg_calls == [(8, TOPK, H, INTER, E_LOCAL, 7)] * 3 + + +def test_fine_grained_sync_without_its_cubins_keeps_the_cute_fc2(monkeypatch): + """TLLM_USE_FINE_GRAINED_SYNC=1 on SM 10.0 / 10.3, which ship no fine-grained cubins: the runner runs the tuned + tactic, so the CuTe FC2 still stands in for its FC2 (and the FC1-only entry runs), bit for bit the stock rows.""" + import tensorrt_llm # noqa: F401 + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import DecodeKernel + + monkeypatch.setenv("TLLM_USE_FINE_GRAINED_SYNC", "1") + ex = _experts() + m = 56 + xq, xsf, ids, wts = _inputs(m, ex, seed=19) + ref, valid = _stock(ex, xq, xsf, ids, wts) + runner = _decode_runner() + _, bitwise8 = _tile8_tactics(runner, m) + assert not runner.get_runner().uses_fine_grained_sync(8, TOPK, H, INTER, E_LOCAL, m) + views, _ = _tables(ids, 8) + e2p = views[0].view(m, TOPK) + picked = _spy_select(monkeypatch) + out = runner.forward( + _op_inputs(ex, xq, xsf), tactic=bitwise8, prerouted=(views, ids, wts), engine_state=None + )[0] + torch.cuda.synchronize() + assert picked == [DecodeKernel.CUTE_FC2], picked + got = out[e2p.flatten()[valid].long()] + assert torch.equal(got.view(torch.int16), ref.view(torch.int16)) + + +def _router_inputs(m, ex, seed, dup=False): + """x [m, H] bf16, a router weight [E, H] bf16 (``dup``: identical row pairs, exact logit ties) and the experts' + NVFP4 global scale.""" + gen = torch.Generator(device="cuda").manual_seed(seed) + x = torch.randn(m, H, device="cuda", generator=gen).to(torch.bfloat16) + w = (torch.randn(E, H, device="cuda", generator=gen) * 0.02).to(torch.bfloat16) + if dup: + w[1::2] = w[0::2] + return x, w, torch.tensor([ex.x_scale], dtype=torch.float32, device="cuda") + + +def _poisoned_routing(m, tile, poison): + """(flat tables, ids, weights) filled with ``poison``, the outputs of a routing engine.""" + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_front import prerouted_table_sizes + + size = sum(prerouted_table_sizes(m, TOPK, E_LOCAL, tile)) + flat = torch.full((size,), poison, dtype=torch.int32, device="cuda") + ids = torch.full((m, TOPK), poison, dtype=torch.int32, device="cuda") + wts = torch.full((m, TOPK), poison, dtype=torch.int16, device="cuda").view(torch.bfloat16) + return flat, ids, wts + + +def _engine_on( + ex, xq, xsf, views, tile, state, poison, sync=True, release_after_wait=False, **route +): + """The engine with the decode hook's n_max / K tile on tables ``views`` (``prerouted_table_views``); with + ``route`` (candidates, ids, weights, local start) it writes them itself.""" + from tensorrt_llm._torch.kernels.blackwell.moe_nvfp4_engine import moe_nvfp4_engine + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_front import max_num_tiles + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import n_max_for, tile_k_for + + m = xq.shape[0] + e2p, p2t, batch, limit, nct, npad = views + cap = max_num_tiles(m, TOPK, E_LOCAL, tile) * tile + h = torch.full((cap, INTER // 2), poison & 0xFF, dtype=torch.uint8, device="cuda") + hsf = torch.full((cap * INTER // 16,), poison & 0xFF, dtype=torch.uint8, device="cuda") + out = torch.full((cap, H), poison, dtype=torch.int16, device="cuda").view(torch.bfloat16) + if route: + route = dict(route, e2p=e2p, num_padded=npad) + n_max = n_max_for(m) + moe_nvfp4_engine( + xq, + xsf, + p2t, + batch, + limit, + nct, + ex.w31, + ex.w31s.view(torch.uint8), + ex.w2, + ex.w2s.view(torch.uint8), + ex.scale_c, + ex.alpha1, + ex.alpha2, + h, + hsf, + out, + state, + tile=tile, + n_max=n_max, + tile_k=tile_k_for(n_max, H, INTER), + release_after_wait=release_after_wait, + **route, + ) + if sync: + torch.cuda.synchronize() + return out + + +def _route_front_chain(ex, x, w, gs, ls, tile, state, poison): + """Today's chain for the same step: the route front steps' CuTe router GEMM, the lean route front (tables in + ``poison``-filled buffers), the engine on its tables. Returns (xq, xsf, ids, weights, table views, gemm2 rows).""" + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_front import ( + RouteFront, + RouteFrontRouterGemm, + prerouted_table_views, + ) + + m = x.shape[0] + logits = RouteFrontRouterGemm()(x, w) + front = RouteFront(lean=True) + fn = front.compiled(x, E, tile, E_LOCAL, TOPK) + assert logits is not None and fn is not None + flat, _, _ = _poisoned_routing(m, tile, poison) + xq, xsf, ids, wts = front(fn, logits, x, gs, flat, tile, ls, E_LOCAL, TOPK) + views = prerouted_table_views(flat, m, TOPK, E_LOCAL, tile) + return xq, xsf, ids, wts, views, _engine_on(ex, xq, xsf, views, tile, state, poison) + + +def _check_routed(got, ref, tag): + """ids, weights, every table word (both started from the same poison) and the gemm2 rows of the real (token, + expert) pairs, bitwise.""" + ids, wts, views, out = got + r_ids, r_wts, r_views, r_out = ref + assert torch.equal(ids, r_ids), (tag, "ids") + assert torch.equal(wts.view(torch.int16), r_wts.view(torch.int16)), (tag, "weights") + names = ("e2p", "p2t", "cta_batch", "cta_limit", "num_ctas", "num_padded") + for name, a, b in zip(names, views, r_views): + assert torch.equal(a, b), (tag, name) + rows = r_views[0][r_views[0] >= 0].long() + assert torch.equal(out[rows].view(torch.int16), r_out[rows].view(torch.int16)), (tag, "rows") + + +# The steps the engine routes (33..63 rows); local experts [ls, ls + 128) of 512; dup: exact logit ties. +@pytest.mark.parametrize( + "m,ls,tile,dup", + [ + (33, 0, 8, False), + (35, 0, 8, False), + (42, 0, 8, True), + (49, 384, 8, False), + (56, 0, 16, False), + (63, 128, 8, False), + ], +) +def test_engine_routes_bit_for_bit(m, ls, tile, dup, state): + """``route``: the engine on the epilogue router GEMM's per-tile candidates writes the ids, weights, e2p, p2t, + tile tables and counts of today's chain (router GEMM, lean route front) bit for bit and the same gemm2 rows; + every output starts from poison, twice with different poison.""" + import tensorrt_llm # noqa: F401 + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_front import ( + RouteFrontRouterGemm, + prerouted_table_views, + ) + + ex = _experts() + x, w, gs = _router_inputs(m, ex, seed=41 + m, dup=dup) + _, cand, xq, xsf = RouteFrontRouterGemm(engine_route=True)(x, w, gs, TOPK) + for poison in (-7, 0x2AAA): + ref = _route_front_chain(ex, x, w, gs, ls, tile, state, poison) + tag = (m, ls, tile, dup, poison) + assert torch.equal(xq, ref[0]) and torch.equal(xsf, ref[1]), (tag, "x quant") + flat, ids, wts = _poisoned_routing(m, tile, poison) + views = prerouted_table_views(flat, m, TOPK, E_LOCAL, tile) + out = _engine_on( + ex, + xq, + xsf, + views, + tile, + state, + poison, + candidates=cand, + topk_ids=ids, + topk_weights=wts, + local_start=ls, + ) + _check_routed((ids, wts, views, out), ref[2:], tag) + + +def _pdl_table_reader(): + """A PDL dependent that copies e2p (int32) and the BF16 weights (as u16) into ``out`` [n, 2] int32 as soon as it + starts, without its dependency wait, with the loads of the MoE-output all-reduce's Lamport fold.""" + import cutlass.cute as cute + from cutlass import Int32, Int64 + + from tensorrt_llm._torch.kernels.blackwell.mnnvl_slot_allreduce_norm import ( + _ld_relaxed_s32, + _ld_relaxed_u16, + ) + from tensorrt_llm._torch.kernels.blackwell.ptx_helpers import _st_global_b32 + + class Reader: + @cute.jit + def __call__(self, e2p: Int64, wts: Int64, out: Int64, n: Int32, stream) -> None: + self.kernel(e2p, wts, out, n).launch( + grid=[1, 1, 1], block=[1024, 1, 1], stream=stream, use_pdl=True + ) + + @cute.kernel + def kernel(self, e2p: Int64, wts: Int64, out: Int64, n: Int32) -> None: + tidx, _, _ = cute.arch.thread_idx() + if tidx < n: + o = out + Int64(tidx) * Int64(8) + _st_global_b32(o, _ld_relaxed_s32(e2p + Int64(tidx) * Int64(4))) + _st_global_b32(o + Int64(4), _ld_relaxed_u16(wts + Int64(tidx) * Int64(2))) + + return Reader() + + +@pytest.mark.parametrize("release_after_wait", [False, True]) +@pytest.mark.parametrize("m", [35, 56, 63]) +def test_engine_routes_before_releasing_its_dependents(m, release_after_wait, state): + """``route``: a dependent launched right behind the engine (PDL, no dependency wait, as the Lamport fold) reads + the e2p table and the weights the engine wrote, never the poison they started from, with few active experts (most + CTAs have no FC1 unit and reach the release point first).""" + import cuda.bindings.driver as cuda + import cutlass.cute as cute + from cutlass import Int32, Int64 + + import tensorrt_llm # noqa: F401 + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_front import ( + RouteFrontRouterGemm, + prerouted_table_views, + ) + + ex = _experts() + x, w, gs = _router_inputs(m, ex, seed=71 + m) + x = x.abs() + w = torch.full_like(w, -0.02) + w[: TOPK + 2] = 0.02 # every token routes to 10 of 12 experts + _, cand, xq, xsf = RouteFrontRouterGemm(engine_route=True)(x, w, gs, TOPK) + n = m * TOPK + got = torch.empty((n, 2), dtype=torch.int32, device="cuda") + reader = _pdl_table_reader() + stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream) + fn = cute.compile(reader, Int64(0), Int64(0), Int64(0), Int32(0), stream) + for it, poison in enumerate((-7, 0x2AAA) * 8): + flat, ids, wts = _poisoned_routing(m, 8, poison) + views = prerouted_table_views(flat, m, TOPK, E_LOCAL, 8) + got.fill_(poison) + torch.cuda.synchronize() + _engine_on( + ex, xq, xsf, views, 8, state, poison, sync=False, + release_after_wait=release_after_wait, + candidates=cand, topk_ids=ids, topk_weights=wts, local_start=0, + ) # fmt: skip + fn( + Int64(views[0].data_ptr()), + Int64(wts.data_ptr()), + Int64(got.data_ptr()), + Int32(n), + stream, + ) + torch.cuda.synchronize() + assert torch.equal(got[:, 0], views[0].reshape(-1)[:n]), (m, release_after_wait, it, "e2p") + assert torch.equal(got[:, 1], wts.view(torch.int16).reshape(-1).to(torch.int32) & 0xFFFF), ( + m, + release_after_wait, + it, + "weights", + ) + + +def _ref_route(logits, top_k): + """Host routing of BF16 ``logits`` for ``top_k``: ids by reduceTopK key (equal logits to the smaller expert) and + the weights with the route front's arithmetic (exp of v - v0, warp-butterfly sum, divide, round to BF16).""" + from tensorrt_llm._torch.kernels.blackwell.moe_bf16_engine import _butterfly_sum + + m, e = logits.shape + bits = logits.view(torch.int16).to(torch.int64) & 0xFFFF + tw = torch.where((bits & 0x8000) != 0, bits ^ 0xFFFF, bits | 0x8000) + keys = (tw << 16) | (65535 - torch.arange(e, device=logits.device)) + top = keys.sort(dim=-1, descending=True).values[:, :top_k] + ids = (65535 - (top & 0xFFFF)).int() + vals = torch.gather(logits.float(), 1, ids.long()) + ex = torch.exp(vals - vals[:, :1]) + + def tree_sum(t): + return ex[:, t] if isinstance(t, int) else tree_sum(t[0]) + tree_sum(t[1]) + + return ids, (ex / tree_sum(_butterfly_sum(top_k))[:, None]).to(torch.bfloat16) + + +@pytest.mark.parametrize("m,top_k,tile", [(42, 8, 8), (63, 4, 16)]) +def test_engine_routes_another_top_k(m, top_k, tile, state): + """The routing engine compiled for another top-k (4 lists of 128 experts): ids and tables equal to host + routing (tables in token order), weights within one BF16 step of it, and the gemm2 rows bitwise those of the + engine on the host tables.""" + import tensorrt_llm # noqa: F401 + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_front import ( + RouteFrontRouterGemm, + prerouted_table_sizes, + prerouted_table_views, + ) + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import n_max_for, tile_k_for + + ex = _experts() + x, w, gs = _router_inputs(m, ex, seed=61 + m) + logits, cand, xq, xsf = RouteFrontRouterGemm(engine_route=True)(x, w, gs, top_k) + assert cand.shape == (m, E // 128, top_k) + flat = torch.full((sum(prerouted_table_sizes(m, top_k, E_LOCAL, tile)),), -7, dtype=torch.int32) + flat = flat.cuda() + ids = torch.full((m, top_k), -7, dtype=torch.int32, device="cuda") + wts = torch.zeros((m, top_k), dtype=torch.bfloat16, device="cuda") + views = prerouted_table_views(flat, m, top_k, E_LOCAL, tile) + out = _engine_on( + ex, + xq, + xsf, + views, + tile, + state, + -7, + candidates=cand, + topk_ids=ids, + topk_weights=wts, + local_start=0, + ) + r_ids, r_wts = _ref_route(logits, top_k) + assert torch.equal(ids, r_ids) + step = (wts.view(torch.int16).int() - r_wts.view(torch.int16).int()).abs().max().item() + assert step <= 1, step + r_views, _ = _tables(r_ids, tile) + e2p, p2t, batch, limit, nct, npad = views + r_e2p, r_p2t, r_batch, r_limit, r_nct, r_npad = r_views + n = int(r_nct[0]) + assert torch.equal(e2p, r_e2p) and torch.equal(nct, r_nct) and torch.equal(npad, r_npad) + assert torch.equal(batch[:n], r_batch[:n]) and torch.equal(limit[:n], r_limit[:n]) + rows = r_e2p[r_e2p >= 0].long() + assert torch.equal(p2t[rows], r_p2t[rows]) + n_max = n_max_for(m) + ref, _, _, _ = _engine( + ex, xq, xsf, r_ids, tile, n_max, state, tile_k=tile_k_for(n_max, H, INTER) + ) + assert torch.equal(out[rows].view(torch.int16), ref[rows].view(torch.int16)) + + +def test_engine_route_bounds(): + """``route_error``: whole 16-byte candidate vectors, at most two per thread for 64 tokens.""" + from tensorrt_llm._torch.kernels.blackwell.moe_nvfp4_engine import route_error + + assert route_error(10, 4) is None and route_error(8, 4) is None and route_error(12, 4) is None + assert route_error(13, 4) is not None # 64 x 52 keys + assert route_error(10, 1) is not None and route_error(0, 4) is not None + assert route_error(36, 1) is not None # the weights' warp sum + + +def test_runner_routes_in_the_engine(monkeypatch): + """A pre-routed un-finalized call with ``candidates`` takes the engine, which writes the routing today's chain + would, also through the op backend (``EngineRouting``); a call that would not take the engine + refuses them.""" + import tensorrt_llm # noqa: F401 + from tensorrt_llm._torch.kernels.blackwell.moe_persistent_engine import new_state + from tensorrt_llm._torch.moe.fused_moe.impl_contract import EngineRouting + from tensorrt_llm._torch.moe.fused_moe.moe_op_backend import TRTLLMOpBackend + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_front import ( + RouteFrontRouterGemm, + prerouted_table_views, + ) + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import DecodeKernel + from tensorrt_llm._torch.utils import ActType_TrtllmGen + + ex = _experts() + m, tile = 42, 8 + state = new_state(torch.device("cuda")) + x, w, gs = _router_inputs(m, ex, seed=43) + ref = _route_front_chain(ex, x, w, gs, 0, tile, state, -7)[2:] + _, cand, xq, xsf = RouteFrontRouterGemm(engine_route=True)(x, w, gs, TOPK) + runner = _decode_runner() + any8, _ = _tile8_tactics(runner, m) + picked = _spy_select(monkeypatch) + flat, ids, wts = _poisoned_routing(m, tile, -7) + views = prerouted_table_views(flat, m, TOPK, E_LOCAL, tile) + kw = dict(tactic=any8, prerouted=(views, ids, wts), candidates=cand) + out = runner.forward(_op_inputs(ex, xq, xsf), engine_state=state, **kw)[0] + torch.cuda.synchronize() + assert picked == [DecodeKernel.ENGINE], picked + _check_routed((ids, wts, views, out), ref, "runner") + with pytest.raises(ValueError, match="candidates"): + runner.forward(_op_inputs(ex, xq, xsf), engine_state=None, **kw) + flat, ids, wts = _poisoned_routing(m, tile, -7) + rows, weights, e2p = TRTLLMOpBackend().run_fp4_block_scale_moe( + None, + None, + xq, + xsf, + ex.w31, + ex.w31s, + None, + None, + None, + None, + ex.w2, + ex.w2s, + None, + ex.scale_c, + ex.alpha1, + ex.alpha2, + E, + TOPK, + None, + None, + INTER, + 0, + E_LOCAL, + None, + 1, + do_finalize=False, + topk_weights=None, + topk_ids=None, + gated_act_type=int(ActType_TrtllmGen.SwiGlu), + prerouted=EngineRouting(flat, any8, ids, wts, cand), + decode_tuning=True, + decode_engine_state=state, + ) + torch.cuda.synchronize() + views = prerouted_table_views(flat, m, TOPK, E_LOCAL, tile) + _check_routed((ids, wts, views, rows), ref, "op backend") + assert weights is wts and torch.equal(e2p.flatten(), views[0]) + + +def test_ring_budget_keeps_the_tuned_stage_counts(): + """On the SM 10.x parts the ring takes 200 KiB of the 227 KiB opt-in shared memory, the budget whose stage counts + (NVFP4 engine: 4 at N 16 / 32 with K tile 512, 7 at N 64 with 256) the engines were measured with.""" + from tensorrt_llm._torch.kernels.blackwell.moe_bf16_engine import stages_for + from tensorrt_llm._torch.kernels.blackwell.moe_persistent_engine import ring_smem_bytes + + budget = ring_smem_bytes(torch.device("cuda")) + assert budget == 200 * 1024 + per_stage = { + (n, k): (128 + n) * k // 2 + 2 * 128 * k // 16 for n in (16, 32, 64) for k in (256, 512) + } + assert [min(10, budget // per_stage[nk]) for nk in ((16, 512), (32, 512), (64, 256))] == [ + 4, + 4, + 7, + ] + assert [stages_for(n, budget) for n in (16, 32)] == [5, 5] diff --git a/tests/unittest/_torch/multi_gpu/test_ll_exchange.py b/tests/unittest/_torch/multi_gpu/test_ll_exchange.py index 36866969c170..75f0450906db 100644 --- a/tests/unittest/_torch/multi_gpu/test_ll_exchange.py +++ b/tests/unittest/_torch/multi_gpu/test_ll_exchange.py @@ -14,8 +14,9 @@ # limitations under the License. """The one-launch TP exchanges (distributed/ll_exchange.py) against the same reduction over every rank's inputs: key max / gather and greedy argmax of TPKeyExchange, its argmax and temperature sample of -vocabulary-sharded logits (also through the spec worker), and TPGroupExchange's subgroup all-gather, -eager and replayed from a CUDA graph (the epochs keep advancing across launches).""" +vocabulary-sharded logits (also through the spec worker), and TPGroupExchange's subgroup all-gather and the +RoPE kernel's in-kernel q all-gather, eager and replayed from a CUDA graph (the epochs keep advancing across +launches); TPGroupExchange's all-to-all merge against an eager merge of every member's partials.""" import math import pickle @@ -26,7 +27,12 @@ import cloudpickle import pytest import torch -from _torch.helpers import gumbel_max_reference +from _torch.helpers import ( + fast_gumbel_max_reference, + gumbel_max_reference, + late_copy, + triton_num_compiled, +) from mpi4py import MPI import tensorrt_llm @@ -147,6 +153,12 @@ def _argmax_logits(tp): torch.cuda.synchronize() assert torch.equal(tokens, expected), (dtype, m, split) assert torch.equal(unpack_argmax_tokens(keys), expected), (dtype, m, split) + # The row-split launch shape draws the same tokens. + ex.argmax_row_split = True + tokens = ex.argmax_logits(local, rank * SHARD) + ex.argmax_row_split = False + torch.cuda.synchronize() + assert torch.equal(tokens, expected), (dtype, m, "row split") # CUDA-graph replays with fresh logits copied into the captured buffer. m = 24 @@ -213,6 +225,7 @@ def _gumbel_sample(tp, base_seed=0): seed = torch.zeros(1, dtype=torch.int64, device="cuda") for step in range(32): seed.fill_(base_seed * 1000 + step + 1) + ex.argmax_row_split = step % 4 == 0 tokens = ex.argmax_logits( local, rank * SHARD, @@ -261,6 +274,166 @@ def _forward_impl(self, *args, **kwargs): ex.close() +def _fast_gumbel_sample(tp): + """fast_gumbel: the four-draws kernel's tokens are fast_gumbel_max_reference's over the whole vocabulary on + every rank (whatever the sharding), greedy below the threshold, and distributed as softmax(logits / T).""" + mapping, rank = _mapping(tp) + ex = TPKeyExchange.create(mapping, max_rows=64, fast_gumbel=True) + assert ex is not None, "no peer memory for the exchange" + vocab, rows, groups = tp * SHARD, 512, 4 + group_temps = torch.tensor([0.6, 1.0, 1.5, 0.5 * GREEDY_TEMPERATURE_THRESHOLD], device="cuda") + g = torch.Generator(device="cuda").manual_seed(3) + dists = (torch.randn((groups, vocab), generator=g, device="cuda") * 3).to(torch.bfloat16) + try: + counts = torch.zeros((groups - 1, vocab), dtype=torch.int64, device="cuda") + seed = torch.zeros(1, dtype=torch.int64, device="cuda") + for step, m in enumerate([rows] * 32 + [1, 7, 33]): + temps = group_temps.repeat_interleave(rows // groups)[:m] + full = dists.repeat_interleave(rows // groups, dim=0)[:m] + local = full[:, rank * SHARD : (rank + 1) * SHARD] + seed.fill_(step + 1) + tokens = ex.argmax_logits( + local, + rank * SHARD, + temperature=temps, + seed=seed, + greedy_threshold=GREEDY_TEMPERATURE_THRESHOLD, + ) + expected = fast_gumbel_max_reference(full, temps, seed, GREEDY_TEMPERATURE_THRESHOLD) + assert torch.equal(tokens, expected), step + gathered = MPI.COMM_WORLD.allgather(tokens.cpu()) + assert all(torch.equal(t, gathered[0]) for t in gathered) + if m == rows: + for group in range(groups - 1): + counts[group] += torch.bincount( + tokens.view(groups, -1)[group].long(), minlength=vocab + ) + greedy = torch.argmax(full.float(), dim=-1).to(torch.int32) + assert torch.equal(tokens.view(groups, -1)[-1], greedy.view(groups, -1)[-1]) + for group in range(groups - 1): + probs = torch.softmax(dists[group].float() / group_temps[group], dim=-1) + stat, crit = _chi_square(counts[group].cpu(), probs.cpu()) + assert stat < crit, (float(group_temps[group]), stat, crit) + torch.cuda.synchronize() + finally: + MPI.COMM_WORLD.barrier() + ex.close() + + +def _sample_accept(tp): + """fused_accept.sample_and_strict_accept: the seed bump, the four-draws Gumbel sample of argmax_logits and the + strict acceptance (natural, forced base, forced base + pool draw) in one launch give the three launches' accepted + tokens, counts, seed and forced-acceptance counter, eager and replayed from a CUDA graph.""" + from tensorrt_llm._torch.speculative.fused_accept import ( + fused_strict_accept, + sample_and_strict_accept, + ) + + mapping, rank = _mapping(tp) + ex = TPKeyExchange.create(mapping, max_rows=64, fast_gumbel=True) + assert ex is not None, "no peer memory for the exchange" + k, vocab = 6, tp * SHARD + pool = torch.rand(1024, generator=torch.Generator(device="cuda").manual_seed(5), device="cuda") + + def inputs(num_contexts, num_gens, step): + g = torch.Generator(device="cuda").manual_seed(100 * step + num_gens) + m = num_contexts + num_gens * (k + 1) + full = (torch.randn((m, vocab), generator=g, device="cuda") * 3).to(torch.bfloat16) + temps = torch.rand(m, generator=g, device="cuda") + 0.3 + temps[::3] = 0.5 * GREEDY_TEMPERATURE_THRESHOLD # greedy rows + greedy = torch.argmax(full.float(), dim=-1).to(torch.int32)[num_contexts:].view(-1, k + 1) + draft = greedy[:, :k].clone() + draft[1::2, 2] += 1 # leading matches stop early on odd requests + return full[:, rank * SHARD : (rank + 1) * SHARD].contiguous(), temps, draft + + def stock(logits, temps, draft, nc, b, seed, force): + seed.add_(1) + tokens = ex.argmax_logits( + logits, + rank * SHARD, + temperature=temps, + seed=seed, + greedy_threshold=GREEDY_TEMPERATURE_THRESHOLD, + ) + return fused_strict_accept(tokens, draft, nc, b, force) + + def fused(logits, temps, draft, nc, b, seed, force): + return sample_and_strict_accept( + ex, logits, rank * SHARD, temps, seed, GREEDY_TEMPERATURE_THRESHOLD, draft, nc, b, force + ) + + def check(a, b, nc, what): + (acc_a, n_a), (acc_b, n_b) = a, b + assert torch.equal(n_a, n_b), what + assert torch.equal(acc_a[:nc, 0], acc_b[:nc, 0]) and torch.equal(acc_a[nc:], acc_b[nc:]), ( + what + ) + + try: + for force_kind in ("natural", "base", "draw"): + counters = [torch.zeros(1, dtype=torch.int64, device="cuda") for _ in range(2)] + + def force_of(i): + if force_kind == "natural": + return None + if force_kind == "base": + return (3, k + 1, 0.0, None, None, 6007, 1009, 1024) + return (3, k + 1, 0.6, pool, counters[i], 6007, 1009, 1024) + + seeds = [torch.full((1,), 7, dtype=torch.int64, device="cuda") for _ in range(2)] + for step, (nc, ng) in enumerate(((0, 5), (2, 3), (0, 8), (1, 0))): + logits, temps, draft = inputs(nc, ng, step) + b = nc + ng + ref = stock(logits, temps, draft, nc, b, seeds[0], force_of(0)) + got = fused(logits, temps, draft, nc, b, seeds[1], force_of(1)) + assert got is not None + torch.cuda.synchronize() + check(ref, got, nc, (force_kind, step)) + assert torch.equal(seeds[0], seeds[1]) and torch.equal(counters[0], counters[1]) + # CUDA graph: one captured fused call replayed on new logits; the stock launches give the reference. + logits, temps, draft = inputs(0, 5, 9) + fused(logits, temps, draft, 0, 5, seeds[1], force_of(1)) # compile outside the capture + stock(logits, temps, draft, 0, 5, seeds[0], force_of(0)) + torch.cuda.synchronize() + MPI.COMM_WORLD.barrier() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + got = fused(logits, temps, draft, 0, 5, seeds[1], force_of(1)) + for replay in range(3): + new_logits, new_temps, new_draft = inputs(0, 5, 20 + replay) + for static, new in zip((logits, temps, draft), (new_logits, new_temps, new_draft)): + static.copy_(new) + graph.replay() + ref = stock(logits, temps, draft, 0, 5, seeds[0], force_of(0)) + torch.cuda.synchronize() + check(ref, got, 0, (force_kind, "replay", replay)) + assert torch.equal(seeds[0], seeds[1]) and torch.equal(counters[0], counters[1]) + del graph + + # The split (programs per row) follows the row count: launches at other splits reuse the compiled kernel + # and draw the same tokens. + from tensorrt_llm._torch.distributed import ll_exchange + from tensorrt_llm._torch.speculative import fused_accept + + real_split = ll_exchange._fast_gumbel_split + seeds = [torch.full((1,), 11, dtype=torch.int64, device="cuda") for _ in range(2)] + compiled = triton_num_compiled(fused_accept._sample_accept_kernel) + try: + for step, split in enumerate((4, 6, 8, 2)): + ll_exchange._fast_gumbel_split = lambda m, v_shard, num_sms, s=split: s + logits, temps, draft = inputs(0, 5, 40 + step) + ref = stock(logits, temps, draft, 0, 5, seeds[0], None) + got = fused(logits, temps, draft, 0, 5, seeds[1], None) + torch.cuda.synchronize() + check(ref, got, 0, ("split", split)) + finally: + ll_exchange._fast_gumbel_split = real_split + assert triton_num_compiled(fused_accept._sample_accept_kernel) == compiled + finally: + MPI.COMM_WORLD.barrier() + ex.close() + + def _group_allgather(tp): mapping, rank = _mapping(tp) group_size = 2 @@ -278,11 +451,393 @@ def x_of(r): torch.cuda.synchronize() ref = torch.cat([x_of(r).reshape(rows, -1) for r in members], dim=-1) assert torch.equal(out.view(torch.int16), ref.view(torch.int16)), ("allgather", rows) + # An epoch is a plain counter whose parity picks the slot half: exchanges across its int32 wrap (-1 -> 0 -> 1) + # deliver like any other. Every rank's previous launch has finished before any rank moves its epochs. + MPI.COMM_WORLD.barrier() + ex._state.fill_(-1) + + def wrap_x(r): + g = torch.Generator(device="cuda").manual_seed(1000 + r) + return torch.randn((64, 4, 256), generator=g, device="cuda").to(torch.bfloat16) + + x = wrap_x(rank) + ref = torch.cat([wrap_x(r).reshape(64, -1) for r in members], dim=-1) + blocks = 64 * 4 * 256 * 2 // 4 // 256 + for launch in range(2): + out = ex.allgather(x) + torch.cuda.synchronize() + assert torch.equal(out.view(torch.int16), ref.view(torch.int16)), ( + "allgather across the wrap", + launch, + ) + assert (ex._state[0, :blocks] == 1).all(), ex._state[0, :blocks] + # Refused before any launch: an integer payload (its all-ones words would arrive rewritten), a pushed + # merge of two partials per row (its producer pushes one), and an in-kernel gather on an exchange created + # without its head dim. + for dtype in (torch.int32, torch.float64): + with pytest.raises(ValueError, match="floating-point"): + ex.allgather(torch.zeros(4, 256, dtype=dtype, device="cuda")) + o = torch.zeros(group_size, 2, 4, 4, 256, dtype=torch.bfloat16, device="cuda") + lse = torch.zeros(group_size, 2, 4, 4, device="cuda") + out = torch.empty(4, 4, 256, dtype=torch.bfloat16, device="cuda") + with pytest.raises(ValueError, match="one partial"): + ex.alltoall_merge(o, lse, out, pushed=True) + with pytest.raises(ValueError, match="head dim"): + ex.rope_gather_args(2, 4, 256) finally: MPI.COMM_WORLD.barrier() ex.close() +def _rope_gather(tp): + """The RoPE / FP8-append kernel's in-kernel q all-gather (fused_qkv_rope_gate_fp8_append_gather) is bit-identical + to the plain kernel followed by TPGroupExchange.allgather of its FP8 query: every output, the KV pool and the + gathered q, over repeated calls of changing token counts and CUDA-graph replays (epochs keep advancing).""" + from tensorrt_llm._torch.attention.backends.fmha.gqa_decode import KvAppendPlan + from tensorrt_llm._torch.attention.kernels.fused_qk_norm_rope_gate import ( + fused_qkv_rope_gate_fp8_append, + fused_qkv_rope_gate_fp8_append_gather, + ) + + mapping, rank = _mapping(tp) + hq, hkv, d, rot, page, max_pages = 4, 1, 256, 64, 64, 8 + mrope, channel = (11, 11, 10), 2 + ex = TPGroupExchange.create( + mapping, tp, max_bytes=1 << 20, max_merge_rows=64, num_channels=3, gather_head_dim=d + ) + assert ex is not None, "no peer memory for the exchange" + g = torch.Generator(device="cuda").manual_seed(1) + q_weight = (torch.randn(d, generator=g, device="cuda") * 0.1).to(torch.bfloat16) + k_weight = (torch.randn(d, generator=g, device="cuda") * 0.1).to(torch.bfloat16) + cos_sin = torch.randn(4096, 2, rot // 2, generator=g, device="cuda") + scale = torch.tensor([0.05], device="cuda") + inv_scale = 1.0 / scale + + def call_inputs(q_len, b, seed): + g = torch.Generator(device="cuda").manual_seed(seed) + seq = torch.randint(q_len, page * max_pages, (b,), generator=g, device="cuda").to( + torch.int32 + ) + tables = torch.randperm(b * 2 * max_pages + 4, generator=g, device="cuda")[ + : b * 2 * max_pages + ] + tables = tables.to(torch.int32).view(b, 2, max_pages).contiguous() + pos = (seq[:, None] - q_len + torch.arange(q_len, device="cuda")).reshape(-1) + positions = pos.expand(3, -1).contiguous() + # q / gate / K / V differ per member, as the heads of a TP rank do + gq = torch.Generator(device="cuda").manual_seed(seed * 101 + rank) + qkv = torch.randn(b * q_len, (2 * hq + 2 * hkv) * d, generator=gq, device="cuda") + return qkv.to(torch.bfloat16), positions, seq, tables + + def plan_of(q_len, b, pool, seq, tables): + return KvAppendPlan(0, b * q_len, b, q_len, pool, tables, seq, inv_scale, scale, 1.0 / 16) + + def run(gather, q_len, b, qkv, positions, seq, tables, pool): + plan = plan_of(q_len, b, pool, seq, tables) + args = (qkv, q_weight, k_weight, cos_sin, positions, 1e-6, hq, hkv, d, rot, mrope, plan) + if gather: + ga = (*ex.rope_gather_args(channel, b * q_len * hq, d), True) + return fused_qkv_rope_gate_fp8_append_gather(*args, ga) + outs = fused_qkv_rope_gate_fp8_append(*args) + return (*outs, ex.allgather(outs[2], channel=0)) + + def pools(b): + return [ + torch.zeros( + b * 2 * max_pages + 4, hkv, page, d, dtype=torch.float8_e4m3fn, device="cuda" + ) + for _ in range(2) + ] + + def check(got, ref, pool_got, pool_ref, what): + torch.cuda.synchronize() + # (qkv, gate, q8, scales, gathered q); the kernels write scales [0:5] only + got, ref = list(got), list(ref) + got[3], ref[3] = got[3][:5], ref[3][:5] + for i, (x, y) in enumerate(zip(got, ref)): + assert x.shape == y.shape and torch.equal(x.view(torch.uint8), y.view(torch.uint8)), ( + what, + i, + ) + assert torch.equal(pool_got.view(torch.uint8), pool_ref.view(torch.uint8)), ( + what, + "kv pool", + ) + + try: + for step, (q_len, b) in enumerate(((7, 3), (1, 5), (7, 8), (7, 3), (1, 1))): + inputs = call_inputs(q_len, b, step) + pool_g, pool_p = pools(b) + got = run(True, q_len, b, *inputs, pool_g) + ref = run(False, q_len, b, *inputs, pool_p) + check(got, ref, pool_g, pool_p, ("eager", step)) + + # CUDA graph: one captured gather call replayed on new inputs. + q_len, b = 7, 4 + qkv, positions, seq, tables = call_inputs(q_len, b, 100) + pool_g, pool_p = pools(b) + run(True, q_len, b, qkv, positions, seq, tables, pool_g) # compile outside the capture + torch.cuda.synchronize() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + got = run(True, q_len, b, qkv, positions, seq, tables, pool_g) + for replay in range(4): + new = call_inputs(q_len, b, 200 + replay) + for static, x in zip((qkv, positions, seq, tables), new): + static.copy_(x) + pool_g.zero_() + pool_p.zero_() + graph.replay() + ref = run(False, q_len, b, qkv, positions, seq, tables, pool_p) + check(got, ref, pool_g, pool_p, ("replay", replay)) + # an eager gather call between replays shares the epochs + eager = run(True, q_len, b, qkv, positions, seq, tables, pools(b)[0]) + torch.cuda.synchronize() + assert torch.equal(eager[4].view(torch.uint8), ref[4].view(torch.uint8)), ( + "eager", + replay, + ) + del graph + + # PDL: the positions come from the immediate predecessor, which releases this launch at entry and stores + # them ~2 ms later; the kernel reads them (and the cos / sin rows they select) only after its wait. + q_len, b = 7, 3 + qkv, positions, seq, tables = call_inputs(q_len, b, 300) + pool_g, pool_p = pools(b) + ref = run(False, q_len, b, qkv, positions, seq, tables, pool_p) + late = torch.zeros_like(positions) + late_copy(positions, late, 1000) # compile outside the timed launch + torch.cuda.synchronize() + late.zero_() + torch.cuda.synchronize() + MPI.COMM_WORLD.barrier() + late_copy(positions, late, 2_000_000) + got = run(True, q_len, b, qkv, late, seq, tables, pool_g) + check(got, ref, pool_g, pool_p, ("pdl predecessor writes the positions",)) + finally: + MPI.COMM_WORLD.barrier() + ex.close() + + +def _receive_words(ex): + """This rank's receive buffers of ``ex`` as int32 words (a device copy).""" + from cuda.bindings import runtime as cudart + + nbytes = ex.channel_bytes * ex.num_channels + words = torch.empty(nbytes // 4, dtype=torch.int32, device="cuda") + torch.cuda.synchronize() + (err,) = cudart.cudaMemcpy( + words.data_ptr(), + ex._buffers.local_ptr, + nbytes, + cudart.cudaMemcpyKind.cudaMemcpyDeviceToDevice, + ) + assert err == cudart.cudaError_t.cudaSuccess + return words + + +def _merge_reference(o_all, lse_all, grank, valid=None, gate=None, extra_o=None, extra_lse=None): + """alltoall_merge's result at member ``grank`` from every member's ``o`` [G, P, T, Hh, D] / ``lse`` [G, P, T, Hh]: + the LSE-weighted mean (base 2, FP32) of the valid partials it receives and the extra partial, rounded to BF16, + then gated.""" + o = torch.stack([x[grank] for x in o_all]).float() # [source, P, T, Hh, D] + lse = torch.stack([x[grank] for x in lse_all]) # [source, P, T, Hh] + ok = lse > float("-inf") + if valid is not None: + ok = ok & (valid[:, :, :, None] != 0) + m = torch.where(ok, lse, float("-inf")).amax(dim=(0, 1)) + if extra_lse is not None: + m = torch.maximum(m, extra_lse) + w = torch.where(ok, torch.exp2(lse - m), 0.0) + num = (w[..., None] * o).sum(dim=(0, 1)) + den = w.sum(dim=(0, 1)) + if extra_o is not None: + wx = torch.where(extra_lse > float("-inf"), torch.exp2(extra_lse - m), 0.0) + num = num + wx[..., None] * extra_o.float() + den = den + wx + res = torch.where(den[..., None] > 0, num / torch.where(den > 0, den, 1.0)[..., None], 0.0) + res = res.to(torch.bfloat16) + if gate is not None: + res = (res.float() * torch.sigmoid(gate.float())).to(torch.bfloat16) + return res + + +def _group_merge(tp): + """TPGroupExchange's Lamport words against references over every member's inputs: its all-gather (one and + several blocks per program) against the concatenation, its all-to-all merge (BF16 and E4M3 out, gate, extra + partial, valid mask, one and two partials per row) against an eager merge, and the RoPE kernel's in-kernel q + all-gather against the plain kernel and every member's FP8 query; eager and replayed from a CUDA graph. After + every call each receive word is empty again.""" + from tensorrt_llm._torch.attention.backends.fmha.gqa_decode import KvAppendPlan + from tensorrt_llm._torch.attention.kernels.fused_qk_norm_rope_gate import ( + fused_qkv_rope_gate_fp8_append, + fused_qkv_rope_gate_fp8_append_gather, + ) + from tensorrt_llm._torch.distributed.ll_exchange import LAMPORT_EMPTY + + mapping, rank = _mapping(tp) + hq, hkv, d, rot, page, max_pages, mrope = 4, 1, 256, 64, 64, 8, (11, 11, 10) + ex = TPGroupExchange.create( + mapping, tp, max_bytes=1 << 20, max_merge_rows=1024, num_channels=3, gather_head_dim=d + ) + assert ex is not None, "no peer memory for the exchange" + g = torch.Generator(device="cuda").manual_seed(1) + q_weight = (torch.randn(d, generator=g, device="cuda") * 0.1).to(torch.bfloat16) + k_weight = (torch.randn(d, generator=g, device="cuda") * 0.1).to(torch.bfloat16) + cos_sin = torch.randn(4096, 2, rot // 2, generator=g, device="cuda") + scale = torch.tensor([0.05], device="cuda") + out_scale = torch.tensor([0.37], device="cuda") + + def inputs(step, member): + """Every input of one step's calls from ``member``; each member's own data differs from its peers'.""" + gr = torch.Generator(device="cuda").manual_seed(step * 101 + member) + rows = (1, 9, 200, 64, 3)[step % 5] # 200 rows: several 256-word blocks per program + x = torch.randn((rows, 4, 256), generator=gr, device="cuda").to(torch.bfloat16) + t, p = (5, 16, 3)[step % 3], 1 + step % 2 + o = torch.randn((tp, p, t, hq, d), generator=gr, device="cuda").to(torch.bfloat16) + lse = torch.randn((tp, p, t, hq), generator=gr, device="cuda") * 4 + lse[0, 0, 0, 0] = float("-inf") + valid = (torch.rand((tp, p, t), generator=gr, device="cuda") > 0.2).to(torch.int32) + gate = torch.randn((t, hq, d), generator=gr, device="cuda").to(torch.bfloat16) + extra_o = torch.randn((t, hq, d), generator=gr, device="cuda").to(torch.bfloat16) + extra_lse = torch.randn((t, hq), generator=gr, device="cuda") * 4 + q_len, b = (7, 3) if step % 2 else (1, 5) + # tables / positions: the same on every member + gs = torch.Generator(device="cuda").manual_seed(step) + tables = torch.randperm(b * 2 * max_pages + 4, generator=gs, device="cuda")[ + : b * 2 * max_pages + ] + tables = tables.to(torch.int32).view(b, 2, max_pages).contiguous() + seq = torch.randint(q_len, page * max_pages, (b,), generator=gs, device="cuda").to( + torch.int32 + ) + pos = (seq[:, None] - q_len + torch.arange(q_len, device="cuda")).reshape(-1) + qkv = torch.randn(b * q_len, (2 * hq + 2 * hkv) * d, generator=gr, device="cuda") + rope = (q_len, b, qkv.to(torch.bfloat16), pos.expand(3, -1).contiguous(), seq, tables) + return x, (o, lse, valid, gate, extra_o, extra_lse), rope + + def rope_call(rope, pool, gather): + q_len, b, qkv, positions, seq, tables = rope + plan = KvAppendPlan(0, b * q_len, b, q_len, pool, tables, seq, 1.0 / scale, scale, 1.0 / 16) + args = (qkv, q_weight, k_weight, cos_sin, positions, 1e-6, hq, hkv, d, rot, mrope, plan) + if gather: + ga = (*ex.rope_gather_args(2, b * q_len * hq, d), True) + return list(fused_qkv_rope_gate_fp8_append_gather(*args, ga)) + return list(fused_qkv_rope_gate_fp8_append(*args)) + + def new_pool(rope): + b = rope[1] + return torch.zeros( + b * 2 * max_pages + 4, hkv, page, d, dtype=torch.float8_e4m3fn, device="cuda" + ) + + def run(x, merge, rope): + o, lse, valid, gate, extra_o, extra_lse = merge + t = o.shape[2] + gathered = ex.allgather(x, channel=0) + out = torch.empty((t, hq, d), dtype=torch.bfloat16, device="cuda") + ex.alltoall_merge(o, lse, out, gate=gate, valid=valid, channel=1) + out8 = torch.empty((t, hq, d), dtype=torch.float8_e4m3fn, device="cuda") + ex.alltoall_merge( + o, + lse, + None, + extra_o=extra_o, + extra_lse=extra_lse, + out_fp8=out8, + out_scale=out_scale, + channel=1, + ) + pool = new_pool(rope) + return [gathered, out, out8, pool, *rope_call(rope, pool, gather=True)] + + def check(got, step, what): + """``got`` (run's outputs from this member's inputs of ``step``) against the references.""" + members = [inputs(step, m) for m in range(tp)] + x, merge, rope = members[rank] + o, lse, valid, gate, extra_o, extra_lse = merge + gathered, out, out8, pool, *rope_got = got + torch.cuda.synchronize() + ref = torch.cat([mx.reshape(mx.shape[0], -1) for mx, _, _ in members], dim=-1) + assert torch.equal(gathered.view(torch.int16), ref.view(torch.int16)), (what, "allgather") + o_all = [mm[0] for _, mm, _ in members] + lse_all = [mm[1] for _, mm, _ in members] + ref = _merge_reference(o_all, lse_all, rank, valid=valid, gate=gate) + torch.testing.assert_close(out.float(), ref.float(), atol=1e-2, rtol=1e-2, msg=str(what)) + ref8 = _merge_reference(o_all, lse_all, rank, extra_o=extra_o, extra_lse=extra_lse) + ref8 = (ref8.float() * (1.0 / out_scale)).to(torch.float8_e4m3fn).float() + # within one E4M3 step of the BF16 reference's quant + step8 = ref8.abs() * 0.125 + 2**-9 + assert bool(((out8.float() - ref8).abs() <= step8).all()), (what, "fp8") + pool_ref = new_pool(rope) + rope_ref = rope_call(rope, pool_ref, gather=False) + q8_all = [rope_call(mr, new_pool(mr), gather=False)[2] for _, _, mr in members] + rope_ref.append(torch.cat([q.reshape(q.shape[0], -1) for q in q8_all], dim=-1)) + # the kernels write scales [0:5] only + rope_got[3], rope_ref[3] = rope_got[3][:5], rope_ref[3][:5] + for i, (a, b) in enumerate(zip(rope_got, rope_ref)): + assert a.shape == b.shape and torch.equal(a.view(torch.uint8), b.view(torch.uint8)), ( + what, + "rope", + i, + ) + assert torch.equal(pool.view(torch.uint8), pool_ref.view(torch.uint8)), (what, "kv pool") + # Every member has read its words of this step before any member starts the next one. + MPI.COMM_WORLD.barrier() + assert bool((_receive_words(ex) == LAMPORT_EMPTY).all()), (what, "Lamport words left") + MPI.COMM_WORLD.barrier() + + try: + assert bool((_receive_words(ex) == LAMPORT_EMPTY).all()), "Lamport buffers start empty" + for step in range(6): + check(run(*inputs(step, rank)), step, ("eager", step)) + # CUDA graph: one captured step replayed on new inputs of the same shapes (step 1 + 30 k). + x, merge, rope = inputs(1, rank) + run(x, merge, rope) # compile outside the capture + check_steps = [1 + 30 * (replay + 1) for replay in range(3)] + torch.cuda.synchronize() + MPI.COMM_WORLD.barrier() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + got = run(x, merge, rope) + for replay, step in enumerate(check_steps): + nx, nmerge, nrope = inputs(step, rank) + for static, new in zip((x, *merge, *rope[2:]), (nx, *nmerge, *nrope[2:])): + static.copy_(new) + got[3].zero_() # the KV pool the captured RoPE kernel appends to + graph.replay() + check(got, step, ("replay", replay)) + del graph + finally: + MPI.COMM_WORLD.barrier() + ex.close() + + +def _peer_fill_failure(tp): + """A sentinel fill that fails on one rank declines the peer buffers on every rank (no rank is left waiting in + the barrier the fill is agreed in).""" + from cuda.bindings import runtime as cudart + + from tensorrt_llm._torch.distributed.ll_exchange import _PeerBuffers + + mapping, rank = _mapping(tp) + real = cudart.cudaMemset + + def memset(ptr, value, nbytes): + # Only the sentinel fill: IpcMemory's own zero fill (before its handle exchange) stays real. + if rank == 1 and value == 0xFF: + return (cudart.cudaError_t.cudaErrorInvalidValue,) + return real(ptr, value, nbytes) + + cudart.cudaMemset = memset + try: + buffers = _PeerBuffers.create(mapping, 1 << 20, fill=0xFF) + finally: + cudart.cudaMemset = real + MPI.COMM_WORLD.barrier() + assert buffers is None, "a rank kept peer buffers whose fill failed on another rank" + + def _worker(fn, tp): try: with torch.inference_mode(): @@ -297,7 +852,12 @@ def _worker(fn, tp): "key_exchange": _key_exchange, "argmax_logits": _argmax_logits, "gumbel_sample": _gumbel_sample, + "fast_gumbel_sample": _fast_gumbel_sample, + "sample_accept": _sample_accept, "group_allgather": _group_allgather, + "rope_gather": _rope_gather, + "group_merge": _group_merge, + "peer_fill_failure": _peer_fill_failure, } @@ -309,3 +869,27 @@ def test_ll_exchange(case, mpi_pool_executor): pytest.skip(f"needs {tp} GPUs") results = mpi_pool_executor.map(_worker, [CASES[case]] * tp, [tp] * tp) assert all(results) + + +def test_group_exchange_is_cached_per_gather_head_dim(monkeypatch): + """get_tp_group_exchange returns the exchange created for the same group, channel count and in-kernel gather + head dim (a PDL-off engine's exchange has no RoPE-gather channel for a later PDL-on one).""" + from tensorrt_llm._torch.distributed import ll_exchange + + created = [] + + def create(cls, mapping, group_size, max_bytes, max_merge_rows, num_channels, gather_head_dim): + created.append(gather_head_dim) + return SimpleNamespace( + transport="ipc", gather_head_dim=gather_head_dim, num_channels=num_channels + ) + + monkeypatch.setattr(ll_exchange.TPGroupExchange, "create", classmethod(create)) + monkeypatch.setattr(ll_exchange, "_GROUP_EXCHANGES", {}) + mapping = SimpleNamespace(tp_group=[0, 1], tp_rank=0, tp_size=2) + a = ll_exchange.get_tp_group_exchange(mapping, 2, 1 << 20, 64, 3, gather_head_dim=256) + b = ll_exchange.get_tp_group_exchange(mapping, 2, 1 << 20, 64, 3, gather_head_dim=128) + assert ll_exchange.get_tp_group_exchange(mapping, 2, 1 << 20, 64, 3, gather_head_dim=256) is a + assert b.gather_head_dim == 128 and created == [256, 128] + c = ll_exchange.get_tp_group_exchange(mapping, 2, 1 << 20, 64, 2, gather_head_dim=256) + assert c is not a and c.num_channels == 2 and a.num_channels == 3 diff --git a/tests/unittest/_torch/multi_gpu/test_mnnvl_fused_allreduce_norm.py b/tests/unittest/_torch/multi_gpu/test_mnnvl_fused_allreduce_norm.py index d4805ce5849f..dfe98c719ffa 100644 --- a/tests/unittest/_torch/multi_gpu/test_mnnvl_fused_allreduce_norm.py +++ b/tests/unittest/_torch/multi_gpu/test_mnnvl_fused_allreduce_norm.py @@ -14,8 +14,10 @@ # limitations under the License. """The CuTe DSL all-reduce + residual + RMSNorm kernels of MNNVLAllReduce against an FP32 reference over all ranks' inputs: the slot (one-shot) and two-shot launches, the shared-expert gate fold (with or -without the in-kernel MoE finalize), the FP8 output, and the FP8 GEMM + all-reduce + norm launch.""" +without the in-kernel MoE finalize), the FP8 output, the FP8 GEMM + all-reduce + norm launches (one-shot and +two-shot), and the TP2 large-message all-reduce + norm (Tp2AllReduceNorm).""" +import operator import os import pickle import sys @@ -46,7 +48,8 @@ H = 4096 EPS = 1e-6 -# Kernel launch: slot below 64 rows, two-shot from 64. ``ar(...)`` takes the CuTe kernels only up to the 1 MiB +# Kernel launch: the slot kernel up to 128 rows (with the two-shot arithmetic from 64), the two-shot kernel above +# (SLOT_MAX_ROWS, TWO_SHOT_ROWS). ``ar(...)`` takes the CuTe kernels only up to the 1 MiB # one-shot message (rows * H * tp * 2 bytes), the library op above, so the two-shot rows are also checked through # ``ar.fused_norm`` directly. Consecutive calls also cycle the Lamport buffers. ROWS = (1, 7, 32, 63, 64, 96, 200) @@ -70,13 +73,56 @@ def _check(got, ref, tag, rtol=2e-2): ) -def _mnnvl(tp, hidden=H): +def _library(ar, x, params): + """The library op's outputs for this call (MNNVLAllReduce with its CuTe kernels set aside).""" + fused = ar.fused_norm + ar.fused_norm = None + try: + out = ar(x, all_reduce_params=params) + finally: + ar.fused_norm = fused + return out if isinstance(out, tuple) else (out,) + + +def _assert_bitwise(got, ref, tag, norm_ulps=0): + """Outputs equal bit for bit (BF16 / E4M3 compared as integers); with ``norm_ulps``, all but the last (the + residual, still bit for bit) within that many ulps / E4M3 codes.""" + assert len(got) == len(ref), tag + for i, (g, r) in enumerate(zip(got, ref)): + assert g.dtype == r.dtype and g.shape == r.shape, (tag, i) + as_int = torch.int16 if g.element_size() == 2 else torch.uint8 + if norm_ulps and i < len(got) - 1: + ulps = (g.view(as_int).int() - r.view(as_int).int()).abs().max().item() + assert ulps <= norm_ulps, (tag, i, ulps) + else: + assert torch.equal(g.view(as_int), r.view(as_int)), (tag, i) + + +def _library_arithmetic(m, tp, hidden=H): + """Which arithmetic the library op runs for ``m`` rows ("one-shot" up to its message size, else "two-shot"), + the one the CuTe kernels run for ``m`` rows (the two-shot's from TWO_SHOT_ROWS), and whether the norm's + reduction tree is the library's too: always for the two-shot (it replays the library's launch shape), for the + slot kernel's one-shot only where the library's one-shot norm takes its SLOT_CTAS CTAs per token (else the FP32 + sum of squares is added in another order and the norm may differ by an ulp).""" + from tensorrt_llm._torch.distributed.mnnvl_fused_allreduce import TWO_SHOT_ROWS, lib_norm_tree + from tensorrt_llm._torch.distributed.ops import _MNNVL_ONE_SHOT_THRESHOLD_BYTES as one_shot + + lib = "one-shot" if m * hidden * tp * 2 <= one_shot else "two-shot" + cute = "two-shot" if m >= TWO_SHOT_ROWS else "one-shot" + sms = torch.cuda.get_device_properties(torch.cuda.current_device()).multi_processor_count + same_tree = ( + cute == "two-shot" or lib_norm_tree(m, hidden, sms)[1] == MnnvlAllReduceNorm.SLOT_CTAS + ) + return lib, cute, same_tree + + +def _mnnvl(tp, hidden=H, max_num_tokens=max(ROWS)): rank = tensorrt_llm.mpi_rank() torch.cuda.set_device(rank) os.environ["TLLM_TEST_MNNVL"] = "1" MPI.COMM_WORLD.barrier() mapping = Mapping(world_size=tp, tp_size=tp, rank=rank) - ar = MNNVLAllReduce(mapping, torch.bfloat16, max_num_tokens=max(ROWS), hidden_size=hidden) + ar = MNNVLAllReduce(mapping, torch.bfloat16, max_num_tokens=max_num_tokens, hidden_size=hidden) assert MnnvlAllReduceNorm.is_supported(mapping, torch.bfloat16, hidden) assert ar.fused_norm is not None, "CuTe DSL kernels not built" return ar, rank @@ -121,6 +167,30 @@ def _norm_cases(tp): _check(norm, ref_norm, ("norm with fp8", m)) # E4M3 holds 3 mantissa bits: half an ulp is 6.25 % relative. _check(fp8.float() * scale, ref_norm.clamp(-448 * 0.05, 448 * 0.05), ("fp8", m), rtol=7e-2) + # Bit for bit the library op wherever it runs the arithmetic the kernels run for m rows. + # Elsewhere (the one-shot rows whose library norm takes fewer CTAs per token) the norm within an ulp. + lib, cute, same_tree = _library_arithmetic(m, tp) + ulps = 0 if same_tree else 1 + if lib == cute: + _assert_bitwise( + ar.fused_norm(residual, norm_weight, EPS, x=xs[rank]), + _library(ar, xs[rank], params), + ("library", lib, m), + ulps, + ) + fp8_params = AllReduceParams( + fusion_op=AllReduceFusionOp.RESIDUAL_RMS_NORM_OUT_QUANT_FP8, + residual=residual, + norm_weight=norm_weight, + eps=EPS, + scale=scale, + ) + _assert_bitwise( + ar.fused_norm(residual, norm_weight, EPS, x=xs[rank], scale=scale, norm_out=True), + _library(ar, xs[rank], fp8_params), + ("library fp8", lib, m), + ulps, + ) # Exercise two and 14 tokens per CTA, including a partially filled final CTA. From 15 tokens an SM holds # one of these CTAs instead of two, and the dispatch declines. wave = 2 * torch.cuda.get_device_properties(torch.cuda.current_device()).multi_processor_count @@ -194,6 +264,9 @@ def shared_memory_size( cutlass.Int64(0), cutlass.Int64(0), cutlass.Int32(0), + cutlass.Int64(0), # no L2 prefetch + cutlass.Int64(0), + cutlass.Int64(0), stream, ) store_size(output, cutlass.Int64(get_kernel_smem_size(kernel.kernel_mt))).launch( @@ -305,6 +378,58 @@ def _moe_fold_cases( _check(res, ref_res, ("finalized fold residual", m)) +def _moe_fold_lamport_cases(tp, top_k=10): + """fc2 rows in a Lamport FC2 buffer (0xFFFFFFFF where not written; MoEAllReduceParams.fc2_lamport): the fold + polls them instead of waiting, gives the plain fold's outputs bit for bit and writes the rows it read back to + 0xFFFFFFFF. Consecutive calls reuse the buffer, as consecutive MoE layers do.""" + ar, rank = _mnnvl(tp) + norm_weight = _rand((H,), 4, 0.1) + 1 + cap = 128 * top_k + 16 + buf = torch.full((cap, H), -1, dtype=torch.int16, device="cuda").view(torch.bfloat16) + for m in (1, 7, 32, 63, 64, 96, 128): + assert ar.supports_moe_fold(m, H), m + s = 2000 * m + 10 * rank + g = torch.Generator(device="cuda").manual_seed(s + 1) + perm = torch.randperm(m * top_k + 16, generator=g, device="cuda")[: m * top_k] + perm = perm.view(m, top_k).to(torch.int32) + rows = perm.flatten().long() + fc2 = _rand((m * top_k + 16, H), s) + topw = torch.softmax(_rand((m, top_k), s + 2, dtype=torch.float32), -1).to(torch.bfloat16) + shared = _rand((m, H), s + 3) + gate = _rand((m, 1), s + 4) + residual = _rand((m, H), 9 * m) + outs = [] + for lamport in (False, True): + src = fc2 + if lamport: + buf[rows] = fc2[rows] + src = buf + params = MoEAllReduceParams( + expanded_idx_to_permuted_idx=perm, + expert_scale_factor=topw, + shared_expert_output=shared, + shared_expert_gate=gate, + residual=residual, + norm_weight=norm_weight, + eps=EPS, + fusion_op=AllReduceFusionOp.RESIDUAL_RMS_NORM, + fc2_lamport=lamport, + ) + outs.append(ar(src, all_reduce_params=params)) + torch.cuda.synchronize() + for plain, polled, tag in zip(outs[0], outs[1], ("norm", "residual")): + assert torch.equal(plain.view(torch.int16), polled.view(torch.int16)), ( + "lamport", + tag, + m, + ) + assert bool((buf.view(torch.int32) == -1).all()), ("lamport rows not reset", m) + # A Lamport buffer needs the un-finalized fold; the call refuses before any launch. + for fold in (None, (shared, shared, gate)): + with pytest.raises(ValueError, match="un-finalized MoE fold"): + ar.fused_norm(residual, norm_weight, EPS, x=shared, moe_fold=fold, fc2_lamport=True) + + def _large_moe_fold_cases(tp: int) -> None: wave = 2 * torch.cuda.get_device_properties(torch.cuda.current_device()).multi_processor_count _moe_fold_cases(tp, hidden=8192, rows=(13 * wave + 1,), quantize=True) @@ -348,6 +473,309 @@ def _gemm_norm_cases(tp, k=1024): _check(res, ref_res, ("gemm residual", m, fp8_payload)) +def _gemm_twoshot_cases( + tp, k=1024, max_num_tokens=max(ROWS), rows=(9, 17, 33, 56, 64, 65, 96, 128), required=False +): + """The tcgen05 FP8 GEMM + two-shot all-reduce + norm launch (GemmTwoShotAllReduceNorm) over its rows, with and + without the FP8 output, and an E4M3 or BF16 input.""" + ar, rank = _mnnvl(tp, max_num_tokens=max_num_tokens) + assert ar.gemm_twoshot is not None, "GEMM + two-shot all-reduce + norm kernel not built" + norm_weight = _rand((H,), 5, 0.1) + 1 + weight_scale = torch.tensor([0.02], dtype=torch.float32, device="cuda") + input_scale = torch.tensor([4.0 / 448], dtype=torch.float32, device="cuda") + scale = torch.tensor([0.05], dtype=torch.float32, device="cuda") + probe = torch.empty((H, k), dtype=torch.float8_e4m3fn, device="cuda") + for m in rows: + if not ar.gemm_twoshot.takes(m, probe): + assert not required, ("GEMM + two-shot refused", m) + continue + outs, args = [], None + for r in range(tp): + x = _rand((m, k), 91 * m + r) + w = _rand((H, k), 6000 + r, 4.0).to(torch.float8_e4m3fn) + xq = (x.float() / input_scale).clamp(-448, 448).to(torch.float8_e4m3fn) + outs.append((xq.float() @ w.float().t()) * input_scale * weight_scale) + if r == rank: + args = (x, xq, w) + residual = _rand((m, H), 13 * m) + ref_norm, ref_res = _ref_norm(sum(outs), residual, norm_weight) + x, xq, w = args + for inp in (xq, x): + params = AllReduceParams( + fusion_op=AllReduceFusionOp.RESIDUAL_RMS_NORM, + residual=residual, + norm_weight=norm_weight, + eps=EPS, + ) + out = ar.gemm_twoshot_allreduce_norm(inp, w, weight_scale, input_scale, params) + assert out is not None, ("GEMM + two-shot declined", m, inp.dtype) + norm, res = out + _check(norm, ref_norm, ("gemm two-shot norm", m, inp.dtype)) + _check(res, ref_res, ("gemm two-shot residual", m, inp.dtype)) + # Bit for bit the unfused calls: the projection on cuBLAS (as FP8QDQLinearMethod.apply), then the library + # op, which runs two-shot at every row count the kernel takes. + # Looked up by name: cloudpickle pickles this module by value and cannot pickle the torch.ops module that an + # attribute access (or import) of ``ops`` here would make it carry along. + cublas_scaled_mm = operator.attrgetter("ops.trtllm.cublas_scaled_mm")(torch) + partial = cublas_scaled_mm( + xq, + w.t(), + scale_a=input_scale, + scale_b=weight_scale, + bias=None, + out_dtype=torch.bfloat16, + ) + assert _library_arithmetic(m, tp)[0] == "two-shot", m + _assert_bitwise( + ar.gemm_twoshot_allreduce_norm(xq, w, weight_scale, input_scale, params), + _library(ar, partial, params), + ("gemm two-shot vs cuBLAS + library", m), + ) + # The kernel exchanges BF16: an E4M3-payload call stays on the library two-shot. + params = AllReduceParams( + fusion_op=AllReduceFusionOp.RESIDUAL_RMS_NORM, + residual=residual, + norm_weight=norm_weight, + eps=EPS, + fp8_payload=True, + ) + assert ar.gemm_twoshot_allreduce_norm(xq, w, weight_scale, input_scale, params) is None, m + params = AllReduceParams( + fusion_op=AllReduceFusionOp.RESIDUAL_RMS_NORM_OUT_QUANT_FP8, + residual=residual, + norm_weight=norm_weight, + eps=EPS, + scale=scale, + ) + norm, fp8, res = ar.gemm_twoshot_allreduce_norm(xq, w, weight_scale, input_scale, params) + _check(norm, ref_norm, ("gemm two-shot norm with fp8", m)) + _check(fp8.float() * scale, ref_norm.clamp(-448 * 0.05, 448 * 0.05), ("fp8", m), rtol=7e-2) + + +def _gemm_twoshot_large_workspace_cases(tp, k=1024): + """The GEMM + two-shot launch on a Lamport buffer of 2 GiB (max_num_tokens 131072 at H 4096), whose size and + offsets the kernel must read as unsigned, over consecutive calls that cycle through all three buffers.""" + from tensorrt_llm._torch.distributed.ops import _MNNVL_ONE_SHOT_THRESHOLD_BYTES as one_shot + from tensorrt_llm._torch.kernels.blackwell import gemm_twoshot_allreduce_norm as kern + + sms = torch.cuda.get_device_properties(0).multi_processor_count + min_rows = one_shot // (H * tp * 2) + 1 + fits = [m for m in range(1, kern.MAX_ROWS + 1) if kern.supports_rows(m, H, tp, sms, min_rows)] + if not fits: # TP2: no row takes the kernel + return + rows = (fits[0], fits[len(fits) // 2], fits[-1]) + _gemm_twoshot_cases(tp, k, max_num_tokens=131072, rows=rows, required=True) + + +def _shifted(t, offset): + """A copy of contiguous ``t`` at ``offset`` bytes past a 128-byte boundary.""" + buf = torch.empty(t.numel() * t.element_size() + 128, dtype=torch.uint8, device="cuda") + assert buf.data_ptr() % 128 == 0 + view = buf[offset : offset + t.numel() * t.element_size()].view(t.dtype).view(t.shape) + view.copy_(t) + return view + + +def _gemm_twoshot_alignment_cases(tp, k=1024): + """The GEMM + two-shot launch takes an E4M3 x and W at any 16-byte aligned address (their TMA descriptors' + requirement) with the aligned call's outputs bit for bit, and declines (before any launch, on every rank) an x or + W that is not 16-byte aligned.""" + ar, rank = _mnnvl(tp) + assert ar.gemm_twoshot is not None, "GEMM + two-shot all-reduce + norm kernel not built" + probe = torch.empty((H, k), dtype=torch.float8_e4m3fn, device="cuda") + fits = [m for m in range(1, max(ROWS) + 1) if ar.gemm_twoshot.takes(m, probe)] + if not fits: # TP2: no row takes the kernel + return + m = fits[0] + norm_weight = _rand((H,), 5, 0.1) + 1 + weight_scale = torch.tensor([0.02], dtype=torch.float32, device="cuda") + input_scale = torch.tensor([4.0 / 448], dtype=torch.float32, device="cuda") + xq = (_rand((m, k), 91 * m + rank).float() / input_scale).clamp(-448, 448) + xq = xq.to(torch.float8_e4m3fn) + w = _rand((H, k), 6000 + rank, 4.0).to(torch.float8_e4m3fn) + residual = _rand((m, H), 13 * m) + params = AllReduceParams( + fusion_op=AllReduceFusionOp.RESIDUAL_RMS_NORM, + residual=residual, + norm_weight=norm_weight, + eps=EPS, + ) + ref = ar.gemm_twoshot_allreduce_norm(xq, w, weight_scale, input_scale, params) + assert ref is not None, m + for x_off, w_off in ((16, 0), (0, 16), (48, 80)): + got = ar.gemm_twoshot_allreduce_norm( + _shifted(xq, x_off), _shifted(w, w_off), weight_scale, input_scale, params + ) + assert got is not None, ("16-byte aligned operands declined", m, x_off, w_off) + _assert_bitwise(got, ref, ("16-byte aligned operands", x_off, w_off)) + for x_off, w_off in ((8, 0), (0, 8)): + x8, w8 = _shifted(xq, x_off), _shifted(w, w_off) + assert not ar.gemm_twoshot.supports(x8, w8), (x_off, w_off) + assert ar.gemm_twoshot_allreduce_norm(x8, w8, weight_scale, input_scale, params) is None + + +def test_gemm_twoshot_rows() -> None: + """The two-shot GEMM kernel takes a call from the library's first two-shot row count (one more than the one-shot + message size holds: 17 at TP8 / H 4096) and only where every owner item has a thread: all of its rows at TP8 / + TP16, fewer at TP4 / TP2 (a rank owns more slices).""" + from tensorrt_llm._torch.distributed.ops import _MNNVL_ONE_SHOT_THRESHOLD_BYTES as one_shot + from tensorrt_llm._torch.kernels.blackwell import gemm_twoshot_allreduce_norm as kern + + sms = torch.cuda.get_device_properties(0).multi_processor_count + min_rows = {tp: one_shot // (H * tp * 2) + 1 for tp in (2, 4, 8, 16)} + for tp, m in min_rows.items(): + assert (m - 1) * H * tp * 2 <= one_shot < m * H * tp * 2 + if one_shot == 64 * 1024 * 8 * 2: + assert min_rows == {2: 65, 4: 33, 8: 17, 16: 9} + fits = { + tp: [ + m + for m in range(1, kern.MAX_ROWS + 1) + if kern.supports_rows(m, H, tp, sms, min_rows[tp]) + ] + for tp in (2, 4, 8, 16) + } + for tp in (8, 16): + assert fits[tp] == [ + m for m in range(min_rows[tp], kern.MAX_ROWS + 1) if kern._replayable(m, H, sms) + ] + assert not fits[2] and all(m <= 64 for m in fits[4]) + assert not kern.supports_hidden(2 * H, 8, sms) + assert not kern.supports_hidden(H // 2, 8, sms) + + +def test_l2_prefetch_args() -> None: + """The L2 prefetch splits a weight into 16-byte multiple slices that cover it, and is off for a weight whose + address or size is not a 16-byte multiple.""" + from tensorrt_llm._torch.distributed.mnnvl_fused_allreduce import _l2pf_args + + weight = torch.empty((3 * 1024 + 8,), dtype=torch.bfloat16, device="cuda") + l2pf, ptr, nbytes, per = _l2pf_args(weight, 7) + assert l2pf and ptr == weight.data_ptr() and nbytes == weight.numel() * 2 + assert per % 16 == 0 and 7 * per >= nbytes > 6 * per + assert _l2pf_args(None, 7) == (False, 0, 0, 0) + assert _l2pf_args(weight, 0) == (False, 0, 0, 0) + assert _l2pf_args(weight[:9], 7) == (False, 0, 0, 0) + assert _l2pf_args(weight[1:9], 7) == (False, 0, 0, 0) + + +def test_slot_kernel_takes_every_supported_hidden_size() -> None: + """Every hidden size MnnvlAllReduceNorm.is_supported accepts builds the slot kernel at every row count it takes + (from TWO_SHOT_ROWS with the two-shot CTA split, which stays within 1024 threads per CTA as the library's), and + the others are rejected up front.""" + from tensorrt_llm._torch.distributed.mnnvl_fused_allreduce import ( + SLOT_MAX_ROWS, + TWO_SHOT_ROWS, + _ctas_per_token, + ) + from tensorrt_llm._torch.kernels.blackwell.mnnvl_slot_allreduce_norm import ( + MnnvlSlotAllReduceNormKernel, + ) + + mapping = Mapping(world_size=8, tp_size=8, rank=0) + sms = torch.cuda.get_device_properties(0).multi_processor_count + assert _ctas_per_token(SLOT_MAX_ROWS, 16384, sms) == 2 + assert not MnnvlAllReduceNorm.is_supported(mapping, torch.bfloat16, 6144) + for hidden in range(2048, 65536 + 1, 2048): + supported = MnnvlAllReduceNorm.is_supported(mapping, torch.bfloat16, hidden) + built = True + for m in range(1, SLOT_MAX_ROWS + 1): + ts = _ctas_per_token(m, hidden, sms) if m >= TWO_SHOT_ROWS else 0 + try: + kernel = MnnvlSlotAllReduceNormKernel( + hidden=hidden, + norm_eps=EPS, + nranks=8, + ctas=MnnvlAllReduceNorm.SLOT_CTAS, + use_pdl=True, + se_fold=False, + norm_out=True, + quant=False, + region_bytes=1, + ts_ctas=ts, + ) + except ValueError: + built = False + continue + # The launch reserves the kernel's shared memory: warp sums, the cluster sums (one per warp of the + # token with the two-shot arithmetic), flags and mbarrier; up to hidden 16384 they fit in the 512-byte + # floor smem_bytes keeps for the measured launches. + nsum = kernel.ctas * kernel.num_warps if ts else kernel.ctas + assert kernel.smem_bytes() >= 4 * (kernel.num_warps + nsum) + 32 + 8, (hidden, m) + assert hidden > 16384 or kernel.smem_bytes() == 512, (hidden, m) + warps = hidden // 2048 + assert supported == (warps & (warps - 1) == 0), hidden + assert not supported or built, hidden + + +def _tp2_cases(tp, max_tokens=4096): + """Tp2AllReduceNorm (TP2 without MNNVL, large messages): residual RMSNorm with and without the FP8 output, at + hidden sizes of 8 and 16 reference warps.""" + from tensorrt_llm._torch.distributed.tp2_allreduce import Tp2AllReduceNorm + + if tp != 2: + return + rank = tensorrt_llm.mpi_rank() + torch.cuda.set_device(rank) + mapping = Mapping(world_size=tp, tp_size=tp, rank=rank) + assert not Tp2AllReduceNorm.is_supported(mapping, H + 128, max_tokens) + assert not Tp2AllReduceNorm.is_supported(mapping, 4 * H, max_tokens) + for hidden in (H, H // 2): + _tp2_hidden_cases(tp, rank, mapping, hidden, max_tokens) + + +def _tp2_hidden_cases(tp, rank, mapping, hidden, max_tokens): + from tensorrt_llm._torch.distributed.ll_exchange import _PeerBuffers + from tensorrt_llm._torch.distributed.tp2_allreduce import Tp2AllReduceNorm + + assert Tp2AllReduceNorm.is_supported(mapping, hidden, max_tokens) + ar = Tp2AllReduceNorm(mapping, hidden, max_tokens) + # Peer memory without a multicast object (the kernel reads only the two unicast mappings): IPC inside a node. + assert isinstance(ar._bufs, _PeerBuffers) and ar._bufs.transport == "IPC" + norm_weight = _rand((hidden,), 6, 0.1) + 1 + scale = torch.tensor([0.05], dtype=torch.float32, device="cuda") + for m in (Tp2AllReduceNorm.MIN_TOKENS, 3001, max_tokens): + xs = [_rand((m, hidden), 300 * m + r) for r in range(tp)] + residual = _rand((m, hidden), 17 * m) + ref_norm, ref_res = _ref_norm(sum(x.float() for x in xs), residual, norm_weight) + op = AllReduceFusionOp.RESIDUAL_RMS_NORM + assert ar.supports(xs[rank], op, residual, norm_weight) + assert not ar.supports(xs[rank], op, residual.float(), norm_weight) + assert not ar.supports(xs[rank], op, residual[:-1], norm_weight) + assert not ar.supports(xs[rank], op, residual, norm_weight.float()) + norm, res = ar( + xs[rank], residual, norm_weight, EPS, AllReduceFusionOp.RESIDUAL_RMS_NORM, None + ) + _check(norm, ref_norm, ("tp2 norm", m)) + _check(res, ref_res, ("tp2 residual", m)) + fp8, res = ar( + xs[rank], + residual, + norm_weight, + EPS, + AllReduceFusionOp.RESIDUAL_RMS_NORM_QUANT_FP8, + scale, + ) + _check( + fp8.float() * scale, ref_norm.clamp(-448 * 0.05, 448 * 0.05), ("tp2 fp8", m), rtol=7e-2 + ) + _check(res, ref_res, ("tp2 fp8 residual", m)) + # The table, dummy-scale and norm-weight views are built once and reused by every later call; another + # layer's norm weight gets its own view. + assert len(ar._norm_weight_views) == 1 + other_weight = _rand((hidden,), 7, 0.1) + 1 + m = Tp2AllReduceNorm.MIN_TOKENS + xs = [_rand((m, hidden), 11 + r) for r in range(tp)] + residual = _rand((m, hidden), 13) + ref_norm, ref_res = _ref_norm(sum(x.float() for x in xs), residual, other_weight) + norm, res = ar(xs[rank], residual, other_weight, EPS, AllReduceFusionOp.RESIDUAL_RMS_NORM, None) + _check(norm, ref_norm, ("tp2 norm, second weight", m)) + _check(res, ref_res, ("tp2 residual, second weight", m)) + assert len(ar._norm_weight_views) == 2 + big = _rand((max_tokens + 1, hidden), 1) + assert not ar.supports(big, AllReduceFusionOp.RESIDUAL_RMS_NORM, big, norm_weight) + + def _meta_init_cases(tp): """Kernels built under MetaInitMode, as the model loader builds the model, hold no meta tensor and run.""" from tensorrt_llm._torch.distributed.mnnvl_fused_allreduce import ( @@ -398,8 +826,13 @@ def _opt_in_cases(tp): "norm": _norm_cases, "large_hidden_norm": _large_hidden_norm_cases, "moe_fold": _moe_fold_cases, + "moe_fold_lamport": _moe_fold_lamport_cases, "large_moe_fold": _large_moe_fold_cases, "gemm_norm": _gemm_norm_cases, + "gemm_twoshot": _gemm_twoshot_cases, + "gemm_twoshot_large_workspace": _gemm_twoshot_large_workspace_cases, + "gemm_twoshot_alignment": _gemm_twoshot_alignment_cases, + "tp2": _tp2_cases, "meta_init": _meta_init_cases, "opt_in": _opt_in_cases, } @@ -413,3 +846,47 @@ def test_mnnvl_fused_allreduce_norm(case, mpi_pool_executor): pytest.skip(f"needs {tp} GPUs") results = mpi_pool_executor.map(_worker, [CASES[case]] * tp, [tp] * tp) assert all(results) + + +def _tp2_setup_failure(tp, error_type=RuntimeError): + """A failure past the peer buffers' collective setup on one rank (the pointer-table init is not collective) fails + Tp2AllReduceNorm's construction on every rank with RuntimeError, naming the failed rank's cause, whatever + ``error_type`` that rank raised. Returns this rank's outcome as text (exceptions stay in the worker).""" + from tensorrt_llm._torch.distributed.ll_exchange import _PeerBuffers + from tensorrt_llm._torch.distributed.tp2_allreduce import Tp2AllReduceNorm + + rank = tensorrt_llm.mpi_rank() + torch.cuda.set_device(rank) + mapping = Mapping(world_size=tp, tp_size=tp, rank=rank) + real = _PeerBuffers.__dict__["create"] + + @classmethod + def create(cls, *args, **kwargs): + bufs = real.__func__(cls, *args, **kwargs) + if rank == 1: + raise error_type("injected pointer-table failure") + return bufs + + _PeerBuffers.create = create + try: + Tp2AllReduceNorm(mapping, H, 4096) + outcome = "constructed" + except RuntimeError as e: + outcome = str(e) + except BaseException as e: # noqa: BLE001 - reported to the parent as text + outcome = f"unexpected {type(e).__name__}: {e}" + finally: + _PeerBuffers.create = real + MPI.COMM_WORLD.barrier() + return outcome + + +@pytest.mark.timeout(300) +# MemoryError: a failure other than RuntimeError (e.g. a host allocation) must not leave the peer waiting. +@pytest.mark.parametrize("error_type", [RuntimeError, MemoryError]) +@pytest.mark.parametrize("mpi_pool_executor", [2], indirect=True) +def test_tp2_setup_failure_on_one_rank(mpi_pool_executor, error_type): + if torch.cuda.device_count() < 2: + pytest.skip("needs 2 GPUs") + outcomes = list(mpi_pool_executor.map(_tp2_setup_failure, [2] * 2, [error_type] * 2)) + assert all("rank 1: injected pointer-table failure" in o for o in outcomes), outcomes diff --git a/tests/unittest/_torch/pyexecutor/engine/runners/decoder/test_graphs.py b/tests/unittest/_torch/pyexecutor/engine/runners/decoder/test_graphs.py index d3dc2aed46e7..41f0d71cbe82 100644 --- a/tests/unittest/_torch/pyexecutor/engine/runners/decoder/test_graphs.py +++ b/tests/unittest/_torch/pyexecutor/engine/runners/decoder/test_graphs.py @@ -583,3 +583,74 @@ def test_prefill_capture_skips_break_graphs_without_graphable_breaks( # Bucket 128 exceeds max_num_tokens // 4, so only bucket 16 is a candidate. captured = [c.args[1] for c in capture_break_graphs.call_args_list] assert captured == ([16] if graphable_breaks else []) + + +class _SplitMetadata: + """resolve_mamba_metadata_cls stand-in: records whether a warmup forward ran under the split knob.""" + + splitting = False + + @classmethod + @contextlib.contextmanager + def inforward_split_for_warmup(cls) -> Iterator[None]: + cls.splitting = True + try: + yield + finally: + cls.splitting = False + + +def _split_warmup_graphs(plans_splits: bool, max_num_tokens: int = 258): + from tensorrt_llm._torch.pyexecutor.kv_cache.kv_cache_manager_v2 import KVCacheManagerV2 + from tensorrt_llm._torch.pyexecutor.resource_manager import ResourceManagerType + + kv = Mock(spec=KVCacheManagerV2) + kv.inforward_snapshot_rows = 2 if plans_splits else 0 + kv.inforward_snapshot_min_main, kv.inforward_snapshot_max_tail = 3, 64 + dummy_requests = MagicMock() + batch = object() + dummy_requests.create_warmup_request.return_value = batch + dummy_requests.release_batch_context.return_value.__enter__.return_value = batch + forwards = [] + graphs = decoder_graphs( + decoder_config(max_num_tokens=max_num_tokens), + cuda_graph_runner=MagicMock(enabled=False, is_warmup_only=False), + dummy_requests=dummy_requests, + forward_warmup=lambda b, rm, **kw: forwards.append((b, _SplitMetadata.splitting)), + ) + return graphs, ResourceManager({ResourceManagerType.KV_CACHE_MANAGER: kv}), forwards + + +@pytest.mark.cpu_only +@pytest.mark.parametrize("plans_splits", [False, True]) +def test_split_kernels_warm_up_without_prefill_graphs(plans_splits): + """With the prefill CUDA graphs off (the default), no break-graph capture runs a snapshot split: the warmup runs + one eager context request under the split knob, so the split's kernels compile before serving; once.""" + graphs, resource_manager, forwards = _split_warmup_graphs(plans_splits) + with ( + patch( + "tensorrt_llm._torch.pyexecutor.engine.runners.decoder.graphs.resolve_mamba_metadata_cls", + return_value=_SplitMetadata, + ), + patch("torch.cuda.synchronize"), + patch.object(graphs, "run_cuda_graph_warmup"), + ): + graphs.warmup_and_capture(resource_manager) + graphs.warmup_and_capture(resource_manager) + assert len(forwards) == (1 if plans_splits else 0) + if plans_splits: + assert forwards[0][1], "the warmup forward must plan a split" + kwargs = graphs._dummy_requests.create_warmup_request.call_args + assert kwargs.args[1:] == (3 + 64, 0) and kwargs.kwargs == {"num_context_requests": 1} + + +@pytest.mark.cpu_only +def test_split_warmup_skipped_after_break_graph_capture_or_without_room(): + """A break-graph capture that ran the split variant already compiled the kernels; a token budget below the + shortest split request cannot plan one.""" + graphs, resource_manager, forwards = _split_warmup_graphs(True) + graphs._inforward_split_warmed = True + graphs._warm_inforward_split(resource_manager) + graphs, resource_manager, forwards_small = _split_warmup_graphs(True, max_num_tokens=32) + graphs._warm_inforward_split(resource_manager) + assert forwards == [] and forwards_small == [] diff --git a/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_budget_split.py b/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_budget_split.py index 100f2a432a0f..ac74b005fb41 100644 --- a/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_budget_split.py +++ b/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_budget_split.py @@ -20,6 +20,7 @@ import numpy as np import pytest +import torch from tensorrt_llm._torch.pyexecutor._util import ( _STANDALONE_DRAFT_TOKENS_PER_BLOCK, @@ -35,6 +36,7 @@ Eagle3DecodingConfig, KvCacheConfig, MTPDecodingConfig, + RemoteCacheConfig, ) from tensorrt_llm.mapping import CpType, Mapping @@ -1111,6 +1113,322 @@ def test_estimation_managers_drop_explicit_offload_tiers(self, budget_attr, tmp_ assert getattr(target_config, budget_attr) is None assert getattr(draft_config, budget_attr) is None + @pytest.mark.parametrize("estimating_kv_cache", [False, True]) + def test_only_final_managers_get_the_remote_config( + self, estimating_kv_cache, tmp_path, monkeypatch + ): + """A probe neither claims remote memory nor donates. The final draft manager gets the config for its host + tier sizing only (TestRemoteLevelOwnership).""" + from tensorrt_llm._torch.pyexecutor.kv_cache import remote_donor + + monkeypatch.setattr(remote_donor, "start_donation", Mock()) + monkeypatch.setattr(torch.cuda, "current_device", lambda: 0) + c = self._make_build_creator(20 * GB, total_gpu=10 * GB, disk_path=str(tmp_path)) + c._kv_cache_config = KvCacheConfig( + max_gpu_total_bytes=10 * GB, + host_cache_size=20 * GB, + remote_cache_config={ + "directory": str(tmp_path), + "level": {"size": 4 * GB}, + "donor": {"size": 4 * GB}, + }, + ) + + c.build_managers({}, estimating_kv_cache=estimating_kv_cache) + + for config in self._configs_passed_to_managers(c): + assert (config.remote_cache_config is None) == estimating_kv_cache + + def _gen_style_donation(self, tmp_path, monkeypatch): + """A donation-only (GEN-style) creator whose donation start and manager constructions are recorded in order.""" + from tensorrt_llm._torch.pyexecutor.kv_cache import remote_donor + + events = [] + donor = Mock() + monkeypatch.setattr( + remote_donor, + "start_donation", + lambda config, device: events.append("donation") or donor, + ) + monkeypatch.setattr(torch.cuda, "current_device", lambda: 0) + c = self._make_build_creator(20 * GB, total_gpu=10 * GB, disk_path=str(tmp_path)) + c._kv_cache_config = KvCacheConfig( + max_gpu_total_bytes=10 * GB, + host_cache_size=0, + remote_cache_config={"directory": str(tmp_path), "donor": {"size": 4 * GB}}, + ) + c._create_kv_cache_manager.side_effect = lambda *args, **kwargs: ( + events.append(("target", kwargs["remote_donor"])) or Mock() + ) + return c, donor, events + + def test_donation_starts_before_the_estimation_and_moves_to_the_final_manager( + self, tmp_path, monkeypatch + ): + """Clients wait for donors, so the donation must not wait for the estimation's warmup. + + It starts before the estimation probe exists, survives the probe's teardown and goes to the final target + manager, which owns it from then on: one donation per rank, never closed in between.""" + c, donor, events = self._gen_style_donation(tmp_path, monkeypatch) + resources = {} + + c.build_managers(resources, estimating_kv_cache=True) + assert events == ["donation", ("target", None)] + c.teardown_managers(resources) + c.build_managers(resources, estimating_kv_cache=False) + + assert events == ["donation", ("target", None), ("target", donor)] + # The draft only waits for the target's donation (TestRemoteLevelOwnership); the target owns it. + assert c._create_one_model_draft_kv_cache_manager.call_args.kwargs["remote_donor"] is donor + assert c._remote_donor is None + c.close_remote_donor() + donor.close.assert_not_called() + + def test_a_failed_draft_build_shuts_the_target_down(self, tmp_path, monkeypatch): + """Nothing holds the target manager until build_managers returns, so its donation would leak.""" + c, donor, _ = self._gen_style_donation(tmp_path, monkeypatch) + targets = [] + c._create_kv_cache_manager.side_effect = lambda *args, **kwargs: ( + targets.append(Mock()) or targets[-1] + ) + c._create_one_model_draft_kv_cache_manager.side_effect = RuntimeError("draft OOM") + resources = {} + + with pytest.raises(RuntimeError, match="draft OOM"): + c.build_managers(resources, estimating_kv_cache=False) + + targets[-1].shutdown.assert_called_once_with() + assert resources == {} + + @staticmethod + def _published_donor(directory: str): + """A real donation published in `directory` by a transport that allocates nothing.""" + from tensorrt_llm._torch.pyexecutor.kv_cache import remote_donor + + class PublishingTransport(remote_donor.DonorTransport): + kind = "test" + + def start(self, donor): + donor._publish([], ["segment 0 1"], "test") + + donor = remote_donor.RemoteMemDonor( + directory, 1 << 30, PublishingTransport(), chunk_bytes=1 << 30 + ) + donor.start() + return donor + + @staticmethod + def _target_owning(donor): + """A final target manager that owns `donor`, with the real shutdown().""" + target = KVCacheManagerV2.__new__(KVCacheManagerV2) + target._remote_donor = donor + target._shutdown_caches = Mock() + target.event_manager = None + return target + + @pytest.mark.parametrize("estimation", [True, False], ids=["estimation", "no_estimation"]) + def test_a_failed_draft_build_marks_the_targets_donation( + self, estimation, tmp_path, monkeypatch + ): + """Peers waiting for expected_num_donors stop at the failure marker; an unmarked withdrawal makes them wait the + full donor_wait_timeout_s. Without the estimation the target starts the donation itself.""" + from tensorrt_llm._torch.pyexecutor.kv_cache import remote_donor + + directory = str(tmp_path / "rendezvous") + remote_donor.ensure_rendezvous_directory(directory) + early = self._published_donor(directory) if estimation else None + monkeypatch.setattr(remote_donor, "start_donation", lambda config, device: early) + monkeypatch.setattr(torch.cuda, "current_device", lambda: 0) + c = self._make_build_creator(20 * GB, total_gpu=10 * GB, disk_path=str(tmp_path)) + c._skip_est = not estimation + c.configure_kv_cache_capacity = Mock() + c._kv_cache_config = KvCacheConfig( + max_gpu_total_bytes=10 * GB, + host_cache_size=0, + remote_cache_config={"directory": directory, "donor": {"size": 1 << 30}}, + ) + c._create_kv_cache_manager.side_effect = lambda estimating, **kwargs: ( + Mock() + if estimating + else self._target_owning(kwargs["remote_donor"] or self._published_donor(directory)) + ) + resources = {} + if estimation: + c.build_managers(resources, estimating_kv_cache=True) + resources.clear() # the probe's teardown + c._create_one_model_draft_kv_cache_manager.side_effect = RuntimeError("draft OOM") + + with pytest.raises(RuntimeError, match="draft OOM"): + c.build_managers(resources, estimating_kv_cache=False) + + published, failed = remote_donor.scan_donors(directory) + assert published == [] + assert len(failed) == 1 and "draft OOM" in failed[0]["error"] + c.close_remote_donor( + RuntimeError("creator cleanup") + ) # the creator's failure path marks nothing twice + assert len(remote_donor.scan_donors(directory)[1]) == 1 + assert "draft OOM" in remote_donor.scan_donors(directory)[1][0]["error"] + + def test_without_estimation_the_draft_waits_for_the_targets_own_donation( + self, tmp_path, monkeypatch + ): + """Skipping the estimation (TRTLLM_SKIP_KV_CACHE_ESTIMATION, sparse-offload decode workers), the target starts + the donation itself; a separate draft that does not get it charges the donation a second time.""" + c, _, _ = self._gen_style_donation(tmp_path, monkeypatch) + c._skip_est = True + c.configure_kv_cache_capacity = Mock() + own = Mock() + c._create_kv_cache_manager.side_effect = lambda *args, **kwargs: SimpleNamespace( + remote_donor=own + ) + + c.build_managers({}, estimating_kv_cache=False) + + assert c._create_one_model_draft_kv_cache_manager.call_args.kwargs["remote_donor"] is own + error = RuntimeError("rebind failed") + c.close_remote_donor(error) # a later startup failure still marks it + own.close.assert_called_once_with(error) + + def test_the_cross_manager_waits_for_the_targets_donation(self, tmp_path): + """Without the estimation (always for encoder-decoder) the target starts its donation in the background. The + cross manager sizes its automatic host tier from free host memory, so it waits for the donation first.""" + c = self._make_build_creator(20 * GB, total_gpu=10 * GB, disk_path=str(tmp_path)) + events = [] + donor = Mock() + donor.wait_started.side_effect = lambda: events.append("donation placed") + c._create_cross_kv_cache_manager = Mock( + side_effect=lambda *args, **kwargs: events.append("cross manager") or Mock() + ) + config = KvCacheConfig(max_gpu_total_bytes=10 * GB) + + c._build_secondary_managers(False, 1024, False, config, None, config, None, donor) + + assert events == ["donation placed", "cross manager"] + donor.close.assert_not_called() # the target owns it + + def test_cross_manager_neither_claims_nor_donates(self, tmp_path): + """The self-attention manager owns the rank's remote level and donation; a cross manager with the config would + donate and claim a second time.""" + c = self._make_build_creator(20 * GB, total_gpu=10 * GB, disk_path=str(tmp_path)) + c._kv_cache_config = KvCacheConfig( + max_gpu_total_bytes=10 * GB, + cross_kv_cache_fraction=0.5, + remote_cache_config={ + "directory": str(tmp_path), + "level": {"size": 4 * GB}, + "donor": {"size": 4 * GB}, + }, + ) + self_config, cross_config = c._split_kv_cache_budget_for_cross() + assert self_config.remote_cache_config is not None + assert cross_config.remote_cache_config is None + + def test_donation_is_placed_before_the_estimation_takes_host_memory( + self, tmp_path, monkeypatch + ): + """A GEN node of two 176 GiB fabric donates (xb2): the second one fits at the default 24 GiB reserve only + before the estimation takes 44 GiB of the node's host memory; started after it, it is 44 GiB short.""" + import contextlib + + from tensorrt_llm._torch.pyexecutor.kv_cache import host_memory, remote_donor + + node_gib = 176.0 + 176.0 + 24.0 + room = {0: node_gib - 176.0} # the co-located rank's donation is placed already + + def place(n_chunks): + def create(node): + room[node] -= 1.0 + return object() + + handles, _ = host_memory.place_chunks( + n_chunks, + [0], + create, + chunk_gib=1.0, + reserve_gib=24.0, + node_lock=lambda node: contextlib.nullcontext(True), + meminfo=lambda node: {"MemFree": room[node]}, + compact=Mock(), + contiguous=lambda node: 0.0, + sleep=lambda seconds: None, + clock=lambda: 0.0, + ) + return len(handles) + + placed = [] + monkeypatch.setattr( + remote_donor, + "start_donation", + lambda config, device: placed.append(place(176)) or Mock(), + ) + monkeypatch.setattr(torch.cuda, "current_device", lambda: 0) + c = self._make_build_creator(20 * GB, total_gpu=10 * GB, disk_path=str(tmp_path)) + c._kv_cache_config = KvCacheConfig( + max_gpu_total_bytes=10 * GB, + host_cache_size=0, + remote_cache_config={"directory": str(tmp_path), "donor": {"size": 176 * GB}}, + ) + + def manager(*args, **kwargs): + if args[0]: # the estimation probe and its warmup + room[0] -= 44.0 + return Mock() + + c._create_kv_cache_manager.side_effect = manager + resources = {} + c.build_managers(resources, estimating_kv_cache=True) + c.teardown_managers(resources) + c.build_managers(resources, estimating_kv_cache=False) + + assert placed == [176] + # The same donation placed after the estimation comes up 44 GiB short. + room[0] = node_gib - 176.0 - 44.0 + assert place(176) == 132 + + def test_donation_no_manager_took_over_is_closed(self, tmp_path, monkeypatch): + c, donor, _ = self._gen_style_donation(tmp_path, monkeypatch) + c.build_managers({}, estimating_kv_cache=True) + + error = RuntimeError("warmup failed") + c.close_remote_donor(error) + + donor.close.assert_called_once_with(error) + assert c._remote_donor is None + + def test_the_estimation_probe_waits_for_the_donation_to_be_placed(self, tmp_path, monkeypatch): + """The donation starts on a thread; the probe and its warmup take host memory only once it is placed.""" + c, donor, events = self._gen_style_donation(tmp_path, monkeypatch) + donor.wait_started.side_effect = lambda: events.append("placed") + + c.build_managers({}, estimating_kv_cache=True) + + assert events == ["donation", "placed", ("target", None)] + + def test_a_failure_after_the_hand_over_still_marks_the_donation(self, tmp_path, monkeypatch): + """Once the final target manager owns the donation, a later startup failure (rebind_resources) still leaves its + failure marker: the manager's shutdown alone would withdraw it unmarked.""" + c, donor, _ = self._gen_style_donation(tmp_path, monkeypatch) + resources = {} + c.build_managers(resources, estimating_kv_cache=True) + c.teardown_managers(resources) + c.build_managers(resources, estimating_kv_cache=False) + assert c._remote_donor is None + + error = RuntimeError("rebind failed") + c.close_remote_donor(error) + + donor.close.assert_called_once_with(error) + c.close_remote_donor(error) # once only + donor.close.assert_called_once_with(error) + + def test_without_estimation_the_manager_starts_the_donation(self, tmp_path, monkeypatch): + c, _, events = self._gen_style_donation(tmp_path, monkeypatch) + + c.build_managers({}, estimating_kv_cache=False) + + assert events == [("target", None)] + def test_gpu_budget_split_stays_skipped_during_estimation(self, tmp_path): """Estimation sizes GPU pools from max_tokens, so it keeps the budget whole.""" c = self._make_build_creator(20 * GB, total_gpu=10 * GB, disk_path=str(tmp_path)) @@ -1122,6 +1440,77 @@ def test_gpu_budget_split_stays_skipped_during_estimation(self, tmp_path): c._needs_gpu_kv_cache_budget_split.assert_not_called() +class TestRemoteLevelOwnership: + """One claim and one donation per rank: the target manager makes both, a separate draft manager neither. + + A draft that claimed too would take a second ``cache_size`` from donors sized for one per rank. + """ + + @staticmethod + def _add_remote_level(is_draft, tmp_path, monkeypatch, transport="nixl"): + from tensorrt_llm._torch.pyexecutor.kv_cache import kv_cache_manager_v2, remote_donor + + transport_cls = Mock(options_from=remote_donor.DONOR_TRANSPORTS[transport].options_from) + monkeypatch.setitem(remote_donor.DONOR_TRANSPORTS, transport, transport_cls) + donor_cls = Mock() + donor_cls.transport_cls = transport_cls + monkeypatch.setattr(remote_donor, "RemoteMemDonor", donor_cls) + monkeypatch.setattr(kv_cache_manager_v2, "RemoteCacheTierConfig", Mock()) + monkeypatch.setattr(kv_cache_manager_v2.torch.cuda, "current_device", lambda: 0) + manager = SimpleNamespace(is_draft=is_draft, _remote_donor=None) + config = RemoteCacheConfig( + directory=str(tmp_path), + level={"size": 4 * GB}, + donor={"size": 4 * GB}, + transport={"kind": transport}, + ) + tiers = [] + KVCacheManagerV2._add_remote_level(manager, config, tiers) + return manager, tiers, donor_cls + + def test_target_claims_and_donates(self, tmp_path, monkeypatch): + manager, tiers, donor_cls = self._add_remote_level(False, tmp_path, monkeypatch) + assert len(tiers) == 1 + donor_cls.assert_called_once() + manager._remote_donor.start_in_background.assert_called_once_with() + + @pytest.mark.parametrize( + "transport, options", + [ + ("nixl", {"ucx_devices": None}), + ("fabric", {"reserve_bytes": 24 * GB, "compact_host_memory": False}), + ], + ) + def test_each_donor_gets_its_transport_options(self, transport, options, tmp_path, monkeypatch): + _, _, donor_cls = self._add_remote_level(False, tmp_path, monkeypatch, transport) + # The transport is made from its own options, apart from the donation it reaches. + donor_cls.transport_cls.assert_called_once_with(**options) + assert donor_cls.call_args.args[2] is donor_cls.transport_cls.return_value + + def test_target_takes_over_a_donation_started_before_it(self, tmp_path, monkeypatch): + from tensorrt_llm._torch.pyexecutor.kv_cache import kv_cache_manager_v2, remote_donor + + start_donation = Mock() + monkeypatch.setattr(remote_donor, "start_donation", start_donation) + monkeypatch.setattr(kv_cache_manager_v2, "RemoteCacheTierConfig", Mock()) + early = Mock() + manager = SimpleNamespace(is_draft=False, _remote_donor=early) + config = RemoteCacheConfig( + directory=str(tmp_path), level={"size": 4 * GB}, donor={"size": 4 * GB} + ) + tiers = [] + KVCacheManagerV2._add_remote_level(manager, config, tiers) + start_donation.assert_not_called() + assert manager._remote_donor is early + assert len(tiers) == 1 + + def test_draft_neither_claims_nor_donates(self, tmp_path, monkeypatch): + manager, tiers, donor_cls = self._add_remote_level(True, tmp_path, monkeypatch) + assert tiers == [] + donor_cls.assert_not_called() + assert manager._remote_donor is None + + class TestExternalDrafterKvDtype: """The draft budget must be charged at the dtype the draft pool is ALLOCATED in. diff --git a/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_compression_manager.py b/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_compression_manager.py index 086cd5a52da9..b5b6dc798b87 100644 --- a/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_compression_manager.py +++ b/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_compression_manager.py @@ -384,7 +384,9 @@ def test_estimation_still_creates_triattention_manager(self) -> None: creator = object.__new__(util_mod.KvCacheCreator) creator._skip_est = False creator._max_seq_len = 1024 - creator._kv_cache_config = SimpleNamespace(host_cache_size=None, disk_cache_size=None) + creator._kv_cache_config = SimpleNamespace( + host_cache_size=None, disk_cache_size=None, remote_cache_config=None + ) creator._llm_args = SimpleNamespace(kv_cache_compression_config=config) creator._model_engine = _factory_model_engine(pretrained_config=pretrained_config) creator._is_encoder_decoder = MagicMock(return_value=False) diff --git a/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_estimation.py b/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_estimation.py index d4e597043c2a..bee460345993 100644 --- a/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_estimation.py +++ b/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_estimation.py @@ -2347,3 +2347,60 @@ def test_profiling_failure_releases_resources_and_restores_response_state(): warmup_scope.__exit__.assert_called_once() assert executor.enable_iter_perf_stats is True assert executor.set_gather_responses.call_args.args == (False,) + + +def _make_v2_field_creator( + manager_cls, kv_cache_config, *, disable_overlap_scheduler=False, pp_size=1 +): + model_engine = Mock() + model_engine.model.model_config.attn_backend = "TRTLLM" + llm_args = Mock( + cache_transceiver_config=None, disable_overlap_scheduler=disable_overlap_scheduler + ) + with patch.object(KvCacheCreator, "_get_model_kv_cache_manager_cls", return_value=manager_cls): + return KvCacheCreator( + model_engine=model_engine, + mapping=Mapping(world_size=pp_size, pp_size=pp_size), + net_max_seq_len=128, + kv_connector_manager=None, + max_num_tokens=128, + max_beam_width=1, + tokens_per_block=32, + max_seq_len=128, + max_batch_size=1, + kv_cache_config=kv_cache_config, + llm_args=llm_args, + speculative_config=None, + sparse_attention_config=None, + profiling_stage_data=None, + is_disagg=True, + ) + + +@pytest.mark.parametrize( + "field", + [ + {"remote_cache_config": {"directory": "/shared/dir", "donor": {"size": 1 << 30}}}, + {"defer_generation_only_release": True}, + ], +) +def test_v2_only_kv_cache_fields_reject_a_v1_manager(field) -> None: + """use_kv_cache_manager_v2='auto' may resolve to V1, which would silently ignore these fields.""" + kv_cache_config = KvCacheConfig(**field) + with pytest.raises(ValueError, match="requires KVCacheManagerV2"): + _make_v2_field_creator(KVCacheManager, kv_cache_config) + _make_v2_field_creator(KVCacheManagerV2, kv_cache_config) + + +@pytest.mark.parametrize("disable_overlap_scheduler, pp_size", [(True, 1), (False, 2)]) +def test_deferred_release_rejects_a_loop_that_ignores_it( + disable_overlap_scheduler, pp_size +) -> None: + kv_cache_config = KvCacheConfig(defer_generation_only_release=True) + with pytest.raises(ValueError, match="overlap scheduler"): + _make_v2_field_creator( + KVCacheManagerV2, + kv_cache_config, + disable_overlap_scheduler=disable_overlap_scheduler, + pp_size=pp_size, + ) diff --git a/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_manager_v2_helix_superblock.py b/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_manager_v2_helix_superblock.py index f40d6d0cc48e..d5273430b0a8 100644 --- a/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_manager_v2_helix_superblock.py +++ b/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_manager_v2_helix_superblock.py @@ -24,6 +24,7 @@ import math import types +from collections import deque from types import SimpleNamespace from typing import Optional @@ -445,13 +446,16 @@ def _failing_gen_scheduler( try_allocate_generation=lambda req: False, is_request_active=lambda request_id: True, has_cache_tier_below_gpu=has_cache_tier_below_gpu, + flush_deferred_closes=lambda: False, ), draft_kv_cache_manager=None, enable_joint_kv_cache_reuse=False, + _joint_draft_manager=None, ) sched._try_allocate_generation = types.MethodType( KVCacheV2Scheduler._try_allocate_generation, sched ) + sched._admit_unpaired_draft = types.MethodType(KVCacheV2Scheduler._admit_unpaired_draft, sched) sched._try_evict_for_gen = lambda req, requests_list, req_it, req_it_end, *args: ( ladder_calls.append("evict") or (req_it_end, False) ) @@ -515,6 +519,37 @@ def test_scheduler_allocation_failure_raises_under_disagg_helix( assert ladder_calls == [] +@pytest.mark.parametrize("fits_after_close", [True, False], ids=["fits", "still_short"]) +def test_disagg_helix_allocation_failure_closes_deferred_releases_first( + fits_after_close: bool, +) -> None: + """A finished generation-only request whose close is deferred + (defer_generation_only_release) still holds its pages. A disaggregated + helix generation server, which cannot preempt, closes it and retries before + raising.""" + from tensorrt_llm._torch.pyexecutor.scheduler.scheduler_v2 import ScheduleAction + + ladder_calls = [] + sched = _failing_gen_scheduler(enable_recompute_pause=False, ladder_calls=ladder_calls) + closed = [] + mgr = sched.kv_cache_manager + mgr._deferred_closes = deque([(9, SimpleNamespace(close=lambda: closed.append(9)))]) + mgr._sharing = None + mgr.impl = SimpleNamespace(clear_stats_excluded=lambda request_id: None) + mgr.flush_deferred_closes = types.MethodType(KVCacheManagerV2.flush_deferred_closes, mgr) + mgr.try_allocate_generation = lambda req: fits_after_close and bool(closed) + + if fits_after_close: + action, tokens, *_ = _schedule_failing_gen(sched, _gen_request()) + assert action is ScheduleAction.SCHEDULED and tokens == 1 + else: + with pytest.raises(RuntimeError, match="cannot preempt"): + _schedule_failing_gen(sched, _gen_request()) + assert closed == [9] + assert not mgr._deferred_closes + assert ladder_calls == [] + + def test_scheduler_allocation_failure_preempts_under_agg_helix() -> None: """Aggregated helix can replay a prefill, and without a tier below GPU suspending frees nothing, so a generation allocation failure goes diff --git a/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_capacity_only.py b/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_capacity_only.py index cadb41077086..0812756bfd1b 100644 --- a/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_capacity_only.py +++ b/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_capacity_only.py @@ -85,6 +85,8 @@ class StopInitialization(RuntimeError): pass class StopAfterPolicyConfig: + remote_cache_config = None + @property def enable_swa_scratch_reuse(self): raise StopInitialization diff --git a/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_scheduler.py b/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_scheduler.py index bfcca11e3a42..f68633dc0550 100644 --- a/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_scheduler.py +++ b/tests/unittest/_torch/pyexecutor/kv_cache/test_kv_cache_v2_scheduler.py @@ -18,8 +18,9 @@ No GPU required. """ +from collections import deque from types import SimpleNamespace -from unittest.mock import Mock, call, patch +from unittest.mock import Mock, PropertyMock, call, patch import pytest @@ -39,10 +40,174 @@ ContextChunkingPolicy, ContextSchedulingPolicy, ) +from tensorrt_llm.runtime.kv_cache_manager_v2 import RemoteMemError pytestmark = pytest.mark.cpu_only +def _manager_for_release(request_id: int, is_draft: bool = False): + """A manager whose `free_resources` runs for real on one mock KvCache.""" + manager = object.__new__(KVCacheManagerV2) + cache = Mock(beam_width=1) + manager.kv_cache_map = {request_id: cache} + manager.impl = Mock() + manager.index_mapper = Mock() + manager.num_pools = 1 + manager.sparse_metadata_batch = None + manager.is_draft = is_draft + manager.kv_connector_manager = None + manager.conversation_manager = None + manager._early_freed_index_requests = set() + manager._deferred_closes = deque() + manager._pending_preemption = {} + manager._allocated_draft_lens = {} + manager._inflight_draft_lens = {} + manager._request_stats_enabled_ids = set() + manager._fresh_pages_filled = {} + manager._disagg_receive_ready = {} + manager._on_allocation_stream = set() + manager._allocation_ready = {} + return manager, cache + + +def _finished_request(request_id: int, generation_only: bool = True) -> Mock: + return Mock( + py_request_id=request_id, is_generation_only_request=generation_only, is_dummy=False + ) + + +@pytest.mark.parametrize("generation_only", [False, True]) +def test_release_closes_immediately_by_default(generation_only: bool) -> None: + manager, cache = _manager_for_release(7) + + manager.free_resources(_finished_request(7, generation_only)) + + cache.close.assert_called_once_with() + manager.impl.clear_stats_excluded.assert_called_once_with(7) + manager.index_mapper.remove_sequence.assert_called_once_with(7) + assert 7 not in manager.kv_cache_map + assert not manager._deferred_closes + + +def test_deferred_release_closes_generation_only_request_on_flush() -> None: + manager, cache = _manager_for_release(7) + manager.enable_deferred_close(True) + + manager.free_resources(_finished_request(7)) + + # Everything but the close happens now; the index slot is free already. + cache.close.assert_not_called() + manager.index_mapper.remove_sequence.assert_called_once_with(7) + assert 7 not in manager.kv_cache_map + assert len(manager._deferred_closes) == 1 + + assert manager.flush_deferred_closes() is True + + cache.close.assert_called_once_with() + manager.impl.clear_stats_excluded.assert_called_once_with(7) + manager.index_mapper.remove_sequence.assert_called_once_with(7) + assert not manager._deferred_closes + assert not manager._early_freed_index_requests + assert manager.flush_deferred_closes() is False + cache.close.assert_called_once_with() + + +def test_deferred_close_that_raises_still_forgets_its_request() -> None: + manager, cache = _manager_for_release(7) + manager.enable_deferred_close(True) + manager.free_resources(_finished_request(7)) + later = Mock() + manager._deferred_closes.append((8, later)) + cache.close.side_effect = RuntimeError("close failed") + + with pytest.raises(RuntimeError, match="close failed"): + manager.flush_deferred_closes() + + manager.impl.clear_stats_excluded.assert_called_once_with(7) + later.close.assert_not_called() + assert list(manager._deferred_closes) == [(8, later)] + + +def test_an_id_reused_before_the_flush_keeps_its_own_early_free() -> None: + """The deferred request leaves nothing under its id, so a new request with the same id whose index slot was freed + early (a context-only worker) still skips the second slot release when it is removed.""" + manager, _ = _manager_for_release(7) + manager.enable_deferred_close(True) + manager.free_resources(_finished_request(7)) + assert 7 not in manager._early_freed_index_requests + + manager._early_freed_index_requests.add(7) # the new request's early free + manager.flush_deferred_closes() + + assert 7 in manager._early_freed_index_requests + + +@pytest.mark.parametrize("defer", [False, True]) +def test_lender_hears_of_the_free_right_before_the_close(defer: bool) -> None: + manager, cache = _manager_for_release(7) + order = Mock() + manager._sharing = order.sharing + order.attach_mock(cache.close, "close") + manager.enable_deferred_close(defer) + + manager.free_resources(_finished_request(7)) + if defer: + # The pages are still held, so the lender must not count them free yet. + assert order.mock_calls == [] + manager.flush_deferred_closes() + + assert order.mock_calls == [call.sharing._on_free(7, cache), call.close()] + + +def test_deferred_release_keeps_other_requests_immediate() -> None: + manager, cache = _manager_for_release(7) + manager.enable_deferred_close(True) + + manager.free_resources(_finished_request(7, generation_only=False)) + + cache.close.assert_called_once_with() + assert not manager._deferred_closes + + +def test_disabling_deferred_release_flushes_pending_closes() -> None: + manager, cache = _manager_for_release(7) + manager.enable_deferred_close(True) + manager.free_resources(_finished_request(7)) + + manager.enable_deferred_close(False) + + cache.close.assert_called_once_with() + assert not manager._defer_close_enabled + assert not manager._deferred_closes + + +def test_draft_manager_never_defers_release() -> None: + manager, cache = _manager_for_release(7, is_draft=True) + manager.enable_deferred_close(True) + + manager.free_resources(_finished_request(7)) + + assert not manager._defer_close_enabled + cache.close.assert_called_once_with() + + +def test_reuse_reset_closes_deferred_caches_first() -> None: + # A close after the clear would commit the request's pages for reuse again. + manager, cache = _manager_for_release(7) + manager._sharing = None + manager.event_manager = None + manager.enable_deferred_close(True) + manager.free_resources(_finished_request(7)) + order = Mock() + order.attach_mock(cache.close, "close") + order.attach_mock(manager.impl.clear_reusable_blocks, "clear") + + manager.reset_reuse_state() + + assert order.mock_calls == [call.close(), call.clear()] + assert not manager._deferred_closes + + # --------------------------------------------------------------------------- # State value constants # --------------------------------------------------------------------------- @@ -407,6 +572,8 @@ def preempt_request(req): mgr.preempt_request.side_effect = preempt_request # A bare Mock would answer truthily and suppress every stall check. mgr.has_pending_preemption.return_value = False + # No deferred close is pending unless a test queues one. + mgr.flush_deferred_closes.return_value = False return mgr @@ -451,6 +618,7 @@ def make_scheduler( enable_recompute_pause: bool = True, context_scheduling_policy: ContextSchedulingPolicy = ContextSchedulingPolicy.FCFS, context_starvation_iterations: int | None = None, + recover_lost_kv_per_rank: bool = True, ) -> object: """Create KVCacheV2Scheduler, patching isinstance check for mock mgr.""" from tensorrt_llm._torch.pyexecutor.scheduler.scheduler_v2 import KVCacheV2Scheduler @@ -480,6 +648,7 @@ def make_scheduler( enable_recompute_pause=enable_recompute_pause, context_scheduling_policy=context_scheduling_policy, context_starvation_iterations=context_starvation_iterations, + recover_lost_kv_per_rank=recover_lost_kv_per_rank, **kwargs, ) @@ -1171,6 +1340,287 @@ def alloc_fn(req): assert 99 not in ids(out.paused_requests) +def _remote_level_failed(): + return RemoteMemError( + "KVCM2 remote level: a READ of 4 page(s) x 1048576 B timed out after 30000 ms" + ) + + +class TestKVPagesLostToAFailedRemoteLevel: + """A resume that raises RemoteMemError lost pages on a failed remote cache level: only that request is affected.""" + + @staticmethod + def _lose_pages_of(lost_id): + def alloc_fn(req): + if req.py_request_id == lost_id: + raise _remote_level_failed() + return True + + return alloc_fn + + def test_a_generation_request_recomputes(self): + mgr = make_kv_cache_manager(try_allocate_generation_fn=self._lose_pages_of(1)) + sched = make_scheduler(mgr, max_num_tokens=100) + lost = make_gen_request(1) + + out = sched.schedule_request([make_gen_request(0), lost, make_gen_request(2)], set()) + + assert ids(out.generation_requests) == [0, 2] + assert ids(out.recompute_paused_requests) == [1] + assert out.paused_requests == [] + mgr.free_resources.assert_called_once_with(lost) + assert sched.take_lost_kv_requests() == [] + + def test_a_request_that_cannot_recompute_is_failed_by_the_executor(self): + """A disaggregated server cannot replay a prefill.""" + mgr = make_kv_cache_manager(try_allocate_generation_fn=self._lose_pages_of(1)) + sched = make_scheduler(mgr, max_num_tokens=100, enable_recompute_pause=False) + lost = make_gen_request(1) + + out = sched.schedule_request([make_gen_request(0), lost, make_gen_request(2)], set()) + + assert ids(out.generation_requests) == [0, 2] + assert out.recompute_paused_requests == [] + [(failed, message)] = sched.take_lost_kv_requests() + assert failed is lost and "failed remote cache level" in message + assert sched.take_lost_kv_requests() == [] + + def test_no_further_victim_is_taken_once_the_pages_are_known_lost(self): + """The first resume found no room; the one after a victim made room read the dead level.""" + calls = [] + + def alloc_fn(req): + calls.append(req.py_request_id) + if req.py_request_id == 1: + if calls.count(1) == 1: + return False + raise _remote_level_failed() + return True + + mgr = make_kv_cache_manager(try_allocate_generation_fn=alloc_fn, can_evict=True) + sched = make_scheduler(mgr, max_num_tokens=100) + reqs = [make_gen_request(i) for i in (0, 1, 98, 99)] + + out = sched.schedule_request(reqs, set()) + + assert ids(out.paused_requests) == [99] + assert ids(out.recompute_paused_requests) == [1] + assert ids(out.generation_requests) == [0, 98] + + def test_a_first_context_chunk_matches_again(self): + """It computed nothing: its caches go, and the next pass matches without the failed level's pages.""" + calls = [0] + + def prepare_fn(req): + calls[0] += 1 + if calls[0] == 1: + raise _remote_level_failed() + return True + + mgr = make_kv_cache_manager(prepare_context_fn=prepare_fn) + sched = make_scheduler(mgr, max_num_tokens=1000) + lost = make_ctx_request(0, context_remaining_length=100) + mgr.kv_cache_map[0] = Mock() + # Where the failed match left it: past the reused prefix. + lost.context_current_position = 64 + lost.estimated_reusable_tokens = 64 + + out = sched.schedule_request( + [lost, make_ctx_request(1, context_remaining_length=100)], set() + ) + + assert ids(out.context_requests) == [1] + assert out.recompute_paused_requests == [] + mgr.free_resources.assert_called_once_with(lost) + assert lost.context_current_position == 0 + assert lost.estimated_reusable_tokens == 0 + lost.set_prepopulated_prompt_len.assert_called_once_with(0, mgr.tokens_per_block) + out = sched.schedule_request([lost], set()) + assert ids(out.context_requests) == [0] + + def test_a_started_context_request_recomputes(self): + def prepare_fn(req): + if req.py_request_id == 0: + raise _remote_level_failed() + return True + + mgr = make_kv_cache_manager(prepare_context_fn=prepare_fn) + sched = make_scheduler(mgr, max_num_tokens=1000) + lost = make_ctx_request(0, context_remaining_length=100, is_first_context_chunk=False) + + out = sched.schedule_request( + [lost, make_ctx_request(1, context_remaining_length=100)], set() + ) + + assert ids(out.context_requests) == [1] + assert ids(out.recompute_paused_requests) == [0] + mgr.free_resources.assert_called_once_with(lost) + + def test_a_disagg_generation_init_request_matches_again(self): + """A generation-init admission whose prefix match resumed pages of a failed level costs only that request.""" + calls = [0] + + def prepare_fn(req): + calls[0] += 1 + if calls[0] == 1: + raise _remote_level_failed() + return True + + mgr = make_kv_cache_manager(prepare_disagg_gen_init_fn=prepare_fn) + sched = make_scheduler(mgr, max_num_tokens=1000, enable_recompute_pause=False) + lost = make_disagg_request(0) + mgr.kv_cache_map[0] = Mock() + + out = sched.schedule_request([lost, make_gen_request(1)], set()) + + assert ids(out.generation_requests) == [1] + assert out.fitting_disagg_gen_init_requests == [] + mgr.free_resources.assert_called_once_with(lost) + assert sched.take_lost_kv_requests() == [] + out = sched.schedule_request([lost], set()) + assert ids(out.fitting_disagg_gen_init_requests) == [0] + + @pytest.mark.parametrize("path", ["generation", "context", "disagg_generation_init"]) + def test_a_lockstep_rank_stops_instead_of_recovering_alone(self, path): + """TP/CP/PP peers did not see this rank's failure: recovering here alone would desynchronize them.""" + + def lose(req): + raise _remote_level_failed() + + mgr = make_kv_cache_manager( + try_allocate_generation_fn=lose if path == "generation" else None, + prepare_context_fn=lose if path == "context" else None, + prepare_disagg_gen_init_fn=lose if path == "disagg_generation_init" else None, + ) + mgr.has_remote_cache_level = True + mgr.any_remote_level_failed = False + sched = make_scheduler(mgr, max_num_tokens=1000, recover_lost_kv_per_rank=False) + request = { + "generation": lambda: make_gen_request(0), + "context": lambda: make_ctx_request(0, context_remaining_length=100), + "disagg_generation_init": lambda: make_disagg_request(0), + }[path]() + + with pytest.raises(RemoteMemError, match="lock step"): + sched.schedule_request([request], set()) + mgr.free_resources.assert_not_called() + assert sched.take_lost_kv_requests() == [] + + @pytest.mark.parametrize("fails_during_pass", [False, True]) + def test_a_lockstep_rank_stops_once_its_level_failed(self, fails_during_pass): + """A level that failed in an eviction WRITE, which the manager retried past, still diverged the reuse tree.""" + mgr = make_kv_cache_manager() + mgr.has_remote_cache_level = True + failed = [not fails_during_pass] + + def alloc_fn(req): + failed[0] = True + return True + + mgr.try_allocate_generation.side_effect = alloc_fn + type(mgr).any_remote_level_failed = PropertyMock(side_effect=lambda: failed[0]) + sched = make_scheduler(mgr, max_num_tokens=1000, recover_lost_kv_per_rank=False) + + with pytest.raises(RemoteMemError, match="lock step"): + sched.schedule_request([make_gen_request(0)], set()) + assert mgr.try_allocate_generation.called == fails_during_pass + + def test_a_per_rank_scheduler_never_polls_the_level(self): + """TP1 and attention DP recover per request: no per-pass query.""" + mgr = make_kv_cache_manager() + mgr.has_remote_cache_level = True + polled = PropertyMock(return_value=False) + type(mgr).any_remote_level_failed = polled + sched = make_scheduler(mgr, max_num_tokens=1000) + + sched.schedule_request([make_gen_request(0)], set()) + + polled.assert_not_called() + + def test_the_executor_fails_lost_requests_under_the_multimodal_scheduler(self): + """MultimodalScheduler forwards the wrapped scheduler's lost requests to PyExecutor._schedule.""" + from tensorrt_llm._torch.pyexecutor.py_executor import PyExecutor + from tensorrt_llm._torch.pyexecutor.scheduler.scheduler import MultimodalScheduler + + class StopAfterLost(RuntimeError): + pass + + mgr = make_kv_cache_manager(try_allocate_generation_fn=self._lose_pages_of(1)) + inner = make_scheduler(mgr, max_num_tokens=100, enable_recompute_pause=False) + lost = make_gen_request(1) + requests = [make_gen_request(0), lost] + for request in requests: + request.py_mm_encoder_state = None + executor = object.__new__(PyExecutor) + executor.active_requests = requests + executor.inflight_req_ids = set() + executor.kv_cache_manager = mgr + executor._maybe_record_hang_diagnostic_phase = Mock() + executor._cancelled_disagg_model_request_ids = Mock(return_value=set()) + executor.scheduler = MultimodalScheduler( + inner, + max_batch_size=8, + max_num_tokens=100, + encoder_cache=Mock(), + get_item_cache_keys=lambda request: None, + bytes_per_encoder_embedding=2, + retain_cache_entries=False, + ) + executor._handle_errors = Mock(side_effect=StopAfterLost) + + with pytest.raises(StopAfterLost): + PyExecutor._schedule(executor) + + executor._handle_errors.assert_called_once() + (message,), kwargs = executor._handle_errors.call_args + assert kwargs == {"requests": [lost], "charge_budget": False} + assert "failed remote cache level" in message + + +class TestDeferredClosesBeforeEviction: + """Deferred closes (defer_generation_only_release) are flushed before any running request pays for room.""" + + @pytest.mark.parametrize("enable_recompute_pause", [True, False]) + def test_a_flush_that_makes_room_pauses_nobody(self, enable_recompute_pause): + pending = [True] + room = [False] + + def flush(): + had, pending[0] = pending[0], False + room[0] = room[0] or had + return had + + def alloc_fn(req): + return req.py_request_id != 0 or room[0] + + mgr = make_kv_cache_manager(try_allocate_generation_fn=alloc_fn, can_evict=True) + mgr.flush_deferred_closes.side_effect = flush + sched = make_scheduler( + mgr, max_num_tokens=100, enable_recompute_pause=enable_recompute_pause + ) + reqs = [make_gen_request(i) for i in (0, 1, 2)] + + out = sched.schedule_request(reqs, set()) + + assert ids(out.generation_requests) == [0, 1, 2] + assert out.paused_requests == [] + assert out.recompute_paused_requests == [] + mgr.flush_deferred_closes.assert_called_once_with() + + def test_without_pending_closes_the_ladder_runs_as_before(self): + def alloc_fn(req): + return req.py_request_id != 0 or mgr.kv_cache_map[2].is_active is False + + mgr = make_kv_cache_manager(try_allocate_generation_fn=alloc_fn, can_evict=True) + sched = make_scheduler(mgr, max_num_tokens=100) + reqs = [make_gen_request(i) for i in (0, 1, 2)] + + out = sched.schedule_request(reqs, set()) + + assert ids(out.paused_requests) == [2] + assert ids(out.generation_requests) == [0, 1] + + class TestUnpairedDraftAdmission: """A draft pool the scheduler suspends but never used to re-admit. diff --git a/tests/unittest/_torch/pyexecutor/kv_cache/test_kvcm2_integration.py b/tests/unittest/_torch/pyexecutor/kv_cache/test_kvcm2_integration.py index 054b69b1fbd9..fff99f63ad76 100644 --- a/tests/unittest/_torch/pyexecutor/kv_cache/test_kvcm2_integration.py +++ b/tests/unittest/_torch/pyexecutor/kv_cache/test_kvcm2_integration.py @@ -46,6 +46,7 @@ _swa_endpoint_priority, _sync_kv_cache_manager_init_status, _update_kv_cache_draft_token_location, + _withdraws_remote_donation_on_error, ) from tensorrt_llm._torch.pyexecutor.kv_cache.regions import RegionLayout from tensorrt_llm._torch.pyexecutor.kv_cache.sparse_offload_memory import ( @@ -419,6 +420,8 @@ def _make_manager_for_cache_tier_test( vocab_size: int | None = 16, dtype: DataType = DataType.HALF, layer_specs: list[KVCacheLayerSpec] | None = None, + remote_donor: object | None = None, + manager_cls: type = KVCacheManagerV2, ) -> tuple[KVCacheManagerV2, Mock]: impl_constructor = Mock(side_effect=impl_side_effect) if mapping is None: @@ -469,7 +472,7 @@ def build_cache_config( patch.object(KVCacheManagerV2, "_log_kv_cache_pool_lifecycle_mapping"), patch(f"{module}.get_pp_layers", return_value=([0], 1)), ): - manager = KVCacheManagerV2( + manager = manager_cls( kv_cache_config, CacheType.SELFKONLY, num_layers=1, @@ -488,6 +491,7 @@ def build_cache_config( vocab_size=vocab_size, execution_stream=Mock(), cold_page_codec_provider=cold_page_codec_provider, + remote_donor=remote_donor, ) return manager, impl_constructor @@ -1891,6 +1895,325 @@ def test_peer_init_failure_discards_local_candidate() -> None: local_impl.shutdown.assert_called_once_with() +class TestRemoteTierInitStatus: + """A remote tier's failure on one rank goes through the cross-rank init status, and the donation is withdrawn. + + Without the sync, the rank raises alone and its peers wait in the first collective. + """ + + module = "tensorrt_llm._torch.pyexecutor.kv_cache.kv_cache_manager_v2" + + @staticmethod + def _config(tmp_path, **remote) -> KvCacheConfig: + return KvCacheConfig( + max_gpu_total_bytes=16 << 20, + host_cache_size=0, + remote_cache_config={"directory": str(tmp_path), **remote}, + ) + + @staticmethod + def _starting_donor(error=None): + """An _add_remote_level that starts a donor, then raises `error` if given.""" + donor = Mock() + + def add_remote_level(self, remote_config, cache_tiers): + self._remote_donor = donor + if error is not None: + raise error + + return donor, add_remote_level + + @pytest.mark.cpu_only + def test_the_manager_waits_for_its_donation_once_its_claims_are_done(self, tmp_path) -> None: + """Without the estimation the target starts the donation itself: it is placed before warmup and capture.""" + donor, add_remote_level = self._starting_donor() + with ( + patch.object(KVCacheManagerV2, "_add_remote_level", add_remote_level), + patch( + f"{self.module}._sync_kv_cache_manager_init_status", + side_effect=lambda status, mapping: status, + ), + ): + manager, _ = _make_manager_for_cache_tier_test( + self._config(tmp_path, donor={"size": 1 << 30}), [Mock()] + ) + donor.wait_started.assert_called_once_with() + donor.close.assert_not_called() + assert manager.remote_donor is donor + + @pytest.mark.cpu_only + def test_local_failure_aborts_every_rank_and_closes_the_donor(self, tmp_path) -> None: + donor, add_remote_level = self._starting_donor(RuntimeError("capacity check failed")) + with ( + patch.object(KVCacheManagerV2, "_add_remote_level", add_remote_level), + patch( + f"{self.module}._sync_kv_cache_manager_init_status", + side_effect=lambda status, mapping: status, + ) as sync, + pytest.raises(RuntimeError, match="capacity check failed"), + ): + _make_manager_for_cache_tier_test( + self._config(tmp_path, level={"size": 1 << 30}, donor={"size": 1 << 30}), [Mock()] + ) + assert sync.call_args.args[0] == _KVCacheManagerInitStatus.ABORT + # Closed with the error, which leaves the donation's failure marker for the peers. + assert str(donor.close.call_args.args[0]) == "capacity check failed" + + @pytest.mark.cpu_only + def test_peer_failure_discards_the_cache_and_closes_the_donor(self, tmp_path) -> None: + donor, add_remote_level = self._starting_donor() + local_impl = Mock() + with ( + patch.object(KVCacheManagerV2, "_add_remote_level", add_remote_level), + patch( + f"{self.module}._sync_kv_cache_manager_init_status", + return_value=_KVCacheManagerInitStatus.ABORT, + ) as sync, + pytest.raises(RuntimeError, match="failed on another rank"), + ): + _make_manager_for_cache_tier_test( + self._config(tmp_path, donor={"size": 1 << 30}), [local_impl] + ) + assert sync.call_args.args[0] == _KVCacheManagerInitStatus.OK + local_impl.shutdown.assert_called_once_with() + donor.close.assert_called_once() + assert "another rank" in str(donor.close.call_args.args[0]) + + @pytest.mark.cpu_only + def test_donation_without_host_memory_left_aborts_through_the_sync(self, tmp_path) -> None: + config = KvCacheConfig( + max_gpu_total_bytes=16 << 20, + remote_cache_config={"directory": str(tmp_path), "donor": {"size": 1 << 50}}, + ) + add_remote_level = Mock() + with ( + patch.object(KVCacheManagerV2, "_add_remote_level", add_remote_level), + patch( + f"{self.module}._sync_kv_cache_manager_init_status", + side_effect=lambda status, mapping: status, + ) as sync, + pytest.raises(ValueError, match="host_cache_size"), + ): + _make_manager_for_cache_tier_test(config, [Mock()]) + assert sync.call_args.args[0] == _KVCacheManagerInitStatus.ABORT + add_remote_level.assert_not_called() + # The donation never started, yet its failure marker counts it as reported for the peers. + assert [p.name.endswith(".failed") for p in tmp_path.iterdir()] == [True] + + @pytest.mark.cpu_only + def test_an_unstarted_donation_is_marked_before_the_sync(self, tmp_path) -> None: + """Peers waiting in check_remote_capacity for this donor stop at once only if the marker precedes the + init-status collective, which waits for them.""" + config = KvCacheConfig( + max_gpu_total_bytes=16 << 20, + remote_cache_config={"directory": str(tmp_path), "donor": {"size": 1 << 50}}, + ) + markers_at_sync = [] + + def sync(status, mapping): + markers_at_sync.append(sorted(p.suffix for p in tmp_path.iterdir())) + return status + + with ( + patch.object(KVCacheManagerV2, "_add_remote_level", Mock()), + patch(f"{self.module}._sync_kv_cache_manager_init_status", side_effect=sync), + pytest.raises(ValueError, match="host_cache_size"), + ): + _make_manager_for_cache_tier_test(config, [Mock()]) + assert markers_at_sync == [[".failed"]] + # One marker, not a second one from the construction guard. + assert len(list(tmp_path.iterdir())) == 1 + + @pytest.mark.cpu_only + def test_a_remote_setup_failure_before_the_donation_is_marked_before_the_sync( + self, tmp_path + ) -> None: + markers_at_sync = [] + + def sync(status, mapping): + markers_at_sync.append(sorted(p.suffix for p in tmp_path.iterdir())) + return status + + with ( + patch.object( + KVCacheManagerV2, + "_add_remote_level", + Mock(side_effect=ValueError("UCX devices: unknown token")), + ), + patch(f"{self.module}._sync_kv_cache_manager_init_status", side_effect=sync), + pytest.raises(ValueError, match="unknown token"), + ): + _make_manager_for_cache_tier_test( + self._config(tmp_path, level={"size": 1 << 30}, donor={"size": 1 << 30}), [Mock()] + ) + assert markers_at_sync == [[".failed"]] + assert "unknown token" in (next(tmp_path.iterdir())).read_text() + + @pytest.mark.cpu_only + def test_failure_after_the_sync_withdraws_the_donation(self, tmp_path) -> None: + donor, add_remote_level = self._starting_donor() + with ( + patch.object(KVCacheManagerV2, "_add_remote_level", add_remote_level), + patch( + f"{self.module}._sync_kv_cache_manager_init_status", + side_effect=lambda status, mapping: status, + ), + patch.object( + KVCacheManagerV2, "_reserve_guard_page", side_effect=RuntimeError("late failure") + ), + pytest.raises(RuntimeError, match="late failure"), + ): + _make_manager_for_cache_tier_test( + self._config(tmp_path, donor={"size": 1 << 30}), [Mock()] + ) + assert str(donor.close.call_args.args[0]) == "late failure" + + @pytest.mark.cpu_only + def test_a_subclass_that_fails_after_the_base_init_withdraws_the_donation_with_its_error( + self, tmp_path + ) -> None: + """E.g. MambaHybridCacheManagerV2 whose state pool comes out too small: it shuts down and raises after + KVCacheManagerV2.__init__. The donation is withdrawn with that error, whose marker tells peers to stop + waiting for this donor, not closed quietly by the shutdown.""" + donor, add_remote_level = self._starting_donor() + + class FinalizesAfterTheBaseInit(KVCacheManagerV2): + @_withdraws_remote_donation_on_error + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + KVCacheManagerV2.shutdown(self) + raise ValueError("state pool too small") + + with ( + patch.object(KVCacheManagerV2, "_add_remote_level", add_remote_level), + patch( + f"{self.module}._sync_kv_cache_manager_init_status", + side_effect=lambda status, mapping: status, + ), + pytest.raises(ValueError, match="state pool too small"), + ): + _make_manager_for_cache_tier_test( + self._config(tmp_path, donor={"size": 1 << 30}), + [Mock()], + manager_cls=FinalizesAfterTheBaseInit, + ) + donor.close.assert_called_once() + assert str(donor.close.call_args.args[0]) == "state pool too small" + + @pytest.mark.cpu_only + def test_an_undecorated_subclass_that_fails_after_the_base_init_is_guarded_too( + self, tmp_path + ) -> None: + """E.g. DSACacheManagerV2, which raises after super().__init__(): every subclass's __init__ is guarded.""" + donor, add_remote_level = self._starting_donor() + + class RaisesAfterTheBaseInit(KVCacheManagerV2): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + raise ValueError("indexer cache too small") + + with ( + patch.object(KVCacheManagerV2, "_add_remote_level", add_remote_level), + patch( + f"{self.module}._sync_kv_cache_manager_init_status", + side_effect=lambda status, mapping: status, + ), + pytest.raises(ValueError, match="indexer cache too small"), + ): + _make_manager_for_cache_tier_test( + self._config(tmp_path, donor={"size": 1 << 30}), + [Mock()], + manager_cls=RaisesAfterTheBaseInit, + ) + donor.close.assert_called_once() + assert str(donor.close.call_args.args[0]) == "indexer cache too small" + + @pytest.mark.cpu_only + def test_a_failed_construction_closes_its_open_caches_before_the_shutdown( + self, tmp_path + ) -> None: + """The runtime's shutdown refuses while a cache is open, e.g. the guard page's (TRTLLM_KV_GUARD_PAGE).""" + donor, add_remote_level = self._starting_donor() + order = Mock() + guard_cache = order.guard_cache + impl = order.impl + + class OpensACacheThenFails(KVCacheManagerV2): + @_withdraws_remote_donation_on_error + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.kv_cache_map[-1] = guard_cache + raise ValueError("late failure") + + with ( + patch.object(KVCacheManagerV2, "_add_remote_level", add_remote_level), + patch( + f"{self.module}._sync_kv_cache_manager_init_status", + side_effect=lambda status, mapping: status, + ), + pytest.raises(ValueError, match="late failure"), + ): + _make_manager_for_cache_tier_test( + self._config(tmp_path, donor={"size": 1 << 30}), + [impl], + manager_cls=OpensACacheThenFails, + ) + calls = [name for name, _, _ in order.mock_calls] + assert calls.index("guard_cache.close") < calls.index("impl.shutdown") + + @pytest.mark.cpu_only + def test_the_mamba_hybrid_manager_guards_its_own_finalization(self) -> None: + from tensorrt_llm._torch.pyexecutor.kv_cache.mamba_cache_manager.mamba_cache_manager_v2 import ( + MambaHybridCacheManagerV2, + ) + + assert hasattr(MambaHybridCacheManagerV2.__init__, "__wrapped__") + + @pytest.mark.cpu_only + def test_shutdown_withdraws_the_donation_when_a_deferred_close_raises(self, tmp_path) -> None: + donor, add_remote_level = self._starting_donor() + with ( + patch.object(KVCacheManagerV2, "_add_remote_level", add_remote_level), + patch( + f"{self.module}._sync_kv_cache_manager_init_status", + side_effect=lambda status, mapping: status, + ), + ): + manager, _ = _make_manager_for_cache_tier_test( + self._config(tmp_path, donor={"size": 1 << 30}), [Mock()] + ) + with ( + patch.object(manager, "flush_deferred_closes", side_effect=RuntimeError("close")), + pytest.raises(RuntimeError, match="close"), + ): + manager.shutdown() + donor.close.assert_called_once_with(None) + + @pytest.mark.cpu_only + def test_draft_waits_for_the_targets_donation_instead_of_charging_it_again( + self, tmp_path + ) -> None: + """The target's donation is resident once the draft measures host memory: subtracting it again would leave the + draft's automatic host tier nothing (here: a donation larger than the host).""" + config = KvCacheConfig( + max_gpu_total_bytes=16 << 20, + remote_cache_config={"directory": str(tmp_path), "donor": {"size": 1 << 50}}, + ) + target_donor = Mock() + with patch( + f"{self.module}._sync_kv_cache_manager_init_status", + side_effect=lambda status, mapping: status, + ): + draft, _ = _make_manager_for_cache_tier_test( + config, [Mock()], is_draft=True, remote_donor=target_donor + ) + target_donor.wait_started.assert_called_once_with() + assert draft._remote_donor is None # the target owns it + draft._close_remote_donor(RuntimeError("draft failed")) + target_donor.close.assert_not_called() + assert list(tmp_path.iterdir()) == [] # nor does the draft mark a donation failed + + @pytest.mark.cpu_only @pytest.mark.parametrize("peer_failed", [False, True]) def test_agg_helix_gpu_only_init_syncs_status_across_ranks(peer_failed: bool) -> None: @@ -6068,6 +6391,33 @@ def test_sparse_offload_admits_by_current_need_with_a_cold_tier() -> None: assert prepare.call_count == 2 +@pytest.mark.cpu_only +def test_a_remote_level_alone_below_the_gpu_reserves_history_and_stops_counting_once_failed() -> ( + None +): + # A remote level retires when its donor dies and then takes no more pages: as the only level + # below the GPU, admission reserves history as without one, and the eviction flags turn off. + manager = _offload_setup_manager([12, 10]) + manager.impl = SimpleNamespace( + cache_tier_list=[CacheTier.GPU_MEM, CacheTier.REMOTE], any_remote_level_failed=False + ) + manager._can_evict = manager._only_remote_below_gpu = True + + with patch.object(KVCacheManagerV2, "_log_sparse_kv_offload_capacity"): + manager._setup_sparse_kv_offload( + KvCacheConfig(), max_seq_len=1024, num_reserved_index_slots=0 + ) + + assert manager._host_history_reservations is not None + assert manager.has_cache_tier_below_gpu and manager.can_evict + manager.impl.any_remote_level_failed = True + assert not manager.has_cache_tier_below_gpu and not manager.can_evict + # A host level below keeps both whatever the remote level does. + manager.impl.cache_tier_list = [CacheTier.GPU_MEM, CacheTier.HOST_MEM, CacheTier.REMOTE] + manager._only_remote_below_gpu = False + assert manager.has_cache_tier_below_gpu and manager.can_evict + + @pytest.mark.cpu_only def test_sparse_offload_setup_warns_when_max_seq_len_outgrows_host_history() -> None: manager = _offload_setup_manager([8]) diff --git a/tests/unittest/_torch/pyexecutor/test_adp_router_home_wait.py b/tests/unittest/_torch/pyexecutor/test_adp_router_home_wait.py new file mode 100644 index 000000000000..f3a0e20431f3 --- /dev/null +++ b/tests/unittest/_torch/pyexecutor/test_adp_router_home_wait.py @@ -0,0 +1,485 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Home-wait admission of ConversationAwareADPRouter (attention_dp_config.kv_cache_routing_home_wait_rounds). + +Without it, a returning conversation whose home rank is at max_num_active_requests overflows round-robin to a rank +without its cached prefix. With home-wait on, pop_requests admits it only into a free slot on its home rank (others +may pass it), and it overflows only after it was held home_wait_rounds rounds while another rank had room. +""" + +import random +from unittest.mock import MagicMock + +import pytest + +from tensorrt_llm._torch.pyexecutor.scheduler import FCFSWaitingQueue, PriorityWaitingQueue +from tensorrt_llm._torch.pyexecutor.scheduler.adp_router import ( + ADPRouter, + ConversationAwareADPRouter, +) +from tensorrt_llm._torch.pyexecutor.scheduler.rank_state import RankState +from tensorrt_llm.conversation_params import ConversationParams +from tensorrt_llm.llmapi.llm_args import AttentionDpConfig + +pytestmark = pytest.mark.cpu_only + + +class _Req(MagicMock): + @property + def num_input_tokens(self): + return len(self.input_token_ids) + + +def _dist(tp_size, tp_rank=0): + dist = MagicMock() + dist.tp_rank = tp_rank + dist.tp_size = tp_size + dist.has_cp_helix = False + dist.mapping.has_pp.return_value = False + return dist + + +def _item(req_id, conv, num_tokens=100, target=None, relax=True, children=0, priority=0.5): + item = MagicMock() + item.id = req_id + item.child_req_ids = ( + list(range(10_000 + req_id * 10, 10_000 + req_id * 10 + children)) if children else None + ) + sp = MagicMock() + sp.attention_dp_rank = target + sp.attention_dp_relax = relax + sp.subagent_affinity_id = None + item.request = _Req() + item.request.py_scheduling_params = sp + item.request.py_conversation_params = ConversationParams(conversation_id=conv) if conv else None + item.request.input_token_ids = list(range(num_tokens)) + item.request.priority = priority + return item + + +def _states(active, tokens=None): + tokens = tokens or [a * 100 for a in active] + return [ + RankState(rank=r, num_active_requests=active[r], num_active_tokens=tokens[r]) + for r in range(len(active)) + ] + + +def _router(tp_size=4, rounds=4, placement="round_robin", tp_rank=0): + return ConversationAwareADPRouter( + dist=_dist(tp_size, tp_rank), new_conv_placement=placement, home_wait_rounds=rounds + ) + + +def _round(router, queue, active, cap, max_new=None): + """One admission round: pop + route. Returns {request id: rank}.""" + states = _states(active) + free = sum(max(0, cap - a) for a in active) + chosen, placement = router.pop_requests( + queue, states, free if max_new is None else max_new, cap + ) + assign, expected = router.route_requests(states, chosen, cap, placement=placement) + pos = {it.id: rank for rank, lst in assign.items() for it in lst} + for r in range(len(active)): + assert active[r] + len(assign[r]) <= max(cap, active[r]), "a rank went over the hard cap" + assert expected >= active[r] + len(assign[r]), "padding invariant" + return pos + + +def _bind(router, conv_ranks, tp_size=4, cap=8): + """Bind conversations to ranks by routing their first turns one rank at a time.""" + rid = 1_000 + for conv, rank in conv_ranks.items(): + active = [cap] * tp_size + active[rank] = 0 + queue = FCFSWaitingQueue() + queue.add_request(_item(rid, conv)) + pos = _round(router, queue, active, cap) + assert pos == {rid: rank} + rid += 1 + + +@pytest.mark.parametrize("rounds", [None, 64]) +def test_config_field_reaches_the_router(rounds): + config = AttentionDpConfig( + kv_cache_routing_conversation_affinity=True, kv_cache_routing_home_wait_rounds=rounds + ) + router = ADPRouter.create( + dist=_dist(4), has_seq_slot_headroom=False, attention_dp_config=config + ) + assert isinstance(router, ConversationAwareADPRouter) + assert router._home_wait_rounds == rounds + + +def test_config_field_rejects_zero(): + with pytest.raises(ValueError): + AttentionDpConfig( + kv_cache_routing_conversation_affinity=True, kv_cache_routing_home_wait_rounds=0 + ) + + +def test_config_field_requires_conversation_affinity(): + with pytest.raises(ValueError, match="kv_cache_routing_conversation_affinity"): + AttentionDpConfig(kv_cache_routing_home_wait_rounds=4) + + +def test_off_is_the_base_fifo_pop(): + """Without home-wait, pop_requests is the base class's FIFO pop (no plan).""" + router = ConversationAwareADPRouter(dist=_dist(4)) + ref = ConversationAwareADPRouter(dist=_dist(4)) + q1, q2 = FCFSWaitingQueue(), FCFSWaitingQueue() + for i in range(6): + q1.add_request(_item(i, f"c{i}")) + q2.add_request(_item(i, f"c{i}")) + got, plan = router.pop_requests(q1, _states([0, 0, 0, 0]), 4, 8) + want, _ = ADPRouter.pop_requests(ref, q2, _states([0, 0, 0, 0]), 4, 8) + assert [x.id for x in got] == [x.id for x in want] == [0, 1, 2, 3] + assert plan == {} + assert [x.id for x in q1] == [4, 5] + + +def test_bound_request_waits_for_home_while_others_pass(): + router = _router(rounds=10) + _bind(router, {"A": 0, "B": 1}) + queue = FCFSWaitingQueue() + queue.add_requests([_item(1, "A"), _item(2, "C"), _item(3, "B")]) + cap = 2 + pos = _round(router, queue, [2, 0, 0, 0], cap) # rank 0 (A's home) is full + assert 1 not in pos, "A must wait for its home rank" + assert pos[3] == 1, "B goes home" + assert pos[2] != 0, "the new conversation C goes where there is room" + assert [x.id for x in queue] == [1], "A stays at the front" + pos = _round(router, queue, [1, 1, 1, 1], cap) # a slot frees on rank 0 + assert pos == {1: 0} + assert len(queue) == 0 + + +def test_overflow_after_rounds_keeps_binding(): + router = _router(rounds=2) + _bind(router, {"A": 0}) + queue = FCFSWaitingQueue() + queue.add_request(_item(1, "A")) + cap = 1 + assert _round(router, queue, [1, 0, 0, 0], cap) == {} # held, age 1 + assert _round(router, queue, [1, 0, 0, 0], cap) == {} # held, age 2 + pos = _round(router, queue, [1, 0, 0, 0], cap) # overflow + assert list(pos) == [1] and pos[1] != 0 + assert router._conv_to_rank["A"] == 0, "the binding stays home, as without home-wait" + + +def test_no_aging_when_no_rank_has_room(): + router = _router(rounds=1) + _bind(router, {"A": 0}) + queue = FCFSWaitingQueue() + queue.add_request(_item(1, "A")) + for _ in range(5): + assert _round(router, queue, [1, 1, 1, 1], 1, max_new=0) == {} + assert _round(router, queue, [1, 1, 1, 1], 1, max_new=1) == {} + assert router._home_wait_age.get(1, 0) == 0 + assert _round(router, queue, [0, 1, 1, 1], 1) == {1: 0} + + +def test_a_request_the_round_does_not_reach_keeps_its_age(): + """The bound on waiting holds even across rounds that stop before the held request.""" + router = _router(rounds=10) + _bind(router, {"A": 0}) + queue = FCFSWaitingQueue() + queue.add_request(_item(1, "A")) + assert _round(router, queue, [1, 0, 0, 0], 1) == {} # A held while other ranks had room + assert router._home_wait_age[1] == 1 + # A new conversation ahead of A takes the round's whole budget, so the round stops before A (still in the window). + queue.prepend_requests([_item(2, "C")]) + assert list(_round(router, queue, [1, 0, 0, 0], 1, max_new=1)) == [2] + assert router._home_wait_age == {1: 1} + + +def test_window_extends_past_held_requests(): + """A round looks past a window of held requests while a rank has room.""" + router = _router(rounds=10) + router.HOME_WAIT_WINDOW = 1 + _bind(router, {"A": 0, "B": 1}) + queue = FCFSWaitingQueue() + queue.add_requests([_item(1, "A"), _item(2, "B"), _item(3, "C"), _item(4, "D")]) + pos = _round(router, queue, [1, 1, 0, 0], 1, max_new=1) + assert list(pos) == [3] and pos[3] in (2, 3) + assert router._home_wait_age == {1: 1, 2: 1} + # Only the requests up to the last admitted one were popped and put back. + assert [x.id for x in queue] == [1, 2, 4] + + +def test_a_request_out_of_the_window_loses_its_age(): + router = _router(rounds=10) + router.HOME_WAIT_WINDOW = 1 + _bind(router, {"A": 0}) + queue = FCFSWaitingQueue() + queue.add_request(_item(1, "A")) + assert _round(router, queue, [1, 0, 0, 0], 1) == {} # A held while other ranks had room + assert router._home_wait_age == {1: 1} + # A new request goes ahead of A and uses the round's whole budget, so the window never reaches A. + queue.prepend_requests([_item(2, "C")]) + assert list(_round(router, queue, [1, 0, 0, 0], 1, max_new=1)) == [2] + assert router._home_wait_age == {} + assert [x.id for x in queue] == [1] + + +def test_unbound_requests_are_placed_as_without_home_wait(): + """Home-wait plans only returning conversations; route_requests places the rest by its own rules.""" + routers = [_router(rounds=4), ConversationAwareADPRouter(dist=_dist(4))] + results = [] + for router in routers: + queue = FCFSWaitingQueue() + queue.add_requests([_item(i, f"n{i}", children=i % 2) for i in range(6)]) + results.append(_round(router, queue, [2, 0, 1, 3], 4)) + assert router._conv_to_rank == {f"n{i}": results[-1][i] for i in range(6)} + assert results[0] == results[1] + + +def test_a_removed_request_drops_its_age(): + router = _router(rounds=10) + _bind(router, {"A": 0}) + queue = FCFSWaitingQueue() + queue.add_requests([_item(1, "A"), _item(2, "A")]) + assert _round(router, queue, [1, 0, 0, 0], 1) == {} + assert router._home_wait_age == {1: 1, 2: 1} + queue.remove_by_ids({1}) # cancelled while held + assert _round(router, queue, [1, 0, 0, 0], 1) == {} + assert router._home_wait_age == {2: 2} + + +def test_unplanned_requests_are_placed_by_the_real_token_load(): + """route_requests places a request pop_requests did not plan as without home-wait, on shared token load.""" + router = _router(tp_size=2, placement="least_tokens") + states = _states([0, 0], tokens=[1000, 0]) + assign, _ = router.route_requests(states, [_item(1, "X")], 8, placement={999: 0}) + assert [it.id for it in assign[1]] == [1] + + +def test_new_conversation_bound_in_the_same_round(): + router = _router(rounds=4) + queue = FCFSWaitingQueue() + queue.add_requests([_item(1, "X"), _item(2, "Y"), _item(3, "X")]) + pos = _round(router, queue, [0, 0, 0, 0], 8) + assert pos[1] == pos[3] == router._conv_to_rank["X"] + + +def test_admission_groups_are_respected(): + """A later admission group passes a held request of an earlier group, but not into its home rank.""" + router = _router(rounds=10) + _bind(router, {"A": 0, "B": 1, "E": 0}) + queue = FCFSWaitingQueue() + # A needs 2 slots and its home rank 0 has 1. Its own group's F may still take that slot; group 1's E may not. + queue.add_requests([_item(1, "A", children=1), _item(4, "F"), _item(2, "B"), _item(3, "E")]) + queue.admission_groups = lambda reqs: [0, 0, 1, 1][: len(reqs)] + pos = _round(router, queue, [1, 0, 0, 0], 2) + assert 1 not in pos and 4 in pos and pos[2] == 1 and 3 not in pos + assert [x.id for x in queue] == [1, 3] + assert router._home_wait_age == {1: 1, 3: 1} + + +def test_continuous_priorities_do_not_block_other_ranks(): + """Priority queue with one group per request (output-length predictor): a request held for a full home rank does + not stop lower-priority requests bound to other ranks, and a lower-priority request does not pass it at home.""" + router = _router(rounds=10) + _bind(router, {"A": 0, "B": 1, "C": 2, "D": 0}) + queue = PriorityWaitingQueue() + queue.add_requests( + [ + _item(1, "A", priority=0.9), + _item(2, "B", priority=0.8), + _item(3, "C", priority=0.7), + _item(4, "D", priority=0.6), + ] + ) + assert queue.admission_groups(queue.peek_requests(4)) == [0, 1, 2, 3] + pos = _round(router, queue, [1, 0, 0, 0], 1) + assert pos == {2: 1, 3: 2} + assert [x.id for x in queue] == [1, 4] + assert router._home_wait_age == {1: 1, 4: 1} + # Rank 0 frees a slot: the higher-priority A takes it, D keeps waiting. + assert _round(router, queue, [0, 1, 1, 0], 1) == {1: 0} + assert [x.id for x in queue] == [4] + + +def test_an_aged_lower_priority_request_does_not_take_a_held_requests_home(): + """Once aged, a lower-priority request is admitted unplanned; route_requests must still keep it off the home rank + of a higher-priority request held in the same round, so each rank admits in priority order.""" + router = _router(tp_size=2, rounds=2) + _bind(router, {"A": 0, "E": 0}, tp_size=2, cap=2) + queue = PriorityWaitingQueue() + queue.add_request(_item(2, "E", priority=0.5)) + for _ in range(2): + assert _round(router, queue, [2, 1], 2) == {} # E held while rank 1 has room + queue.add_request(_item(1, "A", priority=0.9, children=1)) # needs both slots of rank 0 + pos = _round(router, queue, [1, 1], 2) + assert pos == {2: 1}, pos + assert [x.id for x in queue] == [1] + assert router._conv_to_rank["E"] == 0 + + +def test_round_passes_over_a_bounded_number_of_requests(): + """A deep queue of held requests costs a round at most HOME_WAIT_MAX_PASSED requests, not the whole queue.""" + router = _router(rounds=10_000) + router.HOME_WAIT_WINDOW = 4 + router.HOME_WAIT_MAX_PASSED = 8 + _bind(router, {"A": 0}) + queue = FCFSWaitingQueue() + queue.add_requests([_item(i, "A") for i in range(1, 1001)]) + queue.add_request(_item(2000, "C")) + peeked = [] + peek = queue.peek_requests + queue.peek_requests = lambda k: peeked.append(k) or peek(k) + for _ in range(3): + assert _round(router, queue, [1, 0, 0, 0], 1) == {} + assert max(peeked) <= 2 * router.HOME_WAIT_MAX_PASSED + assert router._home_wait_age == {i: 3 for i in range(1, 9)} + assert len(queue) == 1001 + + +def test_children_need_their_slots_on_one_rank(): + router = _router(rounds=10) + _bind(router, {"A": 0}) + queue = FCFSWaitingQueue() + queue.add_request(_item(1, "A", children=2)) + assert _round(router, queue, [6, 0, 0, 0], 8) == {} # home has 2 free, needs 3 + assert _round(router, queue, [5, 0, 0, 0], 8) == {1: 0} + + +def test_a_held_request_with_children_ages_while_another_rank_has_a_slot(): + """An n > 1 turn ages whenever another rank has a free slot (where route_requests overflows it), not only when one + rank has all of its slots free, so a steady single-slot stream cannot hold it past home_wait_rounds.""" + router = _router(tp_size=2, rounds=4) + _bind(router, {"A": 0}, tp_size=2, cap=4) + queue = FCFSWaitingQueue() + queue.add_request(_item(1, "A", children=1)) # needs 2 slots + admitted_at = None + for i in range(20): + queue.add_request(_item(100 + i, f"s{i}")) + pos = _round(router, queue, [3, 3], 4, max_new=2) + if 1 in pos: + admitted_at = i + break + assert admitted_at == 4, (admitted_at, router._home_wait_age) + + +def test_unbound_strict_requests_without_room_do_not_stop_the_round(): + """Strict-rank requests whose rank is full are set aside as by the base pop, not counted against the round's + limit on held requests, so a relaxed request behind any number of them is still admitted.""" + router = _router(rounds=4) + queue = FCFSWaitingQueue() + queue.add_requests( + [_item(i, None, target=0, relax=False) for i in range(1, router.HOME_WAIT_MAX_PASSED + 45)] + ) + queue.add_request(_item(5000, None)) + pos = _round(router, queue, [8, 2, 2, 2], 8) + assert list(pos) == [5000] and pos[5000] != 0 + assert len(queue) == router.HOME_WAIT_MAX_PASSED + 44 + assert router._home_wait_age == {} + + +def test_a_request_no_rank_can_take_whole_is_admitted_at_once(): + """1 + children over the per-rank cap fits no home, so it is not held (it would never age): as without home-wait.""" + router = _router(rounds=10) + _bind(router, {"A": 0}) + queue = FCFSWaitingQueue() + queue.add_request(_item(1, "A", children=2)) # needs 3 slots, the cap is 2 + pos = _round(router, queue, [0, 0, 0, 0], 2) + assert list(pos) == [1] + assert len(queue) == 0 + assert router._conv_to_rank["A"] == 0 + + +def test_no_kv_balance_admits_in_queue_order(): + """Warmup and the benchmark fill phase pass kv_balance=False: FIFO, no request held for its home rank.""" + router = _router(rounds=10) + ref = ConversationAwareADPRouter(dist=_dist(4)) + _bind(router, {"A": 0}) + _bind(ref, {"A": 0}) + q1, q2 = FCFSWaitingQueue(), FCFSWaitingQueue() + for queue in (q1, q2): + queue.add_requests([_item(1, "A"), _item(2, "C")]) + states = _states([1, 0, 0, 0]) + got, plan = router.pop_requests(q1, states, 3, 1, kv_balance=False) + want, _ = ref.pop_requests(q2, states, 3, 1, kv_balance=False) + assert [x.id for x in got] == [x.id for x in want] == [1, 2] + assert plan == {} + assert router._home_wait_age == {} + + +def test_strict_explicit_rank_waits_relaxed_one_moves(): + router = _router(rounds=10) + queue = FCFSWaitingQueue() + queue.add_requests( + [_item(1, None, target=2, relax=False), _item(2, None, target=2, relax=True)] + ) + pos = _round(router, queue, [0, 0, 1, 0], 1) + assert 1 not in pos and pos[2] != 2 + assert [x.id for x in queue] == [1] + + +def test_all_ranks_decide_alike(): + """Every rank runs the router on identical inputs; their decisions must match.""" + rng = random.Random(7) + routers = [_router(tp_size=4, rounds=3, tp_rank=r) for r in range(4)] + queues = [FCFSWaitingQueue() for _ in routers] + rid = 0 + for _ in range(60): + for _ in range(rng.randint(0, 5)): + conv = f"c{rng.randint(0, 20)}" + ntok = rng.randint(10, 500) + for q in queues: + q.add_request(_item(rid, conv, num_tokens=ntok)) + rid += 1 + active = [rng.randint(0, 4) for _ in range(4)] + results = [_round(rt, q, active, 4) for rt, q in zip(routers, queues)] + assert all(res == results[0] for res in results) + assert all([x.id for x in q] == [x.id for x in queues[0]] for q in queues) + + +def _closed_loop(home_wait_rounds, seed=3, rounds=400, tp_size=4, cap=3, convs=24, p_done=0.3): + """Each conversation has one request at a time; a rank finishes each of its requests with prob p_done per round. + Saturated: convs > tp_size x cap. Returns (off-home placements, placements).""" + rng = random.Random(seed) + router = ConversationAwareADPRouter(dist=_dist(tp_size), home_wait_rounds=home_wait_rounds) + queue = FCFSWaitingQueue() + rid = 0 + for c in range(convs): + queue.add_request(_item(rid, f"k{c}")) + rid += 1 + running = [[] for _ in range(tp_size)] # conversation ids active per rank + home, off, placed = {}, 0, 0 + for _ in range(rounds): + for r in range(tp_size): # completions: the conversation's next turn re-enters the queue + keep = [] + for conv in running[r]: + if rng.random() < p_done: + queue.add_request(_item(rid, conv)) + rid += 1 + else: + keep.append(conv) + running[r] = keep + active = [len(x) for x in running] + states = _states(active) + free = sum(max(0, cap - a) for a in active) + chosen, plan = router.pop_requests(queue, states, free, cap) + assign, _ = router.route_requests(states, chosen, cap, placement=plan) + for r, lst in assign.items(): + for it in lst: + conv = it.request.py_conversation_params.conversation_id + if conv in home: + placed += 1 + off += home[conv] != r + else: + home[conv] = r + running[r].append(conv) + assert all(len(x) <= cap for x in running) + return off, placed + + +def test_closed_loop_without_home_wait_misplaces_with_it_does_not(): + off_base, placed_base = _closed_loop(None) + off_hw, placed_hw = _closed_loop(10_000) + assert placed_base > 100 and placed_hw > 100 + assert off_base / placed_base > 0.3, ( + f"without home-wait only {off_base}/{placed_base} turns went off-home" + ) + assert off_hw == 0, f"home-wait placed {off_hw}/{placed_hw} turns off-home" diff --git a/tests/unittest/_torch/pyexecutor/test_disagg_receive_ordering.py b/tests/unittest/_torch/pyexecutor/test_disagg_receive_ordering.py index 1e7c2767fddb..92967e1888e2 100644 --- a/tests/unittest/_torch/pyexecutor/test_disagg_receive_ordering.py +++ b/tests/unittest/_torch/pyexecutor/test_disagg_receive_ordering.py @@ -239,6 +239,7 @@ def test_cancelled_admission_releases_event() -> None: manager._request_stats_enabled_ids = set() manager._fresh_pages_filled = {} manager._early_freed_index_requests = set() + manager._defer_close_enabled = False # the default: closes run in free_resources manager.impl = Mock() manager.index_mapper = Mock() diff --git a/tests/unittest/_torch/pyexecutor/test_executor_resource_rebind.py b/tests/unittest/_torch/pyexecutor/test_executor_resource_rebind.py index 2c5fbead781b..5715c839b988 100644 --- a/tests/unittest/_torch/pyexecutor/test_executor_resource_rebind.py +++ b/tests/unittest/_torch/pyexecutor/test_executor_resource_rebind.py @@ -281,6 +281,7 @@ def test_rebind_resets_phase_state_and_profile_windows(executor, monkeypatch): resource_governor_queue=None, hang_detection_timeout=None, enable_kv_pool_rebalance=False, + defer_generation_only_release=True, ) ex.model_engine.enable_attention_dp = False ex.model_engine.mm_encoder_item_scheduling_enabled = False @@ -303,6 +304,7 @@ def test_rebind_resets_phase_state_and_profile_windows(executor, monkeypatch): enable_iter_req_stats=False, iter_perf_stats_interval=1, stream_interval=1, + return_perf_metrics=False, attention_dp_config=None, batch_wait_timeout_ms=0, batch_wait_timeout_iters=0, @@ -370,13 +372,15 @@ def test_rebind_resets_phase_state_and_profile_windows(executor, monkeypatch): for name in bound_fields: assert getattr(ex, name) is getattr(resources, name), name create_waiting_queue.assert_called_once_with( - resources.waiting_queue_policy, gen_admission=ex._gen_admission + resources.waiting_queue_policy, gen_admission=ex._gen_admission, max_wait_s=None ) engine.register_beam_histories_callable.assert_called_once_with( ex.sampler.start_beam_histories ) assert ex.max_num_active_requests == engine.get_max_num_sequences.return_value assert ex.kv_cache_manager is cache + # Only KV cache manager V2 defers the close; this manager is not one. + assert ex._defer_generation_only_release is False assert ex.model_engine is engine and ex.execution_stream is stream assert ex.sample_stream is sample_stream assert ex.finish_sample_event is sample_event diff --git a/tests/unittest/_torch/pyexecutor/test_fetch_request_hint.py b/tests/unittest/_torch/pyexecutor/test_fetch_request_hint.py index 77b49e526770..723693f80c0b 100644 --- a/tests/unittest/_torch/pyexecutor/test_fetch_request_hint.py +++ b/tests/unittest/_torch/pyexecutor/test_fetch_request_hint.py @@ -58,6 +58,8 @@ def _make_stub_executor(rank=0, queued_items=None): stub._has_pending_connector_transfers = lambda: False # No generation-side receive is retiring. stub.disagg = SimpleNamespace(has_retiring_gen_receives=False) + # FCFS waiting queue: no wait cap, so no rank-0 clock. + stub._waiting_queue_needs_clock = False return stub diff --git a/tests/unittest/_torch/pyexecutor/test_gen_preemption.py b/tests/unittest/_torch/pyexecutor/test_gen_preemption.py index 20f074d46ee0..a18fd2f31781 100644 --- a/tests/unittest/_torch/pyexecutor/test_gen_preemption.py +++ b/tests/unittest/_torch/pyexecutor/test_gen_preemption.py @@ -428,6 +428,8 @@ def prepare(ids, paused=()): def executor_for_preemption(p, reqs, scheduler): from tensorrt_llm._torch.pyexecutor.py_executor import PyExecutor + # As the base scheduler: no request lost its KV pages to a failed remote cache level. + scheduler.take_lost_kv_requests.return_value = [] executor = SimpleNamespace( _gen_preemption=p, scheduler=scheduler, @@ -440,6 +442,7 @@ def executor_for_preemption(p, reqs, scheduler): enable_attention_dp=False, enable_batch_waiting=False, _cap_context_by_total_kv_len=lambda requests: requests, + _cancelled_disagg_model_request_ids=set, _maybe_record_hang_diagnostic_phase=Mock(), ) executor._cancelled_disagg_model_request_ids = MethodType( diff --git a/tests/unittest/_torch/pyexecutor/test_hang_detector_kill.py b/tests/unittest/_torch/pyexecutor/test_hang_detector_kill.py index aa3e55e12cb8..250ec8d68e52 100644 --- a/tests/unittest/_torch/pyexecutor/test_hang_detector_kill.py +++ b/tests/unittest/_torch/pyexecutor/test_hang_detector_kill.py @@ -584,6 +584,28 @@ def crash(): assert isinstance(ex._event_loop_error, ValueError) +def test_event_loop_wrapper_runs_crash_protocol_when_dynamo_hook_raises(monkeypatch): + """The worker-thread Dynamo hook runs inside the wrapper's try, so its failure takes the crash path.""" + from tensorrt_llm._torch.pyexecutor import py_executor as pe + + events = [] + _stub_kill_paths(pe, monkeypatch, events) + ex = _bare_executor(pe, monkeypatch, world_size=4, is_shutdown=False) + ex._executor_loop_cleanup = lambda: events.append("cleanup") + ex.event_loop = lambda: events.append("loop") + + def hook(): + raise ValueError("hook") + + ex._apply_dynamo_recompile_limit = hook + + with pytest.raises(ValueError, match="hook"): + ex._event_loop_wrapper() + + assert events == [("watchdog", 4), "cleanup", "cancel", ("kill", 4, 1234.5)] + assert isinstance(ex._event_loop_error, ValueError) + + def test_event_loop_wrapper_hands_both_kill_paths_this_executors_gate(monkeypatch): """Both kill paths must receive THIS executor's delivery gate. diff --git a/tests/unittest/_torch/pyexecutor/test_multimodal_scheduler.py b/tests/unittest/_torch/pyexecutor/test_multimodal_scheduler.py index 9c7ad582d1bf..96a5ecc5f5d8 100644 --- a/tests/unittest/_torch/pyexecutor/test_multimodal_scheduler.py +++ b/tests/unittest/_torch/pyexecutor/test_multimodal_scheduler.py @@ -1014,6 +1014,23 @@ def test_mm_admission_respects_encoder_batch_size(): assert [item.id for item in waiting] == [2] +def test_mm_admission_marks_only_admitted_requests(): + """A request the encoder budget defers goes back unadmitted, keeping its queue position.""" + marked = [] + + class _RecordingQueue(FCFSWaitingQueue): + def mark_admitted(self, requests): + marked.append([item.id for item in requests]) + + waiting = _RecordingQueue([_waiting_item(1, [1, 1]), _waiting_item(2, [1])]) + executor = _executor_for_mm_admission([], max_batch_size=1) + + admitted, _ = executor._pop_from_waiting_queue(waiting, 0) + + assert [item.id for item in admitted] == [1] + assert marked == [[1]] + + def test_item_encoder_slices_and_restores_selected_item_order(): class _Model(MultimodalModelMixin): def encode_multimodal_inputs(self, multimodal_params): diff --git a/tests/unittest/_torch/pyexecutor/test_perf_metrics_manager.py b/tests/unittest/_torch/pyexecutor/test_perf_metrics_manager.py index fa7d4787c7e3..ad30b85808ad 100644 --- a/tests/unittest/_torch/pyexecutor/test_perf_metrics_manager.py +++ b/tests/unittest/_torch/pyexecutor/test_perf_metrics_manager.py @@ -122,3 +122,47 @@ def test_handle_responses_shares_gpu_times_cache(): assert first_call == call([requests[0]], gpu_times_cache=first_call.kwargs["gpu_times_cache"]) assert second_call == call([requests[1]], gpu_times_cache=second_call.kwargs["gpu_times_cache"]) assert first_call.kwargs["gpu_times_cache"] is second_call.kwargs["gpu_times_cache"] + + +def test_timing_side_stream_records_after_the_current_stream(monkeypatch): + import torch + + side = MagicMock() + fork = MagicMock() + event = MagicMock() + monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False) + manager = PerfMetricsManager(enabled=True) + manager._timing_stream = side + manager._fork_event = fork + + with manager.record_perf_events(event, event): + pass + + # One pre-allocated fork event, recorded on the current stream, orders each record. + assert fork.record.call_args_list == [call(), call()] + assert side.wait_event.call_args_list == [call(fork), call(fork)] + side.wait_stream.assert_not_called() + assert event.record.call_args_list == [call(side), call(side)] + + +def test_side_stream_end_event_is_waited_for_before_the_iteration_stats_read(): + start, end = MagicMock(), MagicMock() + start.elapsed_time.return_value = 2.5 + manager = PerfMetricsManager(enabled=True) + end.query.return_value = False + assert manager.try_compute_gpu_elapsed_time_ms(start, end) is None + end.synchronize.assert_not_called() + + manager._timing_stream = MagicMock() + assert manager.try_compute_gpu_elapsed_time_ms(start, end) == 2.5 + end.synchronize.assert_called_once_with() + + +def test_timing_events_stay_on_the_current_stream_by_default(): + event = MagicMock() + manager = PerfMetricsManager(enabled=True) + + with manager.record_perf_events(None, event): + pass + + event.record.assert_called_once_with() diff --git a/tests/unittest/_torch/pyexecutor/test_py_executor.py b/tests/unittest/_torch/pyexecutor/test_py_executor.py index 8e3fe08ebc0c..e878d1b085d0 100644 --- a/tests/unittest/_torch/pyexecutor/test_py_executor.py +++ b/tests/unittest/_torch/pyexecutor/test_py_executor.py @@ -5194,3 +5194,31 @@ def test_disagg_gen_first_step_is_streamed_once(): executor.active_requests = [request] PyExecutor._handle_responses(executor) assert request.create_response.call_count == 1 + + +def test_dynamo_recompile_limit_is_reapplied_on_the_worker_thread(): + """torch keeps each Dynamo config value per thread: the limit the engine sets while it is built does + not reach PyExecutor's worker thread, which applies it again.""" + from tensorrt_llm._torch.pyexecutor.engine.model_setup import DYNAMO_RECOMPILE_LIMIT + + config = torch._dynamo.config + original = config.cache_size_limit + seen = {} + executor = types.SimpleNamespace(_uses_torch_compile=True) + + def worker(): + seen["inherited"] = config.cache_size_limit + PyExecutor._apply_dynamo_recompile_limit(executor) + seen["applied"] = config.cache_size_limit + + config.cache_size_limit = DYNAMO_RECOMPILE_LIMIT + try: + thread = threading.Thread(target=worker) + thread.start() + thread.join() + finally: + config.cache_size_limit = original + assert seen["inherited"] != DYNAMO_RECOMPILE_LIMIT, ( + "Dynamo config is process-wide; drop the hook" + ) + assert seen["applied"] == DYNAMO_RECOMPILE_LIMIT diff --git a/tests/unittest/_torch/pyexecutor/test_py_executor_creator_mla_cache_reuse_sync.py b/tests/unittest/_torch/pyexecutor/test_py_executor_creator_mla_cache_reuse_sync.py index 769517e4ce8d..cb6d3f064311 100644 --- a/tests/unittest/_torch/pyexecutor/test_py_executor_creator_mla_cache_reuse_sync.py +++ b/tests/unittest/_torch/pyexecutor/test_py_executor_creator_mla_cache_reuse_sync.py @@ -155,6 +155,9 @@ def build_managers(self, resources, estimating_kv_cache): _stream=self._execution_stream, ) + def close_remote_donor(self, error=None): + """No remote donation is started (no-op).""" + class _DummyModelEngine: """Mock model engine that exposes attention runtime features and model configuration.""" diff --git a/tests/unittest/_torch/pyexecutor/test_remote_tail_adp_phase.py b/tests/unittest/_torch/pyexecutor/test_remote_tail_adp_phase.py index 283b90da24eb..6483944df725 100644 --- a/tests/unittest/_torch/pyexecutor/test_remote_tail_adp_phase.py +++ b/tests/unittest/_torch/pyexecutor/test_remote_tail_adp_phase.py @@ -623,6 +623,7 @@ def reserve(resources, draft_len): enable_overlap_headroom=False, mm_encoder_item_scheduling_enabled=False, spec_decode_fast_paths=False, + uses_torch_compile=False, cuda_graph_runner=runner, model=SimpleNamespace( model=SimpleNamespace( @@ -638,6 +639,7 @@ def reserve(resources, draft_len): enable_iter_req_stats=False, iter_perf_stats_interval=1, stream_interval=1, + return_perf_metrics=False, attention_dp_config=None, kv_connector_config=None, batch_wait_timeout_ms=0, diff --git a/tests/unittest/_torch/pyexecutor/test_request_utils.py b/tests/unittest/_torch/pyexecutor/test_request_utils.py index ebb9da1efb47..0bd8ed7700e8 100644 --- a/tests/unittest/_torch/pyexecutor/test_request_utils.py +++ b/tests/unittest/_torch/pyexecutor/test_request_utils.py @@ -942,7 +942,16 @@ class _SingleRoundDist: back on the root, ``received`` stands for what a non-root rank gets. """ - def __init__(self, rank, *, world_size=2, has_pp=False, supports=True, received=None): + def __init__( + self, + rank, + *, + world_size=2, + has_pp=False, + supports=True, + received=None, + received_header=None, + ): self.rank = rank self.world_size = world_size self.tp_size = world_size @@ -955,7 +964,10 @@ def __init__(self, rank, *, world_size=2, has_pp=False, supports=True, received= self.is_last_pp_rank = True self.supports_single_round_broadcast = supports self._received = received + self._received_header = received_header self.calls = [] + # Collectives the single-round transport spends: the size word, plus the payload when there is one. + self.collectives = 0 def tp_cp_broadcast(self, obj, root=0, **kwargs): self.calls.append(("tp_cp_broadcast", obj)) @@ -969,7 +981,15 @@ def send_object(self, *args, **kwargs): def broadcast_or_none(self, obj, root=0): self.calls.append(("broadcast_or_none", obj)) - return obj if self.rank == root else self._received + received = obj if self.rank == root else self._received + self.collectives += 1 + (received is not None) + return received + + def broadcast_or_none_with_header(self, obj, header, root=0): + self.calls.append(("broadcast_or_none_with_header", obj, list(header))) + received = obj if self.rank == root else self._received + self.collectives += 1 + (received is not None) + return (list(header) if self.rank == root else self._received_header), received def broadcast(self, obj, root=0, prefer_cpu=False): self.calls.append(("broadcast", obj, prefer_cpu)) @@ -1024,6 +1044,46 @@ def test_single_round_non_root_receives_payload_or_nothing(): assert RequestBroadcaster(dist, MagicMock()).broadcast([]) == [] +def test_single_round_with_a_synchronized_clock_keeps_one_collective_per_empty_iteration(): + """waiting_queue_max_wait_s (sync_clock) on a single-round transport: rank 0's clock and aux ride in the size + word's header, so an empty iteration still costs one collective and one with requests two.""" + dist = _SingleRoundDist(rank=0) + broadcaster = RequestBroadcaster(dist, MagicMock(), sync_clock=True) + broadcaster.aux = 0.25 + with patch("tensorrt_llm._torch.pyexecutor.request_utils.time.monotonic", return_value=12.5): + assert broadcaster.broadcast([]) == [] + assert dist.collectives == 1 + assert dist.calls == [("broadcast_or_none_with_header", None, [12_500_000, 250_000])] + assert (broadcaster.rank0_now, broadcaster.rank0_aux) == (12.5, 0.25) + + items = [_make_broadcast_item(3)] + assert broadcaster.broadcast(items) == items + assert dist.collectives == 3 + + # A non-root rank reads the clock from the header, with or without requests. + peer = _SingleRoundDist(rank=1, received=None, received_header=[7_000_000, -1]) + broadcaster = RequestBroadcaster(peer, MagicMock(), sync_clock=True) + assert broadcaster.broadcast([]) == [] + assert (broadcaster.rank0_now, broadcaster.rank0_aux, peer.collectives) == (7.0, None, 1) + + +def test_the_generic_header_broadcast_rides_with_the_payload_flag(): + """Transports without a single round send the header with the "anything?" flag: no extra round.""" + from tensorrt_llm._torch.distributed.communicator import Distributed + + calls = [] + fake = SimpleNamespace( + broadcast_int64=lambda values, root=0: calls.append(("int64", list(values))) + or np.asarray(values), + broadcast=lambda obj, root=0: calls.append(("object", obj)) or obj, + ) + assert Distributed.broadcast_or_none_with_header(fake, None, [5, -1]) == ([5, -1], None) + assert calls == [("int64", [0, 5, -1])] + calls.clear() + assert Distributed.broadcast_or_none_with_header(fake, ["r"], [6, 2]) == ([6, 2], ["r"]) + assert calls == [("int64", [1, 6, 2]), ("object", ["r"])] + + @pytest.mark.parametrize( "kwargs, reason", [ @@ -1687,7 +1747,7 @@ def _build(flag): class TestBroadcasterClock: """RequestBroadcaster(sync_clock=True): rank 0's clock and aux ride along - with the request count.""" + with the request count, or in the single-round envelope.""" def _dist(self, rank, world_size=2): dist = Mock() @@ -1712,17 +1772,39 @@ def test_default_probe_unchanged(self): assert list(values) == [0] assert b.rank0_now is None - def test_sync_clock_keeps_the_count_probe(self): - """The single-round broadcast has no room for the clock.""" - for sync_clock, probes in ((False, 0), (True, 1)): + def test_sync_clock_rides_the_single_round(self): + """With the single-round transport, the clock and aux travel in the size word's header: one call, no count + probe, and no payload on an empty iteration.""" + items = [_make_broadcast_item(3)] + for received, want in ( + (([1_000_000, 170_000], None), []), + (([2_000_000, -1], items), items), + ): dist = self._dist(rank=1) dist.supports_single_round_broadcast = True - dist.broadcast_or_none = Mock(return_value=None) - dist.broadcast_int64 = Mock(return_value=[0, 1_000_000, -1]) - b = RequestBroadcaster(dist, self._hang_detector(), sync_clock=sync_clock) - assert b.broadcast([]) == [] - assert dist.broadcast_int64.call_count == probes - assert dist.broadcast_or_none.call_count == 1 - probes + dist.broadcast_or_none_with_header = Mock(return_value=received) + dist.broadcast_int64 = Mock() + b = RequestBroadcaster(dist, self._hang_detector(), sync_clock=True) + b.aux = 9.0 # ignored off rank 0 + assert b.broadcast([]) == want + dist.broadcast_int64.assert_not_called() + assert dist.broadcast_or_none_with_header.call_count == 1 + assert dist.broadcast_or_none_with_header.call_args.args[0] is None + header = received[0] + assert b.rank0_now == pytest.approx(header[0] / 1e6) + assert b.rank0_aux == (None if header[1] < 0 else pytest.approx(0.17)) + + def test_sync_clock_single_round_root_sends_clock_every_iteration(self): + items = [_make_broadcast_item(1)] + for new_requests, payload in (([], None), (items, items)): + dist = _SingleRoundDist(rank=0) + b = RequestBroadcaster(dist, MagicMock(), sync_clock=True) + b.aux = 0.25 + assert b.broadcast(new_requests) == new_requests + assert len(dist.calls) == 1 + kind, sent, (now_us, aux_us) = dist.calls[0] + assert kind == "broadcast_or_none_with_header" and aux_us == 250_000 and sent == payload + assert b.rank0_now == pytest.approx(now_us / 1e6) and b.rank0_aux == pytest.approx(0.25) def test_default_probe_pp_forwards_count(self): dist = self._dist(rank=4, world_size=8) diff --git a/tests/unittest/_torch/pyexecutor/test_steady_spec_prepare.py b/tests/unittest/_torch/pyexecutor/test_steady_spec_prepare.py index e771351d972b..d9cadf289b88 100644 --- a/tests/unittest/_torch/pyexecutor/test_steady_spec_prepare.py +++ b/tests/unittest/_torch/pyexecutor/test_steady_spec_prepare.py @@ -33,7 +33,8 @@ SLOTS, MAX_TOKENS, MAX_DRAFT, BATCH = 8, 64, 8, 4 -def _buffers(): +def _buffers(batch: int = BATCH) -> dict: + """The staging kernel's destination buffers, the per-request ones sized for ``batch`` requests.""" i32 = dict(dtype=torch.int32, device="cuda") return dict( input_ids=torch.full((MAX_TOKENS,), -1, **i32), @@ -41,11 +42,11 @@ def _buffers(): prev_batch_idx=torch.full((MAX_TOKENS,), -1, **i32), prev_pos_idx=torch.full((MAX_TOKENS,), -1, **i32), prev_pos_offsets=torch.zeros((MAX_TOKENS,), **i32), - prev_kv_offsets=torch.zeros((BATCH,), **i32), + prev_kv_offsets=torch.zeros((batch,), **i32), positions=torch.full((MAX_TOKENS,), -1, **i32), mrope_positions=torch.full((3, 1, MAX_TOKENS), -1, **i32), gather_ids=torch.full((MAX_TOKENS,), -1, **i32), - kv_lens_cuda=torch.full((BATCH,), -1, **i32), + kv_lens_cuda=torch.full((batch,), -1, **i32), ) @@ -127,6 +128,142 @@ def test_staging_kernel_matches_full_pass(mrope, b, t, block, host_slab): assert torch.equal(static_pos[..., :n], pos_ref) +@pytest.mark.parametrize("host_slab", [False, True]) +@pytest.mark.parametrize("b,t", [(1, 7), (5, 7), (3, 2)]) +def test_staged_rng_matches_uploaded_rng(b, t, host_slab): + """With an RNG slab the kernel writes SpecMetadata's Philox buffers exactly as + _populate_request_rng_state uploads them: request_* per request, and row j of request r as + (seed_r, offset_r + j * _RNG_SLOT_SPAN).""" + from tensorrt_llm._torch.speculative.interface import _RNG_SLOT_SPAN + + gen = torch.Generator().manual_seed(7 * b + t) + dev = _device_tensors(gen) + slots = torch.randperm(SLOTS, generator=gen)[:b].tolist() + positions = [p for base in range(b) for p in range(100 * base, 100 * base + t)] + seeds = torch.randint(0, 1 << 62, (b,), generator=gen, dtype=torch.int64).tolist() + offsets = torch.randint(0, 1 << 40, (b,), generator=gen, dtype=torch.int64).tolist() + expected_seeds = torch.tensor([s for s in seeds for _ in range(t)], dtype=torch.int64) + expected_offsets = torch.tensor( + [o + j * _RNG_SLOT_SPAN for o in offsets for j in range(t)], dtype=torch.int64 + ) + + rng_buffers = tuple( + torch.full((MAX_TOKENS,), -1, dtype=torch.int64, device="cuda") for _ in range(4) + ) + rng_slab = torch.tensor(seeds + offsets, dtype=torch.int64).pin_memory() + slab = torch.tensor(slots + positions, dtype=torch.int32).pin_memory() + stage_steady_inputs( + slab if host_slab else slab.cuda(), + b, + t, + dev, + # Sized for this case's requests (5 > BATCH). + **{ + k: v + for k, v in _buffers(batch=b).items() + if k not in ("mrope_positions", "kv_lens_cuda") + }, + mrope_positions=None, + rng_slab=rng_slab if host_slab else rng_slab.cuda(), + rng_buffers=rng_buffers, + rng_span=_RNG_SLOT_SPAN, + ) + torch.cuda.synchronize() + request_seeds, request_offsets, row_seeds, row_offsets = (x.cpu() for x in rng_buffers) + assert request_seeds[:b].tolist() == seeds and request_offsets[:b].tolist() == offsets + assert torch.equal(row_seeds[: b * t], expected_seeds) + assert torch.equal(row_offsets[: b * t], expected_offsets) + # Nothing past the batch is written. + assert int(request_seeds[b]) == -1 and int(row_seeds[b * t]) == -1 + + +def _rng_meta(): + """Just enough of SpecMetadata to run _populate_request_rng_state.""" + from tensorrt_llm._torch.speculative.interface import SpecMetadata + + meta = types.SimpleNamespace( + is_all_greedy_sample=False, + max_num_requests=BATCH, + request_seeds=None, + request_offsets=None, + seeds=None, + offsets=None, + temperatures=None, + pack_rng_uploads=False, + _rng_window_counter={}, + _rng_slot_owner={}, + rng_accept_slot=3, + ) + meta._take_rng_window_offsets = lambda *args: SpecMetadata._take_rng_window_offsets(meta, *args) + return meta + + +@pytest.mark.parametrize("uniform", [True, False], ids=["deferred", "uploaded"]) +def test_populate_before_stage_matches_the_upload(uniform): + """The steady MTP step populates the sampling parameters before staging (defer_rows = its rows per request) and + the staging kernel writes the Philox buffers from the deferred values: over consecutive steps of seeded and + unseeded requests, the same buffers and window counters as the uploads of the full pass. A batch whose requests' + rows differ is uploaded.""" + from tensorrt_llm._torch.speculative.interface import _RNG_SLOT_SPAN, SpecMetadata + + t = 4 + seeds = [None, 123, None, (1 << 63) + 5] + requests = [ + types.SimpleNamespace( + sampling_config=types.SimpleNamespace(seed=seed), + py_seq_slot=slot, + py_request_id=100 + slot, + ) + for slot, seed in zip((5, 2, 7, 0), seeds) + ] + b = len(requests) + rows = [t] * b if uniform else [t, 1, t, t] + normalized = [(1.0, 0, 1.0, 0.0, n) for n in rows] + staged, uploaded = _rng_meta(), _rng_meta() + dev = _device_tensors(torch.Generator().manual_seed(3)) + slab = torch.tensor([0, 1, 2, 3] + list(range(b * t)), dtype=torch.int32, device="cuda") + for step in range(3): + deferred = SpecMetadata._populate_request_rng_state( + staged, requests, normalized, defer_rows=t + ) + assert SpecMetadata._populate_request_rng_state(uploaded, requests, normalized) is None + if uniform: + request_seeds, request_offsets = deferred + stage_steady_inputs( + slab, + b, + t, + dev, + **{ + k: v + for k, v in _buffers().items() + if k not in ("mrope_positions", "kv_lens_cuda") + }, + mrope_positions=None, + rng_slab=torch.tensor( + request_seeds + request_offsets, dtype=torch.int64, device="cuda" + ), + rng_buffers=( + staged.request_seeds, + staged.request_offsets, + staged.seeds, + staged.offsets, + ), + rng_span=_RNG_SLOT_SPAN, + ) + else: + assert deferred is None + torch.cuda.synchronize() + for name, n in ( + ("request_seeds", b), + ("request_offsets", b), + ("seeds", sum(rows)), + ("offsets", sum(rows)), + ): + assert torch.equal(getattr(staged, name)[:n], getattr(uploaded, name)[:n]), (step, name) + assert staged._rng_window_counter == uploaded._rng_window_counter + + def _manager(pools=2, rows=4, max_blocks=16): m = object.__new__(KVCacheManagerV2) m.host_kv_cache_block_offsets = torch.zeros(pools, rows, 2, max_blocks, dtype=torch.int32) diff --git a/tests/unittest/_torch/pyexecutor/test_waiting_queue.py b/tests/unittest/_torch/pyexecutor/test_waiting_queue.py index 73821f2f6d61..4b967bf1f1e5 100644 --- a/tests/unittest/_torch/pyexecutor/test_waiting_queue.py +++ b/tests/unittest/_torch/pyexecutor/test_waiting_queue.py @@ -18,23 +18,33 @@ This module tests the waiting queue functionality including: - FCFSWaitingQueue operations - PriorityWaitingQueue operations +- AgingPriorityWaitingQueue operations - WaitingQueue abstract interface - create_waiting_queue factory function """ -from unittest.mock import Mock +from unittest.mock import Mock, patch import pytest +import tensorrt_llm.llmapi.llm_args as llm_args_mod from tensorrt_llm._torch.pyexecutor.executor_request_queue import RequestQueueItem from tensorrt_llm._torch.pyexecutor.scheduler import ( FCFSWaitingQueue, WaitingQueue, create_waiting_queue, ) -from tensorrt_llm._torch.pyexecutor.scheduler.waiting_queue import PriorityWaitingQueue +from tensorrt_llm._torch.pyexecutor.scheduler.waiting_queue import ( + AgingPriorityWaitingQueue, + PriorityWaitingQueue, +) from tensorrt_llm.executor.request import DEFAULT_REQUEST_PRIORITY -from tensorrt_llm.llmapi.llm_args import WaitingQueuePolicy +from tensorrt_llm.llmapi.llm_args import ( + CacheTransceiverConfig, + SchedulerConfig, + TorchLlmArgs, + WaitingQueuePolicy, +) pytestmark = pytest.mark.cpu_only @@ -578,6 +588,37 @@ def _no_full_sort(self): peeked = [item.id for item in q.peek_requests(4)] assert peeked == [6, 13, 20, 27] + def test_peek_requests_reads_only_the_entries_it_returns_and_their_children(self): + """A home-wait round re-peeks a growing window: each peek walks O(k) heap entries, not the whole heap, and + matches the pop order for any k.""" + import random + + rng = random.Random(3) + q = PriorityWaitingQueue() + for i in range(5000): + q.add_request( + create_priority_request_item(i, priority=rng.choice([0.1, 0.3, 0.5, 0.7])) + ) + q.prepend_requests([create_priority_request_item(9000 + i, priority=0.5) for i in range(3)]) + order = [e[2].id for e in sorted(q._heap)] + for k in (0, 1, 7, 256, 5003, 6000): + assert [item.id for item in q.peek_requests(k)] == order[:k] + + class _Counting(list): + reads = 0 + + def __getitem__(self, index): + _Counting.reads += 1 + return super().__getitem__(index) + + def __iter__(self): + _Counting.reads += len(self) + return super().__iter__() + + q._heap = _Counting(q._heap) + assert [item.id for item in q.peek_requests(16)] == order[:16] + assert _Counting.reads <= 1 + 2 * 16 + def test_iter_does_not_consume_items(self): """Iterating over the queue does not remove items.""" q = PriorityWaitingQueue() @@ -590,3 +631,265 @@ def test_iter_does_not_consume_items(self): def test_is_waiting_queue_subclass(self): """PriorityWaitingQueue is a WaitingQueue.""" assert isinstance(PriorityWaitingQueue(), WaitingQueue) + + +def create_aging_request_item( + request_id: int, priority: float, arrival=None, orig_arrival=None +) -> RequestQueueItem: + """Create a mock RequestQueueItem with a priority and rank 0's arrival stamps.""" + mock_request = Mock() + mock_request.priority = priority + item = RequestQueueItem(request_id, mock_request) + item.admit_arrival = arrival + item.admit_orig_arrival = orig_arrival + return item + + +def _started(queue: AgingPriorityWaitingQueue, now: float = 0.0) -> AgingPriorityWaitingQueue: + queue.set_now(now) + return queue + + +class TestAgingPriorityWaitingQueue: + """Tests for AgingPriorityWaitingQueue (waiting_queue_policy=priority with a wait cap).""" + + def test_highest_priority_first_ties_in_arrival_order(self): + queue = _started(AgingPriorityWaitingQueue(max_wait_s=60.0)) + queue.add_requests( + [ + create_aging_request_item(1, 0.3, 0.0), + create_aging_request_item(2, 0.9, 0.0), + create_aging_request_item(3, 0.1, 0.0), + create_aging_request_item(4, 0.9, 0.0), + ] + ) + assert [item.id for item in queue] == [2, 4, 1, 3] + assert [item.id for item in queue.peek_requests(2)] == [2, 4] + assert queue.peek_request().id == 2 + assert [queue.pop_request().id for _ in range(4)] == [2, 4, 1, 3] + + def test_same_order_as_priority_queue_until_a_request_ages(self): + """Below the cap the order is PriorityWaitingQueue's, including its admission groups.""" + priorities = [0.5, 0.2, 0.9, 0.2, 0.7, 0.9, 0.5] + aging = _started(AgingPriorityWaitingQueue(max_wait_s=60.0)) + stock = PriorityWaitingQueue() + for i, p in enumerate(priorities): + aging.add_request(create_aging_request_item(i, p, 0.0)) + stock.add_request(create_aging_request_item(i, p, 0.0)) + assert [item.id for item in aging] == [item.id for item in stock] + window = aging.peek_requests(len(priorities)) + assert aging.admission_groups(window) == stock.admission_groups(stock.peek_requests(7)) + assert [aging.pop_request().id for _ in priorities] == [ + stock.pop_request().id for _ in priorities + ] + + def test_put_back_keeps_arrival_order(self): + queue = _started(AgingPriorityWaitingQueue(max_wait_s=60.0)) + queue.add_requests( + [create_aging_request_item(1, 0.5, 0.0), create_aging_request_item(2, 0.5, 0.0)] + ) + first = queue.pop_request() + queue.add_request(create_aging_request_item(3, 0.5, 0.0)) + queue.prepend_request(first) + assert [item.id for item in queue] == [1, 2, 3] + + @pytest.mark.parametrize("now, first", [(59.0, 2), (60.0, 1)]) + def test_wait_cap_goes_ahead_oldest_first(self, now, first): + queue = _started(AgingPriorityWaitingQueue(max_wait_s=60.0)) + queue.add_requests( + [create_aging_request_item(1, 0.1, 0.0), create_aging_request_item(2, 0.9, 30.0)] + ) + queue.set_now(now) + assert queue.pop_request().id == first + + def test_wait_cap_ages_from_the_original_arrival(self): + """In disaggregated serving the cap counts from the orchestrator's arrival, which the + context server's KV transfer timeout follows.""" + queue = AgingPriorityWaitingQueue(max_wait_s=60.0) + queue.set_now(50.0) + queue.add_requests( + [ + create_aging_request_item(1, 0.2, arrival=50.0, orig_arrival=0.0), + create_aging_request_item(2, 0.1, arrival=40.0, orig_arrival=-5.0), + create_aging_request_item(3, 0.9, arrival=50.0, orig_arrival=45.0), + ] + ) + assert queue.peek_request().id == 3 + queue.set_now(60.0) + # Both aged ones go first, oldest original arrival first. + assert [item.id for item in queue] == [2, 1, 3] + assert [queue.pop_request().id for _ in range(3)] == [2, 1, 3] + + def test_request_aged_when_added_or_put_back(self): + queue = _started(AgingPriorityWaitingQueue(max_wait_s=60.0), 100.0) + queue.add_requests( + [create_aging_request_item(1, 0.9, 90.0), create_aging_request_item(2, 0.1, 0.0)] + ) + aged = queue.pop_request() + assert aged.id == 2 + queue.prepend_request(aged) + assert [item.id for item in queue] == [2, 1] + + def test_cap_needs_clock(self): + queue = AgingPriorityWaitingQueue(max_wait_s=60.0) + queue.add_request(create_aging_request_item(1, 0.5, 0.0)) + with pytest.raises(RuntimeError): + queue.pop_request() + + @pytest.mark.parametrize("bad", [None, 0.0, -1.0, float("inf"), float("nan")]) + def test_cap_must_be_positive_and_finite(self, bad): + with pytest.raises((ValueError, TypeError)): + AgingPriorityWaitingQueue(max_wait_s=bad) + + def test_admission_groups_keep_aged_requests_in_order(self): + """Out-of-order admission may reorder only requests that have not aged and share a priority.""" + queue = _started(AgingPriorityWaitingQueue(max_wait_s=60.0)) + queue.add_requests( + [ + create_aging_request_item(1, 0.1, 0.0), + create_aging_request_item(2, 0.2, 1.0), + create_aging_request_item(3, 0.9, 50.0), + create_aging_request_item(4, 0.9, 50.0), + create_aging_request_item(5, 0.5, 50.0), + ] + ) + queue.set_now(61.0) + window = queue.peek_requests(5) + assert [item.id for item in window] == [1, 2, 3, 4, 5] + assert queue.admission_groups(window) == [0, 1, 2, 2, 3] + assert queue.admission_groups(window[2:]) == [0, 0, 1] + + def test_unadmitted_request_keeps_its_arrival_order(self): + """A popped request put back after a later admission step keeps its place.""" + queue = _started(AgingPriorityWaitingQueue(max_wait_s=60.0)) + queue.add_requests([create_aging_request_item(i, 0.5, 0.0) for i in range(1, 4)]) + popped = [queue.pop_request() for _ in range(2)] + queue.mark_admitted(popped[:1]) + queue.add_request(create_aging_request_item(4, 0.5, 0.0)) + queue.prepend_requests(popped[1:]) + assert [item.id for item in queue] == [2, 3, 4] + + def test_put_back_every_iteration_adds_no_entries(self, monkeypatch): + """Requests that admission rejects and puts back every iteration (strict-rank attention + DP) reuse their heap entries, so the heaps stay bounded without compaction and the + requests still age once, oldest first.""" + queue = _started(AgingPriorityWaitingQueue(max_wait_s=60.0)) + queue.add_requests( + [create_aging_request_item(i, 0.9 - 0.1 * i, float(3 - i)) for i in range(4)] + ) + compactions = [] + compact = AgingPriorityWaitingQueue._compact + monkeypatch.setattr( + AgingPriorityWaitingQueue, + "_compact", + lambda self: compactions.append(len(self)) or compact(self), + ) + for step in range(1000): + queue.set_now(3.0 + step * 0.01) + popped = [queue.pop_request() for _ in range(4)] + assert [item.id for item in popped] == [0, 1, 2, 3] + queue.prepend_requests(popped) + assert len(queue._priority_heap) == 4 + assert len(queue._arrival_heap) == 4 + assert compactions == [] + queue.set_now(63.0) + assert [item.id for item in queue] == [3, 2, 1, 0] + assert [queue.pop_request().id for _ in range(4)] == [3, 2, 1, 0] + + def test_peek_requests_does_not_sort_the_queue(self, monkeypatch): + queue = _started(AgingPriorityWaitingQueue(max_wait_s=60.0)) + queue.add_requests( + [create_aging_request_item(i, 1.0 - i / 1000.0, float(i)) for i in range(1000)] + ) + queue.set_now(62.0) + + def _no_full_sort(self): + raise AssertionError("peek_requests must not sort the whole queue") + + monkeypatch.setattr(AgingPriorityWaitingQueue, "__iter__", _no_full_sort) + assert [item.id for item in queue.peek_requests(5)] == [0, 1, 2, 3, 4] + + def test_never_reads_max_tokens(self): + """The order comes from the priority alone (the orchestrator's predicted output length).""" + + class NoMaxTokens: + priority = 0.5 + + @property + def max_tokens(self): + raise AssertionError("max_tokens must not be read") + + queue = _started(AgingPriorityWaitingQueue(max_wait_s=60.0)) + for i in range(3): + item = RequestQueueItem(i, NoMaxTokens()) + item.admit_arrival = 0.0 + queue.add_request(item) + queue.set_now(100.0) + assert [queue.pop_request().id for _ in range(3)] == [0, 1, 2] + + def test_remove_by_ids(self): + queue = _started(AgingPriorityWaitingQueue(max_wait_s=60.0)) + queue.add_requests([create_aging_request_item(i, 1.0 / i, 0.0) for i in range(1, 5)]) + queue.set_now(60.0) + queue.remove_by_ids({2, 3}) + assert len(queue) == 2 and [item.id for item in queue] == [1, 4] + assert [queue.pop_request().id for _ in range(2)] == [1, 4] + assert not queue + + def test_factory(self): + queue = create_waiting_queue(WaitingQueuePolicy.PRIORITY, max_wait_s=120.0) + assert isinstance(queue, AgingPriorityWaitingQueue) + assert queue.max_wait_s == 120.0 + # Without a cap the policy keeps the stock queue. + assert type(create_waiting_queue(WaitingQueuePolicy.PRIORITY)) is PriorityWaitingQueue + with pytest.raises(ValueError, match="priority"): + create_waiting_queue(WaitingQueuePolicy.FCFS, max_wait_s=60.0) + + def test_factory_refuses_cap_with_gen_admission(self): + gen_admission = Mock(enabled=True) + gen_admission.describe.return_value = "p90" + with pytest.raises(ValueError, match="GEN admission"): + create_waiting_queue( + WaitingQueuePolicy.PRIORITY, gen_admission=gen_admission, max_wait_s=60.0 + ) + + def test_scheduler_config_max_wait(self): + priority = WaitingQueuePolicy.PRIORITY + assert SchedulerConfig().waiting_queue_max_wait_s is None + config = SchedulerConfig(waiting_queue_policy=priority, waiting_queue_max_wait_s=120.0) + assert config.waiting_queue_max_wait_s == 120.0 + SchedulerConfig(**config.model_dump()) + SchedulerConfig(**SchedulerConfig().model_dump()) + with pytest.raises(ValueError, match="priority"): + SchedulerConfig( + waiting_queue_policy=WaitingQueuePolicy.FCFS, waiting_queue_max_wait_s=60.0 + ) + with pytest.raises(ValueError): + SchedulerConfig(waiting_queue_policy="shortest_decode_first") + for bad in (float("inf"), float("nan"), 0.0): + with pytest.raises(ValueError): + SchedulerConfig(waiting_queue_policy=priority, waiting_queue_max_wait_s=bad) + + @pytest.mark.parametrize( + "max_wait_s, timeout_ms, warns", + [(60.0, 60000, False), (30.0, 60000, False), (120.0, 60000, True), (60.0, 30000, True)], + ids=["defaults", "shorter_cap", "longer_cap", "shorter_timeout"], + ) + def test_max_wait_above_transfer_timeout_warns(self, tmp_path, max_wait_s, timeout_ms, warns): + """Only a cap longer than the KV transfer timeout warns: the defaults are equal and stay quiet.""" + with patch.object(llm_args_mod.logger, "warning") as warning: + TorchLlmArgs( + model=tmp_path, + gpus_per_node=1, + scheduler_config=SchedulerConfig( + waiting_queue_policy=WaitingQueuePolicy.PRIORITY, + waiting_queue_max_wait_s=max_wait_s, + ), + cache_transceiver_config=CacheTransceiverConfig( + backend="NIXL", kv_transfer_timeout_ms=timeout_ms + ), + ) + warned = any( + "waiting_queue_max_wait_s" in str(call.args[0]) for call in warning.call_args_list + ) + assert warned == warns diff --git a/tests/unittest/_torch/speculative/hw_agnostic/test_draft_sampler_overrides.py b/tests/unittest/_torch/speculative/hw_agnostic/test_draft_sampler_overrides.py new file mode 100644 index 000000000000..eaec15693f4b --- /dev/null +++ b/tests/unittest/_torch/speculative/hw_agnostic/test_draft_sampler_overrides.py @@ -0,0 +1,165 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""The draft samplers' contract between SpecWorkerBase and its overrides. + +``sample_draft_tokens`` hands ``tokens_out`` to ``greedy_sample_draft_with_tp_gather`` and the +draft loops hand ``out`` to ``sample_draft_tokens``; an override with an older parameter list +raises TypeError at the first draft step. The signature check reads the source of every +override in ``tensorrt_llm/`` (modeling_v2 targets included, whose GPU-only modules it does not +import). +""" + +import ast +from pathlib import Path +from types import SimpleNamespace + +import pytest +import torch +from torch import nn + +from tensorrt_llm._torch.speculative.interface import SpecWorkerBase + +pytestmark = pytest.mark.cpu_only + +_PKG = Path(__file__).resolve().parents[5] / "tensorrt_llm" +_BASE = _PKG / "_torch/speculative/interface.py" +_METHODS = ("greedy_sample_draft_with_tp_gather", "sample_draft_tokens") + + +def _params(fn: ast.FunctionDef) -> list[tuple[str, str]]: + a = fn.args + params = [(p.arg, "positional") for p in a.posonlyargs + a.args] + params += [(p.arg, "keyword") for p in a.kwonlyargs] + if a.vararg is not None: + params.append((a.vararg.arg, "*")) + if a.kwarg is not None: + params.append((a.kwarg.arg, "**")) + return params + + +def _definitions(path: Path) -> list[tuple[str, str, ast.FunctionDef]]: + """(class, method, def) for every draft-sampler method defined in a class of ``path``.""" + found = [] + for node in ast.walk(ast.parse(path.read_text())): + if isinstance(node, ast.ClassDef): + for item in node.body: + if isinstance(item, ast.FunctionDef) and item.name in _METHODS: + found.append((node.name, item.name, item)) + return found + + +def _defaulted(fn: ast.FunctionDef) -> set[str]: + """Parameters of ``fn`` that callers may leave out (a default, or ``*args`` / ``**kwargs``).""" + a = fn.args + positional = a.posonlyargs + a.args + names = {p.arg for p in positional[len(positional) - len(a.defaults) :]} + names |= {p.arg for p, d in zip(a.kwonlyargs, a.kw_defaults) if d is not None} + names |= {p.arg for p in (a.vararg, a.kwarg) if p is not None} + return names + + +def _takes_the_base_call(fn: ast.FunctionDef, base: list[tuple[str, str]]) -> bool: + """Every base parameter, by name and kind, with the base positional ones first and in the base order; any + extra parameter is defaulted. Then every call the base takes reaches the override unchanged.""" + params = _params(fn) + positional = [name for name, kind in params if kind == "positional"] + base_positional = [name for name, kind in base if kind == "positional"] + extra = {name for name, _ in params} - {name for name, _ in base} + return ( + set(base) <= set(params) + and positional[: len(base_positional)] == base_positional + and extra <= _defaulted(fn) + ) + + +def test_every_draft_sampler_override_takes_the_base_parameters() -> None: + base = { + method: _params(fn) for cls, method, fn in _definitions(_BASE) if cls == "SpecWorkerBase" + } + assert set(base) == set(_METHODS) + overrides = [] + for path in sorted(_PKG.rglob("*.py")): + for cls, method, fn in _definitions(path): + if path == _BASE and cls == "SpecWorkerBase": + continue + overrides.append((path.relative_to(_PKG).as_posix(), cls)) + assert _takes_the_base_call(fn, base[method]), (path, cls, method) + # Guard against a scan that finds nothing. + assert overrides + + +_BASE_SIGNATURE = "(self, logits, meta=None, tokens_out=None)" + + +@pytest.mark.parametrize( + "signature,compatible", + [ + (_BASE_SIGNATURE, True), + ("(self, logits, meta=None, tokens_out=None, lane=0)", True), # extra defaulted parameter + ("(self, logits, meta=None, tokens_out=None, **kw)", True), + ("(self, logits, meta=None)", False), # no tokens_out + ("(self, logits, meta=None, tokens_out=None, *, lane)", False), # extra required parameter + ("(self, meta, logits, tokens_out=None)", False), # reordered + ], +) +def test_the_signature_check_accepts_compatible_extensions(signature, compatible) -> None: + """An override may add defaulted parameters (or ``**kwargs``) to the base's, not drop or reorder them.""" + + def fn(sig: str) -> ast.FunctionDef: + return ast.parse(f"def f{sig}: pass").body[0] + + assert _takes_the_base_call(fn(signature), _params(fn(_BASE_SIGNATURE))) is compatible + + +def _worker(cls: type) -> SpecWorkerBase: + w = cls.__new__(cls) + nn.Module.__init__(w) # attribute storage only; the worker's own init needs a model config + w.mapping = SimpleNamespace(tp_size=1, tp_rank=0, enable_attention_dp=False) + w._d2t = None + return w + + +class _Worker(SpecWorkerBase): + """The base samplers on a concrete worker.""" + + def _forward_impl(self, *args, **kwargs): + raise NotImplementedError + + @property + def max_draft_len(self) -> int: + return 1 + + +class _OwnTensorWorker(_Worker): + """An override that ignores ``tokens_out`` and returns a tensor of its own.""" + + def greedy_sample_draft_with_tp_gather( + self, logits, spec_metadata=None, mapping_lm_head_tp=None, tokens_out=None + ): + return logits.argmax(dim=-1).to(torch.int32) + + +class _ThreeArgWorker(_Worker): + """An override without the ``tokens_out`` parameter (out-of-tree subclasses).""" + + def greedy_sample_draft_with_tp_gather( + self, logits, spec_metadata=None, mapping_lm_head_tp=None + ): + return logits.argmax(dim=-1).to(torch.int32) + + +_META = SimpleNamespace(wants_advanced_draft_sampling=False, is_cuda_graph=False) + + +@pytest.mark.parametrize("cls", [_Worker, _OwnTensorWorker, _ThreeArgWorker]) +def test_the_greedy_step_fills_out_on_every_override(cls) -> None: + w = _worker(cls) + logits = torch.randn(5, 64) + want = logits.argmax(dim=-1).to(torch.int32) + assert torch.equal(w.sample_draft_tokens(logits, _META, 5, draft_step=0), want) + if cls is _ThreeArgWorker: + return # takes no tokens_out: only calls without ``out`` reach it unchanged + out = torch.full((5,), -1, dtype=torch.int32) + tokens = w.sample_draft_tokens(logits, _META, 5, draft_step=0, out=out) + assert tokens.data_ptr() == out.data_ptr() # the tokens are out's storage + assert torch.equal(out, want) diff --git a/tests/unittest/_torch/speculative/test_capture_sampling_params.py b/tests/unittest/_torch/speculative/test_capture_sampling_params.py index 14228de7c1c2..83ec6c1bd3a4 100644 --- a/tests/unittest/_torch/speculative/test_capture_sampling_params.py +++ b/tests/unittest/_torch/speculative/test_capture_sampling_params.py @@ -278,7 +278,7 @@ def _populate_meta(mode, draft_len=1): prepare_penalty_buffers=lambda: None, prepare_watermark_buffers=lambda: None, watermark_ready=False, - _populate_request_rng_state=lambda requests, normalized: None, + _populate_request_rng_state=lambda requests, normalized, defer_rows=None: None, _populate_penalty_params=lambda requests: None, _populate_watermark_params=lambda requests: None, ) diff --git a/tests/unittest/_torch/speculative/test_draft_row_pick.py b/tests/unittest/_torch/speculative/test_draft_row_pick.py index 6e1b7ace46f6..2fe188ca24ea 100644 --- a/tests/unittest/_torch/speculative/test_draft_row_pick.py +++ b/tests/unittest/_torch/speculative/test_draft_row_pick.py @@ -204,16 +204,21 @@ def _worker(is_mtp_eagle, fast_paths): w._draft_folds_kv_lens_increment = False w._step0_row_pick = DraftRowPick("test draft layer") w.draft_kv_cache_context = lambda md, mgr: contextlib.nullcontext(md) - w.sample_draft_tokens = ( - lambda logits, - spec_metadata, - batch_size, - draft_step, - mapping_lm_head_tp=None: logits.argmax(-1).to(torch.int32) - ) + w.sample_draft_tokens = _greedy_draft_tokens return w +def _greedy_draft_tokens( + logits, spec_metadata, batch_size, draft_step, mapping_lm_head_tp=None, out=None +): + """Argmax tokens; written into ``out`` when given, like the real sampler.""" + tokens = logits.argmax(-1).to(torch.int32) + if out is None: + return tokens + out.copy_(tokens) + return out + + def _run_loop( layer, is_mtp_eagle, fast_paths, num_contexts, num_gens, k, seed, all_rank=None, subseq=None ): diff --git a/tests/unittest/_torch/speculative/test_eagle3.py b/tests/unittest/_torch/speculative/test_eagle3.py index ad448bf1b84d..3d39394b7600 100644 --- a/tests/unittest/_torch/speculative/test_eagle3.py +++ b/tests/unittest/_torch/speculative/test_eagle3.py @@ -96,6 +96,7 @@ def run_draft_forward(*args, **kwargs): worker = SimpleNamespace( is_mtp_eagle=True, + _draft_takes_kept_rows=False, draft_kv_cache_context=draft_context, _run_draft_forward=run_draft_forward, _step0_draft_layer_picks_rows=lambda draft_model, use_epilogue: False, @@ -441,6 +442,43 @@ def test_mtp_eagle_context_input_uses_prompt_lookahead() -> None: ) +@skip_num_gpus_less_than(1) +@pytest.mark.parametrize("fast_paths", [False, True]) +def test_mtp_eagle_generation_only_draft_input_ids(fast_paths) -> None: + """A generation-only step's draft input ids are the accepted tokens: read + in place on the speculative fast paths, else a concatenated copy.""" + spec_config = MTPDecodingConfig(max_draft_len=3) + spec_metadata = Eagle3OneModelSpecMetadata( + max_num_requests=2, + max_draft_len=3, + max_total_draft_tokens=3, + spec_dec_mode=spec_config.spec_dec_mode, + num_layers=1, + hidden_size=4, + max_num_tokens=8, + ) + spec_metadata.gather_ids = torch.tensor([3, 7], + dtype=torch.int32, + device="cuda") + spec_metadata.runtime_draft_len = 3 + accepted = torch.arange(8, dtype=torch.int32, device="cuda").view(2, 4) + worker = MTPEagleWorker(spec_config, spec_decode_fast_paths=fast_paths) + draft_inputs = worker.prepare_1st_drafter_inputs( + input_ids=torch.zeros(8, dtype=torch.int32, device="cuda"), + position_ids=torch.arange(8, dtype=torch.int32, + device="cuda").unsqueeze(0), + hidden_states=torch.zeros((8, 4), device="cuda"), + accepted_tokens=accepted, + attn_metadata=SimpleNamespace(num_contexts=0, num_ctx_tokens=0), + spec_metadata=spec_metadata, + draft_model=SimpleNamespace(), + ) + input_ids = draft_inputs["input_ids"] + assert input_ids.dtype == torch.int32 + assert torch.equal(input_ids, accepted.flatten()) + assert (input_ids.data_ptr() == accepted.data_ptr()) == fast_paths + + @skip_num_gpus_less_than(1) def test_mtp_eagle_dynamic_tree_context_input_uses_prompt_lookahead() -> None: invalid = INVALID_PROMPT_LOOKAHEAD_TOKEN diff --git a/tests/unittest/_torch/speculative/test_fused_accept.py b/tests/unittest/_torch/speculative/test_fused_accept.py index 6ec28868b8b0..acf1ef26c0f0 100644 --- a/tests/unittest/_torch/speculative/test_fused_accept.py +++ b/tests/unittest/_torch/speculative/test_fused_accept.py @@ -171,6 +171,109 @@ def test_step0_epilogue_matches_stock(num_contexts, num_gens, k, rows): assert torch.all(tok[1:] == -5) # draft rows untouched (written by the heads) +@pytest.mark.parametrize( + "num_contexts,all_rank_num_seqs,all_rank_num_gens,expected", + [ + (0, None, None, True), # TP attention: this rank's batch decides + (2, None, None, False), + (0, [4, 6], [4, 6], True), # attention DP, generation-only on every rank + (0, [4, 6], [4, 5], False), # another rank holds a context request + (1, [5, 6], [4, 6], False), + (0, [4, 6], None, False), + ], +) +def test_kept_rows_only_when_every_rank_is_generation_only( + num_contexts, all_rank_num_seqs, all_rank_num_gens, expected +): + """Pass 0 takes kept rows only when no rank of its MoE collectives holds a context request.""" + from tensorrt_llm._torch.speculative.kept_rows import generation_only_on_every_rank + + assert ( + generation_only_on_every_rank(num_contexts, all_rank_num_seqs, all_rank_num_gens) + == expected + ) + + +@pytest.mark.parametrize( + "num_contexts,num_gens,k", [(3, 5, 6), (0, 64, 6), (0, 1, 6), (2, 0, 7), (0, 128, 8)] +) +def test_kept_rows_match_the_step0_gather(num_contexts, num_gens, k): + """The draft loop's pass-0 kept rows, known before the pass (speculative/kept_rows.py): the ids equal the stock + step-0 gather ids, the two-tensor gather equals index_select, and the step-0 epilogue on the compact rows + (``hidden_compact``) gives the stock ids, positions and metadata with those rows as its hidden rows.""" + from tensorrt_llm._torch.speculative.fused_accept import step0_epilogue + from tensorrt_llm._torch.speculative.kept_rows import gather_rows2, kept_row_ids + + g = torch.Generator(device="cuda").manual_seed(num_contexts * 100 + num_gens + k) + b, H = num_contexts + num_gens, 4096 + ctx_lens = torch.randint(1, 300, (num_contexts,), generator=g, device="cuda", dtype=torch.int32) + seq_lens = torch.cat( + [ctx_lens, torch.full((num_gens,), k + 1, device="cuda", dtype=torch.int32)] + ) + num_acc = torch.randint(1, k + 2, (b,), generator=g, device="cuda", dtype=torch.int32) + batch_indices = torch.arange(b + 4, device="cuda", dtype=torch.int32) + num_ctx_tokens = int(ctx_lens.sum()) + n_tok = num_ctx_tokens + num_gens * (k + 1) + # Stock: eagle3._forward_linear_draft_loop, i == 0 without the epilogue. + last = torch.cumsum(seq_lens, dim=0, dtype=torch.long) - 1 + gen = (batch_indices[:num_gens] * (k + 1)).long() + num_acc[num_contexts:] - 1 + num_ctx_tokens + ids_ref = torch.concat([last[:num_contexts], gen], dim=0) + ids = kept_row_ids(seq_lens, batch_indices, num_acc, num_contexts, num_gens, k, num_ctx_tokens) + torch.cuda.synchronize() + assert ids.dtype == torch.int64 and torch.equal(ids, ids_ref) + + hidden = torch.randn((n_tok, H), generator=g, device="cuda").to(torch.bfloat16) + residual = torch.randn((n_tok, H), generator=g, device="cuda").to(torch.bfloat16) + kept_h, kept_r = gather_rows2(hidden, residual, ids) + assert torch.equal(kept_h, hidden[ids_ref]) and torch.equal(kept_r, residual[ids_ref]) + + pos = torch.randint(0, 200000, (n_tok,), generator=g, device="cuda", dtype=torch.int32) + kv = torch.randint(1000, 5000, (b + 3,), generator=g, device="cuda", dtype=torch.int32) + outs = [] + for compact in (False, True): + seq_live, kv_live = torch.full((b + 3,), 7, device="cuda", dtype=torch.int32), kv.clone() + ep = step0_epilogue( + seq_lens.clone(), + num_acc, + kept_h if compact else hidden, + pos, + seq_live, + kv_live, + num_contexts, + b, + k, + num_ctx_tokens, + hidden_compact=compact, + ) + torch.cuda.synchronize() + assert ep is not None + outs.append((ep, seq_live, kv_live)) + (ref, seq_ref, kv_ref), (got, seq_got, kv_got) = outs + assert torch.equal(got.gather_ids, ref.gather_ids) + assert got.hidden.data_ptr() == kept_h.data_ptr() and torch.equal(got.hidden, ref.hidden) + for j in range(1, k): + assert torch.equal(got.positions(j), ref.positions(j)), j + assert torch.equal(seq_got, seq_ref) and torch.equal(kv_got, kv_ref) + # Compact rows must be one per request. + assert ( + step0_epilogue( + seq_lens.clone(), + num_acc, + hidden, + pos, + torch.zeros_like(seq_live), + kv.clone(), + num_contexts, + b, + k, + num_ctx_tokens, + hidden_compact=True, + ) + is None + or n_tok == b + ) + + def test_accept_kernels_compile_once_across_batch_splits(): """One compiled accept / step-0 kernel per position layout serves every batch split.""" import triton diff --git a/tests/unittest/api_stability/references/trtllm_serve_routes.yaml b/tests/unittest/api_stability/references/trtllm_serve_routes.yaml index 523342d4afae..be3fd6aa9b91 100644 --- a/tests/unittest/api_stability/references/trtllm_serve_routes.yaml +++ b/tests/unittest/api_stability/references/trtllm_serve_routes.yaml @@ -619,6 +619,7 @@ configs: - POST /select APIRoute - POST /finish APIRoute - POST /renew APIRoute + - POST /output_length APIRoute - GET /cluster_info APIRoute - GET /health APIRoute - GET /version APIRoute @@ -632,6 +633,7 @@ configs: - POST /select APIRoute - POST /finish APIRoute - POST /renew APIRoute + - POST /output_length APIRoute - GET /cluster_info APIRoute - GET /health APIRoute - GET /version APIRoute diff --git a/tests/unittest/disaggregated/test_cache_transceiver_single_process.py b/tests/unittest/disaggregated/test_cache_transceiver_single_process.py index 22679bf5e271..5ff2af576bb0 100644 --- a/tests/unittest/disaggregated/test_cache_transceiver_single_process.py +++ b/tests/unittest/disaggregated/test_cache_transceiver_single_process.py @@ -63,6 +63,7 @@ BlockReuseConfig, CacheTransceiverConfig, KvPoolRebalanceConfig, + RemoteCacheConfig, ) AttentionTypeCpp = tensorrt_llm.bindings.internal.batch_manager.AttentionType @@ -180,6 +181,8 @@ class KvCacheConfigV2: # tensorrt_llm/llmapi/llm_args.py; KVCacheManagerV2._build_base_config() # reads it unconditionally. kv_pool_rebalance_config: KvPoolRebalanceConfig = field(default_factory=KvPoolRebalanceConfig) + # Mirrors KvCacheConfig.remote_cache_config; read by KVCacheManagerV2.__init__. + remote_cache_config: Optional[RemoteCacheConfig] = None enable_kv_pool_rebalance: bool = False diff --git a/tests/unittest/disaggregated/test_coordinator_worker.py b/tests/unittest/disaggregated/test_coordinator_worker.py index 526e7cc869d6..23c7750a5780 100644 --- a/tests/unittest/disaggregated/test_coordinator_worker.py +++ b/tests/unittest/disaggregated/test_coordinator_worker.py @@ -992,6 +992,28 @@ def test_coordinator_session_gives_up_idle_connections_before_the_server(): assert connector.call_args.kwargs["keepalive_timeout"] == dc.COORDINATOR_KEEPALIVE_TIMEOUT_S +@pytest.mark.cpu_only +@pytest.mark.parametrize( + ("somaxconn", "expected"), [("4096\n", 4096), ("65535\n", 16384), (None, 16384)] +) +def test_coordinator_uds_backlog_is_capped_by_somaxconn(monkeypatch, somaxconn, expected): + import io + + from tensorrt_llm.serve import coordinator_server + + real_open = open + + def fake_open(path, *args, **kwargs): + if path != "/proc/sys/net/core/somaxconn": + return real_open(path, *args, **kwargs) + if somaxconn is None: + raise FileNotFoundError(path) + return io.StringIO(somaxconn) + + monkeypatch.setattr("builtins.open", fake_open) + assert coordinator_server._effective_uds_backlog() == expected + + @pytest.mark.asyncio @pytest.mark.parametrize( ("keep_alive_kwargs", "expected_timeout"), diff --git a/tests/unittest/disaggregated/test_kv_transfer.py b/tests/unittest/disaggregated/test_kv_transfer.py index 6fe126a1fb45..5074e75de337 100644 --- a/tests/unittest/disaggregated/test_kv_transfer.py +++ b/tests/unittest/disaggregated/test_kv_transfer.py @@ -69,7 +69,7 @@ from tensorrt_llm._utils import TensorWrapper, convert_to_torch_tensor, get_size_in_bytes from tensorrt_llm.bindings import DataType from tensorrt_llm.disaggregated_params import DisaggScheduleStyle -from tensorrt_llm.llmapi.llm_args import BlockReuseConfig, KvPoolRebalanceConfig +from tensorrt_llm.llmapi.llm_args import BlockReuseConfig, KvPoolRebalanceConfig, RemoteCacheConfig from tensorrt_llm.logger import logger # Default to 4 worker threads for all KV transfer tests in this module. @@ -113,6 +113,8 @@ class KvCacheConfigV2: # tensorrt_llm/llmapi/llm_args.py; KVCacheManagerV2._build_base_config() # reads it unconditionally. kv_pool_rebalance_config: KvPoolRebalanceConfig = field(default_factory=KvPoolRebalanceConfig) + # Mirrors KvCacheConfig.remote_cache_config; read by KVCacheManagerV2.__init__. + remote_cache_config: Optional[RemoteCacheConfig] = None enable_kv_pool_rebalance: bool = False diff --git a/tests/unittest/disaggregated/test_openai_disagg_server.py b/tests/unittest/disaggregated/test_openai_disagg_server.py index 4984a1ad749e..469f424a51aa 100644 --- a/tests/unittest/disaggregated/test_openai_disagg_server.py +++ b/tests/unittest/disaggregated/test_openai_disagg_server.py @@ -49,6 +49,7 @@ async def test_server_keep_alive_timeout_is_passed_to_uvicorn( ) server = object.__new__(OpenAIDisaggServer) server._config = config + server._coordinator = None server.app = object() uvicorn_config = object() @@ -65,6 +66,38 @@ async def test_server_keep_alive_timeout_is_passed_to_uvicorn( uvicorn_server.serve.assert_awaited_once_with(sockets=None) +@pytest.mark.asyncio +async def test_single_process_server_fails_seat_waiters_when_shutdown_begins(tmp_path, monkeypatch): + """Graceful shutdown waits for parked selects; they must fail at once, as in a fleet.""" + import asyncio + + from test_common.serve.app_factory import DisaggConfig, isolated_serve_env + + with isolated_serve_env(tmp_path) as env: + server = env.build_disagg_server(DisaggConfig()) + fail = AsyncMock() + monkeypatch.setattr(server._coordinator, "fail_seat_waiters", fail) + uvicorn_server = SimpleNamespace(should_exit=False) + + async def serve(sockets=None): + await asyncio.sleep(0.3) + assert fail.await_count == 0 + uvicorn_server.should_exit = True # what SIGINT / SIGTERM do + # uvicorn now drains the requests in flight, parked selects included. + for _ in range(100): + if fail.await_count: + break + await asyncio.sleep(0.02) + + uvicorn_server.serve = serve + monkeypatch.setattr(openai_disagg_server.uvicorn, "Config", Mock()) + monkeypatch.setattr( + openai_disagg_server, "create_uvicorn_server", Mock(return_value=uvicorn_server) + ) + await asyncio.wait_for(server(host="127.0.0.1", port=0), timeout=10) + fail.assert_awaited_once() + + @pytest.mark.asyncio async def test_http_cluster_storage_request_is_proxied_to_coordinator(): payload = b'{"key":"worker","value":"ready"}' diff --git a/tests/unittest/disaggregated/test_openai_disagg_service.py b/tests/unittest/disaggregated/test_openai_disagg_service.py index 686285198596..4a7366c57996 100644 --- a/tests/unittest/disaggregated/test_openai_disagg_service.py +++ b/tests/unittest/disaggregated/test_openai_disagg_service.py @@ -1049,6 +1049,51 @@ async def test_gen_request_carries_orig_elapsed(monkeypatch, schedule_style): assert ctx_req.disaggregated_params.orig_elapsed_s is None +@pytest.mark.asyncio +async def test_gen_placement_sees_orig_elapsed_after_the_context_phase(monkeypatch): + """The GEN router sees the time since arrival; the GEN request is stamped again after placement. + + A pooled router ages the request by it and bounds the wait by the KV transfer timeout. + """ + monkeypatch.delenv("TRTLLM_DISAGG_BENCHMARK_GEN_ONLY", raising=False) + service = _make_service("context_first") + service._ctx_client = AsyncMock() + service._gen_client = AsyncMock() + service._ctx_router.get_next_server = AsyncMock(return_value=("ctx:9000", {"server_info": {}})) + at_placement = [] + + async def _place(req, *_args, **_kwargs): + at_placement.append(req.disaggregated_params.orig_elapsed_s) + await asyncio.sleep(0.05) + return "gen:9001", {"server_info": {}} + + service._gen_router.get_next_server = AsyncMock(side_effect=_place) + service._ctx_client.send_request = AsyncMock( + side_effect=lambda req, *a, **k: _make_completion_response( + "", + finish_reason="length", + disagg_request_id=req.disaggregated_params.disagg_request_id, + context_only=True, + ) + ) + service._gen_client.send_request = AsyncMock( + side_effect=lambda req, *a, **k: _make_completion_response( + "done", + finish_reason="stop", + disagg_request_id=req.disaggregated_params.disagg_request_id, + context_only=False, + ) + ) + hooks = mock.Mock() + hooks.request_arrival_time = get_global_steady_clock_now_in_seconds() - 5.0 + + await service._send_disagg_request(CompletionRequest(model="test-model", prompt="hello"), hooks) + + assert len(at_placement) == 1 and 5.0 <= at_placement[0] < 60.0 + sent = service._gen_client.send_request.call_args.args[0].disaggregated_params.orig_elapsed_s + assert sent > at_placement[0] + 0.04 + + def test_orig_elapsed_arrival_fallback(): before = get_global_steady_clock_now_in_seconds() assert OpenAIDisaggregatedService._get_arrival_time(None) >= before diff --git a/tests/unittest/disaggregated/test_openai_server_info.py b/tests/unittest/disaggregated/test_openai_server_info.py index 114d6f10319b..2173d55441d0 100644 --- a/tests/unittest/disaggregated/test_openai_server_info.py +++ b/tests/unittest/disaggregated/test_openai_server_info.py @@ -18,18 +18,19 @@ import pytest -from tensorrt_llm.llmapi.llm_args import KvCacheConfig +from tensorrt_llm.llmapi.llm_args import CacheTransceiverConfig, KvCacheConfig from tensorrt_llm.runtime.kv_cache_hash import KV_CACHE_HASH_ALGO_V1, KV_CACHE_HASH_ALGO_V2 from tensorrt_llm.serve.openai_server import OpenAIServer -def _make_server(*, max_batch_size=None, kv_cache_config=None): +def _make_server(*, max_batch_size=None, kv_cache_config=None, cache_transceiver_config=None): server = object.__new__(OpenAIServer) server.generator = SimpleNamespace( disaggregated_params=None, args=SimpleNamespace( max_batch_size=max_batch_size, kv_cache_config=kv_cache_config, + cache_transceiver_config=cache_transceiver_config, ), ) return server @@ -107,3 +108,26 @@ async def test_server_info_preserves_configured_tokens_per_block_on_live_lookup_ content = json.loads(response.body) assert content["tokens_per_block"] == 32 + + +@pytest.mark.cpu_only +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("transceiver", "expected"), + [ + (None, "absent"), + (CacheTransceiverConfig(), 60000), + (CacheTransceiverConfig(transceiver_runtime="CPP", kv_transfer_timeout_ms=None), None), + ], + ids=["no_transceiver", "default", "null"], +) +async def test_server_info_reports_a_null_kv_transfer_timeout(transceiver, expected): + """A null timeout is reported as null, so a pooled router can tell it from not reported.""" + server = _make_server(cache_transceiver_config=transceiver) + + content = json.loads((await server.get_server_info()).body) + + if expected == "absent": + assert "kv_transfer_timeout_ms" not in content + else: + assert content["kv_transfer_timeout_ms"] == expected diff --git a/tests/unittest/disaggregated/test_output_length_predictor.py b/tests/unittest/disaggregated/test_output_length_predictor.py new file mode 100644 index 000000000000..9f0d1a7e6509 --- /dev/null +++ b/tests/unittest/disaggregated/test_output_length_predictor.py @@ -0,0 +1,862 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Online output-length prediction (serve/output_length_predictor.py).""" + +import asyncio +import json +import math +import random +import statistics +import threading +import time + +import pytest + +from tensorrt_llm.serve import output_length_predictor as olp +from tensorrt_llm.serve.openai_protocol import ( + ChatCompletionRequest, + CompletionRequest, + ConversationParams, + DisaggregatedParams, + UsageInfo, +) + +pytestmark = pytest.mark.cpu_only + + +def _gen_request(conv_id="c0", prompt_tokens=1000, cls=CompletionRequest): + kwargs = {"model": "m", "max_tokens": 4096} + kwargs["prompt" if cls is CompletionRequest else "messages"] = ( + "hi" if cls is CompletionRequest else [{"role": "user", "content": "hi"}] + ) + request = cls(**kwargs) + if conv_id is not None: + request.conversation_params = ConversationParams(conversation_id=conv_id) + request.disaggregated_params = DisaggregatedParams( + request_type="generation_only", + ctx_usage=None if prompt_tokens is None else UsageInfo(prompt_tokens=prompt_tokens), + ) + return request + + +class _FakeFitter: + """Fits nothing; returns the result it is given on the poll after ``start``.""" + + def __init__(self, result=None): + self.result = result + self.started = [] + self._busy = False + self._ready = None + + def busy(self): + return self._busy + + def start(self, rows, n, meta): + self.started.append((n, len(rows), dict(meta))) + self._ready = dict(self.result or {}, **meta) + + def poll(self): + ready, self._ready = self._ready, None + return ready + + +_ONE_LEAF = {"baseline": math.log1p(99.0), "trees": [[[True, 0.0, 0, 0.0, True, 0, 0]]]} + + +def _good_fit(**extra): + return {**_ONE_LEAF, "n_iter": 1, "fit_s": 0.01, "export_max_abs_diff": 0.0, **extra} + + +# ---------------------------------------------------------------------------------- table and features + + +def test_priority_is_strictly_decreasing_in_tokens(): + values = [olp.priority_of(t) for t in (0, 1, 100, 400, 1024, 1e6)] + assert values[0] == 1.0 + assert all(a > b for a, b in zip(values, values[1:])) + assert values[3] == pytest.approx(0.7191, abs=1e-4) + assert olp.priority_of(-5) == 1.0 + + +def test_table_reset_and_skip_rules(): + predictor = olp.OnlineLengthPredictor("ridge") + table = predictor.table + assert not predictor.record("c", 1000, 2, None, 0.0) # cache primer: not learned + assert table.skipped == 1 and len(table) == 0 + assert predictor.record(None, 1000, 50, None, 0.0) # no conversation id: global models only + assert len(table) == 0 + assert predictor.record("c", 1000, 50, None, 0.0) and table.recorded == 1 + # One reply with a short prompt, then a jump of more than 10,000 appended tokens: a new prefix. + assert table.snapshot_for("c", 1000 + 50 + 10001) is None + assert table.resets == 1 and len(table) == 0 + table.record("c", 1000, 50) + table.record("c", 1100, 70) + snapshot = table.snapshot_for("c", 20000) # two replies: never reset + assert snapshot == (2.0, 70.0, 60.0, 120.0, 70.0, 1100.0) + + +def test_table_keys_a_long_conversation_id_by_its_digest(): + """A client-chosen id longer than MAX_CONVERSATION_ID_CHARS costs a fixed-size key.""" + table = olp.ConversationLengthTable() + long_id = "x" * (64 * 1024) + table.record(long_id, 1000, 50) + table.record("y" * olp.MAX_CONVERSATION_ID_CHARS, 1000, 70) + assert table.snapshot_for(long_id, 2000)[1] == 50.0 + assert table.snapshot_for(long_id + "z", 2000) is None + assert table.snapshot_for("y" * olp.MAX_CONVERSATION_ID_CHARS, 2000)[1] == 70.0 + assert all(len(key) <= olp.MAX_CONVERSATION_ID_CHARS for key in table._histories) + + +def test_table_evicts_least_recently_used(): + table = olp.ConversationLengthTable(max_conversations=2) + for conv in ("a", "b"): + table.record(conv, 100, 10) + table.snapshot_for("a", 100) + table.record("c", 100, 10) + assert table.snapshot_for("b", 100) is None and table.snapshot_for("a", 100) is not None + + +def test_features(): + first = olp.features(None, 1000) + assert first[:2] == [0.0, math.log1p(1000)] and all(v != v for v in first[2:]) + row = olp.features((2.0, 70.0, 60.0, 120.0, 70.0, 1100.0), 1500) + expected = [math.log1p(2), math.log1p(1500), math.log1p(70), math.log1p(60), math.log1p(60)] + assert row[:5] == pytest.approx(expected) + assert row[5] == pytest.approx(math.log1p(70)) + assert row[6] == pytest.approx(math.log1p(1500 - 1100 - 70)) + assert olp.features((1.0, 500.0, 500.0, 500.0, 500.0, 1000.0), 800)[6] == pytest.approx( + -math.log1p(700) + ) + + +def test_request_inputs_never_reads_max_tokens(): + class Guarded: + conversation_params = ConversationParams(conversation_id="c7") + disaggregated_params = DisaggregatedParams( + request_type="generation_only", ctx_usage=UsageInfo(prompt_tokens=321) + ) + + def __getattr__(self, name): + raise AssertionError(f"{name} must not be read") + + assert olp.request_inputs(Guarded()) == ("c7", 321.0) + assert olp.request_inputs(_gen_request(None, None)) == (None, None) + + +def test_running_median_matches_statistics(): + rng = random.Random(0) + median = olp.RunningMedian() + values = [] + assert median.value() != median.value() + for _ in range(501): + values.append(rng.choice([rng.random() * 1000, float(rng.randint(0, 9))])) + median.add(values[-1]) + assert median.value() == statistics.median(values) + + +# ---------------------------------------------------------------------------------- ridge + + +def _ridge_closed_form(rows, ys, alpha): + np = pytest.importorskip("numpy") + x, y = np.asarray(rows), np.asarray(ys) + xc, yc = x - x.mean(0), y - y.mean() + w = np.linalg.solve(xc.T @ xc + alpha * np.eye(x.shape[1]), xc.T @ yc) + return w, y.mean() - x.mean(0) @ w + + +def test_online_ridge_matches_closed_form_and_sklearn(): + rng = random.Random(1) + rows, ys = [], [] + ridge = olp.OnlineRidge(2 * len(olp.FEATURES)) + for _ in range(400): + snap = ( + None + if rng.random() < 0.3 + else ( + float(rng.randint(1, 9)), + rng.random() * 900, + rng.random() * 900, + rng.random() * 9000, + rng.random() * 900, + rng.random() * 30000, + ) + ) + x = olp.ridge_row(olp.features(snap, rng.random() * 50000)) + y = rng.random() * 8 + rows.append(x) + ys.append(y) + ridge.add(x, y) + ridge.fit() + w, b = _ridge_closed_form(rows, ys, olp.RIDGE_ALPHA) + assert ridge.coef == pytest.approx(list(w), abs=1e-8) + assert ridge.intercept == pytest.approx(float(b), abs=1e-8) + linear_model = pytest.importorskip("sklearn.linear_model") + ref = linear_model.Ridge(alpha=olp.RIDGE_ALPHA).fit(rows, ys) + assert ridge.coef == pytest.approx(list(ref.coef_), abs=1e-6) + assert ridge.intercept == pytest.approx(float(ref.intercept_), abs=1e-6) + + +# ---------------------------------------------------------------------------------- the coordinator's predictor + + +def test_unknown_predictor_is_refused(): + with pytest.raises(ValueError, match="predictor"): + olp.OnlineLengthPredictor("gbm_only") + + +def test_prior_then_median_then_ema(): + predictor = olp.OnlineLengthPredictor("ridge") + tokens, key = predictor.predict("a", 1000, 0.0) + assert tokens == olp.PRIOR_TOKENS + assert predictor.record("a", 1000, 100, key, 1.0) + predictor.record("b", 1000, 300, None, 2.0) + assert predictor.unmatched == 1 + assert predictor.predict("new", 1000, 3.0)[0] == 200.0 # median of the learned replies + assert predictor.predict("a", 1200, 3.0)[0] == 100.0 # the conversation's EMA + assert not predictor.record("a", 1200, 1, None, 4.0) # a primer is not learned + assert predictor.median.n == 2 + + +def _learn(predictor, n, t, conv=lambda i: f"c{i}"): + for i in range(n): + _, key = predictor.predict(conv(i), 1000 + i, t) + predictor.record(conv(i), 1000 + i, 50 + i % 400, key, t) + + +def test_ridge_refits_on_boundaries_after_min_rows(): + predictor = olp.OnlineLengthPredictor("ridge") + _learn(predictor, olp.RIDGE_MIN_ROWS - 1, 0.0) + predictor.predict("x", 1000, olp.RIDGE_REFIT_S) # boundary with too few rows: skipped + assert predictor.ridge_fits == 0 and predictor.ridge.coef is None + _learn(predictor, 1, olp.RIDGE_REFIT_S) + predictor.predict("x", 1000, 2 * olp.RIDGE_REFIT_S - 1e-3) + assert predictor.ridge_fits == 0 + predictor.predict("x", 1000, 2 * olp.RIDGE_REFIT_S) + assert predictor.ridge_fits == 1 and predictor.ridge.fit_rows == olp.RIDGE_MIN_ROWS + assert predictor.sources["ridge"] == 1 + # Several boundaries passed at once (an idle coordinator) fit once, the same coefficients + # as a fit per boundary since no row arrived in between; the next boundary stays on the grid. + coef = list(predictor.ridge.coef) + predictor.predict("x", 1000, 5 * olp.RIDGE_REFIT_S + 1.0) + assert predictor.ridge_fits == 2 and predictor.ridge.coef == coef + assert predictor.next_ridge_fit == 6 * olp.RIDGE_REFIT_S + predictor.predict("x", 1000, 6 * olp.RIDGE_REFIT_S) + assert predictor.ridge_fits == 3 + + +def test_ridge_mode_never_fits_trees(): + predictor = olp.OnlineLengthPredictor("ridge", gbm_fitter=_FakeFitter(_good_fit())) + _learn(predictor, olp.GBM_MIN_ROWS, 0.0) + predictor.predict("x", 1000, 10 * olp.GBM_REFIT_S) + assert predictor.gbm_fitter.started == [] and predictor.gbm is None + + +def test_tree_fit_goes_live_after_it_returns(): + fitter = _FakeFitter(_good_fit()) + predictor = olp.OnlineLengthPredictor("ridge_gbm", gbm_fitter=fitter) + _learn(predictor, olp.GBM_MIN_ROWS, 0.0) + predictor.predict("x", 1000, olp.GBM_REFIT_S) # starts the fit + assert [s[0] for s in fitter.started] == [olp.GBM_MIN_ROWS] + assert fitter.started[0][1] == olp.GBM_MIN_ROWS * (len(olp.FEATURES) + 1) + assert predictor.gbm_fits == 1 # the fake's fit has returned by the poll in the same event + tokens, _ = predictor.predict("x", 1000, olp.GBM_REFIT_S + 1) + assert tokens == pytest.approx(99.0) and predictor.sources["gbm"] >= 1 + + +@pytest.mark.parametrize( + "result", [{"error": "exit 1: boom"}, _good_fit(export_max_abs_diff=1e-3), {"rows": 3}] +) +def test_failed_or_bad_tree_fit_keeps_the_current_model(result): + fitter = _FakeFitter(result) + predictor = olp.OnlineLengthPredictor("ridge_gbm", gbm_fitter=fitter) + _learn(predictor, olp.GBM_MIN_ROWS, 0.0) + predictor.predict("x", 1000, olp.GBM_REFIT_S) + assert predictor.gbm is None and predictor.gbm_errors == 1 + assert predictor.predict("x", 1000, olp.GBM_REFIT_S + 1)[0] != pytest.approx(99.0) + + +def test_busy_fitter_skips_the_boundary(): + fitter = _FakeFitter(None) + fitter._busy = True + predictor = olp.OnlineLengthPredictor("ridge_gbm", gbm_fitter=fitter) + _learn(predictor, olp.GBM_MIN_ROWS, 0.0) + predictor.predict("x", 1000, olp.GBM_REFIT_S) + assert fitter.started == [] and predictor.gbm_busy_skips == 1 + + +def test_fit_does_not_block_predictions(): + """A fit runs on its own thread; predictions keep being served (by the other models) meanwhile.""" + release = threading.Event() + + class SlowFitter(_FakeFitter): + def start(self, rows, n, meta): + self.started.append((n, len(rows), dict(meta))) + self._busy = True + + def run(): + self.fit_thread = threading.get_ident() + release.wait(30) + self._ready = dict(_good_fit(), **meta) + self._busy = False + + threading.Thread(target=run, daemon=True).start() + + fitter = SlowFitter() + predictor = olp.OnlineLengthPredictor("ridge_gbm", gbm_fitter=fitter) + _learn(predictor, olp.GBM_MIN_ROWS, 0.0) + t = olp.GBM_REFIT_S + tokens, _ = predictor.predict("x", 1000, t) # starts the fit, which waits for `release` + assert len(fitter.started) == 1 and fitter.busy() + while_busy = [] + for _ in range(100): + t += 0.01 + tokens, _ = predictor.predict("x", 1000, t) + while_busy.append(tokens) + assert fitter.busy() and predictor.gbm is None + assert all(tokens != pytest.approx(99.0) for tokens in while_busy) + release.set() + deadline = time.monotonic() + 30 + while fitter.busy() and time.monotonic() < deadline: + time.sleep(0.01) + assert fitter.fit_thread != threading.get_ident() + assert predictor.predict("x", 1000, t + 0.01)[0] == pytest.approx(99.0) + assert len(fitter.started) == 1 and predictor.gbm_fits == 1 + + +def test_real_tree_fit_matches_sklearn(): + np = pytest.importorskip("numpy") + pytest.importorskip("sklearn") + olp.check_gbm_dependencies() + rng = np.random.default_rng(0) + n = 3000 + x = rng.normal(size=(n, len(olp.FEATURES))) + x[rng.random(size=x.shape) < 0.2] = np.nan + y = np.nan_to_num(x[:, 1]) * 0.5 + rng.normal(scale=0.1, size=n) + 5.0 + rows = olp.array("d", np.concatenate([x, y[:, None]], axis=1).ravel().tolist()) + fitter = olp.SubprocessGbmFitter(sync=True) + fitter.start(rows, n, {"rows": n}) + result = fitter.poll() + assert "error" not in result, result.get("error") + assert result["export_max_abs_diff"] <= olp.GBM_EXPORT_TOL + from sklearn.ensemble import HistGradientBoostingRegressor + + ref = HistGradientBoostingRegressor(**olp.GBM_PARAMS).fit(x, y) + ensemble = olp.TreeEnsemble(result["baseline"], result["trees"]) + got = [ensemble.raw([float(v) for v in row]) for row in x[:200]] + assert got == pytest.approx(list(ref.predict(x[:200])), abs=1e-5) + + +def test_missing_sklearn_fails_at_start(tmp_path): + fake_python = tmp_path / "python" + fake_python.write_text("#!/bin/sh\necho 'No module named sklearn' >&2\nexit 1\n") + fake_python.chmod(0o755) + with pytest.raises(ImportError, match="scikit-learn"): + olp.check_gbm_dependencies(str(fake_python)) + + +def test_sklearn_without_the_fitted_trees_fails_at_start(tmp_path, monkeypatch): + """The trees are read from scikit-learn internals; a release without them fails at startup.""" + pytest.importorskip("numpy") + package = tmp_path / "sklearn" + package.mkdir() + (package / "__init__.py").write_text("") + (package / "ensemble.py").write_text( + "class HistGradientBoostingRegressor:\n" + " def __init__(self, **kwargs):\n" + " pass\n" + " def fit(self, X, y):\n" + " return self\n" + ) + monkeypatch.syspath_prepend(str(tmp_path)) + with pytest.raises(ImportError, match="(?s)fitted predictors.*_predictors"): + olp.check_gbm_dependencies() + + +@pytest.mark.parametrize( + "result", + [ + {"error": "exit 1: SystemExit: unsupported tree"}, + {"baseline": 0.0, "trees": [], "export_max_abs_diff": 1.0}, + {"baseline": 0.0, "trees": []}, + ], + ids=["unsupported_tree", "walk_differs", "no_export_check"], +) +def test_startup_check_applies_the_refit_install_rules(monkeypatch, result): + """The startup check runs the refit and its install checks, so a refit cannot fail where it passed.""" + started = [] + + def run(self, header, rows): + started.append((header["n"], len(rows))) + return dict(result) + + monkeypatch.setattr(olp.SubprocessGbmFitter, "_run", run) + with pytest.raises(ImportError, match="scikit-learn"): + olp.check_gbm_dependencies() + assert started == [(olp.GBM_CHECK_ROWS, olp.GBM_CHECK_ROWS * (len(olp.FEATURES) + 1))] + predictor = olp.OnlineLengthPredictor("ridge") + predictor._install_gbm(dict(result, rows=1)) + assert predictor.gbm is None and predictor.gbm_errors == 1 + + +# ---------------------------------------------------------------------------------- frontend + + +class _FakeCoordinator: + def __init__(self, tokens=100.0, delay=0.0, error=None): + self.tokens, self.delay, self.error = tokens, delay, error + self.predicted, self.recorded = [], [] + + async def predict_output_length(self, conv_id, isl): + self.predicted.append((conv_id, isl)) + if self.delay: + await asyncio.sleep(self.delay) + if self.error: + raise self.error + return self.tokens, 7 + + async def record_output_lengths(self, records): + self.recorded.extend(records) + return len(records) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("cls", [CompletionRequest, ChatCompletionRequest]) +async def test_assign_sets_priority_from_prediction(cls): + coordinator = _FakeCoordinator(tokens=1024.0) + frontend = olp.OutputLengthPriority(coordinator, "ridge") + request = _gen_request("c1", 2000, cls) + ticket = await frontend.assign(request) + assert request.priority == 0.5 and ticket.key == 7 + assert coordinator.predicted == [("c1", 2000.0)] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "coordinator", [_FakeCoordinator(delay=5.0), _FakeCoordinator(error=RuntimeError("down"))] +) +async def test_assign_without_prediction_uses_the_prior(coordinator, monkeypatch): + monkeypatch.setattr(olp, "PREDICT_TIMEOUT_S", 0.05) + frontend = olp.OutputLengthPriority(coordinator, "ridge") + request = _gen_request("c1", 2000) + ticket = await frontend.assign(request) + assert request.priority == pytest.approx(olp.priority_of(olp.PRIOR_TOKENS)) + assert frontend.missing == 1 and ticket.key is None # the reply is still recorded + + +@pytest.mark.asyncio +async def test_assign_without_prompt_tokens_records_nothing(): + frontend = olp.OutputLengthPriority(_FakeCoordinator(), "ridge") + request = _gen_request("c1", None) + assert await frontend.assign(request) is None + assert request.priority == pytest.approx(frontend.prior_priority) + + +def _sse(obj): + return f"data: {json.dumps(obj)}\n\n".encode() + + +def test_completion_tokens_in(): + assert olp.completion_tokens_in(b"data: {}\n") == (None, False) + usage = {"usage": {"completion_tokens": 42}} + assert olp.completion_tokens_in(_sse(dict(usage, choices=[]))) == (42, True) + assert olp.completion_tokens_in(_sse(dict(usage, choices=[{"x": 1}]))) == (None, False) + assert olp.completion_tokens_in(_sse(dict(usage, choices=None))) == (42, True) + assert olp.completion_tokens_in(_sse(usage)) == (42, True) + assert olp.completion_tokens_in(b"data: [DONE]\n") == (None, False) + + +@pytest.mark.asyncio +async def test_continuous_usage_stream_decodes_only_its_final_chunk(monkeypatch): + """With continuous usage stats every chunk carries usage; only the usage-only one is decoded.""" + decoded = [] + real = olp._sse_json + monkeypatch.setattr(olp, "_sse_json", lambda event: decoded.append(event) or real(event)) + coordinator = _FakeCoordinator() + frontend = olp.OutputLengthPriority(coordinator, "ridge") + ticket = olp._Ticket("c1", 2000.0, 7) + compact = json.dumps( + {"choices": [], "usage": {"completion_tokens": 300}}, separators=(",", ":") + ) + + async def stream(): + for i in range(1, 300): + yield _sse( + {"choices": [{"delta": {"content": "x"}}], "usage": {"completion_tokens": i}} + ) + yield f"data: {compact}\n\n".encode() + yield b"data: [DONE]\n\n" + + assert len([chunk async for chunk in frontend.track(stream(), ticket)]) == 301 + await asyncio.sleep(0.01) + assert coordinator.recorded == [("c1", 2000.0, 300.0, 7)] and len(decoded) == 1 + + +@pytest.mark.asyncio +async def test_track_records_the_final_usage_before_relaying_it(): + coordinator = _FakeCoordinator() + frontend = olp.OutputLengthPriority(coordinator, "ridge") + ticket = olp._Ticket("c1", 2000.0, 7) + final = _sse({"choices": [], "usage": {"completion_tokens": 321}}) + head, tail = final[:10], final[10:] + + async def stream(): + yield _sse({"choices": [{"text": "a"}], "usage": {"completion_tokens": 1}}) + # The final chunk arrives split across two reads. + yield head + yield tail + yield b"data: [DONE]\n\n" + + out = [] + async for chunk in frontend.track(stream(), ticket): + out.append(chunk) + assert ticket.recorded == (len(out) >= 3) + await asyncio.sleep(0.01) + assert b"".join(out).endswith(b"[DONE]\n\n") + assert coordinator.recorded == [("c1", 2000.0, 321.0, 7)] + + +@pytest.mark.asyncio +async def test_track_non_streaming_response(): + coordinator = _FakeCoordinator() + frontend = olp.OutputLengthPriority(coordinator, "ridge") + + class Response: + usage = UsageInfo(prompt_tokens=10, completion_tokens=55) + + response = Response() + assert frontend.track(response, olp._Ticket("c", 10.0, 3)) is response + await asyncio.sleep(0.01) + assert coordinator.recorded == [("c", 10.0, 55.0, 3)] + assert frontend.track(response, None) is response + + +@pytest.mark.asyncio +@pytest.mark.parametrize("stream", [False, True], ids=["complete", "streamed"]) +@pytest.mark.parametrize("cls", [CompletionRequest, ChatCompletionRequest]) +async def test_reply_with_n_sequences_is_learned_per_sequence(stream, cls): + """usage.completion_tokens sums the n sequences; the predictor learns one sequence's length.""" + coordinator = _FakeCoordinator() + frontend = olp.OutputLengthPriority(coordinator, "ridge") + request = _gen_request("c1", 2000, cls=cls) + request.n = 4 + request.stream = stream + ticket = await frontend.assign(request) + if stream: + + async def reply(): + yield _sse({"choices": [{"text": "a"}]}) + yield _sse({"choices": [], "usage": {"completion_tokens": 1200}}) + + assert [chunk async for chunk in frontend.track(reply(), ticket)] + else: + + class Response: + usage = UsageInfo(prompt_tokens=2000, completion_tokens=1200) + + frontend.track(Response(), ticket) + await asyncio.sleep(0.01) + assert coordinator.recorded == [("c1", 2000.0, 300.0, 7)] + + +# ------------------------------------------------------ input validation, bounded state and streams + + +def test_non_finite_values_never_reach_the_models(): + predictor = olp.OnlineLengthPredictor("ridge") + for bad in (float("nan"), float("inf"), -1.0): + _, key = predictor.predict("c", 1000, 0.0) + assert not predictor.record("c", 1000, bad, key, 0.0) + assert not predictor.record("c", bad, 100, None, 0.0) + with pytest.raises(ValueError, match="finite"): + predictor.predict("c", bad, 0.0) + assert predictor.invalid == 6 and predictor.learned == 0 and predictor.ridge.n == 0 + assert predictor.median.n == 0 and len(predictor.table) == 0 + _learn(predictor, olp.RIDGE_MIN_ROWS, 0.0) + tokens, _ = predictor.predict("x", 1000, olp.RIDGE_REFIT_S) + assert math.isfinite(tokens) and all(math.isfinite(w) for w in predictor.ridge.coef) + assert olp.priority_of(float("nan")) == pytest.approx(olp.priority_of(olp.PRIOR_TOKENS)) + assert olp.priority_of(float("inf")) == 0.0 + + +def test_out_of_range_lengths_never_reach_the_models(): + """Finite lengths past MAX_TOKENS are invalid, and a model's log prediction is clamped before expm1.""" + predictor = olp.OnlineLengthPredictor("ridge") + for i in range(300): + _, key = predictor.predict(f"c{i}", 1000 + i, 0.0) + assert predictor.record(f"c{i}", 1000 + i, 200.0 + i, key, 0.0) + for _ in range(2000): + assert not predictor.record(None, 1000, 1e308, None, 0.0) + assert not predictor.record(None, olp.MAX_TOKENS + 1, 100.0, None, 0.0) + assert not predictor.record(None, 10**400, 100.0, None, 0.0) + assert predictor.invalid == 2002 and predictor.learned == 300 + with pytest.raises(ValueError, match="finite"): + predictor.predict(None, 1e308, 0.0) + for isl in (1000, 8192, 131072, olp.MAX_TOKENS): + tokens, _ = predictor.predict(None, isl, olp.RIDGE_REFIT_S) + assert 0.0 <= tokens <= olp.MAX_TOKENS * (1 + 1e-12) + assert predictor.ridge_fits == 1 + # A model that extrapolates past expm1's range (log1p > 709.78) predicts MAX_TOKENS. + predictor.ridge.intercept = 1e4 + tokens, _ = predictor.predict(None, 8192, olp.RIDGE_REFIT_S) + assert tokens == pytest.approx(olp.MAX_TOKENS) + predictor.ridge.intercept = -1e4 + assert predictor.predict(None, 8192, olp.RIDGE_REFIT_S)[0] == 0.0 + predictor.ridge.intercept = float("nan") + assert predictor.predict(None, 8192, olp.RIDGE_REFIT_S)[0] == olp.PRIOR_TOKENS + assert olp.is_token_count(olp.MAX_TOKENS) and olp.is_token_count(0) + assert not olp.is_token_count(olp.MAX_TOKENS + 1) and not olp.is_token_count(float("nan")) + + +def test_conversationless_replies_train_the_global_models(): + predictor = olp.OnlineLengthPredictor("ridge") + for i in range(olp.RIDGE_MIN_ROWS): + _, key = predictor.predict(None, 1000 + i, 0.0) + assert predictor.record(None, 1000 + i, 300.0, key, 0.0) + assert predictor.learned == predictor.without_conversation == olp.RIDGE_MIN_ROWS + assert len(predictor.table) == 0 and predictor.median.value() == 300.0 + assert predictor.predict(None, 1000, 1.0)[0] == 300.0 # the median, not the prior + # A conversation-less reply without its key still has its (history-free) features. + assert predictor.record(None, 1000, 300.0, None, 1.0) and predictor.unmatched == 0 + predictor.predict(None, 1000, olp.RIDGE_REFIT_S) + assert predictor.ridge_fits == 1 + + +def test_nothing_learned_is_reported(monkeypatch): + warnings = [] + monkeypatch.setattr(olp.logger, "warning", lambda msg, *a, **k: warnings.append(msg)) + monkeypatch.setattr(olp, "NOTHING_LEARNED_WARN_AFTER", 5) + predictor = olp.OnlineLengthPredictor("ridge") + for _ in range(5): + predictor.record("c", 1000, 1.0, None, 0.0) + assert any("none of the first 5 replies was learned" in w for w in warnings) + + +def test_predictor_state_is_bounded(): + median = olp.RunningMedian(window=3) + for v in (100, 1, 2, 3, 50): + median.add(v) + assert median.value() == 3 and median.n == 5 and len(median._sorted) == 3 + fitter = _FakeFitter(_good_fit()) + predictor = olp.OnlineLengthPredictor("ridge_gbm", gbm_fitter=fitter) + predictor.gbm_max_rows = olp.GBM_MIN_ROWS + width = len(olp.FEATURES) + 1 + _learn(predictor, 3 * olp.GBM_MIN_ROWS, 0.0) + assert len(predictor.gbm_rows) == olp.GBM_MIN_ROWS * width + assert predictor.gbm_n == 3 * olp.GBM_MIN_ROWS + # The newest reply overwrote the oldest slot of the ring. + newest = 3 * olp.GBM_MIN_ROWS - 1 + slot = (newest % olp.GBM_MIN_ROWS) * width + assert predictor.gbm_rows[slot + width - 1] == pytest.approx(math.log1p(50 + newest % 400)) + predictor.predict("x", 1000, olp.GBM_REFIT_S) + assert fitter.started[0][:2] == (olp.GBM_MIN_ROWS, olp.GBM_MIN_ROWS * width) + assert olp.RunningMedian().window == olp.MEDIAN_WINDOW + + +def test_fit_children_get_the_server_import_path(tmp_path, monkeypatch): + """-I drops PYTHONPATH and the user site; the children get the server's sys.path instead.""" + extra = tmp_path / "site" + extra.mkdir() + monkeypatch.syspath_prepend(str(extra)) + monkeypatch.chdir(tmp_path) + monkeypatch.syspath_prepend(str(tmp_path)) + paths = olp.child_sys_path() + assert str(extra) in paths and str(tmp_path) not in paths and "" not in paths + argv_file = tmp_path / "argv.json" + fake_python = tmp_path / "python" + fake_python.write_text( + "#!/usr/bin/env python3\n" + "import json, sys\n" + f"json.dump(sys.argv[1:], open({str(argv_file)!r}, 'w'))\n" + ) + fake_python.chmod(0o755) + with pytest.raises(ImportError, match="unreadable fit output"): + olp.check_gbm_dependencies(str(fake_python)) # it runs the fit script, which wrote nothing + argv = json.loads(argv_file.read_text()) + header = json.loads(argv[-1]) + assert argv[0] == "-I" and header["n"] == olp.GBM_CHECK_ROWS + assert str(extra) in header["sys_path"] + fitter = olp.SubprocessGbmFitter(python=str(fake_python), sync=True) + fitter.start(olp.array("d", [0.0] * len(olp.FEATURES) + [1.0]), 1, {"rows": 1}) + argv = json.loads(argv_file.read_text()) + header = json.loads(argv[-1]) + assert argv[0] == "-I" and header["n"] == 1 and str(extra) in header["sys_path"] + # A real -I child imports a module that only the server's path has. + (extra / "only_on_server_path.py").write_text("VALUE = 7\n") + import subprocess + import sys as _sys + + result = subprocess.run( + [ + _sys.executable, + "-I", + "-c", + "import json, sys; sys.path[:0] = json.loads(sys.argv[1]); " + "import only_on_server_path as m; print(m.VALUE)", + json.dumps(olp.child_sys_path()), + ], + capture_output=True, + check=False, + ) + assert result.stdout.strip() == b"7", result.stderr + + +@pytest.mark.asyncio +async def test_streams_ask_for_usage_and_drop_it_when_the_client_did_not(): + coordinator = _FakeCoordinator() + frontend = olp.OutputLengthPriority(coordinator, "ridge") + request = _gen_request("c1", 2000) + request.stream = True + ticket = await frontend.assign(request) + assert ( + request.stream_options.include_usage and not request.stream_options.continuous_usage_stats + ) + assert ticket.strip_usage + final = _sse({"choices": [], "usage": {"completion_tokens": 321}}) + + async def stream(): + yield _sse({"choices": [{"text": "a"}]})[:7] + yield _sse({"choices": [{"text": "a"}]})[7:] + final[:9] + yield final[9:] + b"data: [DONE]\n\n" + + relayed = b"".join([chunk async for chunk in frontend.track(stream(), ticket)]) + assert relayed == _sse({"choices": [{"text": "a"}]}) + b"data: [DONE]\n\n" + await asyncio.sleep(0.01) + assert coordinator.recorded == [("c1", 2000.0, 321.0, 7)] + # A client that asked for usage keeps the chunk. + asked = _gen_request("c1", 2000) + asked.stream = True + asked.stream_options = olp_stream_options(include_usage=True) + assert not (await frontend.assign(asked)).strip_usage + + +def olp_stream_options(**kwargs): + from tensorrt_llm.serve.openai_protocol import StreamOptions + + return StreamOptions(**kwargs) + + +@pytest.mark.asyncio +async def test_interrupted_stream_is_not_learned(): + """Continuous usage of a stream that ends before its final usage chunk is not a reply length.""" + coordinator = _FakeCoordinator() + frontend = olp.OutputLengthPriority(coordinator, "ridge") + ticket = olp._Ticket("c1", 2000.0, 7) + + async def stream(): + yield _sse({"choices": [{"text": "a"}], "usage": {"completion_tokens": 5}}) + raise ConnectionResetError("client went away") + + with pytest.raises(ConnectionResetError): + async for _ in frontend.track(stream(), ticket): + pass + await asyncio.sleep(0.01) + # Not learned: the coordinator only drops its row (out None). + assert coordinator.recorded == [("c1", 2000.0, None, 7)] and frontend.no_usage == 1 + assert frontend.recorded == 0 + + +@pytest.mark.asyncio +async def test_replies_are_reported_in_batches(monkeypatch): + monkeypatch.setattr(olp, "RECORD_BATCH_MAX", 3) + calls = [] + + class Coordinator(_FakeCoordinator): + async def record_output_lengths(self, records): + calls.append(list(records)) + return len(records) + + frontend = olp.OutputLengthPriority(Coordinator(), "ridge", record_flush_s=0.05) + for i in range(4): + frontend._record(olp._Ticket("c", 10.0, i), 50 + i) + await asyncio.sleep(0) + assert [len(c) for c in calls] == [3] + await asyncio.sleep(0.1) + assert [len(c) for c in calls] == [3, 1] + + +@pytest.mark.asyncio +async def test_prediction_from_the_generation_placement(): + """In a fleet the prediction arrives with /select; no separate coordinator call.""" + coordinator = _FakeCoordinator() + frontend = olp.OutputLengthPriority(coordinator, "ridge", via_select=True) + request = _gen_request("c1", 2000) + ticket = await frontend.assign(request, placed_later=True) + assert coordinator.predicted == [] and ticket.via_select + frontend.placed(ticket, request, {olp.OUTPUT_LENGTH_KEY: {"tokens": 9.0, "key": 11}}) + assert ticket.key == 11 and frontend.assigned == 1 + missing = _gen_request("c2", 2000) + ticket = await frontend.assign(missing, placed_later=True) + frontend.placed(ticket, missing, {}) + assert frontend.missing == 1 and missing.priority == pytest.approx(frontend.prior_priority) + # A request placed before its context phase (conditional disaggregation) asks separately. + early = _gen_request("c3", 2000) + assert (await frontend.assign(early)).key == 7 and coordinator.predicted == [("c3", 2000.0)] + + +def test_generated_subagent_ids_stay_out_of_the_conversation_table(): + """A parent-only sub-agent request gets a fresh id per request: it trains the global models only.""" + from types import SimpleNamespace + + from tensorrt_llm.serve.openai_disagg_server import OpenAIDisaggServer + + predictor = olp.OnlineLengthPredictor("ridge") + for i in range(3): + request = _gen_request(None, 1000 + i) + OpenAIDisaggServer._extract_conversation_id( + request, SimpleNamespace(headers={"x-parent-id": "parent"}), "x-parent-id" + ) + assert request.conversation_params.conversation_id.startswith("subagent:") + conv, isl = olp.request_inputs(request) + assert conv is None and isl == 1000 + i + _, key = predictor.predict(conv, isl, 0.0) + assert predictor.record(conv, isl, 300.0, key, 0.0) + assert len(predictor.table) == 0 and predictor.learned == 3 + assert predictor.without_conversation == 3 and predictor.unmatched == 0 + # The context request's copy keeps the mark; a client-sent id with that prefix is a conversation. + assert ConversationParams.for_one_request("x").model_copy().generated_for_one_request + assert olp.request_inputs(_gen_request("subagent:mine", 1000))[0] == "subagent:mine" + + +def test_pending_rows_leave_on_failure_reuse_and_age(): + """A row leaves when its request fails, a repeated prediction keeps one row, old rows expire.""" + predictor = olp.OnlineLengthPredictor("ridge") + _, key = predictor.predict("c", 1000, 0.0) + # The same request predicted again (a repeated /select) keeps its key and its one row. + assert predictor.predict("c", 1000, 1.0, key)[1] == key and len(predictor._pending) == 1 + # A failed request is reported with out None: its row goes, nothing is learned. + assert not predictor.record("c", 1000, None, key, 2.0) + assert len(predictor._pending) == 0 and predictor.dropped == 1 + assert predictor.reported == 0 and predictor.learned == 0 + # An unknown (already dropped) key gets a new one. + _, new_key = predictor.predict("c", 1000, 3.0, key) + assert new_key != key + # A row older than PENDING_MAX_AGE_S leaves although the count cap is far away. + _, recent = predictor.predict("d", 1000, olp.PENDING_MAX_AGE_S) + predictor.predict("e", 1000, olp.PENDING_MAX_AGE_S + 3.5) + assert new_key not in predictor._pending and recent in predictor._pending + + +@pytest.mark.asyncio +async def test_abandoned_request_drops_its_row(): + coordinator = _FakeCoordinator() + frontend = olp.OutputLengthPriority(coordinator, "ridge") + ticket = olp._Ticket("c1", 2000.0, 7) + frontend.abandon(ticket) + frontend.abandon(ticket) # once only + frontend.abandon(olp._Ticket("c2", 10.0, None)) # nothing to drop without a key + frontend.abandon(None) + await asyncio.sleep(0.01) + assert coordinator.recorded == [("c1", 2000.0, None, 7)] and frontend.recorded == 0 diff --git a/tests/unittest/disaggregated/test_output_length_service.py b/tests/unittest/disaggregated/test_output_length_service.py new file mode 100644 index 000000000000..4dbd0473316e --- /dev/null +++ b/tests/unittest/disaggregated/test_output_length_service.py @@ -0,0 +1,538 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""output_length_prediction wired through the disaggregated config, coordinator and service.""" + +import asyncio +import json +from unittest.mock import AsyncMock + +import msgpack +import pytest +from fastapi.testclient import TestClient + +from tensorrt_llm.llmapi.disagg_utils import ( + DisaggServerConfig, + OutputLengthPredictionConfig, + extract_disagg_cfg, +) +from tensorrt_llm.serve import output_length_predictor as olp +from tensorrt_llm.serve.coordinator_server import CoordinatorServer +from tensorrt_llm.serve.disagg_coordinator import CoordinatorClient, DisaggCoordinatorService +from tensorrt_llm.serve.openai_disagg_service import OpenAIDisaggregatedService +from tensorrt_llm.serve.openai_protocol import ( + CompletionRequest, + CompletionResponse, + CompletionResponseChoice, + ConversationParams, + DisaggregatedParams, + UsageInfo, +) +from tensorrt_llm.serve.router import Router + +pytestmark = pytest.mark.cpu_only + + +def _client_factory(*_args, **_kwargs): + return AsyncMock() + + +def _config(predictor="ridge"): + config = DisaggServerConfig(server_configs=[]) + if predictor is not None: + config.output_length_prediction = OutputLengthPredictionConfig(predictor=predictor) + return config + + +def test_config_parsing(): + assert extract_disagg_cfg().output_length_prediction is None + assert extract_disagg_cfg(output_length_prediction={}).output_length_prediction.predictor == ( + "ridge" + ) + config = extract_disagg_cfg(output_length_prediction={"predictor": "ridge"}) + assert config.output_length_prediction.predictor == "ridge" + with pytest.raises(ValueError): + extract_disagg_cfg(output_length_prediction={"predictor": "ema"}) + with pytest.raises(ValueError): + extract_disagg_cfg(output_length_prediction={"model": "file.json"}) + # Not a per-role option: it is not copied into the server sections. + config = extract_disagg_cfg( + output_length_prediction={"predictor": "ridge"}, context_servers={"num_instances": 0} + ) + assert all("output_length_prediction" not in s.other_args for s in config.server_configs) + + +@pytest.mark.asyncio +async def test_coordinator_predicts_and_learns_in_process(): + coordinator = DisaggCoordinatorService(_config(), client_factory=_client_factory) + tokens, key = await coordinator.predict_output_length("c", 1000) + assert tokens == olp.PRIOR_TOKENS + assert await coordinator.record_output_lengths([("c", 1000, 64.0, key)]) == 1 + assert (await coordinator.predict_output_length("c", 1200))[0] == 64.0 + off = DisaggCoordinatorService(_config(None), client_factory=_client_factory) + with pytest.raises(ValueError, match="not configured"): + await off.predict_output_length("c", 1000) + + +def test_coordinator_server_route(): + coordinator = DisaggCoordinatorService(_config(), client_factory=_client_factory) + # No lifespan: the coordinator is not started (it has no servers to wait for). + http = TestClient(CoordinatorServer(coordinator).app) + + def post(body): + raw = http.post("/output_length", content=msgpack.packb(body, use_bin_type=True)) + return raw.status_code, msgpack.unpackb(raw.content, raw=False) + + status, reply = post({"op": "predict", "conv": "c", "isl": 1000}) + assert status == 200 and reply["tokens"] == olp.PRIOR_TOKENS + status, reply = post({"op": "record", "records": [["c", 1000, 80, reply["key"]]]}) + assert status == 200 and reply == {"learned": 1} + assert post({"op": "predict", "conv": "c", "isl": 1100})[1]["tokens"] == 80.0 + nan, inf = float("nan"), float("inf") + for bad in ( + {"op": "fit"}, + {"op": "predict", "conv": 3, "isl": 1}, + {"op": "predict", "conv": "c", "isl": True}, + {"op": "predict", "conv": "c", "isl": nan}, + {"op": "predict", "conv": "c", "isl": -inf}, + {"op": "record", "conv": "c", "isl": 1}, + {"op": "record", "records": [["c", 1, 5, "k"]]}, + {"op": "record", "records": [["c", 1, nan, None]]}, + {"op": "record", "records": [["c", inf, 5, None]]}, + {"op": "record", "records": [["c", 1, -5, None]]}, + {"op": "record", "records": [[None, 1000, 1e308, None]]}, + {"op": "record", "records": [["c", olp.MAX_TOKENS + 1, 5, None]]}, + {"op": "predict", "conv": "c", "isl": 1e308}, + {"op": "record", "records": [["c", 1, 5]]}, + {"op": "record", "records": [["c", 1, 5, None]] * (olp.RECORD_BATCH_MAX + 1)}, + ): + assert post(bad)[0] == 400, bad + # NaN never reached the models: predictions and priorities stay finite. + tokens = post({"op": "predict", "conv": None, "isl": 1100})[1]["tokens"] + assert tokens == tokens and 0.0 <= olp.priority_of(tokens) <= 1.0 + + +@pytest.mark.asyncio +async def test_coordinator_client_round_trip(): + """A fleet worker's CoordinatorClient reaches the coordinator's predictor over /output_length.""" + from aiohttp import web + from aiohttp.test_utils import TestServer + + coordinator = DisaggCoordinatorService(_config(), client_factory=_client_factory) + seen = [] + + async def handler(request): + body = msgpack.unpackb(await request.read(), raw=False) + seen.append(body) + if body["op"] == "predict": + tokens, key = await coordinator.predict_output_length(body["conv"], body["isl"]) + reply = {"tokens": tokens, "key": key} + else: + reply = { + "learned": await coordinator.record_output_lengths( + [tuple(record) for record in body["records"]] + ) + } + return web.Response(body=msgpack.packb(reply), content_type="application/msgpack") + + app = web.Application() + app.router.add_post("/output_length", handler) + async with TestServer(app) as server: + client = CoordinatorClient(f"http://{server.host}:{server.port}", _config()) + try: + tokens, key = await client.predict_output_length("c", 1000) + assert tokens == olp.PRIOR_TOKENS + assert await client.record_output_lengths([("c", 1000, 77.0, key)]) == 1 + assert (await client.predict_output_length("c", 1100))[0] == 77.0 + finally: + await client.stop() + assert [b["op"] for b in seen] == ["predict", "record", "predict"] + + +def _ctx_response(prompt_tokens): + return CompletionResponse( + model="m", + usage=UsageInfo( + prompt_tokens=prompt_tokens, completion_tokens=1, total_tokens=prompt_tokens + 1 + ), + prompt_token_ids=[1, 2, 3], + choices=[ + CompletionResponseChoice( + index=0, + text="", + finish_reason="length", + disaggregated_params=DisaggregatedParams( + request_type="context_only", disagg_request_id=42, ctx_request_id=42 + ), + ) + ], + ) + + +@pytest.mark.asyncio +async def test_service_sets_priority_before_generation_placement(monkeypatch): + monkeypatch.delenv("TRTLLM_DISAGG_BENCHMARK_GEN_ONLY", raising=False) + config = _config() + coordinator = DisaggCoordinatorService(config, client_factory=_client_factory) + coordinator._ctx_router = AsyncMock(spec=Router) + coordinator._gen_router = AsyncMock(spec=Router) + coordinator._ctx_router.get_next_server.return_value = ("ctx:1", {}) + placed = [] + + async def place_generation(req, **kwargs): + placed.append(req.priority) + return "gen:1", {} + + coordinator._gen_router.get_next_server.side_effect = place_generation + service = OpenAIDisaggregatedService(config, coordinator, client_factory=_client_factory) + service._ctx_client = AsyncMock() + service._gen_client = AsyncMock() + service._ctx_client.send_request.return_value = _ctx_response(5000) + final = f"data: {json.dumps({'choices': [], 'usage': {'completion_tokens': 300}})}\n\n" + + async def gen_stream(): + yield b'data: {"choices": [{"text": "x"}]}\n\n' + yield final.encode() + + service._gen_client.send_request.return_value = gen_stream() + + async def send(conv): + request = CompletionRequest( + model="m", + prompt="hi", + max_tokens=7, + stream=True, + conversation_params=ConversationParams(conversation_id=conv), + ) + response = await service._send_disagg_request_ctx_first(request) + return [chunk async for chunk in response] + + chunks = await send("conv-1") + # The client did not ask for usage: the generation leg did, and its usage chunk is dropped. + gen_req = service._gen_client.send_request.call_args.args[0] + assert gen_req.stream_options.include_usage + assert final.encode() not in b"".join(chunks) + assert placed == [pytest.approx(olp.priority_of(olp.PRIOR_TOKENS))] + await asyncio.sleep(0.01) # the record task + predictor = coordinator._output_length_predictor + assert predictor.table.recorded == 1 + service._gen_client.send_request.return_value = gen_stream() + await send("conv-1") + # The conversation's learned reply (300 tokens) now sets the priority; max_tokens=7 does not. + assert placed[-1] == pytest.approx(olp.priority_of(300.0)) + + +@pytest.mark.asyncio +async def test_service_without_prediction_leaves_priority_alone(monkeypatch): + monkeypatch.delenv("TRTLLM_DISAGG_BENCHMARK_GEN_ONLY", raising=False) + config = _config(None) + coordinator = DisaggCoordinatorService(config, client_factory=_client_factory) + coordinator._ctx_router = AsyncMock(spec=Router) + coordinator._gen_router = AsyncMock(spec=Router) + coordinator._ctx_router.get_next_server.return_value = ("ctx:1", {}) + coordinator._gen_router.get_next_server.return_value = ("gen:1", {}) + service = OpenAIDisaggregatedService(config, coordinator, client_factory=_client_factory) + assert service._output_length_priority is None + service._ctx_client = AsyncMock() + service._gen_client = AsyncMock() + service._ctx_client.send_request.return_value = _ctx_response(5000) + service._gen_client.send_request.return_value = "response" + request = CompletionRequest(model="m", prompt="hi") + assert await service._send_disagg_request_ctx_first(request) == "response" + assert service._gen_client.send_request.call_args.args[0].priority is None + + +@pytest.mark.asyncio +async def test_select_predicts_the_output_length(): + """The coordinator predicts inside /select: the pooled placement orders by it, no extra call.""" + from tensorrt_llm.llmapi.disagg_utils import CtxGenServerConfig, RouterConfig, ServerRole + + config = _config() + config.server_configs = [CtxGenServerConfig(type="gen", hostname="g", port=1)] + config.ctx_router_config = RouterConfig(type="round_robin", server_role=ServerRole.CONTEXT) + config.gen_router_config = RouterConfig( + type="load_balancing", + server_role=ServerRole.GENERATION, + args={"max_requests_per_server": 1}, + ) + coordinator = DisaggCoordinatorService(config, client_factory=_client_factory) + await coordinator.record_output_lengths( + [("short", 1000, 50.0, None), ("long", 1000, 5000.0, None)] + ) + server, info, _ = await coordinator.select("generation", {}, 1, None) + assert server == "g:1" and olp.OUTPUT_LENGTH_KEY not in info + waits = { + rid: asyncio.create_task( + coordinator.select( + "generation", {olp.OUTPUT_LENGTH_KEY: {"conv": conv, "isl": 1500.0}}, rid, None + ) + ) + for rid, conv in ((2, "long"), (3, "short")) + } + for _ in range(5): + await asyncio.sleep(0) + await coordinator.finish("generation", 1) + for _ in range(5): + await asyncio.sleep(0) + assert waits[3].done() and not waits[2].done() # the shorter predicted reply goes first + _, info, _ = await waits[3] + prediction = info[olp.OUTPUT_LENGTH_KEY] + assert prediction["tokens"] == 50.0 and isinstance(prediction["key"], int) + assert prediction["priority"] == pytest.approx(olp.priority_of(50.0)) + await coordinator.finish("generation", 3) + assert (await waits[2])[1][olp.OUTPUT_LENGTH_KEY]["tokens"] == 5000.0 + await coordinator.finish("generation", 2) + # Invalid inputs are ignored rather than predicted. + _, info, _ = await coordinator.select( + "generation", {olp.OUTPUT_LENGTH_KEY: {"conv": None, "isl": float("nan")}}, 4, None + ) + assert olp.OUTPUT_LENGTH_KEY not in info + await coordinator.finish("generation", 4) + + # A predictor error never fails the placement: the request gets the prior's priority. + def overflow(*_args): + raise OverflowError("math range error") + + coordinator._output_length_predictor.predict = overflow + routing_key = {olp.OUTPUT_LENGTH_KEY: {"conv": "c", "isl": 9000.0}} + server, info, _ = await coordinator.select("generation", routing_key, 5, None) + assert server == "g:1" and olp.OUTPUT_LENGTH_KEY not in info + assert routing_key["priority"] == pytest.approx(olp.priority_of(olp.PRIOR_TOKENS)) + assert coordinator._output_length_errors == 1 + await coordinator.finish("generation", 5) + await coordinator.stop() + + +@pytest.mark.asyncio +async def test_fleet_worker_gets_the_prediction_from_select(monkeypatch): + """A delegating generation router sends the prediction inputs and applies the returned priority.""" + from tensorrt_llm.llmapi.disagg_utils import RouterConfig, ServerRole + from tensorrt_llm.serve.router import CoordinatorDelegatingRouter, create_router + + local = create_router( + RouterConfig(type="load_balancing", server_role=ServerRole.GENERATION), ["g:1"] + ) + router = CoordinatorDelegatingRouter("http://c:1", local, "generation", 5.0) + assert router.enable_output_length_prediction() + # A conversation router's key is the conversation id: it keeps the separate prediction call. + conversation = create_router( + RouterConfig(type="conversation", server_role=ServerRole.GENERATION), ["g:1"] + ) + assert not CoordinatorDelegatingRouter( + "http://c:1", conversation, "generation", 5.0 + ).enable_output_length_prediction() + assert not CoordinatorDelegatingRouter( + "http://c:1", local, "context", 5.0 + ).enable_output_length_prediction() + sent = [] + + async def post_select(payload): + sent.append(payload) + return { + "server": "g:1", + "info": {olp.OUTPUT_LENGTH_KEY: {"tokens": 1024.0, "key": 3, "priority": 0.5}}, + } + + monkeypatch.setattr(router, "_post_select", post_select) + request = CompletionRequest( + model="m", + prompt="x", + conversation_params=ConversationParams(conversation_id="c"), + disaggregated_params=DisaggregatedParams( + request_type="generation_only", + ctx_request_id=5, + ctx_usage=UsageInfo(prompt_tokens=777), + ), + ) + server, info = await router.get_next_server(request) + assert server == "g:1" and request.priority == 0.5 and info[olp.OUTPUT_LENGTH_KEY]["key"] == 3 + assert sent[0]["routing_key"][olp.OUTPUT_LENGTH_KEY] == {"conv": "c", "isl": 777.0} + await router.close() + + +def test_prediction_requires_context_first(): + """generation_first requests reach the generation server without a prompt length to predict from.""" + with pytest.raises(ValueError, match="context_first"): + extract_disagg_cfg(output_length_prediction={}, schedule_style="generation_first") + config = extract_disagg_cfg(output_length_prediction={}, schedule_style="context_first") + assert config.output_length_prediction.predictor == "ridge" + + +def test_prediction_refuses_a_generation_first_override_after_parsing(): + """`trtllm-serve disaggregated -s generation_first` sets schedule_style after the parse-time check.""" + config = _config() + config.schedule_style = "generation_first" + coordinator = DisaggCoordinatorService(config, client_factory=_client_factory) + with pytest.raises(ValueError, match="context_first"): + OpenAIDisaggregatedService(config, coordinator, client_factory=_client_factory) + + +@pytest.mark.asyncio +async def test_request_without_a_context_phase_gets_the_prior_priority(monkeypatch): + """Conditional disaggregation served locally: a client-sent priority never passes through.""" + monkeypatch.delenv("TRTLLM_DISAGG_BENCHMARK_GEN_ONLY", raising=False) + config = _config() + coordinator = DisaggCoordinatorService(config, client_factory=_client_factory) + coordinator._ctx_router = AsyncMock(spec=Router) + coordinator._gen_router = AsyncMock(spec=Router) + service = OpenAIDisaggregatedService(config, coordinator, client_factory=_client_factory) + service._check_conditional_disagg = AsyncMock(return_value=("gen:1", False)) + service._ctx_client = AsyncMock() + service._gen_client = AsyncMock() + service._gen_client.send_request.return_value = "response" + request = CompletionRequest(model="m", prompt="hi", priority=1.0) + assert await service._send_disagg_request_ctx_first(request) == "response" + gen_req = service._gen_client.send_request.call_args.args[0] + assert gen_req.priority == pytest.approx(olp.priority_of(olp.PRIOR_TOKENS)) + service._ctx_client.send_request.assert_not_called() + + +@pytest.mark.asyncio +async def test_generation_first_stream_releases_the_context_server_without_a_seat(monkeypatch): + """No generation seat (503): the context reservation made before it is released at once.""" + from tensorrt_llm.llmapi.disagg_utils import ServerRole + from tensorrt_llm.serve.router import LoadBalancingRouter + from tensorrt_llm.serve.seat_pool import NoGenerationSeatError + + monkeypatch.delenv("TRTLLM_DISAGG_BENCHMARK_GEN_ONLY", raising=False) + config = _config(None) + config.schedule_style = "generation_first" + coordinator = DisaggCoordinatorService(config, client_factory=_client_factory) + ctx_router = LoadBalancingRouter(ServerRole.CONTEXT, ["ctx:1"]) + coordinator._ctx_router = ctx_router + coordinator._gen_router = AsyncMock(spec=Router) + service = OpenAIDisaggregatedService(config, coordinator, client_factory=_client_factory) + service._ctx_client = AsyncMock() + service._gen_client = AsyncMock() + service._gen_client.send_request.side_effect = NoGenerationSeatError("no seat within 60 s") + request = CompletionRequest(model="m", prompt="hi", stream=True) + with pytest.raises(NoGenerationSeatError): + await service._send_disagg_request_gen_first(request) + assert ctx_router._get_server_load("ctx:1") == 0 and ctx_router._req_routing_table == {} + service._ctx_client.send_request.assert_not_called() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("fleet", [False, True], ids=["in_process", "fleet"]) +async def test_responses_request_waits_for_a_seat_at_the_prior(fleet): + """/v1/responses is not predicted: a pooled seat queue ranks it at the prior, not by a client value.""" + from tensorrt_llm.llmapi.disagg_utils import CtxGenServerConfig, RouterConfig, ServerRole + from tensorrt_llm.serve.openai_protocol import ResponsesRequest + from tensorrt_llm.serve.router import CoordinatorDelegatingRouter, PooledLoadBalancingRouter + + config = _config() + config.server_configs = [CtxGenServerConfig(type="gen", hostname="g", port=1)] + config.ctx_router_config = RouterConfig(type="round_robin", server_role=ServerRole.CONTEXT) + config.gen_router_config = RouterConfig( + type="load_balancing", + server_role=ServerRole.GENERATION, + args={"max_requests_per_server": 1}, + ) + coordinator = DisaggCoordinatorService(config, client_factory=_client_factory) + if fleet: + coordinator._gen_router = CoordinatorDelegatingRouter( + "http://c:1", coordinator.gen_router, "generation", 5.0 + ) + service = OpenAIDisaggregatedService(config, coordinator, client_factory=_client_factory) + gen_router = service._gen_router + local = gen_router._local if fleet else gen_router + assert isinstance(local, PooledLoadBalancingRouter) + prior = olp.priority_of(olp.PRIOR_TOKENS) + for client_priority in (0.0, 1.0): + # ResponsesRequest keeps unknown fields: a client "priority" is an extra, not a priority. + request = ResponsesRequest(model="m", input="hi", priority=client_priority) + assert local.routing_key(request)["priority"] == pytest.approx(prior) + # A request model with a priority field keeps its (orchestrator-set) value. + assert local.routing_key(CompletionRequest(model="m", prompt="x", priority=0.9))[ + "priority" + ] == pytest.approx(0.9) + if not fleet: + # The in-process placement orders by the same priority. + first = CompletionRequest(model="m", prompt="x", priority=0.5) + assert (await local.get_next_server(first))[0] == "g:1" + responses = asyncio.create_task( + local.get_next_server(ResponsesRequest(model="m", input="hi", priority=0.0)) + ) + completion = asyncio.create_task( + local.get_next_server(CompletionRequest(model="m", prompt="x", priority=0.6)) + ) + for _ in range(5): + await asyncio.sleep(0) + await local.finish_request(first) + for _ in range(5): + await asyncio.sleep(0) + assert responses.done() and not completion.done() + completion.cancel() + await asyncio.gather(completion, return_exceptions=True) + await coordinator.stop() + + +@pytest.mark.asyncio +async def test_select_keeps_one_row_per_request_and_drops_it_on_failure(): + """A repeated /select reuses its prediction key; a select that gets no seat drops its row.""" + from tensorrt_llm.llmapi.disagg_utils import CtxGenServerConfig, RouterConfig, ServerRole + from tensorrt_llm.serve.seat_pool import NoGenerationSeatError + + config = _config() + config.server_configs = [CtxGenServerConfig(type="gen", hostname="g", port=1)] + config.ctx_router_config = RouterConfig(type="round_robin", server_role=ServerRole.CONTEXT) + config.gen_router_config = RouterConfig( + type="load_balancing", + server_role=ServerRole.GENERATION, + args={"max_requests_per_server": 1}, + ) + coordinator = DisaggCoordinatorService(config, client_factory=_client_factory) + predictor = coordinator._output_length_predictor + + def key_of(rid): + return {olp.OUTPUT_LENGTH_KEY: {"conv": "c", "isl": 1000.0}} + + _, info, _ = await coordinator.select("generation", key_of(1), 1, None) + _, again, _ = await coordinator.select("generation", key_of(1), 1, None) + assert again[olp.OUTPUT_LENGTH_KEY]["key"] == info[olp.OUTPUT_LENGTH_KEY]["key"] + assert len(predictor._pending) == 1 + parked = asyncio.create_task(coordinator.select("generation", key_of(2), 2, None)) + for _ in range(5): + await asyncio.sleep(0) + assert len(predictor._pending) == 2 + await coordinator.stop() # fails the parked select: no seat, so no reply will come + with pytest.raises(NoGenerationSeatError): + await parked + assert len(predictor._pending) == 1 and predictor.dropped == 1 + await coordinator.finish("generation", 1) + assert coordinator._prediction_keys == {} + + +@pytest.mark.asyncio +async def test_failed_generation_drops_the_prediction_row(monkeypatch): + monkeypatch.delenv("TRTLLM_DISAGG_BENCHMARK_GEN_ONLY", raising=False) + config = _config() + coordinator = DisaggCoordinatorService(config, client_factory=_client_factory) + coordinator._ctx_router = AsyncMock(spec=Router) + coordinator._gen_router = AsyncMock(spec=Router) + coordinator._ctx_router.get_next_server.return_value = ("ctx:1", {}) + coordinator._gen_router.get_next_server.return_value = ("gen:1", {}) + service = OpenAIDisaggregatedService(config, coordinator, client_factory=_client_factory) + service._ctx_client = AsyncMock() + service._gen_client = AsyncMock() + service._ctx_client.send_request.return_value = _ctx_response(5000) + service._gen_client.send_request.side_effect = ConnectionResetError("generation server died") + request = CompletionRequest( + model="m", prompt="hi", conversation_params=ConversationParams(conversation_id="c") + ) + with pytest.raises(ConnectionResetError): + await service._send_disagg_request_ctx_first(request) + await asyncio.sleep(0.01) # the record task + predictor = coordinator._output_length_predictor + assert len(predictor._pending) == 0 and predictor.dropped == 1 and predictor.learned == 0 diff --git a/tests/unittest/disaggregated/test_peer.py b/tests/unittest/disaggregated/test_peer.py index 09c8ae18a255..7d0f0ce0ca57 100644 --- a/tests/unittest/disaggregated/test_peer.py +++ b/tests/unittest/disaggregated/test_peer.py @@ -759,6 +759,39 @@ def test_receiver_rejects_view_mismatch_before_registration( receiver.shutdown() +def test_receiver_registers_with_sender_lacking_layers(monkeypatch: pytest.MonkeyPatch) -> None: + # A generation rank with a drafter layer the context server does not send + # still registers; only the shared layers are transferred. + from tensorrt_llm._torch.disaggregation.native.transfer import MessageType + + local_ri, sender_ri = [ + make_rankinfo( + instance_name=name, + tp_size=1, + tokens_per_block=2, + dims_per_head=2, + layer_num_per_pp=layers, + page_table=_make_per_view_page_table([2, 1], MapperKind.INDEXED), + ) + for name, layers in (("receiver", [3]), ("sender", [2])) + ] + sender_ri.sender_endpoints = ["tcp://sender"] + registrar = _make_peer_registrar(local_ri) + receiver, messengers, _ = _make_receiver_for_view_validation( + monkeypatch, registrar, {"tcp://info": sender_ri}, enforce_physical_ownership=False + ) + try: + params = SimpleNamespace(ctx_info_endpoint="tcp://info", ctx_dp_rank=0) + sender_info = receiver._get_sender_info(params) + assert sender_info.layer_num_per_pp == [2] + assert receiver._incompatible_peers == {} + messengers["tcp://sender"].send.assert_called_once_with( + [MessageType.REGISTER_RANK_INFO, local_ri.to_bytes()] + ) + finally: + receiver.shutdown() + + def test_view_validation_allows_nonoverlapping_pp_stage() -> None: local_page_table = _make_per_view_page_table([2, 1], MapperKind.INDEXED) local_page_table.layer_groups[0].local_layers = [LocalLayer(0, 2), LocalLayer(1, 3)] @@ -935,6 +968,33 @@ def test_peer_registrar_rejects_mismatched_protocol_version(): reg.register(peer_ri.instance_name, peer_ri.instance_rank, peer_ri) +@pytest.mark.parametrize(("self_layers", "peer_layers"), [([3], [2]), ([2], [3]), ([3], [1, 1])]) +def test_peer_registrar_layer_count_mismatch_warns(monkeypatch, self_layers, peer_layers): + # Either side may hold layers the other lacks, e.g. a drafter whose cache the + # context server does not transfer; only the shared layers are mapped. + reg = _make_peer_registrar(make_rankinfo(instance_name="gen", layer_num_per_pp=self_layers)) + peer_ri = make_rankinfo( + instance_name="ctx", + instance_rank=1, + pp_size=len(peer_layers), + layer_num_per_pp=peer_layers, + page_table=make_page_table(), + ) + warnings = [] + monkeypatch.setattr(peer_module.logger, "warning", lambda *message: warnings.append(message)) + + reg.register(peer_ri.instance_name, peer_ri.instance_rank, peer_ri) + + assert reg.get_peer_rank_info("ctx", 1) is peer_ri + assert [m for m in warnings if "layer count differs" in " ".join(map(str, m))] == [ + ( + "PeerRegistrar: layer count differs " + f"(local={sum(self_layers)}, peer={sum(peer_layers)}), " + "allowing partial layer transfer.", + ) + ] + + def test_peer_registrar_self_rank_info_property(): self_rankinfo = make_rankinfo(instance_name="local") reg = _make_peer_registrar(self_rankinfo) diff --git a/tests/unittest/disaggregated/test_seat_pool.py b/tests/unittest/disaggregated/test_seat_pool.py new file mode 100644 index 000000000000..4b81c1d945da --- /dev/null +++ b/tests/unittest/disaggregated/test_seat_pool.py @@ -0,0 +1,1053 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Pooled generation dispatch: serve/seat_pool.py and router.PooledLoadBalancingRouter.""" + +import asyncio +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock + +import msgpack +import pytest +from fastapi import HTTPException + +from tensorrt_llm.executor.request import DEFAULT_REQUEST_PRIORITY +from tensorrt_llm.llmapi.disagg_utils import ( + CtxGenServerConfig, + DisaggServerConfig, + RouterConfig, + ServerRole, + extract_disagg_cfg, +) +from tensorrt_llm.serve.coordinator_server import CoordinatorServer +from tensorrt_llm.serve.disagg_coordinator import ( + POOLED_RESERVATION_TIMEOUT_S, + DisaggCoordinatorService, +) +from tensorrt_llm.serve.openai_disagg_server import OpenAIDisaggServer +from tensorrt_llm.serve.openai_protocol import CompletionRequest, DisaggregatedParams +from tensorrt_llm.serve.router import ( + POOLED_SELECT_TIMEOUT_S, + CoordinatorDelegatingRouter, + LoadBalancingRouter, + PooledLoadBalancingRouter, + Router, + build_disagg_routers, + create_router, +) +from tensorrt_llm.serve.seat_pool import NoGenerationSeatError, SeatPool, priority_or_default + +pytestmark = pytest.mark.cpu_only + + +class _Clock: + def __init__(self): + self.now = 0.0 + + def __call__(self): + return self.now + + +# ---------------------------------------------------------------------------------- SeatPool + + +def test_priority_or_default(): + assert priority_or_default(0.25) == 0.25 and priority_or_default(1) == 1.0 + for bad in (None, True, "0.3", float("nan"), -0.1, 1.5): + assert priority_or_default(bad) == DEFAULT_REQUEST_PRIORITY + + +@pytest.mark.parametrize("seats, cap", [(0, None), (True, None), (1.5, None), (1, 0.0), (1, -1.0)]) +def test_pool_rejects_bad_options(seats, cap): + with pytest.raises(ValueError): + SeatPool(seats, cap) + + +def test_pool_order_highest_priority_then_arrival(): + pool = SeatPool(1, clock=_Clock()) + for rid, priority in [(1, 0.3), (2, 0.9), (3, 0.9), (4, None)]: + pool.add(rid, priority, None, None) + order = [] + while len(pool): + waiter, servers = pool.pick(["s0"]) + assert servers == ["s0"] + pool.record_grant(waiter) + order.append(waiter.rid) + assert order == [2, 3, 4, 1] + assert pool.placed == 4 and pool.reordered == 3 + + +def test_pool_cap_puts_aged_waiters_first_oldest_first(): + clock = _Clock() + pool = SeatPool(1, max_wait_s=60.0, clock=clock) + pool.add(1, 0.1, None, None) + clock.now = 10.0 + pool.add(2, 0.2, None, None) + clock.now = 50.0 + pool.add(3, 0.9, None, None) + clock.now = 69.0 + assert pool.pick(["s"])[0].rid == 1 # only request 1 has waited 60 s + clock.now = 70.0 + first = pool.pick(["s"])[0] + pool.record_grant(first) + assert first.rid == 1 and pool.aged == 1 + assert pool.pick(["s"])[0].rid == 2 + + +def test_pool_ages_from_the_orchestrator_arrival(): + """A request past its context phase has waited since it reached the orchestrator.""" + clock = _Clock() + pool = SeatPool(1, max_wait_s=60.0, clock=clock) + pool.add(1, 0.9, None, None) + pool.add(2, 0.1, None, None, orig_elapsed_s=55.0) + assert pool.pick(["s"])[0].rid == 1 + clock.now = 5.0 + assert pool.pick(["s"])[0].rid == 2 # 60 s since its arrival, 5 s in the pool + + +def test_pool_expires_at_the_kv_transfer_timeout(): + """Every waiter gets the deadline, counted from its entry here (generation_first ones too). + + It comes KV_DEADLINE_MARGIN early: the C++ transceiver counts the timeout from the KV send. + """ + clock = _Clock() + pool = SeatPool(1, clock=clock, kv_transfer_timeout_s=60.0) + pool.add(1, 0.5, None, None, orig_elapsed_s=10.0) + clock.now = 10.0 + pool.add(2, 0.5, None, None) # no context phase yet: generation_first + clock.now = 56.9 + assert pool.expire() == [] and pool.remaining_s(pool.waiter(1)) == pytest.approx(0.1) + clock.now = 57.0 + expired = pool.expire() + assert [w.rid for w in expired] == [1] and pool.expired == 1 + assert "KV transfer timeout (60 s less a 5% margin" in pool.expiry_message(expired[0]) + assert len(pool) == 1 and pool.remaining_s(pool.waiter(2)) == pytest.approx(10.0) + clock.now = 67.0 + assert [w.rid for w in pool.expire()] == [2] and len(pool) == 0 + # Without the timeout nothing expires on its own. + plain = SeatPool(1, clock=clock) + plain.add(3, 0.5, None, None, orig_elapsed_s=10.0) + clock.now = 1e6 + assert plain.expire() == [] + + +def test_pool_ages_by_arrival_then_seq(): + """Aged waiters go by arrival at the orchestrator, like AgingPriorityWaitingQueue.""" + clock = _Clock() + pool = SeatPool(1, max_wait_s=60.0, clock=clock) + pool.add(1, 0.5, None, None) # arrival 0 + clock.now = 1.0 + pool.add(2, 0.5, None, None, orig_elapsed_s=30.0) # arrival -29, joined later + clock.now = 60.0 + assert pool.pick(["s"])[0].rid == 2 + assert pool.sort_key(pool.waiter(2), 60.0) < pool.sort_key(pool.waiter(1), 60.0) + + +def test_pool_pick_does_not_scan_every_waiter(monkeypatch): + """A placement looks at one waiter per excluded server, not at the whole queue.""" + clock = _Clock() + pool = SeatPool(1, max_wait_s=600.0, clock=clock, kv_transfer_timeout_s=60.0) + for rid in range(2000): + pool.add(rid, (rid % 97) / 97.0, "ctx0" if rid % 2 else None, None) + calls = [] + real = pool.sort_key + monkeypatch.setattr(pool, "sort_key", lambda w, now: calls.append(w) or real(w, now)) + order = [] + while len(pool) > 1990: + waiter, _ = pool.pick(["s"]) + pool.record_grant(waiter) + order.append(waiter.priority) + assert len(calls) <= 2 * 10 + assert order == sorted(order, reverse=True) and order[0] == 96 / 97.0 + # Removed and placed waiters are never picked again, and expiry pops only the expired. + for rid in range(0, 2000, 3): + pool.remove(rid) + live = len(pool) + assert 0 < live == len(pool.waiters()) < 1990 + clock.now = 56.0 # the deadline is KV_DEADLINE_MARGIN before the 60 s timeout + assert pool.expire() == [] + clock.now = 57.0 + assert len(pool.expire()) == live and len(pool) == 0 and pool.pick(["s"]) is None + + +@pytest.mark.parametrize("cap", [None, 600.0]) +def test_pool_heaps_stay_bounded_under_a_queue_that_never_drains(cap): + """Granted waiters leave both heaps, with or without a wait cap: no growth per placement.""" + pool = SeatPool(1, max_wait_s=cap, clock=_Clock()) + live = 9 + for rid in range(live): + pool.add(rid, 0.5, None, None) + for rid in range(live, live + 20000): + pool.add(rid, 0.5, None, None) + waiter, _ = pool.pick(["s"]) + pool.record_grant(waiter) + bucket = pool._buckets[None] + assert len(bucket.by_arrival) <= 2 * bucket.live + 64 + assert len(bucket.by_priority) <= 2 * bucket.live + 64 + assert len(pool) == live + + +def test_pool_skips_excluded_server(): + pool = SeatPool(1, clock=_Clock()) + pool.add(1, 0.9, "s0", None) + pool.add(2, 0.1, None, None) + assert pool.pick(["s0"])[0].rid == 2 + waiter, servers = pool.pick(["s0", "s1"]) + assert waiter.rid == 1 and servers == ["s1"] + assert pool.pick([]) is None + + +# ---------------------------------------------------------------------------------- router + + +def _router(servers=("s0", "s1"), seats=1, cap=None, kv_ms=None) -> PooledLoadBalancingRouter: + args = {"max_requests_per_server": seats, "max_queue_wait_s": cap} + if kv_ms is not None: + args["kv_transfer_timeout_ms"] = kv_ms + config = RouterConfig(type="load_balancing", server_role=ServerRole.GENERATION, args=args) + router = create_router(config, list(servers)) + assert isinstance(router, PooledLoadBalancingRouter) + return router + + +def test_create_router(): + plain = create_router( + RouterConfig(type="load_balancing", server_role=ServerRole.GENERATION), ["s"] + ) + assert type(plain) is LoadBalancingRouter and not getattr(plain, "pooled", False) + with pytest.raises(ValueError, match="load_balancing"): + create_router( + RouterConfig( + type="round_robin", + server_role=ServerRole.GENERATION, + args={"max_requests_per_server": 1}, + ), + ["s"], + ) + with pytest.raises(ValueError, match="generation"): + create_router( + RouterConfig( + type="load_balancing", + server_role=ServerRole.CONTEXT, + args={"max_requests_per_server": 1}, + ), + ["s"], + ) + with pytest.raises(ValueError, match="use_tokens"): + create_router( + RouterConfig( + type="load_balancing", + server_role=ServerRole.GENERATION, + args={"max_requests_per_server": 1, "use_tokens": True}, + ), + ["s"], + ) + + +def test_routing_key_carries_priority(): + router = _router() + assert router.routing_key(CompletionRequest(model="m", prompt="x", priority=0.25)) == { + "num_tokens": 0, + "priority": 0.25, + } + assert router.routing_key(CompletionRequest(model="m", prompt="x"))["priority"] == 0.5 + after_ctx = CompletionRequest( + model="m", + prompt="x", + disaggregated_params=DisaggregatedParams( + request_type="generation_only", orig_elapsed_s=2.5 + ), + ) + assert router.routing_key(after_ctx)["orig_elapsed_s"] == 2.5 + + +def test_extract_disagg_cfg_gives_the_pooled_router_the_ctx_kv_timeout(): + pooled = {"router": {"type": "load_balancing", "max_requests_per_server": 1}} + default = extract_disagg_cfg(generation_servers=dict(pooled, router=dict(pooled["router"]))) + assert default.gen_router_config.args["kv_transfer_timeout_ms"] == 60000 + config = extract_disagg_cfg( + context_servers={"cache_transceiver_config": {"kv_transfer_timeout_ms": 30000}}, + generation_servers=dict(pooled, router=dict(pooled["router"])), + ) + assert config.gen_router_config.args["kv_transfer_timeout_ms"] == 30000 + router = create_router(config.gen_router_config, ["s"]) + assert router._pool.kv_transfer_timeout_s == 30.0 + plain = extract_disagg_cfg(generation_servers={"router": {"type": "load_balancing"}}) + assert "kv_transfer_timeout_ms" not in plain.gen_router_config.args + + +async def _settle(): + for _ in range(5): + await asyncio.sleep(0) + + +@pytest.mark.asyncio +async def test_free_seats_place_at_once_like_load_balancing(): + router = _router(seats=2) + stock = LoadBalancingRouter(ServerRole.GENERATION, ["s0", "s1"]) + placed, expected = [], [] + for rid in range(4): + placed.append((await router.get_next_server_by_key({}, req_id=rid))[0]) + expected.append((await stock.get_next_server_by_key({}, req_id=rid))[0]) + assert placed == expected + assert router._pool.placed_at_once == 4 + + +@pytest.mark.asyncio +async def test_freed_seat_goes_to_the_best_waiter(): + router = _router(servers=("s0",), seats=1) + assert (await router.get_next_server_by_key({}, req_id=0))[0] == "s0" + waits = { + rid: asyncio.create_task(router.get_next_server_by_key({"priority": p}, req_id=rid)) + for rid, p in [(1, 0.2), (2, 0.8), (3, 0.8)] + } + await _settle() + assert not any(t.done() for t in waits.values()) and len(router._pool) == 3 + order = [] + for done_rid in (0, 2, 3): + await router.finish_request_by_id(done_rid) + await _settle() + ready = [rid for rid, t in waits.items() if t.done() and rid not in order] + assert len(ready) == 1 + order.extend(ready) + assert order == [2, 3, 1] + assert (await waits[1])[0] == "s0" + + +@pytest.mark.asyncio +async def test_repeated_select_keeps_its_seat_and_place(): + router = _router(servers=("s0",), seats=1) + first = await router.get_next_server_by_key({}, req_id=1) + assert await router.get_next_server_by_key({}, req_id=1) == first + a = asyncio.create_task(router.get_next_server_by_key({}, req_id=2)) + b = asyncio.create_task(router.get_next_server_by_key({}, req_id=2)) + await _settle() + assert len(router._pool) == 1 and router._pool.waiter(2).holders == 2 + await router.finish_request_by_id(1) + assert (await a)[0] == (await b)[0] == "s0" + assert router._get_server_load("s0") == 1 + + +@pytest.mark.asyncio +async def test_finish_while_waiting_drops_the_waiter(): + router = _router(servers=("s0",), seats=1) + await router.get_next_server_by_key({}, req_id=1) + waiting = asyncio.create_task(router.get_next_server_by_key({}, req_id=2)) + await _settle() + await router.finish_request_by_id(2) + with pytest.raises(ValueError, match="finished while waiting"): + await waiting + assert len(router._pool) == 0 and router._get_server_load("s0") == 1 + + +@pytest.mark.asyncio +async def test_cancellation_releases_queue_place_and_seat(): + router = _router(servers=("s0",), seats=1) + await router.get_next_server_by_key({}, req_id=1) + waiting = asyncio.create_task(router.get_next_server_by_key({}, req_id=2)) + await _settle() + waiting.cancel() + with pytest.raises(asyncio.CancelledError): + await waiting + assert len(router._pool) == 0 + # A placement whose only caller was cancelled gives its seat back. + late = asyncio.create_task(router.get_next_server_by_key({}, req_id=3)) + await _settle() + await router.finish_request_by_id(1) + late.cancel() + with pytest.raises(asyncio.CancelledError): + await late + assert router._get_server_load("s0") == 0 and router._req_routing_table == {} + + +@pytest.mark.asyncio +async def test_waiter_fails_at_the_kv_transfer_timeout(): + """A request that finds no seat within the timeout fails, generation_first ones too.""" + router = _router(servers=("s0",), seats=1, kv_ms=50) + await router.get_next_server_by_key({}, req_id=0) + doomed = asyncio.create_task( + router.get_next_server_by_key({"priority": 0.9, "orig_elapsed_s": 3.0}, req_id=1) + ) + gen_first = asyncio.create_task(router.get_next_server_by_key({"priority": 0.1}, req_id=2)) + with pytest.raises(NoGenerationSeatError, match="KV transfer timeout"): + await asyncio.wait_for(doomed, timeout=5) + with pytest.raises(NoGenerationSeatError, match="KV transfer timeout"): + await asyncio.wait_for(gen_first, timeout=5) + assert len(router._pool) == 0 and router._pool.expired == 2 + # The in-process path reads the elapsed time from the request. + request = CompletionRequest( + model="m", + prompt="x", + disaggregated_params=DisaggregatedParams( + request_type="generation_only", orig_elapsed_s=1.0 + ), + ) + with pytest.raises(ValueError, match="KV transfer timeout"): + await asyncio.wait_for(router.get_next_server(request), timeout=5) + assert router._get_server_load("s0") == 1 and len(router._pool) == 0 + + +@pytest.mark.asyncio +async def test_in_process_path_keys_by_request(): + router = _router(servers=("s0",), seats=1) + first = CompletionRequest(model="m", prompt="x", priority=0.1) + second = CompletionRequest(model="m", prompt="x", priority=0.9) + assert (await router.get_next_server(first))[0] == "s0" + waiting = asyncio.create_task(router.get_next_server(second)) + await _settle() + assert not waiting.done() + await router.finish_request(first) + assert (await waiting)[0] == "s0" + + +# ---------------------------------------------------------------------------------- coordinator + + +def _client_factory(*_args, **_kwargs): + return AsyncMock() + + +def _coordinator(seats=1): + config = DisaggServerConfig( + server_configs=[CtxGenServerConfig(type="gen", hostname="g", port=1)], + ctx_router_config=RouterConfig(type="round_robin", server_role=ServerRole.CONTEXT), + gen_router_config=RouterConfig( + type="load_balancing", + server_role=ServerRole.GENERATION, + args={"max_requests_per_server": seats}, + ), + ) + return DisaggCoordinatorService(config, _client_factory, reservation_timeout_secs=60) + + +@pytest.mark.asyncio +async def test_pooled_select_waits_outside_the_reservation_lock(): + """A waiting select must not block the finish (on the same lock stripe) that frees its seat.""" + coordinator = _coordinator() + assert isinstance(coordinator.gen_router, PooledLoadBalancingRouter) + stripe = coordinator._reservation_lock(("generation", 1)) + other = next( + rid + for rid in range(2, 100000) + if coordinator._reservation_lock(("generation", rid)) is stripe + ) + assert (await coordinator.select("generation", {}, 1, None))[0] == "g:1" + waiting = asyncio.create_task(coordinator.select("generation", {"priority": 0.5}, other, None)) + await _settle() + assert not waiting.done() + await asyncio.wait_for(coordinator.finish("generation", 1), timeout=5) + server, _, req_id = await asyncio.wait_for(waiting, timeout=5) + assert (server, req_id) == ("g:1", other) + # A repeated select renews the reservation and keeps the seat. + await coordinator.select("generation", {}, other, None) + assert coordinator.gen_router._get_server_load("g:1") == 1 + await coordinator.finish("generation", other) + assert coordinator.gen_router._get_server_load("g:1") == 0 + assert coordinator._reservation_tasks == {} + + +def test_delegating_router_waits_longer_for_a_pooled_select(): + pooled = CoordinatorDelegatingRouter("http://c:1", _router(), "generation", 5.0) + plain = CoordinatorDelegatingRouter( + "http://c:1", LoadBalancingRouter(ServerRole.GENERATION, ["s"]), "generation", 5.0 + ) + assert pooled._select_timeout_s == POOLED_SELECT_TIMEOUT_S + assert plain._select_timeout_s == 5.0 + + +# ------------------------------------------------ server churn, seat lifecycle and /finish delivery + + +async def _set_servers(router, servers): + """What add_server / remove_server / the cluster watch do to the server list.""" + async with router._lock: + old = router._servers.copy() + router._servers = list(servers) + router._on_servers_updated(old, router._servers) + + +@pytest.mark.asyncio +async def test_seat_count_survives_a_server_leaving_and_rejoining(): + """A re-registered server keeps the seats its running requests hold (no -k drift).""" + router = _router(servers=("s0",), seats=1) + await router.get_next_server_by_key({}, req_id=1) + await _set_servers(router, []) + await _set_servers(router, ["s0"]) + assert router._get_server_load("s0") == 1 # request 1 still holds its seat + waiting = asyncio.create_task(router.get_next_server_by_key({}, req_id=2)) + await _settle() + assert not waiting.done() + await router.finish_request_by_id(1) + assert (await asyncio.wait_for(waiting, 5))[0] == "s0" + await router.finish_request_by_id(2) + assert router._get_server_load("s0") == 0 and router._departed_state == {} + # A server that leaves for good drops its state once its last seat is released. + await router.get_next_server_by_key({}, req_id=3) + await _set_servers(router, []) + await router.finish_request_by_id(3) + assert router._departed_state == {} and router._seat_state == {} + + +def _ctx_router_with(infos): + ctx = create_router( + RouterConfig(type="round_robin", server_role=ServerRole.CONTEXT), list(infos) + ) + ctx._server_info.update(infos) + return ctx + + +@pytest.mark.asyncio +async def test_seat_wait_bound_comes_from_the_context_servers(): + """The context servers' own kv_transfer_timeout_ms (/server_info) wins over the server YAML.""" + gen_config = RouterConfig( + type="load_balancing", + server_role=ServerRole.GENERATION, + args={"max_requests_per_server": 1, "kv_transfer_timeout_ms": 60000}, + ) + ctx_config = RouterConfig(type="round_robin", server_role=ServerRole.CONTEXT) + ctx, gen = build_disagg_routers(ctx_config, gen_config, ["c0", "c1"], ["s0"]) + assert gen._context_router is ctx + ctx._server_info.update( + {"c0": {"kv_transfer_timeout_ms": 600000}, "c1": {"kv_transfer_timeout_ms": 300000}} + ) + await gen.get_next_server_by_key({}, req_id=1) + assert gen._pool.kv_transfer_timeout_s == 300.0 + # Without a reported value the configured one applies. + gen.set_context_router(_ctx_router_with({"c0": {}})) + waiting = asyncio.create_task(gen.get_next_server_by_key({}, req_id=2)) + await _settle() + assert gen._pool.kv_transfer_timeout_s == 60.0 + assert gen._pool.waiter(2).deadline - gen._pool.waiter(2).entered == pytest.approx(57.0) + waiting.cancel() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("infos", "expected_s"), + [ + ({"c0": {"kv_transfer_timeout_ms": None}, "c1": {"kv_transfer_timeout_ms": None}}, None), + ({"c0": {"kv_transfer_timeout_ms": None}, "c1": {}}, None), + ({"c0": {"kv_transfer_timeout_ms": None}, "c1": {"kv_transfer_timeout_ms": 30000}}, 30.0), + ({"c0": {}}, 60.0), + ], + ids=["all_null", "null_and_unreported", "null_and_bounded", "unreported"], +) +async def test_a_null_kv_transfer_timeout_leaves_the_seat_wait_unbounded(infos, expected_s): + """Context servers without a KV transfer timeout never drop the transfer: no 503 at 60 s.""" + gen = _router(servers=("s0",), seats=1, kv_ms=60000) + gen.set_context_router(_ctx_router_with(infos)) + await gen.get_next_server_by_key({}, req_id=1) + waiting = asyncio.create_task(gen.get_next_server_by_key({}, req_id=2)) + await _settle() + assert gen._pool.kv_transfer_timeout_s == expected_s + assert (gen._pool.waiter(2).deadline is None) == (expected_s is None) + waiting.cancel() + await asyncio.gather(waiting, return_exceptions=True) + + +def test_max_queue_wait_without_pooling_is_rejected(): + with pytest.raises(ValueError, match="max_requests_per_server"): + extract_disagg_cfg( + generation_servers={"router": {"type": "load_balancing", "max_queue_wait_s": 30}} + ) + for context_router in ( + {"max_queue_wait_s": 30}, + {"max_queue_wait_s": 30, "max_requests_per_server": 4}, + ): + with pytest.raises(ValueError, match="context_servers.router.* generation router option"): + extract_disagg_cfg(context_servers={"router": context_router}) + + +def test_router_declares_pooled(): + assert Router.pooled is False and PooledLoadBalancingRouter.pooled is True + assert not create_router( + RouterConfig(type="load_balancing", server_role=ServerRole.GENERATION), ["s"] + ).pooled + assert CoordinatorDelegatingRouter("http://c:1", _router(), "generation", 5.0).pooled + + +@pytest.mark.asyncio +async def test_coordinator_stop_fails_seat_waiters(): + coordinator = _coordinator() + await coordinator.select("generation", {}, 1, None) + waiting = asyncio.create_task(coordinator.select("generation", {}, 2, None)) + await _settle() + await asyncio.wait_for(coordinator.stop(), timeout=5) + with pytest.raises(NoGenerationSeatError, match="stopping"): + await asyncio.wait_for(waiting, timeout=5) + # A request arriving after that is refused at once rather than queued. + with pytest.raises(NoGenerationSeatError, match="stopping"): + await asyncio.wait_for(coordinator.select("generation", {}, 3, None), timeout=5) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("uds", [False, True], ids=["lifespan", "uds_and_tcp"]) +async def test_coordinator_shutdown_answers_parked_selects_at_once(tmp_path, monkeypatch, uds): + """Uvicorn's graceful shutdown waits for in-flight requests: a parked /select gets 503 first.""" + import socket + + import aiohttp + + from tensorrt_llm.serve import coordinator_server + + created = [] + real_create = coordinator_server.create_uvicorn_server + + def create(config): + created.append(real_create(config)) + return created[-1] + + monkeypatch.setattr(coordinator_server, "create_uvicorn_server", create) + coordinator = _coordinator() + coordinator.start = AsyncMock() # no servers to prepare or wait for + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + monkeypatch.chdir(tmp_path) # a relative path keeps the socket under AF_UNIX's 108-byte limit + uds_path = "coordinator.sock" if uds else None + serving = asyncio.create_task( + CoordinatorServer(coordinator)("127.0.0.1", port, uds=uds_path, sockets=[sock]) + ) + connector = aiohttp.UnixConnector(path=uds_path) if uds else aiohttp.TCPConnector() + base = "http://localhost" if uds else f"http://127.0.0.1:{port}" + try: + async with aiohttp.ClientSession(connector=connector) as session: + + async def select(rid): + body = msgpack.packb({"role": "generation", "routing_key": {}, "req_id": rid}) + async with session.post(f"{base}/select", data=body) as resp: + return resp.status, msgpack.unpackb(await resp.read(), raw=False) + + for _ in range(200): + try: + status, _ = await select(1) # takes the only seat + break + except aiohttp.ClientConnectionError: + await asyncio.sleep(0.05) + assert status == 200 + parked = asyncio.create_task(select(2)) + await asyncio.sleep(0.3) + assert not parked.done() + for server in created: + server.should_exit = True # what SIGINT / SIGTERM do + status, body = await asyncio.wait_for(parked, timeout=3) + assert status == 503 and body["no_generation_seat"] is True + await asyncio.wait_for(asyncio.shield(serving), timeout=3) + finally: + await coordinator.stop() + for server in created: + server.force_exit = True + await asyncio.wait_for(serving, timeout=10) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("uds", [False, True], ids=["tcp", "uds"]) +async def test_parked_select_of_a_disconnected_client_takes_no_seat(tmp_path, monkeypatch, uds): + """A worker that dies while its /select waits for a seat leaves no waiter and no seat behind.""" + import socket + + coordinator = _coordinator() + coordinator.start = AsyncMock() # no servers to prepare or wait for + router = coordinator.gen_router + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + monkeypatch.chdir(tmp_path) # a relative path keeps the socket under AF_UNIX's 108-byte limit + uds_path = "coordinator.sock" if uds else None + server = CoordinatorServer(coordinator) + serving = asyncio.create_task(server("127.0.0.1", port, uds=uds_path, sockets=[sock])) + + async def post_select(rid): + """Send a /select over a raw socket; return its reader and writer.""" + for _ in range(200): + try: + if uds: + reader, writer = await asyncio.open_unix_connection(uds_path) + else: + reader, writer = await asyncio.open_connection("127.0.0.1", port) + break + except OSError: + await asyncio.sleep(0.05) + body = msgpack.packb({"role": "generation", "routing_key": {}, "req_id": rid}) + writer.write( + b"POST /select HTTP/1.1\r\nHost: c\r\nContent-Type: application/msgpack\r\n" + + f"Content-Length: {len(body)}\r\n\r\n".encode() + + body + ) + await writer.drain() + return reader, writer + + try: + reader, writer = await post_select(1) # takes the only seat + assert b" 200 " in await asyncio.wait_for(reader.readline(), timeout=10) + writer.close() + _, parked = await post_select(2) + for _ in range(100): + if router._pool.waiter(2) is not None: + break + await asyncio.sleep(0.02) + assert router._pool.waiter(2) is not None + parked.close() # the worker dies: its socket closes + for _ in range(100): + if len(router._pool) == 0: + break + await asyncio.sleep(0.02) + assert len(router._pool) == 0 + await coordinator.finish("generation", 1) + await _settle() + assert router._get_server_load("g:1") == 0 and router._req_routing_table == {} + assert ("generation", 2) not in coordinator._reservation_tasks + finally: + for uvicorn_server in server.servers: + uvicorn_server.should_exit = True + await asyncio.wait_for(serving, timeout=10) + await coordinator.stop() + + +@pytest.mark.asyncio +async def test_finish_before_select_refuses_the_late_select(monkeypatch): + """A cancelled request's /finish can overtake its /select; that select must not queue.""" + coordinator = _coordinator() + assert (await coordinator.select("generation", {}, 1, None))[0] == "g:1" + await coordinator.finish("generation", 2) + with pytest.raises(ValueError, match="finished before its placement"): + await asyncio.wait_for(coordinator.select("generation", {}, 2, None), timeout=5) + router = coordinator.gen_router + assert len(router._pool) == 0 and ("generation", 2) not in coordinator._reservation_tasks + await coordinator.finish("generation", 1) + assert (await coordinator.select("generation", {}, 3, None))[0] == "g:1" + await coordinator.finish("generation", 3) + # The memory is bounded in count and in time. + monkeypatch.setattr("tensorrt_llm.serve.router.POOLED_FINISHED_MAX", 4) + for rid in range(10, 20): + await coordinator.finish("generation", rid) + assert list(router._finished_ids) == [16, 17, 18, 19] + monkeypatch.setattr("tensorrt_llm.serve.router.POOLED_FINISHED_TTL_S", 0.0) + assert (await coordinator.select("generation", {}, 19, None))[0] == "g:1" + await coordinator.finish("generation", 19) + + +@pytest.mark.asyncio +async def test_pooled_seat_is_not_reclaimed_at_the_reservation_ttl(): + """A granted seat outlives the coordinator's 180 s TTL: only /finish (or the 6 h net) frees it.""" + coordinator = _coordinator() + coordinator._reservation_timeout_secs = 0.05 + await coordinator.select("generation", {}, 1, None) + await asyncio.sleep(0.3) + assert coordinator.gen_router._get_server_load("g:1") == 1 + assert coordinator._reservation_timeout_for(coordinator.gen_router) == ( + POOLED_RESERVATION_TIMEOUT_S + ) + assert coordinator._reservation_timeout_for(coordinator.ctx_router) == 0.05 + await coordinator.finish("generation", 1) + assert coordinator.gen_router._get_server_load("g:1") == 0 + + +def test_seat_timeout_reaches_the_client_as_503(monkeypatch): + from fastapi.testclient import TestClient + + coordinator = _coordinator() + + async def no_seat(*_args): + raise NoGenerationSeatError("no seat within 60 s") + + monkeypatch.setattr(coordinator, "select", no_seat) + http = TestClient(CoordinatorServer(coordinator).app) + raw = http.post( + "/select", + content=msgpack.packb({"role": "generation", "routing_key": {}, "req_id": 1}), + ) + assert raw.status_code == 503 + assert msgpack.unpackb(raw.content, raw=False)["no_generation_seat"] is True + server = SimpleNamespace(_perf_metrics_collector=Mock()) + with pytest.raises(HTTPException) as error: + OpenAIDisaggServer._handle_exception(server, NoGenerationSeatError("no seat")) + assert error.value.status_code == 503 + + +class _FakeCoordinatorHttp: + """A coordinator whose pooled /select waits until a /finish for its req_id arrives.""" + + def __init__(self, select_delay_s=None): + self.finished = [] + self.select_delay_s = select_delay_s + self._finish_events = {} + + async def select(self, request): + from aiohttp import web + + body = msgpack.unpackb(await request.read(), raw=False) + if self.select_delay_s is not None: + await asyncio.sleep(self.select_delay_s) + else: + event = self._finish_events.setdefault(body["req_id"], asyncio.Event()) + await event.wait() + return web.Response( + status=503, + body=msgpack.packb({"error": "finished while waiting"}), + content_type="application/msgpack", + ) + return web.Response( + body=msgpack.packb({"server": "s0", "info": {}, "req_id": body["req_id"]}), + content_type="application/msgpack", + ) + + async def finish(self, request): + from aiohttp import web + + body = msgpack.unpackb(await request.read(), raw=False) + self.finished.append(body["req_id"]) + self._finish_events.setdefault(body["req_id"], asyncio.Event()).set() + return web.Response(body=msgpack.packb({}), content_type="application/msgpack") + + +async def _with_fake_coordinator(fake, body): + from aiohttp import web + from aiohttp.test_utils import TestServer + + app = web.Application() + app.router.add_post("/select", fake.select) + app.router.add_post("/finish", fake.finish) + async with TestServer(app) as server: + router = CoordinatorDelegatingRouter( + f"http://{server.host}:{server.port}", _router(), "generation", 5.0 + ) + try: + await body(router) + finally: + await router.close() + + +def _gen_request(rid): + return CompletionRequest( + model="m", + prompt="x", + disaggregated_params=DisaggregatedParams( + request_type="generation_only", ctx_request_id=rid, disagg_request_id=rid + ), + ) + + +@pytest.mark.asyncio +async def test_delegating_router_finishes_a_cancelled_pooled_select_at_once(): + """A cancelled caller sends /finish at once; it does not wait for the seat first.""" + fake = _FakeCoordinatorHttp() + + async def body(router): + selecting = asyncio.create_task(router.get_next_server(_gen_request(7))) + await asyncio.sleep(0.2) + selecting.cancel() + done, _ = await asyncio.wait({selecting}, timeout=5) + assert selecting in done and selecting.cancelled() + await asyncio.wait_for(router._finish_queue.join(), timeout=5) + assert 7 in fake.finished + + await _with_fake_coordinator(fake, body) + + +@pytest.mark.asyncio +async def test_delegating_router_finishes_a_timed_out_select(): + fake = _FakeCoordinatorHttp(select_delay_s=2.0) + + async def body(router): + router._select_timeout_s = 0.1 + with pytest.raises(asyncio.TimeoutError): + await router.get_next_server(_gen_request(9)) + await asyncio.wait_for(router._finish_queue.join(), timeout=5) + assert fake.finished == [9] + + await _with_fake_coordinator(fake, body) + + +class _LossyCoordinatorHttp(_FakeCoordinatorHttp): + """A coordinator that takes the first /select but whose reply never arrives. + + ``disconnect``: attempt 1 parks (its connection drops) and every retry's connection drops too. + ``refused``: attempt 1 parks (its connection drops) and attempt 2 gets an error status. + ``truncated``: attempt 1 is granted, but its 200 reply is cut short. + """ + + def __init__(self, failure): + super().__init__() + self.failure = failure + self.selects = 0 + + async def select(self, request): + from aiohttp import web + + body = msgpack.unpackb(await request.read(), raw=False) + self.selects += 1 + if self.failure == "truncated": + response = web.StreamResponse( + headers={"Content-Type": "application/msgpack", "Content-Length": "1000"} + ) + await response.prepare(request) + await response.write(b"\x83") + request.transport.close() + return response + if self.failure == "refused" and self.selects > 1: + return web.Response( + status=500, + body=msgpack.packb({"error": "refused"}), + content_type="application/msgpack", + ) + request.transport.close() + if self.selects == 1: + # Parked: the coordinator still waits for a seat for this request. + await self._finish_events.setdefault(body["req_id"], asyncio.Event()).wait() + return web.Response(body=msgpack.packb({}), content_type="application/msgpack") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure", ["disconnect", "refused", "truncated"]) +async def test_delegating_router_finishes_a_select_whose_reply_is_lost(monkeypatch, failure): + """A select the coordinator took is ended by /finish when the worker gets no reply.""" + import aiohttp + + monkeypatch.setattr("tensorrt_llm.serve.router.COORDINATOR_SELECT_RETRY_DELAY_S", 0.001) + fake = _LossyCoordinatorHttp(failure) + + async def body(router): + with pytest.raises((aiohttp.ClientError, ValueError)): + await asyncio.wait_for(router.get_next_server(_gen_request(11)), timeout=10) + await asyncio.wait_for(router._finish_queue.join(), timeout=5) + assert fake.finished == [11] + assert fake.selects == {"disconnect": 4, "refused": 2, "truncated": 1}[failure] + + await _with_fake_coordinator(fake, body) + + +class _FlakyCoordinatorFinish: + """A coordinator /finish that fails its first ``failures`` calls, then reaches ``coordinator``.""" + + def __init__(self, coordinator, failures, status=503): + self.coordinator = coordinator + self.failures = failures + self.status = status + self.calls = 0 + self.finished = [] + + async def finish(self, request): + from aiohttp import web + + body = msgpack.unpackb(await request.read(), raw=False) + self.calls += 1 + if self.calls <= self.failures: + return web.Response( + status=self.status, + body=msgpack.packb({"error": "unavailable"}), + content_type="application/msgpack", + ) + await self.coordinator.finish(body["role"], body["req_id"], body["success"]) + self.finished.append(body["req_id"]) + return web.Response(body=msgpack.packb({}), content_type="application/msgpack") + + +async def _finish_through_flaky_coordinator(local_router, fake, rids, monkeypatch): + """Finish ``rids`` through a delegating router whose finish queue holds one entry.""" + from aiohttp import web + from aiohttp.test_utils import TestServer + + monkeypatch.setattr("tensorrt_llm.serve.router.COORDINATOR_FINISH_RETRY_DELAY_S", 0.001) + app = web.Application() + app.router.add_post("/finish", fake.finish) + async with TestServer(app) as server: + router = CoordinatorDelegatingRouter( + f"http://{server.host}:{server.port}", local_router, "generation", 5.0 + ) + if not router.pooled: + router._finish_queue = asyncio.Queue(maxsize=1) + try: + # No await between the puts: the workers have not run, so a bounded queue is full. + for rid in rids: + await router.finish_request(_gen_request(rid), req_id=rid) + await asyncio.wait_for(router._finish_queue.join(), timeout=30) + finally: + await router.close() + return router + + +@pytest.mark.asyncio +async def test_pooled_finish_is_parked_and_retried_until_the_seat_is_released(monkeypatch): + """A pooled /finish is never dropped (its queue is unbounded) nor abandoned after 3 failures.""" + coordinator = _coordinator(seats=2) + for rid in (1, 2): + assert (await coordinator.select("generation", {}, rid, None))[0] == "g:1" + assert coordinator.gen_router._get_server_load("g:1") == 2 + fake = _FlakyCoordinatorFinish(coordinator, failures=5) + router = await _finish_through_flaky_coordinator(_router(), fake, (1, 2), monkeypatch) + assert router._dropped_finishes == 0 and router._finish_queue.maxsize == 0 + assert sorted(fake.finished) == [1, 2] + assert coordinator.gen_router._get_server_load("g:1") == 0 + assert coordinator._reservation_tasks == {} + + +@pytest.mark.asyncio +async def test_non_pooled_finish_still_drops_on_a_full_queue_and_gives_up(monkeypatch): + """The non-pooled path is unchanged: overflow is dropped and a finish stops after 3 attempts.""" + local_router = LoadBalancingRouter(server_role=None, servers=["s0"]) + assert not local_router.pooled + fake = _FlakyCoordinatorFinish(AsyncMock(), failures=5) + router = await _finish_through_flaky_coordinator(local_router, fake, (1, 2), monkeypatch) + assert router._dropped_finishes == 1 + assert fake.calls == 3 and fake.finished == [] + + +@pytest.mark.asyncio +async def test_pooled_finish_stops_on_a_malformed_reply_or_at_the_expiry(monkeypatch): + fake = _FlakyCoordinatorFinish(AsyncMock(), failures=100, status=400) + router = await _finish_through_flaky_coordinator(_router(), fake, (1,), monkeypatch) + assert fake.calls == 1 + monkeypatch.setattr( + CoordinatorDelegatingRouter, + "__init__", + _with_finish_window(CoordinatorDelegatingRouter.__init__, 0.05), + ) + fake = _FlakyCoordinatorFinish(AsyncMock(), failures=10**6) + router = await _finish_through_flaky_coordinator(_router(), fake, (1,), monkeypatch) + assert router._pooled_finish_window_s == 0.05 + assert 3 < fake.calls < 10**6 and fake.finished == [] + + +def _with_finish_window(init, window_s): + def patched(self, *args, **kwargs): + init(self, *args, **kwargs) + self._pooled_finish_window_s = window_s + + return patched + + +def test_pooled_finish_window_follows_the_coordinator_expiry(monkeypatch): + """The env timeout can lengthen the pooled expiry (and the finish retry window), not shorten it.""" + monkeypatch.setenv("TRTLLM_DISAGG_COORDINATOR_RESERVATION_TIMEOUT", "60") + router = CoordinatorDelegatingRouter("http://c:1", _router(), "generation", 5.0) + assert router._pooled_finish_window_s == POOLED_RESERVATION_TIMEOUT_S + coordinator = DisaggCoordinatorService(_coordinator()._config, _client_factory) + assert coordinator._reservation_timeout_for(coordinator.gen_router) == ( + POOLED_RESERVATION_TIMEOUT_S + ) + longer = 2 * POOLED_RESERVATION_TIMEOUT_S + monkeypatch.setenv("TRTLLM_DISAGG_COORDINATOR_RESERVATION_TIMEOUT", str(longer)) + router = CoordinatorDelegatingRouter("http://c:1", _router(), "generation", 5.0) + assert router._pooled_finish_window_s == longer + # A request timeout above 6 h lengthens both sides alike (one helper computes them). + monkeypatch.delenv("TRTLLM_DISAGG_COORDINATOR_RESERVATION_TIMEOUT") + worker = CoordinatorDelegatingRouter("http://c:1", _router(), "generation", longer + 1) + coordinator = DisaggCoordinatorService( + _coordinator()._config, _client_factory, request_timeout_secs=longer + 1 + ) + assert worker._pooled_finish_window_s == longer + 1 + assert coordinator._reservation_timeout_for(coordinator.gen_router) == longer + 1 diff --git a/tests/unittest/kv_cache_manager_v2_tests/remote_donor_cli.py b/tests/unittest/kv_cache_manager_v2_tests/remote_donor_cli.py new file mode 100644 index 000000000000..899ae3ce8115 --- /dev/null +++ b/tests/unittest/kv_cache_manager_v2_tests/remote_donor_cli.py @@ -0,0 +1,111 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""A remote-level donor in its own process, for the remote-level tests (test_remote_level.py). + +Usage:: + + python remote_donor_cli.py --dir /shared/dir --gib 128 + +Stop it with SIGTERM: it withdraws its files, deregisters its memory and exits. +""" + +import argparse +import os +import signal +import sys +import threading + +from tensorrt_llm._torch.pyexecutor.kv_cache.remote_donor import ( + TRANSPORTS, + make_donor, + resolve_ucx_devices, +) +from tensorrt_llm.llmapi.llm_args import REMOTE_CACHE_CHUNK_BYTES + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--dir", required=True, help="rendezvous directory (shared file system)") + size = parser.add_mutually_exclusive_group(required=True) + size.add_argument("--gib", type=float, help="GiB to donate") + size.add_argument("--bytes", type=int, help="bytes to donate") + parser.add_argument("--chunk-mib", type=float, default=REMOTE_CACHE_CHUNK_BYTES / (1 << 20)) + parser.add_argument("--numa-node", type=int, default=None) + parser.add_argument( + "--device", + type=int, + default=None, + help="CUDA device for a fabric donation's context (default 0)", + ) + parser.add_argument("--transport", choices=TRANSPORTS, default="nixl") + parser.add_argument( + "--ucx-devices", default=None, help="NIXL only; {GPU} is this rank's GPU index" + ) + parser.add_argument("--name", default=None) + parser.add_argument( + "--seconds", + type=float, + default=None, + help="exit after this long (default: until signalled)", + ) + parser.add_argument( + "--parent-pid", + type=int, + default=None, + help="exit once this process is gone (a test runner that died without stopping the donor)", + ) + args = parser.parse_args(argv) + nbytes = args.bytes if args.bytes is not None else int(args.gib * (1 << 30)) + # The transport's own options: only NIXL takes UCX devices. + options = {} + if args.ucx_devices is not None: + options["ucx_devices"] = resolve_ucx_devices(args.ucx_devices, args.device) + donor = make_donor( + args.dir, + nbytes, + transport=args.transport, + chunk_bytes=int(args.chunk_mib * (1 << 20)), + name=args.name, + numa_node=args.numa_node, + device=args.device, + **options, + ) + stop = threading.Event() + for sig in (signal.SIGINT, signal.SIGTERM): + signal.signal(sig, lambda *_: stop.set()) + if args.parent_pid is not None: + + def watch_parent() -> None: + while not stop.wait(1.0): + if os.getppid() != args.parent_pid: + stop.set() + + threading.Thread(target=watch_parent, daemon=True).start() + try: + donor.start() + except Exception as error: + donor.close() + donor.publish_failure(error) + raise + print(f"READY {donor.name} {donor.transport.kind} {donor.nbytes}", flush=True) + try: + stop.wait(args.seconds) + finally: + donor.close() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/unittest/kv_cache_manager_v2_tests/remote_test_utils.py b/tests/unittest/kv_cache_manager_v2_tests/remote_test_utils.py new file mode 100644 index 000000000000..94eb6a7e734a --- /dev/null +++ b/tests/unittest/kv_cache_manager_v2_tests/remote_test_utils.py @@ -0,0 +1,85 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Which remote-level transports this machine can run, for the remote-level tests.""" + +import functools + + +@functools.cache +def gpu_count() -> int: + try: + from cuda.bindings import driver as drv + + if drv.cuInit(0)[0] != drv.CUresult.CUDA_SUCCESS: + return 0 + err, count = drv.cuDeviceGetCount() + return count if err == drv.CUresult.CUDA_SUCCESS else 0 + except ImportError: + return 0 + + +@functools.cache +def nixl_available() -> bool: + try: + from tensorrt_llm.tensorrt_llm_transfer_agent_binding import NixlTransferAgent # noqa: F401 + except ImportError: + return False + return True + + +@functools.cache +def fabric_available() -> bool: + """Whether device 0 can export a host-NUMA fabric allocation, as a fabric donor does (driver, Grace, IMEX).""" + if gpu_count() == 0: + return False + from cuda.bindings import driver as drv + + from tensorrt_llm._torch.pyexecutor.kv_cache.host_memory import host_numa_node_of + from tensorrt_llm._torch.pyexecutor.kv_cache.remote_donor import FabricDonorTransport + + ok = drv.CUresult.CUDA_SUCCESS + err, device = drv.cuDeviceGet(0) + attr = drv.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_HANDLE_TYPE_FABRIC_SUPPORTED + if err != ok or drv.cuDeviceGetAttribute(attr, device)[1] == 0: + return False + err, ctx = drv.cuDevicePrimaryCtxRetain(device) + if err != ok: + return False + drv.cuCtxPushCurrent(ctx) + try: + prop = FabricDonorTransport._fabric_prop(drv, host_numa_node_of(drv, device)) + err, gran = drv.cuMemGetAllocationGranularity( + prop, drv.CUmemAllocationGranularity_flags.CU_MEM_ALLOC_GRANULARITY_MINIMUM + ) + if err != ok: + return False + err, handle = drv.cuMemCreate(gran, prop, 0) + if err != ok: + return False + try: + fabric = drv.CUmemAllocationHandleType.CU_MEM_HANDLE_TYPE_FABRIC + return drv.cuMemExportToShareableHandle(handle, fabric, 0)[0] == ok + finally: + drv.cuMemRelease(handle) + finally: + drv.cuCtxPopCurrent() + drv.cuDevicePrimaryCtxRelease(device) + + +def available_transports() -> list: + """The remote-level transports a test can run here: none without a GPU.""" + if gpu_count() == 0: + return [] + return [t for t, ok in (("nixl", nixl_available), ("fabric", fabric_available)) if ok()] diff --git a/tests/unittest/kv_cache_manager_v2_tests/test_kv_cache_manager_v2.py b/tests/unittest/kv_cache_manager_v2_tests/test_kv_cache_manager_v2.py index 59cc9d19dc25..42aefedd340e 100755 --- a/tests/unittest/kv_cache_manager_v2_tests/test_kv_cache_manager_v2.py +++ b/tests/unittest/kv_cache_manager_v2_tests/test_kv_cache_manager_v2.py @@ -67,6 +67,10 @@ PageIndexMode, PlannedDropHandle, PoolRebalanceConfig, + RemoteCacheTierConfig, # noqa: F401 - for test_remote_level + RemoteMemError, # noqa: F401 - for test_remote_level + RemoteTransferConfig, # noqa: F401 - for test_remote_level + RemoteTransport, # noqa: F401 - for test_remote_level ReuseScope, SlidingWindowSize, SparseCacheConfig, @@ -128,6 +132,10 @@ PageIndexMode, PlannedDropHandle, PoolRebalanceConfig, + RemoteCacheTierConfig, # noqa: F401 - for test_remote_level + RemoteMemError, # noqa: F401 - for test_remote_level + RemoteTransferConfig, # noqa: F401 - for test_remote_level + RemoteTransport, # noqa: F401 - for test_remote_level ReuseScope, SlidingWindowSize, SparseCacheConfig, diff --git a/tests/unittest/kv_cache_manager_v2_tests/test_remote_capacity.py b/tests/unittest/kv_cache_manager_v2_tests/test_remote_capacity.py new file mode 100644 index 000000000000..7f61569e5807 --- /dev/null +++ b/tests/unittest/kv_cache_manager_v2_tests/test_remote_capacity.py @@ -0,0 +1,1043 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The remote level's capacity check, donor failure markers and fabric chunk placement. + +No GPU, except TestFabricPlacement (the fabric transport) and TestFailedStartReleaseCudaState. + +check_remote_capacity waits until the expected donors have published (donor..ready + .meta) or failed +(donor..failed), then compares what they offer with what the clients claim. It must fail as soon as the +last donor reports with a shortfall, pass as soon as the offer covers the need, and name failed and short donors. +""" + +import contextlib +import errno +import gc +import mmap +import os +import re +import shutil +import sys +import tempfile +import threading +import time +import types +import unittest +from unittest import mock + +import pytest + +from tensorrt_llm._torch.pyexecutor.kv_cache import host_memory, remote_donor +from tensorrt_llm._torch.pyexecutor.kv_cache.remote_donor import ( + FabricDonorTransport, + check_remote_capacity, + make_donor, + scan_donors, +) + +_TEST_DIR = os.path.dirname(os.path.abspath(__file__)) +_ADDED_TEST_DIR = _TEST_DIR not in sys.path +if _ADDED_TEST_DIR: + sys.path.insert(0, _TEST_DIR) +try: + from remote_test_utils import fabric_available, gpu_count +finally: + if _ADDED_TEST_DIR: + sys.path.remove(_TEST_DIR) + +_GIB = 1 << 30 + + +def _publish( + directory, name, gib, chunk_gib=1, short_gib=0, host="hostA", extra=(), transport="fabric" +): + lines = [ + "version 1", + f"name {name}", + f"host {host}", + "pid 1", + f"chunk_bytes {chunk_gib * _GIB}", + f"transport {transport}", + "numa 0", + f"segment 0 {gib * _GIB}", + *extra, + ] + if short_gib: + lines.append(f"short_bytes {short_gib * _GIB}") + with open(os.path.join(directory, f"donor.{name}.meta"), "w") as f: + f.write("\n".join(lines) + "\n") + open(os.path.join(directory, f"donor.{name}.ready"), "w").close() + + +@pytest.mark.cpu_only +class TestCapacityCheck(unittest.TestCase): + def setUp(self): + self.dir = tempfile.mkdtemp(prefix="kvcm2_capacity_") + + def tearDown(self): + shutil.rmtree(self.dir, ignore_errors=True) + + def test_scan_counts_whole_chunks_and_failures(self): + _publish(self.dir, "a", 160) + _publish(self.dir, "b", 100, short_gib=60) + donor = make_donor(self.dir, 160 * _GIB, chunk_bytes=_GIB, name="c") + donor.publish_failure(RuntimeError("CUDA_ERROR_OUT_OF_MEMORY")) + open(os.path.join(self.dir, "claim.a.0"), "w").close() # claims are not donors + published, failed = scan_donors(self.dir) + self.assertEqual(sorted(p["name"] for p in published), ["a", "b"]) + self.assertEqual(sum(p["offered_bytes"] for p in published), 260 * _GIB) + self.assertEqual([p["short_bytes"] for p in published if p["name"] == "b"], [60 * _GIB]) + self.assertEqual([f["name"] for f in failed], ["c"]) + self.assertEqual(failed[0]["planned_bytes"], 160 * _GIB) + self.assertIn("OUT_OF_MEMORY", failed[0]["error"]) + + def test_a_donor_file_without_its_transport_is_malformed(self): + """Every writer names its transport; a .meta or .failed without it counts as no donor.""" + _publish(self.dir, "ok", 4) + _publish(self.dir, "bare", 4) + meta = os.path.join(self.dir, "donor.bare.meta") + lines = [line for line in open(meta) if not line.startswith("transport ")] + with open(meta, "w") as f: + f.writelines(lines) + with open(os.path.join(self.dir, "donor.lost.failed"), "w") as f: + f.write("version 1\nname lost\nhost h\npid 1\nplanned_bytes 1\nerror e\n") + published, failed = scan_donors(self.dir) + self.assertEqual([p["name"] for p in published], ["ok"]) + self.assertEqual(failed, []) + # The capacity check warns once per malformed file and names them, instead of blaming a missing donor. + with mock.patch.object(remote_donor.logger, "warning") as warning: + with self.assertRaisesRegex( + RuntimeError, "malformed.*donor.bare.meta, donor.lost.failed" + ): + check_remote_capacity( + self.dir, 3, 20 * _GIB, timeout_s=0.3, poll_s=0.05, log=lambda _: None + ) + self.assertEqual( + sorted(c.args[0].split()[4] for c in warning.call_args_list), + ["donor.bare.meta", "donor.lost.failed"], + ) + + def test_every_donor_names_its_transport(self): + for kind in remote_donor.TRANSPORTS: + donor = make_donor(self.dir, _GIB, kind, chunk_bytes=_GIB, name=f"named-{kind}") + donor._publish([], ["segment 0 1"], "test") + donor.publish_failure(RuntimeError("e")) + fields = remote_donor._meta_fields(os.path.join(self.dir, f"donor.named-{kind}.meta")) + self.assertEqual(fields["transport"], kind) + failed = remote_donor._meta_fields(os.path.join(self.dir, f"donor.named-{kind}.failed")) + self.assertEqual(failed["transport"], kind) + donor.close() + + def test_only_donors_of_the_clients_transport_count(self): + """Clients skip donors of another transport, so their capacity does not cover the need.""" + _publish(self.dir, "fabric", 160) + _publish(self.dir, "nixl", 40, transport="nixl") + check_remote_capacity(self.dir, 2, 100 * _GIB, timeout_s=10, log=lambda _: None) + with self.assertRaises(RuntimeError) as ctx: + check_remote_capacity( + self.dir, + 2, + 100 * _GIB, + transport="nixl", + timeout_s=0.2, + poll_s=0.05, + log=lambda _: None, + ) + self.assertIn("1 of 2 planned donors published 40 GiB", str(ctx.exception)) + self.assertIn("donor.size", str(ctx.exception)) + + def test_passes_when_offer_covers_need(self): + for i in range(8): + _publish(self.dir, f"l{i}", 160) + result = check_remote_capacity(self.dir, 8, 1218 * _GIB, timeout_s=10, log=lambda _: None) + self.assertEqual(result["offered_bytes"], 1280 * _GIB) + + def test_fails_fast_when_all_donors_reported_short(self): + # 5 of 8 donors published 160 GiB, 3 failed; the clients claim 6 x 203 GiB. + for i in range(5): + _publish(self.dir, f"ok{i}", 160) + for i in range(3): + make_donor(self.dir, 160 * _GIB, chunk_bytes=_GIB, name=f"bad{i}").publish_failure( + RuntimeError("CUDA_ERROR_OUT_OF_MEMORY") + ) + t0 = time.monotonic() + with self.assertRaises(RuntimeError) as ctx: + check_remote_capacity( + self.dir, + 8, + 1218 * _GIB, + timeout_s=600, + poll_s=0.05, + log=lambda _: None, + ) + self.assertLess( + time.monotonic() - t0, 5.0 + ) # no wait for the timeout: every donor has reported + message = str(ctx.exception) + self.assertIn("5 of 8 planned donors published 800 GiB, 3 failed", message) + self.assertIn("claim 1218 GiB", message) + self.assertIn("bad0", message) + self.assertIn("OUT_OF_MEMORY", message) + + def test_names_short_donors(self): + _publish(self.dir, "a", 100, short_gib=60) + _publish(self.dir, "b", 160) + with self.assertRaises(RuntimeError) as ctx: + check_remote_capacity( + self.dir, + 2, + 300 * _GIB, + timeout_s=10, + poll_s=0.05, + log=lambda _: None, + ) + self.assertIn("a (hostA) is 60 GiB short", str(ctx.exception)) + + def test_short_donor_note_names_its_numa_placement(self): + _publish(self.dir, "a", 100, short_gib=60, extra=["numa_chunks 0:60,1:40"]) + _publish(self.dir, "b", 160) + published, _ = scan_donors(self.dir) + self.assertEqual( + {p["name"]: p["numa_chunks"] for p in published}, {"a": "0:60,1:40", "b": ""} + ) + with self.assertRaises(RuntimeError) as ctx: + check_remote_capacity( + self.dir, + 2, + 300 * _GIB, + timeout_s=10, + poll_s=0.05, + log=lambda _: None, + ) + message = str(ctx.exception) + self.assertIn("a (hostA) is 60 GiB short (chunks per NUMA node 0:60,1:40)", message) + self.assertNotIn("\n", message) + + def test_times_out_when_donors_do_not_report(self): + _publish(self.dir, "a", 10) + t0 = time.monotonic() + with self.assertRaises(RuntimeError) as ctx: + check_remote_capacity( + self.dir, + 3, + 20 * _GIB, + timeout_s=0.3, + poll_s=0.05, + log=lambda _: None, + ) + self.assertGreaterEqual(time.monotonic() - t0, 0.3) + self.assertIn("2 not reported", str(ctx.exception)) + + def test_passes_before_all_report_once_covered(self): + _publish(self.dir, "a", 160) + _publish(self.dir, "b", 160) + t0 = time.monotonic() + check_remote_capacity( + self.dir, + 8, + 300 * _GIB, + timeout_s=600, + poll_s=0.05, + log=lambda _: None, + ) + self.assertLess(time.monotonic() - t0, 5.0) + + def test_waits_for_a_donor_that_publishes_later(self): + _publish(self.dir, "a", 100) + threading.Timer(0.3, lambda: _publish(self.dir, "b", 100)).start() + result = check_remote_capacity( + self.dir, + 2, + 200 * _GIB, + timeout_s=10, + poll_s=0.05, + log=lambda _: None, + ) + self.assertEqual(result["offered_bytes"], 200 * _GIB) + + def test_failure_marker_survives_close(self): + donor = make_donor(self.dir, 4 * _GIB, chunk_bytes=_GIB, name="gone") + donor.close() + donor.publish_failure(RuntimeError("boom\nsecond line")) + path = os.path.join(self.dir, "donor.gone.failed") + self.assertTrue(os.path.exists(path)) + text = open(path).read() + self.assertIn("planned_bytes 4294967296", text) + self.assertNotIn("\nsecond line", text) # the error stays on one line + + def test_close_waits_for_a_failed_background_start_closing_itself(self): + # The start thread closes the donor itself on failure; a concurrent close() must not withdraw alongside it. + donor = make_donor(self.dir, 4 * _GIB, chunk_bytes=_GIB, name="racy") + entered, release = threading.Event(), threading.Event() + active, depths = [0], [] + real_withdraw = donor._withdraw + + def withdraw(): + active[0] += 1 + depths.append(active[0]) + if threading.current_thread().name == "kvcm2-remote-donor": + entered.set() + release.wait(10) + real_withdraw() + active[0] -= 1 + + start_threads = [] + + def failing_start(): + start_threads.append(threading.current_thread()) + raise RuntimeError("no memory") + + donor._withdraw = withdraw + donor.start = failing_start + donor.start_in_background() + self.assertTrue(entered.wait(10)) + closer = threading.Thread(target=donor.close) + closer.start() + closer.join(0.3) + self.assertTrue( + closer.is_alive(), "close() returned while the start thread was still closing" + ) + release.set() + closer.join(10) + self.assertFalse(closer.is_alive()) + self.assertEqual(depths, [1, 1]) + start_threads[0].join(10) # it still writes the failure marker after its close + self.assertFalse(start_threads[0].is_alive()) + + def test_wait_started_returns_once_a_failed_start_is_released(self): + """A failed background start closes itself; wait_started() must not return while that release still runs.""" + released = threading.Event() + + class _SlowRelease(remote_donor.DonorTransport): + kind = "nixl" + + def start(self, donor): + time.sleep(0.2) + raise RuntimeError("registration failed") + + def release_unowned(self): + time.sleep(0.8) + released.set() + + donor = remote_donor.RemoteMemDonor( + self.dir, 4 * _GIB, _SlowRelease(), chunk_bytes=_GIB, name="slow" + ) + donor.start_in_background() + time.sleep(0.4) # the start failed at 0.2 s; its release runs until 1.0 s + donor.wait_started() + self.assertTrue( + released.is_set(), "wait_started() returned during the failed start's release" + ) + _, failed = scan_donors(self.dir) + self.assertEqual([f["name"] for f in failed], ["slow"]) + donor.close() + + def _started(self, name): + donor = make_donor(self.dir, 4 * _GIB, "fabric", chunk_bytes=_GIB, name=name) + with mock.patch.object( + FabricDonorTransport, + "start", + lambda self, donor: donor._publish([], ["segment 0 1"], "test"), + ): + donor.start() + return donor + + def test_a_donor_nobody_closed_withdraws_and_leaves_a_marker(self): + # E.g. startup failed between the donation start and the manager that would own it. + donor = self._started("orphan") + ready = os.path.join(self.dir, "donor.orphan.ready") + self.assertTrue(os.path.exists(ready)) + del donor + gc.collect() + self.assertFalse(os.path.exists(ready)) + _, failed = scan_donors(self.dir) + self.assertEqual([f["name"] for f in failed], ["orphan"]) + + def test_a_start_still_running_when_the_finalizer_withdraws_publishes_nothing(self): + """A start still running when the finalizer withdrew the donor publishes nothing. + + At exit the finalizer runs while a daemon start thread may still be past its registration: once it withdrew + the donor and left the failure marker, the start must not publish .ready for memory it released. + """ + registered, finalized = threading.Event(), threading.Event() + + class _Racing(remote_donor.DonorTransport): + kind = "fabric" + + def start(self, donor): + registered.set() + finalized.wait(10) + donor._publish([], ["segment 0 1"], "test") + + donor = remote_donor.RemoteMemDonor( + self.dir, 4 * _GIB, _Racing(), chunk_bytes=_GIB, name="exiting" + ) + donor.start_in_background() + self.assertTrue(registered.wait(10)) + donor._finalizer() # what atexit runs for a donor nobody closed + finalized.set() + donor.wait_started() + published, failed = scan_donors(self.dir) + self.assertEqual(published, []) + self.assertEqual([f["name"] for f in failed], ["exiting"]) + self.assertFalse(os.path.exists(os.path.join(self.dir, "donor.exiting.meta"))) + + def test_a_closed_donor_leaves_no_marker(self): + donor = self._started("done") + donor.close() + del donor + gc.collect() + self.assertEqual(scan_donors(self.dir), ([], [])) + + def test_close_with_an_error_leaves_a_marker(self): + donor = self._started("aborted") + donor.close(RuntimeError("initialization failed on another rank")) + _, failed = scan_donors(self.dir) + self.assertIn("another rank", failed[0]["error"]) + + def test_donor_names_are_unique_within_a_process(self): + names = {make_donor(self.dir, _GIB, chunk_bytes=_GIB).name for _ in range(64)} + self.assertEqual(len(names), 64) + + +@pytest.mark.cpu_only +class TestBindingDefaults(unittest.TestCase): + def test_the_binding_timeouts_default_to_remote_cache_config(self): + """The C++ defaults (config.h) match RemoteCacheConfig's; a launcher that omits a field gets one.""" + from tensorrt_llm.llmapi.llm_args import RemoteCacheConfig + from tensorrt_llm.runtime.kv_cache_manager_v2 import ( + RemoteCacheTierConfig, + RemoteTransferConfig, + RemoteTransport, + ) + + defaults = RemoteCacheConfig(directory="d", level={"size": 1}) + transfer = RemoteTransferConfig() + self.assertEqual(transfer.timeout_ms, defaults.transport.transfer_timeout_s * 1000) + self.assertEqual(transfer.transport, RemoteTransport[defaults.transport.kind.upper()]) + tier = RemoteCacheTierConfig(quota=0, path="") + self.assertEqual(tier.wait_timeout_ms, defaults.level.donor_wait_timeout_s * 1000) + + +def _capture_mode(): + """The calling thread's stream-capture mode.""" + from cuda.bindings import driver as drv + + relaxed = drv.CUstreamCaptureMode.CU_STREAM_CAPTURE_MODE_RELAXED + err, mode = drv.cuThreadExchangeStreamCaptureMode(relaxed) + assert err == drv.CUresult.CUDA_SUCCESS, err + drv.cuThreadExchangeStreamCaptureMode(mode) + return mode + + +@unittest.skipUnless(gpu_count() > 0, "needs a GPU") +class TestFailedStartReleaseCudaState(unittest.TestCase): + """A start that fails after registration releases on the donor thread, in the start's relaxed capture mode. + + The serving thread may capture a CUDA graph in global mode meanwhile, which a capture-unsafe call made in global + mode on another thread (e.g. deregistering host memory) would invalidate. + """ + + def setUp(self): + self.dir = tempfile.mkdtemp(prefix="kvcm2_release_mode_") + + def tearDown(self): + shutil.rmtree(self.dir, ignore_errors=True) + + def test_a_nixl_donation_deregisters_in_relaxed_mode(self): + modes = [] + + class _Agent: + def __init__(self, config): + pass + + def register_memory(self, descs): + pass + + def deregister_memory(self, descs): + modes.append(_capture_mode()) + + def get_local_agent_desc(self): + raise RuntimeError("no agent descriptor") + + binding = types.ModuleType("tensorrt_llm.tensorrt_llm_transfer_agent_binding") + binding.BaseAgentConfig = types.SimpleNamespace + binding.NixlTransferAgent = _Agent + binding.MemoryDesc = lambda *args: args + binding.MemoryDescs = lambda *args: args + binding.MemoryType = types.SimpleNamespace(DRAM="DRAM") + donor = make_donor(self.dir, 4 << 20, "nixl", chunk_bytes=2 << 20, device=0) + with mock.patch.dict(sys.modules, {binding.__name__: binding}): + donor.start_in_background() + donor.wait_started() + from cuda.bindings import driver as drv + + self.assertEqual(modes, [drv.CUstreamCaptureMode.CU_STREAM_CAPTURE_MODE_RELAXED]) + _, failed = scan_donors(self.dir) + self.assertIn("no agent descriptor", failed[0]["error"]) + + @unittest.skipUnless(fabric_available(), "needs the fabric transport") + def test_a_fabric_donation_releases_its_chunks_in_relaxed_mode(self): + modes = [] + real_release = FabricDonorTransport._release_fabric + + def release(transport): + if transport._fabric: + modes.append(_capture_mode()) + real_release(transport) + + def failing_publish(*args, **kwargs): + raise OSError("publish failed") + + donor = make_donor(self.dir, 2 * (16 << 20), "fabric", chunk_bytes=16 << 20, device=0) + donor._publish = failing_publish + with mock.patch.object(FabricDonorTransport, "_release_fabric", release): + donor.start_in_background() + donor.wait_started() + from cuda.bindings import driver as drv + + self.assertEqual(modes, [drv.CUstreamCaptureMode.CU_STREAM_CAPTURE_MODE_RELAXED]) + self.assertEqual(donor.transport._fabric, []) + + +@pytest.mark.cpu_only +class TestRendezvousPermissions(unittest.TestCase): + """Donor files hold NIXL registration keys and fabric handles: the directory and its files are the user's.""" + + def setUp(self): + self.dir = tempfile.mkdtemp(prefix="kvcm2_perm_") + + def tearDown(self): + os.chmod(self.dir, 0o700) + shutil.rmtree(self.dir, ignore_errors=True) + + def test_a_new_directory_is_private(self): + path = os.path.join(self.dir, "rendezvous") + remote_donor.ensure_rendezvous_directory(path) + self.assertEqual(os.stat(path).st_mode & 0o777, 0o700) + + def test_a_directory_others_can_write_is_refused(self): + os.chmod(self.dir, 0o777) + with self.assertRaises(PermissionError): + remote_donor.ensure_rendezvous_directory(self.dir) + os.chmod(self.dir, 0o755) + remote_donor.ensure_rendezvous_directory(self.dir) + + def test_a_symlinked_directory_is_refused(self): + """The leaf is checked without following a link: a link can be pointed elsewhere after the check.""" + target = os.path.join(self.dir, "target") + os.mkdir(target, 0o700) + link = os.path.join(self.dir, "rendezvous") + os.symlink(target, link) + with self.assertRaises(PermissionError): + remote_donor.ensure_rendezvous_directory(link) + + def test_a_symlinked_directory_with_a_trailing_slash_is_refused(self): + """A path ending in a separator follows the link in lstat and in the C++ client's O_NOFOLLOW open.""" + target = os.path.join(self.dir, "target") + os.mkdir(target, 0o700) + link = os.path.join(self.dir, "rendezvous") + os.symlink(target, link) + with self.assertRaises(PermissionError): + remote_donor.ensure_rendezvous_directory(link + "/") + self.assertEqual(remote_donor.resolve_rendezvous_directory(link + "//"), link) + + def test_missing_parents_are_private_too(self): + path = os.path.join(self.dir, "a", "b", "rendezvous") + remote_donor.ensure_rendezvous_directory(path) + for d in (os.path.join(self.dir, "a"), os.path.join(self.dir, "a", "b"), path): + self.assertEqual(os.stat(d).st_mode & 0o077, 0, d) + + def test_an_unset_variable_in_the_directory_is_refused(self): + """An unset variable would leave one literal directory that every run without it shares.""" + with mock.patch.dict(os.environ, {"KVCM2_TEST_JOB": "7"}): + os.environ.pop("KVCM2_TEST_UNSET", None) + self.assertEqual( + remote_donor.resolve_rendezvous_directory(f"{self.dir}/${{KVCM2_TEST_JOB}}/"), + f"{self.dir}/7", + ) + for unset in ("${KVCM2_TEST_UNSET}", "$KVCM2_TEST_UNSET"): + with self.assertRaisesRegex(ValueError, re.escape(unset)): + remote_donor.resolve_rendezvous_directory(f"{self.dir}/{unset}/x") + + def test_the_compaction_lock_is_not_opened_through_a_link(self): + victim = os.path.join(self.dir, "victim") + open(victim, "w").close() + os.symlink(victim, os.path.join(self.dir, "compact.h.node0.lock")) + with host_memory.node_compaction_lock(self.dir, "h", 0) as held: + self.assertFalse(held) + + def test_a_planted_tmp_link_is_not_written_through(self): + """Files are written through fresh exclusive temporaries, never through a file or link already there.""" + victim = os.path.join(self.dir, "victim") + with open(victim, "w") as f: + f.write("keep") + path = os.path.join(self.dir, "donor.x.failed") + os.symlink(victim, f"{path}.tmp.{os.getpid()}") + remote_donor._write_atomically(path, b"marker") + self.assertEqual(open(victim).read(), "keep") + self.assertEqual(open(path, "rb").read(), b"marker") + self.assertFalse(os.path.islink(path)) + + def test_donor_files_are_private(self): + make_donor(self.dir, _GIB, chunk_bytes=_GIB, name="x").publish_failure(RuntimeError("e")) + self.assertEqual(os.stat(os.path.join(self.dir, "donor.x.failed")).st_mode & 0o077, 0) + + +@pytest.mark.cpu_only +class TestPopulate(unittest.TestCase): + """Populate errors other than a missing MADV_POPULATE_WRITE (test_remote_donor_memory) raise.""" + + def _populate_with(self, error): + region = mmap.mmap(-1, 1 << 20, flags=mmap.MAP_PRIVATE | mmap.MAP_ANONYMOUS) + try: + with mock.patch.object(host_memory, "madvise_range", side_effect=error): + host_memory.populate(region, 0, 1 << 20) + finally: + region.close() + + def test_other_errors_raise(self): + for code in (errno.ENOMEM, getattr(errno, "EHWPOISON", 133)): + with self.assertRaises(OSError): + self._populate_with(OSError(code, os.strerror(code))) + + +@pytest.mark.cpu_only +class TestPlaceChunks(unittest.TestCase): + """Chunk placement when the driver refuses chunks on a node that still has room. + + Pure Python: the allocator, the node memory, the reclaim-and-compact pass, the per-node lock and the clock are + fakes. The policy is the module's (2 s of retries, passes of at least 8 GiB) with a 24 GiB reserve per node. + """ + + def setUp(self): + self.t = [0.0] + self.room = {0: 200.0, 1: 200.0} # GiB free per node (no page cache) + # GiB free in >= 2 MiB blocks; passes raise it only where a test says so. + self.contig = {0: 0.0, 1: 0.0} + self.passes = [] + self.locked = set() # nodes whose compaction lock is held + self.on_lock = lambda node: True # runs as the lock is taken; False refuses it + + @contextlib.contextmanager + def _node_lock(self, node): + granted = self.on_lock(node) + if granted: + self.locked.add(node) + try: + yield granted + finally: + self.locked.discard(node) + + def _sleep(self, seconds): + self.t[0] += seconds + + def _meminfo(self, node): + return {"MemFree": self.room[node], "MemTotal": 480.0} + + def _compact(self, node, gib): + assert node in self.locked, "a pass ran without its node's lock" + self.passes.append((node, gib)) + + def _place(self, n_chunks, create, **overrides): + args = dict( + chunk_gib=1.0, + reserve_gib=24.0, + meminfo=self._meminfo, + compact=self._compact, + contiguous=lambda node: self.contig[node], + sleep=self._sleep, + clock=lambda: self.t[0], + node_lock=self._node_lock, + ) + args.update(overrides) + return host_memory.place_chunks(n_chunks, [0, 1], create, **args) + + def _allocator(self, refuse): + """create(node) refuses when refuse(node, call number) says so; an accepted chunk takes 1 GiB of the node.""" + calls = [] + + def create(node): + calls.append(node) + if refuse(node, len(calls)): + return None + self.room[node] -= 1.0 + return object() + + return create, calls + + def _passes_on(self, node): + return [gib for n, gib in self.passes if n == node] + + def test_without_compaction_passes_a_refused_chunk_moves_on_after_its_retries(self): + """compact_host_memory off (the default): no pass and no node lock; what fits is placed.""" + create, _ = self._allocator(lambda node, call: node == 0) + handles, placement = self._place(4, create, compact_passes=False) + self.assertEqual(self.passes, []) + self.assertEqual(placement, {0: 0, 1: 4}) + self.assertEqual(len(handles), 4) + + def test_all_accepted(self): + create, calls = self._allocator(lambda node, i: False) + handles, placement = self._place(10, create) + self.assertEqual(len(handles), 10) + self.assertEqual(placement, {0: 10, 1: 0}) + self.assertEqual(calls, [0] * 10) + + def test_transient_refusal_is_retried(self): + # Refuse chunk 3's first try and its first retry. + create, calls = self._allocator(lambda node, i: i in (4, 5)) + handles, placement = self._place(10, create) + self.assertEqual(placement, {0: 10, 1: 0}) + self.assertEqual(calls, [0] * 12) + self.assertEqual(self.passes, []) + self.assertGreater(self.t[0], 0.0) # backed off before the retries + + def test_pass_recovers_a_refusal(self): + # Node 0 refuses from chunk 5 on until one reclaim-and-compact pass has run on it. + create, _ = self._allocator(lambda node, i: node == 0 and i > 5 and not self.passes) + handles, placement = self._place(10, create) + self.assertEqual(placement, {0: 10, 1: 0}) + self.assertEqual(self.passes, [(0, 8.0)]) # the smallest pass: the node has plenty of room + self.assertGreaterEqual(self.t[0], 2.0) # the retries came first + + def test_pass_is_sized_to_keep_the_reserve_and_margin(self): + self.room[0] = 24.0 + 1.0 + 8.0 + 3.5 # reserve + chunk + margin + 3.5 GiB + create, _ = self._allocator(lambda node, i: node == 0 and not self.passes) + handles, placement = self._place(1, create) + self.assertEqual(placement[0], 1) + self.assertEqual(len(self.passes), 1) + self.assertAlmostEqual(self.passes[0][1], 3.5) + + def test_no_room_for_a_pass_moves_on_and_stops_trying_the_node(self): + self.room[0] = 24.0 + 1.0 + 8.0 + 0.5 # less than 1 GiB left for a pass + create, calls = self._allocator(lambda node, i: node == 0) + handles, placement = self._place(5, create) + self.assertEqual(placement, {0: 0, 1: 5}) + self.assertEqual(self.passes, []) + # Refused (and retried) for the first chunk only, then skipped for the later ones. + self.assertNotIn(0, calls[calls.index(1) :]) + + def test_short_when_every_node_refuses(self): + create, _ = self._allocator(lambda node, i: i > 3) # three chunks, then nothing anywhere + handles, placement = self._place(10, create) + self.assertEqual(len(handles), 3) + self.assertEqual(placement, {0: 3, 1: 0}) + self.assertEqual(len(self._passes_on(0)), host_memory._MAX_PASSES_PER_REFUSAL) + + def test_a_failing_pass_stops_passes_on_the_node(self): + attempts = [] + + def broken(node, gib): + attempts.append(node) + raise RuntimeError("libnuma is unavailable") + + create, _ = self._allocator(lambda node, i: node == 0 and i > 2) + handles, placement = self._place(4, create, compact=broken) + self.assertEqual(placement, {0: 2, 1: 2}) + self.assertEqual(attempts, [0]) + + def test_a_pass_is_sized_to_the_donation_still_missing(self): + create, _ = self._allocator(lambda node, i: node == 0 and i > 5 and not self.passes) + self._place(40, create) + self.assertEqual(self.passes, [(0, 35.0)]) # 40 - 5 chunks, more than the smallest pass + + def test_a_pass_stays_within_its_cap(self): + create, _ = self._allocator(lambda node, i: node == 0 and i > 5 and not self.passes) + self._place(150, create) + self.assertEqual(self.passes, [(0, 64.0)]) # _MAX_PASS_CHUNKS chunks + + def test_pass_floor_and_margin_follow_the_reserve(self): + # A third of a 48 GiB reserve: passes of at least 16 GiB, leaving 16 GiB above the reserve and the chunk. + create, _ = self._allocator(lambda node, i: node == 0 and i > 5 and not self.passes) + self._place(10, create, reserve_gib=48.0) + self.assertEqual(self.passes, [(0, 16.0)]) + self.passes.clear() + self.room[0] = 48.0 + 1.0 + 16.0 + 3.5 + create, _ = self._allocator(lambda node, i: node == 0 and not self.passes) + self._place(1, create, reserve_gib=48.0) + self.assertEqual(len(self.passes), 1) + self.assertAlmostEqual(self.passes[0][1], 3.5) + + def test_passes_go_on_while_they_raise_contiguous_memory(self): + # Node 0 refuses until five passes have run; each pass leaves its size free in >= 2 MiB blocks. + def compact(node, gib): + self.passes.append((node, gib)) + self.contig[node] += gib + + create, _ = self._allocator(lambda node, i: node == 0 and i > 2 and len(self.passes) < 5) + handles, placement = self._place(4, create, compact=compact) + self.assertEqual(placement, {0: 4, 1: 0}) + self.assertEqual(len(self.passes), 5) + + def test_a_node_given_up_on_is_swept_once_more(self): + # Node 0 is fragmented while node 1 still has room; once node 1 is full, node 0 holds memory in >= 2 MiB blocks + # again after the donor left it. + self.room[1] = 24.0 + 4.0 # four chunks above the reserve + + def contiguous(node): + return 10.0 if node == 0 and self.room[1] < 25.0 else 0.0 + + create, _ = self._allocator(lambda node, i: node == 0 and contiguous(0) < 1.0) + handles, placement = self._place(8, create, contiguous=contiguous) + self.assertEqual(placement, {0: 4, 1: 4}) + self.assertEqual(len(self._passes_on(0)), host_memory._MAX_PASSES_PER_REFUSAL) + + def test_the_sweep_runs_once(self): + # Nodes that look recovered but refuse every chunk: the donation ends short after one sweep, without looping. + create, calls = self._allocator(lambda node, i: i > 3) + self.contig = {0: 5.0, 1: 5.0} + handles, placement = self._place(10, create) + self.assertEqual(len(handles), 3) + self.assertLess(len(calls), 200) + + def test_a_pass_is_sized_from_the_memory_left_once_it_holds_the_lock(self): + # Another donor on the node fills 160 GiB of it while this one waits for the lock. + def other_donor_ran(node): + self.room[node] -= 160.0 + return True + + self.on_lock = other_donor_ran + create, _ = self._allocator(lambda node, i: node == 0 and i > 5 and not self.passes) + self._place(150, create) + self.assertEqual(len(self.passes), 1) + self.assertAlmostEqual(self.passes[0][1], 200.0 - 5 - 160.0 - 24.0 - 1.0 - 8.0) + + def test_no_pass_without_the_lock(self): + self.on_lock = lambda node: False + create, _ = self._allocator(lambda node, i: node == 0 and i > 2) + handles, placement = self._place(4, create) + self.assertEqual(placement, {0: 2, 1: 2}) + self.assertEqual(self.passes, []) + + def test_reserve_skips_a_node_without_trying_it(self): + self.room[0] = 24.5 # below reserve + chunk + create, calls = self._allocator(lambda node, i: False) + handles, placement = self._place(3, create) + self.assertEqual(placement, {0: 0, 1: 3}) + self.assertNotIn(0, calls) + + +@pytest.mark.cpu_only +class TestNodeCompactionLock(unittest.TestCase): + """The flock that lets one donor per host and NUMA node run reclaim-and-compact passes at a time.""" + + def setUp(self): + self.dir = tempfile.mkdtemp(prefix="kvcm2_compaction_lock_") + + def tearDown(self): + shutil.rmtree(self.dir, ignore_errors=True) + + def test_donors_on_one_node_take_turns(self): + order = [] + holding = threading.Event() + + def second(): + holding.wait(10) + with host_memory.node_compaction_lock(self.dir, "hostA", 0) as locked: + order.append(("second", locked)) + + thread = threading.Thread(target=second) + thread.start() + with host_memory.node_compaction_lock(self.dir, "hostA", 0) as locked: + holding.set() + thread.join(0.3) + self.assertTrue(thread.is_alive(), "the second donor passed a held lock") + order.append(("first", locked)) + thread.join(10) + self.assertEqual(order, [("first", True), ("second", True)]) + + def test_other_nodes_and_hosts_do_not_wait(self): + with host_memory.node_compaction_lock(self.dir, "hostA", 0) as locked: + self.assertTrue(locked) + for host, node in (("hostA", 1), ("hostB", 0)): + with host_memory.node_compaction_lock(self.dir, host, node) as other: + self.assertTrue(other) + + def test_unusable_directory_refuses_the_lock(self): + missing = os.path.join(self.dir, "missing") + with host_memory.node_compaction_lock(missing, "hostA", 0) as locked: + self.assertFalse(locked) + + +@pytest.mark.cpu_only +class TestBuddyInfo(unittest.TestCase): + TEXT = ( + "Node 0, zone Normal 10 5 3 2 1 0 0 0 0 4 2\n" + "Node 1, zone Normal 100 50 30 20 10 5 0 0 0 0 0\n" + ) + + def test_free_memory_in_blocks_of_2_mib_or_more(self): + f = host_memory.contiguous_free_gib + # 4 KiB pages: order 9 is 2 MiB, order 10 is 4 MiB: 4 x 2 + 2 x 4 = 16 MiB on node 0, none on node 1. + self.assertAlmostEqual(f(0, text=self.TEXT, page=4096), 16 / 1024) + self.assertEqual(f(1, text=self.TEXT, page=4096), 0.0) + # 64 KiB pages (aarch64): order 5 is 2 MiB. Node 0: 4 x 32 + 2 x 64 MiB; node 1: 5 x 2 MiB. + self.assertAlmostEqual(f(0, text=self.TEXT, page=65536), 256 / 1024) + self.assertAlmostEqual(f(1, text=self.TEXT, page=65536), 10 / 1024) + self.assertEqual(f(7, text=self.TEXT, page=4096), 0.0) + + +@unittest.skipUnless( + len(host_memory.host_numa_nodes()) >= 2 and fabric_available(), + "needs the fabric transport (a Grace GPU with an IMEX channel) and two NUMA nodes with memory", +) +class TestFabricPlacement(unittest.TestCase): + """Where a fabric donation's chunks go when its node is full or the driver refuses them. + + A HOST_NUMA allocation never leaves its node, and the driver can refuse chunks with room left. Node fullness and + refusals are faked; the allocations are real. + """ + + CHUNK = 16 << 20 + + def setUp(self): + self.dir = tempfile.mkdtemp(prefix="kvcm2_fabric_placement_") + self.real = host_memory.node_meminfo + + def tearDown(self): + shutil.rmtree(self.dir, ignore_errors=True) + + def _full(self, node): + return dict(self.real(node), MemFree=0.0, **{"Active(file)": 0.0, "Inactive(file)": 0.0}) + + def _meta(self, donor): + return remote_donor._meta_fields(os.path.join(self.dir, f"donor.{donor.name}.meta")) + + def test_full_preferred_node_spills_to_the_other(self): + donor = make_donor( + self.dir, + 4 * self.CHUNK, + transport="fabric", + chunk_bytes=self.CHUNK, + numa_node=0, + device=0, + ) + fake = lambda n: self._full(n) if n == 0 else self.real(n) # noqa: E731 + with mock.patch.object(host_memory, "node_meminfo", fake): + donor.start() + try: + fields = self._meta(donor) + self.assertEqual(fields["numa_chunks"], "1:4") + self.assertEqual(fields["segments"], [[0, 4 * self.CHUNK]]) + self.assertNotIn("short_bytes", fields) + fabric = os.path.join(self.dir, f"donor.{donor.name}.fabric") + self.assertEqual(os.path.getsize(fabric), 4 * 64) + finally: + donor.close() + + def test_donation_that_only_partly_fits_is_published_short(self): + donor = make_donor( + self.dir, + 4 * self.CHUNK, + transport="fabric", + chunk_bytes=self.CHUNK, + numa_node=0, + device=0, + ) + + # Node 0 is full, node 1 has room for two chunks. + def fake(n): + return self._full(n) if n == 0 or len(donor.transport._fabric) >= 2 else self.real(n) + + with mock.patch.object(host_memory, "node_meminfo", fake): + donor.start() + try: + fields = self._meta(donor) + self.assertEqual(fields["segments"], [[0, 2 * self.CHUNK]]) + self.assertEqual(int(fields["short_bytes"]), 2 * self.CHUNK) + published, _ = scan_donors(self.dir) + self.assertEqual(published[0]["offered_bytes"], 2 * self.CHUNK) + finally: + donor.close() + + def test_refused_chunks_are_retried_with_real_allocations(self): + # The driver refuses two calls (chunk 1's first try and its first retry); the donation still completes on + # node 0. + real_create = FabricDonorTransport._try_create + calls = [0] + + def flaky(transport, drv, prop): + calls[0] += 1 + return None if calls[0] in (2, 3) else real_create(transport, drv, prop) + + donor = make_donor( + self.dir, + 4 * self.CHUNK, + transport="fabric", + chunk_bytes=self.CHUNK, + numa_node=0, + device=0, + ) + with ( + mock.patch.object(FabricDonorTransport, "_try_create", flaky), + mock.patch.object(host_memory, "_REFUSAL_RETRY_S", 0.5), + ): + donor.start() + try: + fields = self._meta(donor) + self.assertEqual(fields["numa_chunks"], "0:4") + self.assertEqual(calls[0], 6) + finally: + donor.close() + + def test_a_real_reclaim_pass_recovers_a_refusal(self): + # Refuse until one real reclaim-and-compact pass (64 chunks of 16 MiB, libnuma-bound, huge pages) has run on + # node 0. + real_create = FabricDonorTransport._try_create + real_compact = host_memory.compact_node + passes = [] + + def counted(node, gib): + passes.append((node, gib)) + return real_compact(node, gib) + + def refusing(transport, drv, prop): + return real_create(transport, drv, prop) if passes or not transport._fabric else None + + donor = make_donor( + self.dir, + 3 * self.CHUNK, + transport="fabric", + chunk_bytes=self.CHUNK, + numa_node=0, + device=0, + compact_host_memory=True, + ) + with ( + mock.patch.object(FabricDonorTransport, "_try_create", refusing), + mock.patch.object(host_memory, "compact_node", counted), + mock.patch.object(host_memory, "_REFUSAL_RETRY_S", 0.2), + ): + donor.start() + try: + fields = self._meta(donor) + self.assertEqual(fields["numa_chunks"], "0:3") + self.assertEqual(passes, [(0, 1.0)]) + finally: + donor.close() + + def test_no_room_anywhere_leaves_a_failure_marker(self): + donor = make_donor(self.dir, 4 * self.CHUNK, "fabric", chunk_bytes=self.CHUNK) + with mock.patch.object(host_memory, "node_meminfo", self._full): + donor.start_or_report() + self.assertFalse(os.path.exists(os.path.join(self.dir, f"donor.{donor.name}.ready"))) + published, failed = scan_donors(self.dir) + self.assertEqual(published, []) + self.assertEqual([f["name"] for f in failed], [donor.name]) + self.assertIn("no NUMA node can hold", failed[0]["error"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unittest/kv_cache_manager_v2_tests/test_remote_donor_memory.py b/tests/unittest/kv_cache_manager_v2_tests/test_remote_donor_memory.py new file mode 100644 index 000000000000..8ef3ba03af80 --- /dev/null +++ b/tests/unittest/kv_cache_manager_v2_tests/test_remote_donor_memory.py @@ -0,0 +1,136 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The remote-level donor makes all of its memory resident before it publishes it. Linux only, no GPU.""" + +import ctypes +import errno +import gc +import mmap +import os +import shutil +import sys +import tempfile +import unittest +import weakref +from unittest import mock + +import pytest + +from tensorrt_llm._torch.pyexecutor.kv_cache import host_memory, remote_donor + +_SIZE = 96 << 20 + + +# Host-only (no GPU): runs in the CPU stages. +pytestmark = pytest.mark.cpu_only + + +def _resident_bytes(address: int, size: int) -> int: + """Bytes of [address, address + size) in memory, page by page with mincore(2). + + /proc/self/smaps is not exact here: the kernel may merge the test mapping with a neighbouring anonymous one. + """ + page = mmap.PAGESIZE + pages = (size + page - 1) // page + vec = (ctypes.c_ubyte * pages)() + libc = ctypes.CDLL(None, use_errno=True) + libc.mincore.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.POINTER(ctypes.c_ubyte)] + libc.mincore.restype = ctypes.c_int + if libc.mincore(ctypes.c_void_p(address), ctypes.c_size_t(size), vec) != 0: + raise OSError(ctypes.get_errno(), "mincore failed") + return sum(v & 1 for v in vec) * page + + +@unittest.skipUnless(sys.platform.startswith("linux"), "uses mincore(2)") +class TestPopulate(unittest.TestCase): + def _region(self): + flags = mmap.MAP_PRIVATE | mmap.MAP_ANONYMOUS | remote_donor._MAP_NORESERVE + region = mmap.mmap(-1, _SIZE, flags=flags) + self.addCleanup(region.close) + return region, ctypes.addressof(ctypes.c_char.from_buffer(region)) + + def test_every_page_is_resident(self): + region, address = self._region() + self.assertEqual(_resident_bytes(address, _SIZE), 0) + host_memory.populate(region, address, _SIZE) + self.assertEqual(_resident_bytes(address, _SIZE), _SIZE) + + def test_fallback_without_madv_populate_write(self): + region, address = self._region() + self.assertEqual(_resident_bytes(address, _SIZE), 0) + # A kernel without MADV_POPULATE_WRITE (EINVAL) takes the zero-fill path. + with mock.patch.object( + host_memory, "madvise_range", side_effect=OSError(errno.EINVAL, "EINVAL") + ): + host_memory.populate(region, address, _SIZE) + self.assertEqual(_resident_bytes(address, _SIZE), _SIZE) + + +class _RecordingTransport(remote_donor.DonorTransport): + """Publishes without memory and counts releases.""" + + kind = "test" + + def __init__(self): + self.releases = 0 + + def start(self, donor): + donor._publish([], ["segment 0 0"], "test") + + def release_unowned(self): + self.releases += 1 + + +class TestUnclosedDonor(unittest.TestCase): + """A donor nobody closed frees its transport's memory too, not just its files: the process may live on.""" + + def setUp(self): + self.directory = tempfile.mkdtemp(prefix="kvcm2_unclosed_") + self.addCleanup(shutil.rmtree, self.directory, ignore_errors=True) + + def _started(self, transport): + donor = remote_donor.RemoteMemDonor(self.directory, 1 << 20, transport, chunk_bytes=1 << 20) + donor.start() + self.assertTrue(os.path.exists(donor._path("ready"))) + return donor + + def test_a_collected_donor_releases_its_transport(self): + transport = _RecordingTransport() + donor = self._started(transport) + ready, failed = donor._path("ready"), donor._path("failed") + del donor + gc.collect() + self.assertEqual(transport.releases, 1) + self.assertFalse(os.path.exists(ready)) + self.assertTrue(os.path.exists(failed)) + + def test_a_closed_donor_releases_once(self): + transport = _RecordingTransport() + donor = self._started(transport) + donor.close() + del donor + gc.collect() + self.assertEqual(transport.releases, 1) + + def test_the_finalizer_does_not_keep_the_donor_alive(self): + donor = self._started(_RecordingTransport()) + ref = weakref.ref(donor) + del donor + gc.collect() + self.assertIsNone(ref()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unittest/kv_cache_manager_v2_tests/test_remote_fabric_available.py b/tests/unittest/kv_cache_manager_v2_tests/test_remote_fabric_available.py new file mode 100644 index 000000000000..0aa781daa44c --- /dev/null +++ b/tests/unittest/kv_cache_manager_v2_tests/test_remote_fabric_available.py @@ -0,0 +1,49 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The remote-level tests skip a transport this machine lacks; on Grace Blackwell the fabric one must be there.""" + +import os +import platform +import sys + +import pytest + +_TEST_DIR = os.path.dirname(os.path.abspath(__file__)) +_ADDED_TEST_DIR = _TEST_DIR not in sys.path +if _ADDED_TEST_DIR: + sys.path.insert(0, _TEST_DIR) +try: + from remote_test_utils import fabric_available, gpu_count +finally: + if _ADDED_TEST_DIR: + sys.path.remove(_TEST_DIR) + + +def _grace_blackwell() -> bool: + if platform.machine() != "aarch64" or gpu_count() == 0: + return False + import torch + + return torch.cuda.get_device_capability(0)[0] == 10 + + +@pytest.mark.skipif( + not _grace_blackwell(), reason="the fabric transport is expected on Grace Blackwell only" +) +def test_fabric_transport_is_available_on_grace_blackwell(): + assert fabric_available(), ( + "no fabric transport (driver, IMEX channel or host-NUMA fabric allocation): the remote-level fabric tests " + "would skip" + ) diff --git a/tests/unittest/kv_cache_manager_v2_tests/test_remote_level.py b/tests/unittest/kv_cache_manager_v2_tests/test_remote_level.py new file mode 100644 index 000000000000..94e8006bd2b7 --- /dev/null +++ b/tests/unittest/kv_cache_manager_v2_tests/test_remote_level.py @@ -0,0 +1,1432 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""KV cache manager v2 with a remote cold level (``RemoteCacheTierConfig``). + +The level keeps its slots in host memory that donor processes (``remote_donor.py``) publish in a rendezvous +directory, and moves pages with NIXL READ / WRITE or over NVLink fabric memory (``storage/remoteMem.h``). Every test +class runs once per transport; a transport this machine lacks (remote_test_utils) is skipped. +""" + +import contextlib +import gc +import glob +import itertools +import os +import shutil +import signal +import subprocess +import sys +import tempfile +import threading +import time +import unittest +from dataclasses import replace +from typing import cast +from unittest import mock + +import cuda.bindings.driver as drv +import pytest +from parameterized import parameterized_class + +_TEST_DIR = os.path.dirname(os.path.abspath(__file__)) +_ADDED_TEST_DIR = _TEST_DIR not in sys.path +if _ADDED_TEST_DIR: + sys.path.insert(0, _TEST_DIR) +try: + import test_kv_cache_manager_v2 as base # the suite's fixtures, helpers and imports + from remote_test_utils import available_transports, gpu_count +finally: + if _ADDED_TEST_DIR: + sys.path.remove(_TEST_DIR) + +AttentionLayerConfig = base.AttentionLayerConfig +BufferConfig = base.BufferConfig +CacheLevel = base.CacheLevel +CudaStream = base.CudaStream +DataRole = base.DataRole +DiskCacheTierConfig = base.DiskCacheTierConfig +FakeEngine = base.FakeEngine +GpuCacheTierConfig = base.GpuCacheTierConfig +HostCacheTierConfig = base.HostCacheTierConfig +KVCacheManager = base.KVCacheManager +KVCacheManagerConfig = base.KVCacheManagerConfig +LayerId = base.LayerId +SsmLayerConfig = base.SsmLayerConfig +Step = base.Step +TokenId = base.TokenId +_introspection = base._introspection +RemoteCacheTierConfig = base.RemoteCacheTierConfig +RemoteMemError = base.RemoteMemError +RemoteTransferConfig = base.RemoteTransferConfig +RemoteTransport = base.RemoteTransport + + +def _sync_device() -> None: + """Wait for all device work, and with it every fabric copy queued behind it.""" + (err,) = drv.cuCtxSynchronize() + assert err == drv.CUresult.CUDA_SUCCESS, err + + +_TRANSPORTS = available_transports() +pytestmark = pytest.mark.skipif( + not _TRANSPORTS, reason="needs a GPU and the NIXL or fabric transport" +) +# One concrete class per transport: _0_nixl, _1_fabric. +_per_transport = parameterized_class(("transport",), [("nixl",), ("fabric",)]) +# The largest claim of one test (the suite's 1 GiB disk quota, rounded up to whole chunks per pool group) and room. +_DONOR_BYTES = 2 << 30 +_CHUNK_BYTES = 8 << 20 +_counter = itertools.count() +_NIXL_DEATH_ONLY = ( + "fabric: a dead donor's effect is the driver's; this test checks NIXL's fail-stop" +) + + +class _Donor: + """A donor in its own process, as on a GEN tray. + + Inside a Slurm step the subprocess joins the step's PMIx job (`import tensorrt_llm` runs MPI_Init), so it is + stopped with SIGTERM and exits normally: a SIGKILLed donor makes Slurm abort the whole step. A stopped donor has + deregistered its memory and destroyed its NIXL agent, which is what a client sees of a dead one. + """ + + def __init__( + self, + directory: str, + nbytes: int, + transport: str, + chunk_bytes: int = _CHUNK_BYTES, + env: "dict[str, str] | None" = None, + ): + self.directory = directory + self.name = f"test-donor-{os.getpid()}-{next(_counter)}" + self.log_path = os.path.join(directory, f"donor_{self.name}.log") + self._log = open(self.log_path, "w") + self.proc = subprocess.Popen( + [ + sys.executable, + os.path.join(_TEST_DIR, "remote_donor_cli.py"), + "--dir", + directory, + "--bytes", + str(nbytes), + "--chunk-mib", + str(chunk_bytes / (1 << 20)), + "--name", + self.name, + "--transport", + transport, + # The last GPU, so that on a multi-GPU node donor and client sit on different devices. + "--device", + str(gpu_count() - 1), + "--parent-pid", + str(os.getpid()), + ], + stdout=self._log, + stderr=subprocess.STDOUT, + text=True, + env=None if env is None else {**os.environ, **env}, + ) + ready = os.path.join(directory, f"donor.{self.name}.ready") + deadline = time.monotonic() + 300 + while not os.path.exists(ready): + if self.proc.poll() is not None: + raise RuntimeError( + f"donor exited early (rc {self.proc.returncode}):\n{self._tail()}" + ) + if time.monotonic() > deadline: + self.stop() + raise TimeoutError(f"donor did not publish within 300 s:\n{self._tail()}") + time.sleep(0.2) + + def _tail(self, n: int = 40) -> str: + self._log.flush() + with open(self.log_path) as f: + return "".join(f.readlines()[-n:]) + + def stop(self) -> None: + if self.proc.poll() is None: + self.proc.terminate() + try: + self.proc.wait(timeout=120) + except subprocess.TimeoutExpired: + # Last resort only: inside a Slurm step this aborts the step. + self.proc.kill() + self.proc.wait(timeout=60) + self._log.close() + + +# Per transport: the rendezvous directory of the module's donor, the donor, and why it could not start. A transport's +# donor starts with the first test that reads its directory, so that a run selecting one transport ("-k fabric") +# starts only that donor. +_module_dirs: "dict[str, str]" = {} +_module_donors: "dict[str, _Donor]" = {} +_module_donor_errors: "dict[str, BaseException]" = {} + + +def _module_dir(transport: str) -> str: + if transport in _module_donor_errors: + raise RuntimeError( + f"the module's {transport} donor failed to start" + ) from _module_donor_errors[transport] + if transport not in _module_donors: + directory = _module_dirs.setdefault( + transport, tempfile.mkdtemp(prefix=f"kvcm2_remote_{transport}_") + ) + try: + _module_donors[transport] = _Donor(directory, _DONOR_BYTES, transport) + except BaseException as error: + _module_donor_errors[transport] = error + raise + return _module_dirs[transport] + + +def tearDownModule() -> None: + for donor in _module_donors.values(): + donor.stop() + _module_donors.clear() + _module_donor_errors.clear() + for directory in _module_dirs.values(): + shutil.rmtree(directory, ignore_errors=True) + _module_dirs.clear() + + +class _Transport: + """A test class's transport (set per class by _per_transport), its module directory and its remote tier.""" + + transport: str = "nixl" + + def setUp(self) -> None: + if self.transport not in _TRANSPORTS: + self.skipTest(f"the {self.transport} transport is unavailable here") + super().setUp() + + @property + def module_dir(self) -> str: + return _module_dir(self.transport) + + def remote_tier( + self, + quota: int, + directory: "str | None" = None, + transfer_timeout_ms: int = 30_000, + pool_ratio: "list[float] | None" = None, + wait_timeout_ms: int = 60_000, + expected_donors: int = 0, + ): + return RemoteCacheTierConfig( + quota=quota, + path=directory or self.module_dir, + wait_timeout_ms=wait_timeout_ms, + expected_donors=expected_donors, + pool_ratio=pool_ratio or [], + transfer=RemoteTransferConfig( + transport=RemoteTransport[self.transport.upper()], timeout_ms=transfer_timeout_ms + ), + ) + + +@_per_transport +class TestRemoteMemDonor(_Transport, unittest.TestCase): + def test_donor_publishes_whole_chunks_and_withdraws_them(self) -> None: + directory = tempfile.mkdtemp(prefix="kvcm2_donor_") + donor = None + try: + donor = _Donor(directory, (64 << 20) + (3 << 20), self.transport, chunk_bytes=16 << 20) + meta = open(os.path.join(directory, f"donor.{donor.name}.meta")).read().split("\n") + fields = dict(line.split(" ", 1) for line in meta if line) + self.assertEqual(fields["version"], "1") + self.assertEqual(fields["name"], donor.name) + self.assertEqual(int(fields["chunk_bytes"]), 16 << 20) + base_address, nbytes = (int(x) for x in fields["segment"].split()) + self.assertEqual(nbytes, 64 << 20) # the partial fifth chunk is not donated + if self.transport == "fabric": + # Each chunk is its own fabric allocation: one 64-byte handle per chunk, in chunk order. + self.assertEqual(fields.get("transport"), "fabric") + self.assertEqual(base_address, 0) + self.assertEqual( + os.path.getsize(os.path.join(directory, f"donor.{donor.name}.fabric")), 4 * 64 + ) + else: + self.assertGreater(base_address, 0) + self.assertGreater( + os.path.getsize(os.path.join(directory, f"donor.{donor.name}.desc")), 0 + ) + donor.stop() + self.assertEqual(glob.glob(os.path.join(directory, f"donor.{donor.name}.*")), []) + finally: + if donor is not None: + donor.stop() # a no-op once stopped + shutil.rmtree(directory, ignore_errors=True) + + +@_per_transport +class TestRemoteLevelRoundTrip(_Transport, unittest.TestCase): + """Attention pages and recurrent state go to the remote level and come back bit-exact. + + FakeEngine checks every reused page and the SSM slot. + """ + + tokens_per_block = 32 + buf_size = 256 << 10 # per block per buffer: a block of 2 attention layers x (K, V) is 1 MiB + + def setUp(self) -> None: + super().setUp() + base.init_cuda_once() + self._token_ids = itertools.count(1_000_000 * (os.getpid() % 1000)) + gc.collect() + gc.disable() + + def tearDown(self) -> None: + gc.enable() + if hasattr(self, "manager"): + try: + self.manager.shutdown() + finally: + del self.manager + + def _config( + self, + with_host: bool, + directory: "str | None" = None, + transfer_timeout_ms: int = 30_000, + remote_quota: int = 512 << 20, + wait_timeout_ms: int = 60_000, + expected_donors: int = 0, + gpu_quota: int = 32 << 20, + ): + layers = [] + for lid in range(2): + layers.append( + AttentionLayerConfig( + layer_id=LayerId(lid), + buffers=[ + BufferConfig(role=DataRole("key"), size=self.buf_size), + BufferConfig(role=DataRole("value"), size=self.buf_size), + ], + ) + ) + for lid in range(2, 4): + layers.append( + SsmLayerConfig( + layer_id=LayerId(lid), + buffers=[BufferConfig(role=DataRole("ssm_state"), size=self.buf_size)], + ) + ) + tiers = [GpuCacheTierConfig(quota=gpu_quota)] + if with_host: + tiers.append(HostCacheTierConfig(quota=16 << 20)) + tiers.append( + self.remote_tier( + remote_quota, + directory, + transfer_timeout_ms, + wait_timeout_ms=wait_timeout_ms, + expected_donors=expected_donors, + ) + ) + return KVCacheManagerConfig( + tokens_per_block=self.tokens_per_block, + cache_tiers=tiers, + layers=layers, + enable_partial_reuse=False, + commit_min_snapshot=True, + ) + + def _prompt(self, length: int): + return [TokenId(next(self._token_ids)) for _ in range(length)] + + def _prefill(self, prompt, stream) -> None: + kv = self.manager.create_kv_cache() + self.assertTrue(kv.resume(stream)) + kv.capacity = len(prompt) + kv.history_length = len(prompt) + self.engine.execute([Step(kv, prompt, [])], stream) + kv.commit(prompt) + kv.stop_committing() + kv.close() + + def _residency(self, prompt) -> list: + kv = self.manager.create_kv_cache(input_tokens=prompt) + try: + return list(kv.cached_tokens_by_level) + finally: + kv.close() + + def _push_to_last_level(self, prompt, stream) -> list: + """Prefill unrelated prompts until every cached token of `prompt` sits on the last level.""" + last = len(self.cfg.cache_tiers) - 1 + for _ in range(64): + levels = self._residency(prompt) + if sum(levels) > 0 and levels[last] == sum(levels): + return levels + self._prefill(self._prompt(256), stream) + self.fail(f"pages never reached level {last}: {self._residency(prompt)}") + + def _reuse_and_check(self, prompt, stream) -> list: + kv = self.manager.create_kv_cache(input_tokens=prompt) + levels = list(kv.cached_tokens_by_level) + self.assertTrue(kv.resume(stream)) + kv.capacity = len(prompt) + kv.history_length = len(prompt) + # Reads every reused attention page and the SSM slot and compares them with what the prefill wrote. + self.engine.execute([Step(kv, [], prompt)], stream) + history = list(prompt) + for _ in range(4): + kv.capacity = len(history) + 1 + token = TokenId(next(self._token_ids)) + self.engine.execute([Step(kv, [token], history)], stream) + history.append(token) + kv.history_length = len(history) + kv.close() + return levels + + def _round_trip(self, with_host: bool) -> None: + self.cfg = self._config(with_host) + self.manager = KVCacheManager(self.cfg) + self.engine = FakeEngine(self.cfg) + stream_holder = base.CachedCudaStream() + stream = cast(CudaStream, stream_holder.handle) + self.assertTrue( + glob.glob(os.path.join(self.module_dir, "claim.*")), "no remote chunk was claimed" + ) + + prompt = self._prompt(4 * self.tokens_per_block) + self._prefill(prompt, stream) + before = self._push_to_last_level(prompt, stream) + self.assertGreater(before[-1], 0) + levels = self._reuse_and_check(prompt, stream) + self.assertEqual(levels, before) + # The pages were promoted on reuse: the prompt is cached on the GPU now. + after = self._residency(prompt) + self.assertGreater(after[0], 0, after) + + def test_round_trip_through_host_and_remote(self) -> None: + """GPU -> host -> remote on eviction (codec encode, host-to-remote WRITE), remote -> GPU on reuse.""" + self._round_trip(with_host=True) + + def test_round_trip_without_host(self) -> None: + """GPU -> remote and back directly (encode into staging + WRITE, READ + decode).""" + self._round_trip(with_host=False) + + def test_rebase_onto_remote_copies_keeps_the_fresh_pages(self) -> None: + """Rebasing onto remote copies installs the request's own GPU pages, and reuse reads them correctly. + + The request computes a prompt whose blocks the tree holds on the remote level (it did not reuse them). + """ + self.cfg = self._config(with_host=True) + self.manager = KVCacheManager(self.cfg) + self.engine = FakeEngine(self.cfg) + stream_holder = base.CachedCudaStream() + stream = cast(CudaStream, stream_holder.handle) + prompt = self._prompt(4 * self.tokens_per_block) + self._prefill(prompt, stream) + self._push_to_last_level(prompt, stream) + # Same tokens, no reuse: committing meets the tree's full blocks, whose attention pages are remote. + self._prefill(prompt, stream) + # Still reusable in full. (The level reported follows the SSM snapshot as well, which may sit on the host.) + levels = self._residency(prompt) + self.assertEqual(sum(levels), len(prompt), levels) + # FakeEngine reads every reused page (now the second request's attention pages) and the SSM slot. + self._reuse_and_check(prompt, stream) + + def test_rebase_onto_remote_copies_reads_nothing(self) -> None: + """The same rebase with the donor gone: moving a remote copy back would fail the commit.""" + if self.transport == "fabric": + self.skipTest(_NIXL_DEATH_ONLY) + directory = tempfile.mkdtemp(prefix="kvcm2_rebase_") + donor = _Donor(directory, 1 << 30, self.transport) + try: + self.cfg = self._config(with_host=True, directory=directory, transfer_timeout_ms=10_000) + self.manager = KVCacheManager(self.cfg) + self.engine = FakeEngine(self.cfg) + stream_holder = base.CachedCudaStream() + stream = cast(CudaStream, stream_holder.handle) + prompt = self._prompt(4 * self.tokens_per_block) + self._prefill(prompt, stream) + self._push_to_last_level(prompt, stream) + # Take the second request's GPU pages while the donor still serves the evictions that frees. + kv = self.manager.create_kv_cache() + self.assertTrue(kv.resume(stream)) + kv.capacity = len(prompt) + kv.history_length = len(prompt) + _sync_device() + donor.stop() + self.engine.execute([Step(kv, prompt, [])], stream) + # Rebasing must not move the remote copies back to the GPU here: making room for them would evict to the + # remote level and read the copies from it, so the commit would fail on a WRITE to the gone donor. + kv.commit(prompt) + kv.stop_committing() + kv.close() + del kv + finally: + donor.stop() + if hasattr(self, "manager"): + try: + self.manager.shutdown() + except Exception: + pass + del self.manager + gc.collect() + base.take_poison() + shutil.rmtree(directory, ignore_errors=True) + + def _attention_layers(self, window: "int | None" = None) -> list: + """Two attention layers; with `window`, the second one slides over that many tokens.""" + return [ + AttentionLayerConfig( + layer_id=LayerId(lid), + buffers=[ + BufferConfig(role=DataRole("key"), size=self.buf_size), + BufferConfig(role=DataRole("value"), size=self.buf_size), + ], + sliding_window_size=window if lid == 1 else None, + ) + for lid in range(2) + ] + + def test_rebase_leaves_the_remote_copies_of_stale_sliding_window_blocks_unread(self) -> None: + """Rebasing a stale sliding-window block onto the tree's remote copy reads nothing. + + Its page is held only to be committed: the rebase drops it instead of reading that copy back, which with the + donor gone would fail the commit. + """ + if self.transport == "fabric": + self.skipTest(_NIXL_DEATH_ONLY) + directory = tempfile.mkdtemp(prefix="kvcm2_swa_") + donor = _Donor(directory, 1 << 30, self.transport) + try: + cfg = self._config(with_host=True, directory=directory, transfer_timeout_ms=10_000) + # All-reusable commits: the sliding layer's stale blocks keep their pages (held) until committed. + self.cfg = replace( + cfg, + layers=self._attention_layers(window=self.tokens_per_block), + commit_min_snapshot=False, + ) + self.manager = KVCacheManager(self.cfg) + self.engine = FakeEngine(self.cfg) + stream_holder = base.CachedCudaStream() + stream = cast(CudaStream, stream_holder.handle) + prompt = self._prompt(4 * self.tokens_per_block) + + def compute(tokens: list, stop_donor: bool = False) -> None: + kv = self.manager.create_kv_cache() + self.assertTrue(kv.resume(stream)) + kv.capacity = len(tokens) + if stop_donor: + _sync_device() + donor.stop() + self.engine.execute([Step(kv, tokens, [])], stream) + # The window moves past the sliding layer's first blocks: their pages are held for the commit only. + kv.history_length = len(tokens) + kv.commit(tokens) + kv.stop_committing() + kv.close() + + # The suite's prefill sets the history before computing, which a sliding window cannot take. + self._prefill = lambda tokens, _stream: compute(tokens) + compute(prompt) + self._push_to_last_level(prompt, stream) + compute(prompt, stop_donor=True) + self.assertIsNone(base.poison_reason()) + finally: + donor.stop() + if hasattr(self, "manager"): + with contextlib.suppress(Exception): + self.manager.shutdown() + del self.manager + gc.collect() + base.take_poison() + shutil.rmtree(directory, ignore_errors=True) + + def test_a_page_that_supersedes_a_remote_copy_keeps_its_retention(self) -> None: + """The committed page takes the superseded copy's retention priority, as reusing that copy would keep it.""" + cfg = self._config(with_host=True) + self.cfg = replace(cfg, layers=self._attention_layers()) + self.manager = KVCacheManager(self.cfg) + self.engine = FakeEngine(self.cfg) + stream_holder = base.CachedCudaStream() + stream = cast(CudaStream, stream_holder.handle) + prompt = self._prompt(4 * self.tokens_per_block) + # Below the default (35) and above the cold-tier offload threshold (30), so that it reaches the remote level. + retention = base.KvCacheRetentionConfig( + [base.KvCacheRetentionConfig.TokenRangeRetentionConfig(0, None, 31, None)] + ) + kv = self.manager.create_kv_cache( + expected_prompt_length=len(prompt), kv_cache_retention_config=retention + ) + self.assertTrue(kv.resume(stream)) + kv.capacity = len(prompt) + kv.history_length = len(prompt) + self.engine.execute([Step(kv, prompt, [])], stream) + kv.commit(prompt) + kv.stop_committing() + kv.close() + self._push_to_last_level(prompt, stream) + # A default-priority request computes the same prompt and supersedes the remote copies with its pages. + kv = self.manager.create_kv_cache() + self.assertTrue(kv.resume(stream)) + kv.capacity = len(prompt) + kv.history_length = len(prompt) + self.engine.execute([Step(kv, prompt, [])], stream) + kv.commit(prompt) + self.assertEqual(kv.get_page_priorities(0), [31] * 4) + kv.stop_committing() + kv.close() + + def test_dead_donor_fails_the_promotion_instead_of_reusing(self) -> None: + """The promotion itself raises.""" + if self.transport == "fabric": + self.skipTest(_NIXL_DEATH_ONLY) + directory = tempfile.mkdtemp(prefix="kvcm2_dead_") + donor = _Donor(directory, 1 << 30, self.transport) + try: + self.cfg = self._config(with_host=True, directory=directory, transfer_timeout_ms=10_000) + self.manager = KVCacheManager(self.cfg) + self.engine = FakeEngine(self.cfg) + stream_holder = base.CachedCudaStream() + stream = cast(CudaStream, stream_holder.handle) + prompt = self._prompt(4 * self.tokens_per_block) + self._prefill(prompt, stream) + self._push_to_last_level(prompt, stream) + # The donor goes away with its memory registration and agent (its files go too; this client has loaded + # it already), so the next READ of the prompt's pages has nowhere to go. + donor.stop() + kv = self.manager.create_kv_cache(input_tokens=prompt) + # Its own class, not RuntimeError: callers tell a retired remote level from any other failure. + with self.assertRaisesRegex(RemoteMemError, "remote level"): + kv.resume(stream) + try: + kv.close() + except Exception: + pass + del kv + # The failed resume gave back the GPU slots it had taken for the promotion: with no cache open, every + # GPU slot is free or evictable. + gpu = cast(CacheLevel, CacheLevel(0)) + for pool in self.manager.get_storage_statistics(gpu): + self.assertEqual(pool.available, pool.total) + finally: + donor.stop() + if hasattr(self, "manager"): + try: + self.manager.shutdown() + except Exception: + pass + del self.manager + # Fail-stop: after a failed transfer the manager is not expected to tear down cleanly. Collect what is + # left now, so a destructor's poison lands here and is cleared, not in the next test. + gc.collect() + base.take_poison() + shutil.rmtree(directory, ignore_errors=True) + + def test_failed_level_drops_its_pages_and_takes_no_more(self) -> None: + """After a failed transfer the level is retired instead of failing every later request. + + Its pages leave the tree, and evictions go past it (here: they drop, since it is the last level). + """ + if self.transport == "fabric": + self.skipTest(_NIXL_DEATH_ONLY) + directory = tempfile.mkdtemp(prefix="kvcm2_retired_") + donor = _Donor(directory, 1 << 30, self.transport) + try: + self.cfg = self._config(with_host=True, directory=directory, transfer_timeout_ms=10_000) + self.manager = KVCacheManager(self.cfg) + self.engine = FakeEngine(self.cfg) + stream_holder = base.CachedCudaStream() + stream = cast(CudaStream, stream_holder.handle) + prompt = self._prompt(4 * self.tokens_per_block) + self._prefill(prompt, stream) + self._push_to_last_level(prompt, stream) + donor.stop() + kv = self.manager.create_kv_cache(input_tokens=prompt) + with self.assertRaisesRegex(Exception, "remote level"): + kv.resume(stream) + kv.close() + del kv + self.assertEqual(self._residency(prompt)[-1], 0, "the failed level still offers pages") + # Prefills evict through the host level and past the failed one; a fresh prompt round-trips. + for _ in range(8): + self._prefill(self._prompt(256), stream) + fresh = self._prompt(2 * self.tokens_per_block) + self._prefill(fresh, stream) + self._reuse_and_check(fresh, stream) + self.assertEqual(self._residency(prompt)[-1], 0) + finally: + donor.stop() + if hasattr(self, "manager"): + try: + self.manager.shutdown() + except Exception: + pass + del self.manager + gc.collect() + base.take_poison() + shutil.rmtree(directory, ignore_errors=True) + + def _with_dying_donor(self, prefix: str, body, attention_only: bool = False) -> None: + """Run body(stream, donor) against a remote level whose donor the body stops; the manager must stay usable. + + attention_only: two attention layers, 8 MiB GPU and host tiers (8 blocks each), so that every page is tracked. + """ + if self.transport == "fabric": + self.skipTest(_NIXL_DEATH_ONLY) + directory = tempfile.mkdtemp(prefix=prefix) + donor = _Donor(directory, 1 << 30, self.transport) + try: + self.cfg = self._config(with_host=True, directory=directory, transfer_timeout_ms=10_000) + if attention_only: + tiers = list(self.cfg.cache_tiers) + tiers[0] = GpuCacheTierConfig(quota=8 << 20) + tiers[1] = HostCacheTierConfig(quota=8 << 20) + self.cfg = replace(self.cfg, cache_tiers=tiers, layers=self.cfg.layers[:2]) + self.manager = KVCacheManager(self.cfg) + self.engine = FakeEngine(self.cfg) + stream_holder = base.CachedCudaStream() + body(cast(CudaStream, stream_holder.handle), donor) + self.assertIsNone(base.poison_reason()) + finally: + donor.stop() + if hasattr(self, "manager"): + with contextlib.suppress(Exception): + self.manager.shutdown() + del self.manager + gc.collect() + base.take_poison() + shutil.rmtree(directory, ignore_errors=True) + + def test_a_failed_eviction_write_retires_the_level_instead_of_failing_the_request(self) -> None: + """A WRITE to a gone donor while making room retires the level instead of failing the request. + + The eviction goes past the level (here: drops, as it is the last level), so the request still gets its room. + """ + + def body(stream, donor) -> None: + prompt = self._prompt(4 * self.tokens_per_block) + self._prefill(prompt, stream) + self._push_to_last_level(prompt, stream) + donor.stop() + self.assertFalse(self.manager.any_remote_level_failed) + # The host tier is full: every prefill evicts toward the remote level. + for _ in range(8): + self._prefill(self._prompt(256), stream) + self.assertTrue(self.manager.any_remote_level_failed) + self.assertEqual(self._residency(prompt)[-1], 0, "the failed level still offers pages") + fresh = self._prompt(2 * self.tokens_per_block) + self._prefill(fresh, stream) + self._reuse_and_check(fresh, stream) + + self._with_dying_donor("kvcm2_write_", body) + + def test_pages_a_request_holds_on_a_failed_level_leave_the_reuse_tree(self) -> None: + """Pages a suspended request holds on a failed remote level are matched by no new request. + + Only the holder's resume fails; the prompt is computed again for everyone else. + """ + + def body(stream, donor) -> None: + prompt = self._prompt(4 * self.tokens_per_block) + holder = self.manager.create_kv_cache() + self.assertTrue(holder.resume(stream)) + holder.capacity = len(prompt) + holder.history_length = len(prompt) + self.engine.execute([Step(holder, prompt, [])], stream) + holder.commit(prompt) + holder.suspend() + self._push_to_last_level(prompt, stream) + donor.stop() + for _ in range(2): + with self.assertRaisesRegex(RemoteMemError, "remote level"): + holder.resume(stream) + self.assertEqual( + self._residency(prompt)[-1], 0, "a new request matched the failed level's pages" + ) + self._prefill(prompt, stream) + self._reuse_and_check(prompt, stream) + holder.close() + del holder + self._reuse_and_check(prompt, stream) + + self._with_dying_donor("kvcm2_held_", body) + + def test_a_probe_after_the_failure_counts_no_page_of_the_failed_level(self) -> None: + """Probes stop counting a failed level's pages as soon as the failure happened. + + Schedulers and the ADP router call probe_reuse and probe_first_new_block_key before any allocation. + """ + + def body(stream, donor) -> None: + # `prompt` is cached on the remote level only (droppable); `held` is held there by a suspended request. + prompt = self._prompt(4 * self.tokens_per_block) + held = self._prompt(4 * self.tokens_per_block) + self._prefill(prompt, stream) + holder = self.manager.create_kv_cache() + self.assertTrue(holder.resume(stream)) + holder.capacity = len(held) + holder.history_length = len(held) + self.engine.execute([Step(holder, held, [])], stream) + holder.commit(held) + holder.suspend() + self._push_to_last_level(prompt, stream) + self._push_to_last_level(held, stream) + # Free GPU slots (an uncommitted cache's), so that the failing resume evicts nothing: only its READ fails. + spacer = self.manager.create_kv_cache() + self.assertTrue(spacer.resume(stream)) + spacer.capacity = 12 * self.tokens_per_block + spacer.close() + self.assertEqual(self.manager.probe_reuse(input_tokens=prompt), len(prompt)) + _sync_device() + donor.stop() + with self.assertRaisesRegex(RemoteMemError, "remote level"): + holder.resume(stream) + # No create_kv_cache(input_tokens=...) in between, which would drop and unlink the level's pages itself. + probed = self.manager.probe_reuse(input_tokens=prompt) + new_key = self.manager.probe_first_new_block_key(input_tokens=prompt) + self.assertEqual(probed, 0) + self.assertIsNotNone(new_key) + self.assertEqual(sum(self._residency(prompt)), 0) + holder.close() + del holder + + self._with_dying_donor("kvcm2_probe_", body) + + def test_a_failed_eviction_write_still_offloads_to_the_host(self) -> None: + """The GPU pages a failed host -> remote WRITE was making room for reach the host on the retry. + + The failed attempt had accepted them for migration; they must survive its unwinding so that its rollback puts + them back, and the retry past the failed level then offloads them to the host instead of losing them. + """ + + def body(stream, donor) -> None: + older = self._prompt(2 * self.tokens_per_block) + self._prefill(older, stream) + # Two-block prompts until the GPU and host tiers hold only these, the remote level the older ones. + recent = [self._prompt(2 * self.tokens_per_block) for _ in range(16)] + for prompt in recent: + self._prefill(prompt, stream) + levels = {i: self._residency(prompt) for i, prompt in enumerate(recent)} + on_gpu = [i for i, lv in levels.items() if lv[0] == len(recent[i])] + self.assertTrue(on_gpu, levels) + self.assertGreater( + self._residency(older)[-1], 0, "the older prompt is not on the remote level" + ) + _sync_device() + donor.stop() + # Needs GPU room: GPU -> host, whose own eviction WRITEs to the dead donor and fails the level. + self._prefill(self._prompt(2 * self.tokens_per_block), stream) + self.assertEqual( + self._residency(older)[-1], 0, "the remote level did not fail in this prefill" + ) + # The oldest GPU prompt left the GPU for the host; no GPU prompt lost a cached token. + after = {i: self._residency(recent[i]) for i in on_gpu} + self.assertEqual( + {i: sum(lv) for i, lv in after.items()}, {i: len(recent[i]) for i in on_gpu} + ) + self.assertGreater(after[on_gpu[0]][1], 0, after) + + self._with_dying_donor("kvcm2_offload_", body, attention_only=True) + + def test_a_transfer_past_its_deadline_keeps_its_staging_until_it_quiesces(self) -> None: + """A READ past its deadline keeps its staging lease out of use until it concludes, then is reaped. + + The READ fails the level but is not released while in progress. + + Over UCX's TCP transport a one-sided READ needs the donor's progress thread, so a stopped (SIGSTOP) donor holds + the request in progress until it is continued. + """ + if self.transport == "fabric": + self.skipTest( + "fabric copies are stream-ordered: their staging is retired on the stream" + ) + directory = tempfile.mkdtemp(prefix="kvcm2_unquiesced_") + # cuda_copy only because NIXL refuses a UCX_TLS without CUDA support on a GPU node; it moves no host memory. + tcp = {"UCX_TLS": "tcp,cuda_copy"} + donor = _Donor(directory, 1 << 30, self.transport, env=tcp) + stopped = False + try: + self.cfg = self._config(with_host=True, directory=directory, transfer_timeout_ms=2_000) + # The client's agent reads UCX_TLS when it is created, with the manager. + with mock.patch.dict(os.environ, tcp): + self.manager = KVCacheManager(self.cfg) + self.engine = FakeEngine(self.cfg) + stream_holder = base.CachedCudaStream() + stream = cast(CudaStream, stream_holder.handle) + prompt = self._prompt(4 * self.tokens_per_block) + self._prefill(prompt, stream) + self._push_to_last_level(prompt, stream) + self.assertEqual(_introspection.remote_unquiesced_transfers(self.manager), 0) + os.kill(donor.proc.pid, signal.SIGSTOP) + stopped = True + kv = self.manager.create_kv_cache(input_tokens=prompt) + with self.assertRaisesRegex(RemoteMemError, "timed out"): + kv.resume(stream) + # The request is still in progress: its staging stays out of use. + self.assertEqual(_introspection.remote_unquiesced_transfers(self.manager), 1) + os.kill(donor.proc.pid, signal.SIGCONT) + stopped = False + deadline = time.monotonic() + 60 + while ( + _introspection.remote_unquiesced_transfers(self.manager) + and time.monotonic() < deadline + ): + time.sleep(0.1) + self.assertEqual(_introspection.remote_unquiesced_transfers(self.manager), 0) + with contextlib.suppress(Exception): + kv.close() + del kv + finally: + if stopped: + os.kill(donor.proc.pid, signal.SIGCONT) + donor.stop() + if hasattr(self, "manager"): + with contextlib.suppress(Exception): + self.manager.shutdown() + del self.manager + gc.collect() + base.take_poison() + shutil.rmtree(directory, ignore_errors=True) + + def test_a_stalled_transfer_holding_all_staging_fails_later_resumes_with_remote_mem_error( + self, + ) -> None: + """A READ past its deadline that holds the whole page-staging ring fails later remote resumes as RemoteMemError. + + The level is checked before staging is leased: otherwise the next resume of a request holding pages on it fails + to lease staging with a plain error, which the scheduler does not take for a lost remote level. + """ + if self.transport == "fabric": + self.skipTest( + "fabric copies are stream-ordered: their staging is retired on the stream" + ) + # 16 MiB attention pages: the 64 MiB ring is 4 of them, and the 8-block READ below asks for all of it. + self.buf_size = 4 << 20 + directory = tempfile.mkdtemp(prefix="kvcm2_ring_") + tcp = {"UCX_TLS": "tcp,cuda_copy"} + # Room for both prompts and the pushes on the remote level, so that neither is evicted from it; chunks hold + # whole 16 MiB pages. + donor = _Donor(directory, 2 << 30, self.transport, chunk_bytes=64 << 20, env=tcp) + stopped = False + kvs = [] + try: + self.cfg = self._config( + with_host=False, + directory=directory, + transfer_timeout_ms=2_000, + remote_quota=1 << 30, + gpu_quota=256 << 20, + ) + with mock.patch.dict(os.environ, tcp): + self.manager = KVCacheManager(self.cfg) + self.engine = FakeEngine(self.cfg) + stream_holder = base.CachedCudaStream() + stream = cast(CudaStream, stream_holder.handle) + first = self._prompt(8 * self.tokens_per_block) + second = self._prompt(4 * self.tokens_per_block) + self._prefill(first, stream) + self._prefill(second, stream) + self._push_to_last_level(first, stream) + self._push_to_last_level(second, stream) + self.assertEqual(self._residency(first)[-1], len(first)) + # Room on the GPU, so that the first transfer to stall is the 8-page READ, which leases the whole ring, + # rather than an eviction WRITE of a few pages. + self.assertTrue(self.manager.resize(cast(CacheLevel, CacheLevel(0)), 1 << 30)) + # Both match the level's pages before it fails. + kvs = [self.manager.create_kv_cache(input_tokens=p) for p in (first, second)] + os.kill(donor.proc.pid, signal.SIGSTOP) + stopped = True + with self.assertRaises(RemoteMemError): + kvs[0].resume(stream) + self.assertGreaterEqual(_introspection.remote_unquiesced_transfers(self.manager), 1) + # Not a staging-lease failure: the scheduler re-matches or recomputes on RemoteMemError only. + with self.assertRaisesRegex(RemoteMemError, "remote level"): + kvs[1].resume(stream) + finally: + if stopped: + os.kill(donor.proc.pid, signal.SIGCONT) + if hasattr(self, "manager"): + deadline = time.monotonic() + 60 + while ( + _introspection.remote_unquiesced_transfers(self.manager) + and time.monotonic() < deadline + ): + time.sleep(0.1) + for kv in kvs: + with contextlib.suppress(Exception): + kv.close() + kvs.clear() + donor.stop() + if hasattr(self, "manager"): + with contextlib.suppress(Exception): + self.manager.shutdown() + del self.manager + gc.collect() + base.take_poison() + shutil.rmtree(directory, ignore_errors=True) + + def test_held_pages_stop_at_the_host_level_above_a_failed_remote_level(self) -> None: + """Once the trailing remote level failed, the host level is the last one. + + Held pages falling to it are kept, and the droppable pages it evicts are counted as dropped. Treated as a + middle level, the host let pages fall to the failed level: held ones, which nothing there can hold (every + later allocation then failed with OutOfPagesError), and droppable ones, cleared there uncounted. + """ + + def body(stream, donor) -> None: + lost = self._prompt(4 * self.tokens_per_block) + self._prefill(lost, stream) + self._push_to_last_level(lost, stream) + donor.stop() + kv = self.manager.create_kv_cache(input_tokens=lost) + with self.assertRaisesRegex(RemoteMemError, "remote level"): + kv.resume(stream) + kv.close() + del kv + # Held pages fill the host level's attention pool but one slot, so when the last of them fall the host + # has room for them and not for the droppable pages falling with them. + groups = _introspection.level_pool_groups(self.manager, 1) + attention_slots = max(groups, key=lambda group: group[1])[0] + ssm_slots = min(groups, key=lambda group: group[1])[0] + num_holders = max(1, min(4, ssm_slots - 1)) + held_blocks = (attention_slots - 1) // num_holders + self.assertGreater(held_blocks, 0, groups) + holders = [] + for _ in range(num_holders): + prompt = self._prompt(held_blocks * self.tokens_per_block) + holder = self.manager.create_kv_cache() + self.assertTrue(holder.resume(stream)) + holder.capacity = len(prompt) + holder.history_length = len(prompt) + self.engine.execute([Step(holder, prompt, [])], stream) + holder.commit(prompt) + holder.suspend() + holders.append((holder, prompt)) + # The GPU fills with droppable pages: the held ones go down to the host, the droppable ones drop. + self.manager.get_and_reset_iteration_stats() + for _ in range(8): + self._prefill(self._prompt(256), stream) + stats = self.manager.get_and_reset_iteration_stats() + self.assertGreater( + sum(delta.iter_host_dropped_blocks for delta in stats.values()), + 0, + "pages the host level evicted were dropped uncounted", + ) + for holder, prompt in holders: + self.assertTrue(holder.resume(stream), "a held page fell past the host level") + history = list(prompt) + holder.capacity = len(history) + 1 + token = TokenId(next(self._token_ids)) + # Reads every page of the holder's history and compares it with what its prefill wrote. + self.engine.execute([Step(holder, [token], history)], stream) + holder.suspend() + for holder, _ in holders: + holder.close() + holders.clear() + + self._with_dying_donor("kvcm2_held_host_", body) + + def test_withdrawn_donor_takes_no_new_claims(self) -> None: + """Growing the level after its donor withdrew claims nothing from it, though the client knew its chunks.""" + directory = tempfile.mkdtemp(prefix="kvcm2_withdrawn_") + donor = _Donor(directory, 128 << 20, self.transport) + try: + self.cfg = self._config( + with_host=False, directory=directory, remote_quota=32 << 20, wait_timeout_ms=2_000 + ) + self.manager = KVCacheManager(self.cfg) + claims = sorted(glob.glob(os.path.join(directory, f"claim.{donor.name}.*"))) + self.assertTrue(claims, "no chunk was claimed") + donor.stop() + last = cast(CacheLevel, CacheLevel(len(self.cfg.cache_tiers) - 1)) + self.assertFalse(self.manager.resize(last, 96 << 20), "grew on a withdrawn donor") + self.assertEqual( + sorted(glob.glob(os.path.join(directory, f"claim.{donor.name}.*"))), claims + ) + finally: + donor.stop() + if hasattr(self, "manager"): + self.manager.shutdown() + del self.manager + gc.collect() + shutil.rmtree(directory, ignore_errors=True) + + def test_claims_stop_once_every_expected_donor_reported(self) -> None: + """With every expected donor reported (published or failed) and no free chunk, a claim fails at once.""" + directory = tempfile.mkdtemp(prefix="kvcm2_reported_") + donor = _Donor(directory, 128 << 20, self.transport) + with open(os.path.join(directory, "donor.gone.failed"), "w") as f: + f.write(f"version 1\nname gone\ntransport {self.transport}\n") + try: + self.cfg = self._config( + with_host=False, + directory=directory, + wait_timeout_ms=600_000, + expected_donors=2, + ) + start = time.monotonic() + with self.assertRaisesRegex(Exception, "expected donors reported"): + self.manager = KVCacheManager(self.cfg) + self.assertLess(time.monotonic() - start, 120) + finally: + donor.stop() + gc.collect() + base.take_poison() + shutil.rmtree(directory, ignore_errors=True) + + def test_a_donor_reported_twice_counts_once(self) -> None: + """A donor whose .ready and .failed are both listed counts once. + + A listing can see both when the donor exits between the two; a claim then keeps waiting for the other expected + donor instead of failing as if all had reported. + """ + directory = tempfile.mkdtemp(prefix="kvcm2_twice_") + try: + meta = f"version 1\nname x\nhost h\npid 1\nchunk_bytes {_CHUNK_BYTES}\ntransport {self.transport}\n" + for suffix, text in ( + ("meta", meta + f"segment 4096 {4 * _CHUNK_BYTES}\n"), + ("ready", ""), + ("failed", f"version 1\nname x\ntransport {self.transport}\n"), + ): + with open(os.path.join(directory, f"donor.x.{suffix}"), "w") as f: + f.write(text) + self.cfg = self._config( + with_host=False, directory=directory, wait_timeout_ms=1_500, expected_donors=2 + ) + start = time.monotonic() + with self.assertRaisesRegex(Exception, "after 1500 ms"): + self.manager = KVCacheManager(self.cfg) + self.assertGreaterEqual(time.monotonic() - start, 1.0) + finally: + gc.collect() + base.take_poison() + shutil.rmtree(directory, ignore_errors=True) + + def test_a_donor_found_full_earlier_is_probed_again_before_a_claim_fails(self) -> None: + """A donor found full earlier is probed again before a claim fails at once. + + Every expected donor reported, but a peer may have returned its chunks since the donor was found full while a + claim was served elsewhere, e.g. an abandoned construction. + """ + directory = tempfile.mkdtemp(prefix="kvcm2_refull_") + donors = [_Donor(directory, _CHUNK_BYTES, self.transport) for _ in range(2)] + peer_claim = os.path.join(directory, f"claim.{donors[0].name}.0") + last = cast(CacheLevel, CacheLevel(1)) + try: + cfg = self._config( + with_host=False, + directory=directory, + remote_quota=_CHUNK_BYTES, + wait_timeout_ms=600_000, + expected_donors=2, + ) + self.cfg = replace(cfg, layers=self._attention_layers()) + # Whether the first claim passes over the full donor depends on where this client starts probing, which + # its random name decides: repeat with new clients. + for attempt in range(8): + with open(peer_claim, "w") as f: + f.write("peer\n") + self.manager = KVCacheManager(self.cfg) + os.unlink(peer_claim) # the peer lets go of its chunk + self.assertTrue(self.manager.resize(last, 2 * _CHUNK_BYTES), f"attempt {attempt}") + self.manager.shutdown() + del self.manager + gc.collect() + finally: + for donor in donors: + donor.stop() + if hasattr(self, "manager"): + with contextlib.suppress(Exception): + self.manager.shutdown() + del self.manager + gc.collect() + base.take_poison() + shutil.rmtree(directory, ignore_errors=True) + + def test_crashed_donor_is_passed_over(self) -> None: + """A donor that died without withdrawing (its files stay) gets no claims; the next donor serves them.""" + if self.transport != "fabric": + self.skipTest("a dead NIXL donor shows at its first transfer, not at the claim") + directory = tempfile.mkdtemp(prefix="kvcm2_crashed_") + dead = _Donor(directory, 128 << 20, self.transport) + files = sorted(glob.glob(os.path.join(directory, f"donor.{dead.name}.*"))) + contents = {path: open(path, "rb").read() for path in files} + dead.stop() + for path in sorted(files, key=lambda path: path.endswith(".ready")): # .ready last + with open(path, "wb") as f: + f.write(contents[path]) + # The live donor publishes while the client already waits, so the client meets the dead one first. + live = [] + thread = threading.Thread( + target=lambda: live.append(_Donor(directory, 128 << 20, self.transport)) + ) + thread.start() + try: + self.cfg = self._config( + with_host=False, directory=directory, remote_quota=32 << 20, wait_timeout_ms=300_000 + ) + self.manager = KVCacheManager(self.cfg) + thread.join() + self.assertEqual(glob.glob(os.path.join(directory, f"claim.{dead.name}.*")), []) + self.assertTrue(glob.glob(os.path.join(directory, f"claim.{live[0].name}.*"))) + finally: + thread.join() + if hasattr(self, "manager"): + self.manager.shutdown() + del self.manager + for donor in live: + donor.stop() + gc.collect() + shutil.rmtree(directory, ignore_errors=True) + + +@_per_transport +class TestRemotePoolRatio(_Transport, unittest.TestCase): + """RemoteCacheTierConfig.pool_ratio splits only the remote level's quota across layer groups. + + The model has an attention layer group (a 1 MiB block) and an SSM group (a 512 KiB state), at initial_pool_ratio + 0.5 / 0.5. Without the ratio, every cold level follows that split. With it, the remote level gives each layer + group the requested share of its own bytes, and the GPU and host levels keep their split. + """ + + buf_size = 256 << 10 + remote_quota = 256 << 20 + + def setUp(self) -> None: + super().setUp() + base.init_cuda_once() + + def _config(self, pool_ratio): + layers = [ + AttentionLayerConfig( + layer_id=LayerId(lid), + buffers=[ + BufferConfig(role=DataRole("key"), size=self.buf_size), + BufferConfig(role=DataRole("value"), size=self.buf_size), + ], + ) + for lid in range(2) + ] + layers += [ + SsmLayerConfig( + layer_id=LayerId(lid), + buffers=[BufferConfig(role=DataRole("ssm_state"), size=self.buf_size)], + ) + for lid in range(2, 4) + ] + return KVCacheManagerConfig( + tokens_per_block=32, + cache_tiers=[ + GpuCacheTierConfig(quota=32 << 20), + HostCacheTierConfig(quota=64 << 20), + self.remote_tier(self.remote_quota, pool_ratio=pool_ratio), + ], + layers=layers, + enable_partial_reuse=False, + commit_min_snapshot=True, + initial_pool_ratio=[0.5, 0.5], + ) + + def _levels(self, pool_ratio: "list[float] | None"): + """Build a manager whose remote level has `pool_ratio` (None: unset); return its levels' pool groups.""" + manager = KVCacheManager(self._config(pool_ratio)) + try: + levels = [_introspection.level_pool_groups(manager, level) for level in range(3)] + ssm = _introspection.ssm_life_cycle_id(manager) + finally: + manager.shutdown() + gc.collect() + self.assertIsNotNone(ssm) + return levels, ssm + + @staticmethod + def _bytes(groups) -> int: + return sum(slots * slot_bytes for slots, slot_bytes, _ in groups) + + @classmethod + def _share(cls, groups, life_cycle: int) -> float: + """The share of a level's bytes held by the pool group of `life_cycle`.""" + held = sum(slots * slot_bytes for slots, slot_bytes, lcs in groups if life_cycle in lcs) + return held / cls._bytes(groups) + + def test_unset_keeps_the_hot_split_on_every_cold_level(self) -> None: + (_, host, remote), ssm = self._levels(None) + self.assertAlmostEqual(self._share(remote, ssm), self._share(host, ssm), delta=0.05) + self.assertGreater(self._share(remote, ssm), 0.3) + + def test_override_splits_only_the_remote_level(self) -> None: + (gpu0, host0, remote0), ssm = self._levels(None) + num_life_cycles = sum(len(lcs) for _, _, lcs in gpu0) + weights = [9.0] * num_life_cycles + weights[ssm] = 1.0 + target = 1 / (1 + 9 * (num_life_cycles - 1)) + (gpu1, host1, remote1), _ = self._levels(weights) + self.assertEqual(gpu1, gpu0) + self.assertEqual(host1, host0) + self.assertAlmostEqual(self._share(remote1, ssm), target, delta=0.05) + self.assertLess(self._share(remote1, ssm), self._share(remote0, ssm) - 0.2) + # The same quota, only split differently. + self.assertAlmostEqual( + self._bytes(remote1), self._bytes(remote0), delta=0.05 * self.remote_quota + ) + # Weights are normalized. + (gpu2, host2, remote2), _ = self._levels([w / 10 for w in weights]) + self.assertEqual((gpu2, host2, remote2), (gpu1, host1, remote1)) + + def test_malformed_values_fail_before_remote_memory_is_claimed(self) -> None: + claims = sorted(glob.glob(os.path.join(self.module_dir, "claim.*"))) + for value in ( + [0.5], + [0.5, 0.0], + [0.5, -1.0], + [float("nan"), 1.0], + [float("inf"), 1.0], + [1.0, 1.0, 1.0], + ): + # TLLM_CHECK, from the tier config (a bad entry) or the storage manager (a wrong entry count). + with ( + self.subTest(value=value), + self.assertRaisesRegex(RuntimeError, "pool ratio"), + ): + self._levels(value) + self.assertEqual(sorted(glob.glob(os.path.join(self.module_dir, "claim.*"))), claims) + + +@_per_transport +class TestRemoteTierCombinations(_Transport, unittest.TestCase): + """A remote level stages pages through pinned host memory, so it cannot sit next to a file-backed disk level.""" + + def _single_level_manager(self, directory: str): + layers = [ + AttentionLayerConfig( + layer_id=LayerId(0), + buffers=[BufferConfig(role=DataRole("key"), size=64 << 10)], + ) + ] + return KVCacheManager( + KVCacheManagerConfig( + tokens_per_block=32, + cache_tiers=[ + GpuCacheTierConfig(quota=32 << 20), + self.remote_tier(64 << 20, directory=directory, wait_timeout_ms=5_000), + ], + layers=layers, + ) + ) + + def test_the_rendezvous_directory_must_be_this_users_private_directory(self) -> None: + """The client reads donor files only through the directory it checked. + + Never through a symlink in its place, never from a directory others can write. + """ + parent = tempfile.mkdtemp(prefix="kvcm2_pin_") + try: + link = os.path.join(parent, "link") + os.symlink(self.module_dir, link) + with self.assertRaisesRegex(Exception, "symlink"): + self._single_level_manager(link) + shared = os.path.join(parent, "shared") + os.mkdir(shared) + os.chmod(shared, 0o770) + with self.assertRaisesRegex(Exception, "not writable by group or others"): + self._single_level_manager(shared) + finally: + gc.collect() + shutil.rmtree(parent, ignore_errors=True) + + def test_a_file_backed_disk_level_is_rejected(self) -> None: + disk_dir = tempfile.mkdtemp(prefix="kvcm2_disk_") + try: + layers = [ + AttentionLayerConfig( + layer_id=LayerId(0), + buffers=[BufferConfig(role=DataRole("key"), size=64 << 10)], + ) + ] + with self.assertRaisesRegex(Exception, "file-backed disk level"): + KVCacheManager( + KVCacheManagerConfig( + tokens_per_block=32, + cache_tiers=[ + GpuCacheTierConfig(quota=32 << 20), + HostCacheTierConfig(quota=32 << 20), + DiskCacheTierConfig(quota=64 << 20, path=disk_dir), + self.remote_tier(64 << 20), + ], + layers=layers, + ) + ) + finally: + gc.collect() + shutil.rmtree(disk_dir, ignore_errors=True) + + +class TestRemoteInPlaceOfDisk(_Transport, base.TestKVCacheManagerV2): + """The suite's cache-reuse tests and one shrink case, with the remote level in the disk level's place.""" + + Request = base.TestNoBatching.Request + new_request = base.TestNoBatching.new_request + run_request = base.TestNoBatching.run_request + run_naive = base.TestNoBatching.run_naive + + def prepare( + self, + gpu_quota, + host_quota, + disk_quota, + num_layers, + window_size, + sink_tokens, + tokens_per_block=32, + kv_buf_size=8192, + block_quant_buf_size=None, + ) -> None: + cfg = base.create_config( + tokens_per_block, + gpu_quota, + host_quota, + disk_quota, + num_layers, + window_size, + sink_tokens, + kv_buf_size, + block_quant_buf_size, + ) + cfg = replace( + cfg, + cache_tiers=[ + self.remote_tier(t.quota) if isinstance(t, DiskCacheTierConfig) else t + for t in cfg.cache_tiers + ], + ) + self.cfg = cfg + self.engine = FakeEngine(self.cfg) + self.manager = KVCacheManager(self.cfg) + + +# The suite's cache-reuse tests, whose pages reach the disk level and come back (each generated name), and one +# shrink case; the base suite covers the rest of the manager. +_cases = sorted( + name + for name, test in vars(base.TestNoBatching).items() + if name.startswith("test_cache_reuse") and callable(test) +) +_cases += sorted( + name + for name, test in vars(base.TestNoBatching).items() + if name.startswith("test_shrink_capacity") and "truncates" not in name and callable(test) +)[:1] +for _name in _cases: + setattr(TestRemoteInPlaceOfDisk, _name, getattr(base.TestNoBatching, _name)) +del _name, _cases +TestRemoteInPlaceOfDisk = _per_transport(TestRemoteInPlaceOfDisk) diff --git a/tests/unittest/kv_cache_manager_v2_tests/test_remote_ucx_devices.py b/tests/unittest/kv_cache_manager_v2_tests/test_remote_ucx_devices.py new file mode 100644 index 000000000000..8b387edef5d6 --- /dev/null +++ b/tests/unittest/kv_cache_manager_v2_tests/test_remote_ucx_devices.py @@ -0,0 +1,172 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""remote_cache_config.transport.ucx_devices: the {GPU} token and the NIXL backend parameter. No GPU needed.""" + +import os +import shutil +import sys +import tempfile +import types +import unittest +from unittest import mock + +import pytest + +from tensorrt_llm._torch.pyexecutor.kv_cache import remote_donor +from tensorrt_llm._torch.pyexecutor.kv_cache.remote_donor import ( + make_donor, + nixl_ucx_backend_params, + resolve_ucx_devices, +) + + +def _visible(value=None): + env = {k: v for k, v in os.environ.items() if k != "CUDA_VISIBLE_DEVICES"} + if value is not None: + env["CUDA_VISIBLE_DEVICES"] = value + return mock.patch.dict(os.environ, env, clear=True) + + +@pytest.mark.cpu_only +class TestRemoteUcxDevices(unittest.TestCase): + def test_unset_and_literal_values_pass_through(self): + self.assertIsNone(resolve_ucx_devices(None, device=0)) + self.assertEqual( + resolve_ucx_devices("rdma_vf_rail0:1,rdma_vf_rail2:1", device=3), + "rdma_vf_rail0:1,rdma_vf_rail2:1", + ) + + def test_gpu_token_maps_the_device_through_cuda_visible_devices(self): + # A TP2 CTX instance on GPUs 2,3: its second rank (CUDA device 1) is GPU 3 and uses rail 3. + with _visible("2,3"): + self.assertEqual( + resolve_ucx_devices("rdma_vf_rail{GPU}:1", device=1), "rdma_vf_rail3:1" + ) + with _visible(): + self.assertEqual( + resolve_ucx_devices("rdma_vf_rail{GPU}:1", device=2), "rdma_vf_rail2:1" + ) + + def test_gpu_token_maps_a_uuid_through_the_pci_bus_id(self): + with ( + _visible("GPU-1a2b,GPU-3c4d"), + mock.patch.object(remote_donor, "_nvml_gpu_index", return_value=5) as nvml, + ): + self.assertEqual( + resolve_ucx_devices("rdma_vf_rail{GPU}:1", device=1), "rdma_vf_rail5:1" + ) + nvml.assert_called_once_with(1) + + def test_unresolvable_tokens_raise(self): + cases = [ + ("rdma_vf_rail{GPU}:1", "0"), # device 1 not visible + ("rdma_vf_rail{RANK}:1", None), + ] + for devices, visible in cases: + with self.subTest(devices=devices, visible=visible), _visible(visible): + with self.assertRaises(ValueError): + resolve_ucx_devices(devices, device=1) + + +class TestNixlUcxBackendParams(unittest.TestCase): + """NIXL 1.5.2's UCX backend reads `device_list` (names split on ", ", port 1 appended); `ucx_devices` is ignored.""" + + @pytest.mark.cpu_only + def test_devices_become_the_device_list_nixl_reads(self): + self.assertEqual(nixl_ucx_backend_params(None), {}) + self.assertEqual(nixl_ucx_backend_params("mlx5_0:1"), {"device_list": "mlx5_0"}) + self.assertEqual( + nixl_ucx_backend_params("rdma_vf_rail0:1, rdma_vf_rail2:1,mlx5_3"), + {"device_list": "rdma_vf_rail0, rdma_vf_rail2, mlx5_3"}, + ) + + @pytest.mark.cpu_only + def test_a_port_other_than_1_raises(self): + for devices in ("mlx5_0:2", "mlx5_0:1,", ":1"): + with self.subTest(devices=devices), self.assertRaises(ValueError): + nixl_ucx_backend_params(devices) + + # Not cpu_only: the NIXL donor registers its memory with a CUDA context current. + def test_the_donor_agent_gets_the_device_list(self): + """The donor's NIXL agent is created with `device_list` in its backend parameters.""" + configs = [] + + class _Config: + def __init__(self): + self.backend_params = {} + + class _Agent: + def __init__(self, config): + configs.append(config) + + def register_memory(self, descs): + pass + + def deregister_memory(self, descs): + pass + + def get_local_agent_desc(self): + return types.SimpleNamespace(serialize=lambda: b"desc") + + binding = types.ModuleType("tensorrt_llm.tensorrt_llm_transfer_agent_binding") + binding.BaseAgentConfig = _Config + binding.NixlTransferAgent = _Agent + binding.MemoryDesc = lambda *args: args + binding.MemoryDescs = lambda *args: args + binding.MemoryType = types.SimpleNamespace(DRAM="DRAM") + directory = tempfile.mkdtemp(prefix="kvcm2_ucx_devices_") + try: + donor = make_donor( + directory, + 4 << 20, + transport="nixl", + chunk_bytes=2 << 20, + ucx_devices="mlx5_0:1,mlx5_3:1", + ) + with mock.patch.dict(sys.modules, {binding.__name__: binding}): + donor.start() + donor.close() + finally: + shutil.rmtree(directory, ignore_errors=True) + self.assertEqual(len(configs), 1) + self.assertEqual(configs[0].backend_params, {"device_list": "mlx5_0, mlx5_3"}) + + @pytest.mark.cpu_only + def test_the_remote_level_agent_gets_the_device_list(self): + """The remote level's tier carries `device_list` to its NIXL agent's backend parameters.""" + from tensorrt_llm._torch.pyexecutor.kv_cache.kv_cache_manager_v2 import KVCacheManagerV2 + from tensorrt_llm.llmapi.llm_args import RemoteCacheConfig + + manager = object.__new__(KVCacheManagerV2) + manager.is_draft = False + directory = tempfile.mkdtemp(prefix="kvcm2_ucx_devices_") + try: + tiers = [] + manager._add_remote_level( + RemoteCacheConfig( + directory=directory, + level={"size": 1 << 30}, + transport={"kind": "nixl", "ucx_devices": "mlx5_0:1,mlx5_3:1"}, + ), + tiers, + ) + finally: + shutil.rmtree(directory, ignore_errors=True) + self.assertEqual(len(tiers), 1) + self.assertEqual(tiers[0].transfer.backend_params, {"device_list": "mlx5_0, mlx5_3"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unittest/llmapi/test_llm_args.py b/tests/unittest/llmapi/test_llm_args.py index 0eec4862edfe..c36742a50b26 100644 --- a/tests/unittest/llmapi/test_llm_args.py +++ b/tests/unittest/llmapi/test_llm_args.py @@ -1646,6 +1646,21 @@ def test_KvCacheConfig_declaration(offload_field): BlockReuseConfig(max_num_turns=0) +@pytest.mark.cpu_only +def test_KvCacheConfig_defer_generation_only_release(): + assert KvCacheConfig().defer_generation_only_release is False + for v2 in (True, "auto"): + assert KvCacheConfig( + defer_generation_only_release=True, + use_kv_cache_manager_v2=v2).defer_generation_only_release is True + assert KvCacheConfig(use_kv_cache_manager_v2=False, + defer_generation_only_release=False) + with pytest.raises(ValidationError, + match="defer_generation_only_release requires"): + KvCacheConfig(defer_generation_only_release=True, + use_kv_cache_manager_v2=False) + + @pytest.mark.cpu_only def test_KvCacheConfig_offload_priority_compatibility(): assert KvCacheConfig().cold_tier_offload_min_priority is None @@ -2054,6 +2069,253 @@ def test_KvCacheConfig_disk_cache_validation(tmp_path): assert "disk_cache_path" in str(exc_info.value) +@pytest.mark.cpu_only +def test_KvCacheConfig_remote_cache_validation(tmp_path): + remote = llm_args_mod.RemoteCacheConfig + config = KvCacheConfig( + remote_cache_config={ + "directory": str(tmp_path), + "transport": { + "kind": "fabric" + }, + "level": { + "size": 200 << 30, + "pool_ratio": [0.02, 0.98], + "expected": { + "num_donors": 8, + "claim_size": 406 << 30 + }, + }, + }) + level = config.remote_cache_config.level + assert level.size == 200 << 30 + assert level.donor_wait_timeout_s == 900.0 + assert isinstance(config.remote_cache_config.transport, + llm_args_mod.RemoteFabricTransportConfig) + assert config.remote_cache_config.donor is None + # The default transport is NIXL with its defaults. + nixl = remote(directory=str(tmp_path), donor={"size": 1 << 30}).transport + assert (nixl.kind, nixl.transfer_timeout_s, + nixl.ucx_devices) == ("nixl", 30.0, None) + assert KvCacheConfig().remote_cache_config is None + + for bad in ( + {}, # neither a donor nor a level + { + "level": { + "size": 1, + "expected": { + "num_donors": 8 + } + } + }, + # Each transport's fields only on that transport. + { + "donor": { + "size": 1 << 30 + }, + "transport": { + "kind": "fabric", + "ucx_devices": "mlx5_0:1" + } + }, + { + "level": { + "size": 1 + }, + "transport": { + "kind": "fabric", + "transfer_timeout_s": 10.0 + } + }, + { + "donor": { + "size": 1 << 30 + }, + "transport": { + "kind": "nixl", + "donor_reserve_size": 8 << 30 + } + }, + { + "donor": { + "size": 1 << 30 + }, + "transport": { + "kind": "rdma" + } + }, + { + "level": { + "size": 1, + "pool_ratio": [0.5, 0.0] + } + }, + { + "donor": { + "size": 1 << 30 + }, + "transport": { + "kind": "nixl", + "ucx_devices": "mlx5_0:2" # NIXL's UCX backend uses port 1 + } + }, + { + "donor": { + "size": 1 << 30 + }, + "transport": { + "kind": "nixl", + "ucx_devices": "mlx5_0:1,,mlx5_1:1" + } + }, + { + "donor": { + "size": (1 << 30) - 1 # below the donor's 1 GiB chunk + } + }, + { + "level": { + "size": 0 + } + }, + { + "level": { + "size": 1, + "donor_wait_timeout_s": 0 + } + }, + { + "level": { + "size": 1 + }, + "transport": { + "kind": "nixl", + "transfer_timeout_s": float("inf") + } + }, + # The old flat fields are gone. + { + "cache_size": 1 + }, + { + "donate_size": 1 << 30 + }, + ): + with pytest.raises(ValidationError): + remote(directory=str(tmp_path), **bad) + # A dumped config, defaults included, validates again. + for good in ( + config.remote_cache_config, + remote(directory=str(tmp_path), donor={"size": 1 << 30}), + remote(directory=str(tmp_path), + donor={"size": 1 << 30}, + transport={ + "kind": "fabric", + "donor_reserve_size": 8 << 30 + }), + ): + assert remote(**good.model_dump()) == good + assert remote(directory=str(tmp_path), + donor={ + "size": 1 << 30 + }, + transport={ + "kind": "fabric", + "donor_reserve_size": 8 << 30 + }).transport.donor_reserve_size == 8 << 30 + assert remote(directory=str(tmp_path), + donor={ + "size": 1 << 30 + }, + transport={ + "kind": "nixl", + "ucx_devices": "rdma_vf_rail{GPU}:1, mlx5_1" + }).transport.ucx_devices + with pytest.raises(ValidationError): + KvCacheConfig(remote_cache_config={ + "directory": str(tmp_path), + "donor": { + "size": 1 << 30 + } + }, + use_kv_cache_manager_v2=False) + with pytest.raises(ValidationError): + KvCacheConfig(remote_cache_config={ + "directory": str(tmp_path), + "level": { + "size": 1 + } + }, + disk_cache_size=1, + disk_cache_path=str(tmp_path)) + # A rebalance would claim donor chunks inside adjust(), which holds every request. + with pytest.raises(ValidationError, match="enable_kv_pool_rebalance"): + KvCacheConfig(remote_cache_config={ + "directory": str(tmp_path), + "level": { + "size": 1 + } + }, + enable_kv_pool_rebalance=True) + assert KvCacheConfig(remote_cache_config={ + "directory": str(tmp_path), + "donor": { + "size": 1 << 30 + } + }, + enable_kv_pool_rebalance=True).enable_kv_pool_rebalance + + +@pytest.mark.cpu_only +@pytest.mark.parametrize( + "remote_config", + [ + # CTX style: a remote level and a donation. + { + "transport": { + "kind": "fabric" + }, + "donor": { + "size": 8 << 30 + }, + "level": { + "size": 200 << 30, + "pool_ratio": [0.02, 0.98], + "expected": { + "num_donors": 8, + "claim_size": 406 << 30 + }, + }, + }, + # GEN style: donation only. + { + "transport": { + "kind": "fabric" + }, + "donor": { + "size": 160 << 30 + }, + }, + ], + ids=["ctx", "gen"]) +def test_remote_cache_config_survives_model_defaults(tmp_path, remote_config): + # apply_model_defaults_to_llm_args rebuilds the args from a full dump, defaults included. + remote_config = dict(remote_config, directory=str(tmp_path)) + llm_args = TorchLlmArgs( + model=str(tmp_path), + kv_cache_config=KvCacheConfig(remote_cache_config=remote_config)) + expected = llm_args.kv_cache_config.remote_cache_config + apply_model_defaults_to_llm_args( + llm_args, {"kv_cache_config": { + "enable_block_reuse": False + }}) + assert llm_args.kv_cache_config.enable_block_reuse is False + assert llm_args.kv_cache_config.remote_cache_config == expected + rebuilt = TorchLlmArgs(**llm_args.model_dump()) + assert rebuilt.kv_cache_config.remote_cache_config == expected + + @pytest.mark.cpu_only class TestMultimodalEncoderCudaGraphConfig: @@ -2533,6 +2795,20 @@ def test_gen_preemption_rejects_pp_and_attention_dp(parallel) -> None: TorchLlmArgs(model=llama_model_path, **parallel) # off: no restriction +@pytest.mark.cpu_only +@pytest.mark.parametrize("loop", [{ + "pipeline_parallel_size": 2 +}, { + "disable_overlap_scheduler": True +}]) +def test_defer_generation_only_release_needs_the_overlap_loop(loop) -> None: + """Rejected at parse time, before any rank loads the checkpoint.""" + defer = KvCacheConfig(defer_generation_only_release=True) + with pytest.raises(ValueError, match="overlap scheduler loop"): + TorchLlmArgs(model=llama_model_path, kv_cache_config=defer, **loop) + TorchLlmArgs(model=llama_model_path, kv_cache_config=defer) + + @pytest.mark.cpu_only def test_PeftCacheConfig_declaration(): config = PeftCacheConfig(num_host_module_layer=1, diff --git a/tests/unittest/llmapi/test_llm_multi_gpu_pytorch.py b/tests/unittest/llmapi/test_llm_multi_gpu_pytorch.py index dcab052a7470..83ebac1566ba 100644 --- a/tests/unittest/llmapi/test_llm_multi_gpu_pytorch.py +++ b/tests/unittest/llmapi/test_llm_multi_gpu_pytorch.py @@ -1,6 +1,10 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +import json +import time +from typing import Dict + import pytest from utils.util import skip_ray @@ -155,3 +159,85 @@ def test_llm_get_stats_async_tp2(): @pytest.mark.gpu2 def test_llm_get_stats_async_pp2(): llm_get_stats_async_test_harness(pp_size=2, pytorch_backend=True) + + +def _context_requests_per_rank(llm: LLM) -> Dict[int, int]: + """Context requests each attention-DP rank scheduled since the last call. + + One per request (no chunking), from the iteration stats that arrived. + + Args: + llm: An attention-DP LLM with iteration stats on. + + Returns: + Attention-DP rank -> context requests it ran. + """ + time.sleep(2) # as llm_get_stats_test_harness: let the stats arrive + counts: Dict[int, int] = {} + for stats in llm.get_stats(2): + stats = json.loads(stats) if isinstance(stats, str) else stats + rank = stats["attentionDpRank"] + counts[rank] = counts.get( + rank, 0) + stats["inflightBatchingStats"]["numContextRequests"] + return {rank: n for rank, n in counts.items() if n} + + +@skip_ray +@pytest.mark.gpu2 +def test_llm_attention_dp_home_wait_tp2(): + """Home-wait runs every turn of a conversation on its home rank. + + Conversation-affinity routing with home-wait on 2-GPU attention DP. + + With one request slot per rank, later turns of a conversation wait for + their full home rank (the rank its first turn ran on), even while the + other rank is free: the per-rank context requests of the turns are three + per conversation homed there. Each turn completes with the same greedy + output as its first turn. + """ + from tensorrt_llm.conversation_params import ConversationParams + from tensorrt_llm.llmapi import AttentionDpConfig + + prompts = { + "conv-a": "The capital of France is", + "conv-b": "One, two, three, four," + } + params = SamplingParams(max_tokens=8, temperature=0, end_id=-1) + with LLM( + model=llama_model_path, + kv_cache_config=global_kv_cache_config, + tensor_parallel_size=2, + enable_attention_dp=True, + max_batch_size=1, + enable_iter_perf_stats=True, + attention_dp_config=AttentionDpConfig( + kv_cache_routing_conversation_affinity=True, + # More rounds than the six turns take on one rank, so that + # no turn overflows to the free rank. + kv_cache_routing_home_wait_rounds=1000)) as llm: + _context_requests_per_rank(llm) # drop any warmup rows + first, home = {}, {} + for conv, prompt in prompts.items(): + first[conv] = llm.generate( + prompt, + params, + conversation_params=ConversationParams( + conversation_id=conv)).outputs[0].token_ids + ranks = list(_context_requests_per_rank(llm)) + assert len(ranks) == 1, (conv, ranks) + home[conv] = ranks[0] + convs = [conv for conv in prompts for _ in range(3)] + results = llm.generate([prompts[conv] for conv in convs], + params, + conversation_params=[ + ConversationParams(conversation_id=conv) + for conv in convs + ]) + per_rank = _context_requests_per_rank(llm) + for conv, result in zip(convs, results): + assert len(first[conv]) == 8 + assert result.outputs[0].token_ids == first[conv], conv + expected: Dict[int, int] = {} + for conv in convs: + expected[home[conv]] = expected.get(home[conv], 0) + 1 + assert per_rank == expected, (home, per_rank) diff --git a/tests/unittest/llmapi/test_llm_pytorch.py b/tests/unittest/llmapi/test_llm_pytorch.py index e463c633f69f..53bdd9f97bce 100644 --- a/tests/unittest/llmapi/test_llm_pytorch.py +++ b/tests/unittest/llmapi/test_llm_pytorch.py @@ -1518,6 +1518,71 @@ async def await_and_record(output, req_id: int): f"Completion order: {completion_order}") +@pytest.mark.threadleak(enabled=False) +@pytest.mark.part0 +@skip_ray +@pytest.mark.timeout(120) +def test_priority_wait_cap_admits_an_aged_request_first(): + """With waiting_queue_max_wait_s, a request that waited the cap goes ahead of a higher-priority one. + + max_batch_size=1: Request 1 holds the only slot. Request 2 (priority 0.1) waits past the cap before + Request 3 (priority 0.9) arrives, so Request 2 is admitted first when the slot frees; without the cap + Request 3 would be (test_priority_request_completes_before_low_priority). + """ + max_wait_s = 0.25 + llm = LLM( + model=llama_model_path, + max_batch_size=1, + kv_cache_config=KvCacheConfig(enable_block_reuse=False), + scheduler_config=SchedulerConfig( + waiting_queue_policy=WaitingQueuePolicy.PRIORITY, + waiting_queue_max_wait_s=max_wait_s), + ) + + prompt = "A B C D E F G H I J" + completion_order = [] + slot_busy_at_request3 = [] + + async def run(): + out1 = llm.generate_async( + prompt, + SamplingParams(max_tokens=1500, temperature=0, ignore_eos=True)) + out2 = llm.generate_async(prompt, + SamplingParams(max_tokens=5, temperature=0), + priority=0.1) + await asyncio.sleep(2 * max_wait_s) + out3 = llm.generate_async(prompt, + SamplingParams(max_tokens=5, temperature=0), + priority=0.9) + slot_busy_at_request3.append(not out1.finished) + + async def await_and_record(output, req_id: int): + await output.aresult() + completion_order.append(req_id) + + await asyncio.wait_for( + asyncio.gather( + await_and_record(out1, 1), + await_and_record(out2, 2), + await_and_record(out3, 3), + ), + timeout=90, + ) + + try: + asyncio.run(run()) + finally: + llm.shutdown() + + assert slot_busy_at_request3 == [ + True + ], ("Request 1 finished before Request 3 arrived; the test needs it to hold the slot" + ) + assert completion_order.index(2) < completion_order.index(3), ( + f"Request 2 (waited past the cap) should complete before Request 3 (priority=0.9). " + f"Completion order: {completion_order}") + + @pytest.mark.threadleak(enabled=False) @pytest.mark.part0 @skip_ray diff --git a/tests/unittest/llmapi/test_trtllm_serve_config_schemas.py b/tests/unittest/llmapi/test_trtllm_serve_config_schemas.py index e4d00d4f25b6..24920340ef01 100644 --- a/tests/unittest/llmapi/test_trtllm_serve_config_schemas.py +++ b/tests/unittest/llmapi/test_trtllm_serve_config_schemas.py @@ -585,6 +585,33 @@ def test_load_balancer_schema_matches_runtime( MoeConfig(load_balancer=load_balancer) +@pytest.mark.parametrize( + ("config", "valid"), + [ + ({"output_length_prediction": {}}, True), + ({"output_length_prediction": {"predictor": "ridge"}}, True), + ({"output_length_prediction": {"predictor": "ridge_gbm"}}, True), + ({"output_length_prediction": None, "schedule_style": "generation_first"}, True), + ({"output_length_prediction": {}, "schedule_style": "context_first"}, True), + ({"output_length_prediction": {"predictor": "ema"}}, False), + ({"output_length_prediction": {"unknown": 1}}, False), + ({"output_length_prediction": {}, "schedule_style": "generation_first"}, False), + ], +) +def test_output_length_prediction_schema_matches_runtime( + schemas: dict[str, dict], config: dict, valid: bool +) -> None: + from tensorrt_llm.llmapi.disagg_utils import extract_disagg_cfg + + errors = list(Draft202012Validator(schemas[generator.DISAGG_SCHEMA]).iter_errors(config)) + assert (not errors) == valid, [error.message for error in errors] + if valid: + extract_disagg_cfg(**config) + else: + with pytest.raises(ValueError): + extract_disagg_cfg(**config) + + @pytest.mark.parametrize("filename", [generator.SERVE_SCHEMA, generator.DISAGG_SCHEMA]) @pytest.mark.parametrize( ("settings", "valid"), @@ -691,6 +718,246 @@ def test_dwdp_modes_match_runtime( assert validator.is_valid({section: config}) == (error is None), section +_GIB = 1 << 30 + + +@pytest.mark.parametrize( + ("section", "config", "valid"), + [ + # RemoteCacheConfig + *( + ("kv_cache_config", {"remote_cache_config": {"directory": "d", **remote}}, valid) + for remote, valid in ( + ({"level": {"size": _GIB}}, True), + ({"donor": {"size": _GIB}}, True), + ({}, False), + ({"donor": {"size": 1}}, False), + ({"level": {"size": 0}}, False), + ({"cache_size": _GIB}, False), + ({"level": {"size": 1, "expected": {"num_donors": 2}}}, False), + ({"level": {"size": 1, "expected": {"num_donors": 2, "claim_size": _GIB}}}, True), + ( + {"level": {"size": 1}, "transport": {"kind": "nixl", "transfer_timeout_s": 5}}, + True, + ), + ( + { + "level": {"size": 1}, + "transport": {"kind": "fabric", "transfer_timeout_s": 5}, + }, + False, + ), + ( + {"level": {"size": 1}, "transport": {"kind": "fabric", "ucx_devices": "m:1"}}, + False, + ), + ( + { + "donor": {"size": _GIB}, + "transport": {"kind": "nixl", "donor_reserve_size": 0}, + }, + False, + ), + ( + { + "donor": {"size": _GIB}, + "transport": {"kind": "fabric", "donor_reserve_size": 0}, + }, + True, + ), + ({"donor": {"size": _GIB}, "transport": {"kind": "rdma"}}, False), + ) + ), + # KvCacheConfig + ( + "kv_cache_config", + { + "remote_cache_config": {"directory": "d", "level": {"size": 1}}, + "disk_cache_size": 1, + "disk_cache_path": str(_REPO_ROOT), + }, + False, + ), + ( + "kv_cache_config", + { + "remote_cache_config": {"directory": "d", "donor": {"size": _GIB}}, + "disk_cache_size": 1, + "disk_cache_path": str(_REPO_ROOT), + }, + True, + ), + ( + "kv_cache_config", + { + "remote_cache_config": {"directory": "d", "level": {"size": 1}}, + "use_kv_cache_manager_v2": False, + }, + False, + ), + ( + "kv_cache_config", + { + "remote_cache_config": {"directory": "d", "level": {"size": 1}}, + "enable_kv_pool_rebalance": True, + }, + False, + ), + ( + "kv_cache_config", + { + "remote_cache_config": {"directory": "d", "donor": {"size": _GIB}}, + "enable_kv_pool_rebalance": True, + }, + True, + ), + *( + ( + "kv_cache_config", + { + "remote_cache_config": { + "directory": "d", + "level": {"size": 1}, + "transport": {"kind": "nixl", "ucx_devices": devices}, + } + }, + valid, + ) + for devices, valid in ( + ("mlx5_0", True), + ("mlx5_0:1, mlx5_{GPU}", True), + ("mlx5_0:", True), + ("mlx5_0:2", False), + ("mlx5_0::1", False), + ("mlx5_0,,mlx5_1", False), + (":1", False), + ("", False), + ) + ), + ("kv_cache_config", {"defer_generation_only_release": True}, True), + ( + "kv_cache_config", + {"defer_generation_only_release": True, "use_kv_cache_manager_v2": False}, + False, + ), + # AttentionDpConfig + ( + "attention_dp_config", + { + "kv_cache_routing_conversation_affinity": True, + "kv_cache_routing_home_wait_rounds": 4, + }, + True, + ), + ("attention_dp_config", {"kv_cache_routing_home_wait_rounds": 4}, False), + # SchedulerConfig + ( + "scheduler_config", + {"waiting_queue_policy": "priority", "waiting_queue_max_wait_s": 30}, + True, + ), + ( + "scheduler_config", + {"waiting_queue_policy": "priority", "waiting_queue_max_wait_s": None}, + True, + ), + ("scheduler_config", {"waiting_queue_max_wait_s": None}, True), + ("scheduler_config", {"waiting_queue_max_wait_s": 30}, False), + ( + "scheduler_config", + {"waiting_queue_policy": "fcfs", "waiting_queue_max_wait_s": 60}, + False, + ), + ], +) +def test_cross_field_rules_match_runtime( + schemas: dict[str, dict], section: str, config: dict, valid: bool +) -> None: + """Both schemas accept the remote cache, home-wait and waiting-queue options exactly when the models do.""" + from tensorrt_llm.llmapi.llm_args import AttentionDpConfig, KvCacheConfig, SchedulerConfig + + model = { + "kv_cache_config": KvCacheConfig, + "attention_dp_config": AttentionDpConfig, + "scheduler_config": SchedulerConfig, + }[section] + if valid: + model(**config) + else: + with pytest.raises(ValueError): + model(**config) + + for filename in (generator.SERVE_SCHEMA, generator.DISAGG_SCHEMA): + validator = Draft202012Validator(schemas[filename]) + assert validator.is_valid({section: config}) == valid, filename + if filename == generator.DISAGG_SCHEMA: + assert validator.is_valid({"generation_servers": {section: config}}) == valid + + +@pytest.mark.parametrize( + ("config", "valid"), + [ + ({"kv_cache_config": {"defer_generation_only_release": True}}, True), + ( + { + "kv_cache_config": {"defer_generation_only_release": True}, + "disable_overlap_scheduler": False, + "pipeline_parallel_size": 1, + }, + True, + ), + ( + { + "kv_cache_config": {"defer_generation_only_release": True}, + "disable_overlap_scheduler": True, + }, + False, + ), + ( + { + "kv_cache_config": {"defer_generation_only_release": True}, + "pipeline_parallel_size": 2, + }, + False, + ), + ( + { + "kv_cache_config": {"defer_generation_only_release": False}, + "disable_overlap_scheduler": True, + }, + True, + ), + ({"disable_overlap_scheduler": True, "pipeline_parallel_size": 2}, True), + ], +) +def test_deferred_release_launch_rule_matches_runtime( + schemas: dict[str, dict], config: dict, valid: bool +) -> None: + """Both schemas accept defer_generation_only_release with the overlap loop exactly when TorchLlmArgs does.""" + from types import SimpleNamespace + + from tensorrt_llm.llmapi.llm_args import KvCacheConfig, TorchLlmArgs + + kv_cache_config = config.get("kv_cache_config") or {} + args = SimpleNamespace( + kv_cache_config=KvCacheConfig(**kv_cache_config), + disable_overlap_scheduler=config.get("disable_overlap_scheduler", False), + pipeline_parallel_size=config.get("pipeline_parallel_size", 1), + ) + if valid: + TorchLlmArgs.validate_defer_generation_only_release(args) + else: + with pytest.raises(ValueError, match="defer_generation_only_release"): + TorchLlmArgs.validate_defer_generation_only_release(args) + + for filename in (generator.SERVE_SCHEMA, generator.DISAGG_SCHEMA): + validator = Draft202012Validator(schemas[filename]) + assert validator.is_valid(config) == valid, filename + if filename == generator.DISAGG_SCHEMA: + for section in ("context_servers", "generation_servers"): + assert validator.is_valid({section: config}) == valid, section + + def _assert_serving_fields_in_schema(source: str, function_name: str, properties: dict) -> None: """Check literal top-level config accesses, without tracing aliases or dynamic keys.""" function = next( @@ -1022,6 +1289,77 @@ class UpdatedRouterConfig(disagg_utils.RouterConfig): assert disagg_utils.extract_router_config({"router": {"type": "explicit"}}).type == "explicit" +_LB = "load_balancing" + + +@pytest.mark.parametrize( + ("section", "router", "valid"), + [ + ("generation_servers", {"type": _LB, "max_requests_per_server": 64}, True), + ( + "generation_servers", + {"type": _LB, "max_requests_per_server": 1, "max_queue_wait_s": 30}, + True, + ), + ("generation_servers", {"type": "Load_Balancing", "max_requests_per_server": 2}, True), + ( + "generation_servers", + {"type": _LB, "max_requests_per_server": 2, "use_tokens": False}, + True, + ), + ( + "generation_servers", + {"type": "round_robin", "max_requests_per_server": None, "max_queue_wait_s": None}, + True, + ), + ("generation_servers", {"type": _LB, "max_requests_per_server": 0}, False), + ("generation_servers", {"type": _LB, "max_requests_per_server": 1.5}, False), + ("generation_servers", {"type": _LB, "max_requests_per_server": True}, False), + ("generation_servers", {"type": _LB, "max_requests_per_server": "4"}, False), + ("generation_servers", {"type": "round_robin", "max_requests_per_server": 4}, False), + ("generation_servers", {"max_requests_per_server": 4}, False), + ( + "generation_servers", + {"type": _LB, "max_requests_per_server": 4, "use_tokens": True}, + False, + ), + ("generation_servers", {"type": _LB, "max_queue_wait_s": 30}, False), + ( + "generation_servers", + {"type": _LB, "max_requests_per_server": 4, "max_queue_wait_s": 0}, + False, + ), + ( + "generation_servers", + {"type": _LB, "max_requests_per_server": 4, "max_queue_wait_s": -1}, + False, + ), + ("context_servers", {"type": _LB, "max_requests_per_server": None}, True), + ("context_servers", {"type": _LB, "max_requests_per_server": 64}, False), + ("context_servers", {"type": _LB, "max_queue_wait_s": 30}, False), + ], +) +def test_pooled_router_keys_match_runtime( + schemas: dict[str, dict], section: str, router: dict, valid: bool +) -> None: + """The disagg schema accepts the pooled generation dispatch keys exactly when startup does.""" + from tensorrt_llm.llmapi.disagg_utils import extract_disagg_cfg + from tensorrt_llm.serve.router import create_router + + def start() -> None: + config = extract_disagg_cfg(**{section: {"router": copy.deepcopy(router)}}) + for router_config in (config.ctx_router_config, config.gen_router_config): + create_router(router_config, ["s"]) + + if valid: + start() + else: + with pytest.raises((ValueError, TypeError)): + start() + validator = Draft202012Validator(schemas[generator.DISAGG_SCHEMA]) + assert validator.is_valid({section: {"router": router}}) == valid + + def test_disagg_node_id_matches_runtime(schemas: dict[str, dict]) -> None: from tensorrt_llm.llmapi.disagg_utils import DISAGG_NODE_ID_BITS diff --git a/tests/unittest/scripts/test_perf_submit.py b/tests/unittest/scripts/test_perf_submit.py index 4b56aff18ba7..996c16203314 100644 --- a/tests/unittest/scripts/test_perf_submit.py +++ b/tests/unittest/scripts/test_perf_submit.py @@ -832,3 +832,28 @@ def test_local_submit_adds_eplb_shm_mount_to_launch_script( local_submit_module.main() content = launch.read_text() assert f'"--container-mounts=/a:/a,{REPO_ROOT}:{REPO_ROOT},tmpfs:/dev/shm:size=640G"' in content + + +@pytest.mark.cpu_only +@pytest.mark.parametrize( + ("ctx_transceiver", "expected"), + [ + ({"kv_transfer_timeout_ms": None}, {"kv_transfer_timeout_ms": None}), + ({}, None), + (None, None), + ], + ids=["null", "unset", "no_transceiver"], +) +def test_example_server_config_copies_a_null_ctx_kv_transfer_timeout( + example_submit_module: ModuleType, ctx_transceiver, expected +): + """An explicit null (no timeout) must reach the orchestrator, or it assumes the 60 s default.""" + allocations = { + "CTX": {0: {"nodes": {"n0": [0]}, "port": 8001}}, + "GEN": {0: {"nodes": {"n1": [0]}, "port": 8002}}, + } + config = example_submit_module.convert_allocations_to_server_config( + allocations, ctx_cache_transceiver_config=ctx_transceiver + ) + assert config["context_servers"].get("cache_transceiver_config") == expected + assert "cache_transceiver_config" not in config["generation_servers"] diff --git a/tests/unittest/tools/test_layer_wise_benchmarks_runner_args.py b/tests/unittest/tools/test_layer_wise_benchmarks_runner_args.py index cb1f91e620ee..da83a5481bfd 100644 --- a/tests/unittest/tools/test_layer_wise_benchmarks_runner_args.py +++ b/tests/unittest/tools/test_layer_wise_benchmarks_runner_args.py @@ -19,6 +19,7 @@ """ import pytest +import torch from tensorrt_llm.llmapi.llm_args import MoeLoadBalancerConfig, MoePerLayerDynamicLoadBalancerConfig from tensorrt_llm.mapping import Mapping @@ -114,3 +115,41 @@ def test_runner_rejects_load_balancers_a_layer_slice_cannot_run( ) def test_runner_accepts_load_balancers_a_layer_slice_can_run(load_balancer, use_cuda_graph): runner_module._check_load_balancer_support(load_balancer, use_cuda_graph) + + +def test_balanced_routing_routes_logits_routed_backends_on_the_host(): + """Balanced routing reaches the TRTLLM-Gen BF16 leaf, which routes inside its op from the logits. + + The leaf never calls routing_method.apply; while the balanced replacement is active it routes on the host, and + afterwards in the op again. + """ + from types import SimpleNamespace + + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.trtllm_bf16 import TrtllmTrtllmGenBf16Impl + from tensorrt_llm.tools.layer_wise_benchmarks.runner import BalanceMethod, Runner + + routing = SimpleNamespace( + apply=lambda logits, input_ids=None: (None, None), + apply_with_sort=lambda *args, **kwargs: None, + top_k=2, + ) + # A stand-in built without the leaf's __init__ (no weights): only the routing decision is exercised. + backend = TrtllmTrtllmGenBf16Impl.__new__(TrtllmTrtllmGenBf16Impl) + torch.nn.Module.__init__(backend) + moe = SimpleNamespace( + routing_method=routing, num_experts=8, forward_impl=lambda *a, **k: None, backend=backend + ) + runner = SimpleNamespace( + model_config=SimpleNamespace( + moe_backend="TRTLLM", + mapping=SimpleNamespace(enable_attention_dp=False, tp_rank=0, dp_size=1, moe_ep_size=1), + ), + layer_indices=[0], + model=SimpleNamespace( + model=SimpleNamespace(layers=[SimpleNamespace(mlp=SimpleNamespace(experts=moe))]) + ), + ) + assert backend._requires_separated_routing() is False + with Runner.replace_routing_method_ctx(runner, BalanceMethod.Balanced, 1.0): + assert backend._requires_separated_routing() is True + assert backend._requires_separated_routing() is False diff --git a/tests/unittest/utils/post_transform_qualification.py b/tests/unittest/utils/post_transform_qualification.py index 2b5dcbde7b7f..962ffe6a2f5d 100644 --- a/tests/unittest/utils/post_transform_qualification.py +++ b/tests/unittest/utils/post_transform_qualification.py @@ -51,6 +51,8 @@ class AllReduceStub(nn.Module): def __init__(self, *_args: object, **_kwargs: object) -> None: super().__init__() + # AllReduce's MNNVL backend, which an identity all-reduce never has. + self.mnnvl_allreduce = None def uses_nccl_symmetric_memory_window(self) -> bool: """Report that no NCCL symmetric memory window is in use.""" From f62b25688c8e3c19499cae3f661a018211eb71e1 Mon Sep 17 00:00:00 2001 From: Zhenhuan Chen Date: Sat, 14 Nov 2026 08:50:07 -0800 Subject: [PATCH 2/5] [None][fix] CI 70254: in-forward split warmup default and test stand-ins, router item ids, GDN alpha ulp bound Signed-off-by: Zhenhuan Chen --- .../_torch/pyexecutor/engine/runners/decoder/graphs.py | 4 +++- .../_torch/compilation/test_phase_selective_forward.py | 1 + tests/unittest/_torch/modules/mamba/test_gdn_prefill_conv.py | 5 +++-- .../_torch/pyexecutor/test_moe_comm_timeout_warmup.py | 3 +++ .../hw_agnostic/test_dspark_model_engine_runtime.py | 1 + tests/unittest/disaggregated/test_openai_disagg_service.py | 3 ++- 6 files changed, 13 insertions(+), 4 deletions(-) diff --git a/tensorrt_llm/_torch/pyexecutor/engine/runners/decoder/graphs.py b/tensorrt_llm/_torch/pyexecutor/engine/runners/decoder/graphs.py index a8fc417fee52..500eb0f1c633 100644 --- a/tensorrt_llm/_torch/pyexecutor/engine/runners/decoder/graphs.py +++ b/tensorrt_llm/_torch/pyexecutor/engine/runners/decoder/graphs.py @@ -189,6 +189,9 @@ class DecoderCudaGraphs: and ``_capture_additional_cuda_graphs``. """ + # Whether a warmup batch already ran an in-forward Mamba snapshot split (its Triton copy kernels compiled). + _inforward_split_warmed: bool = False + def __init__( self, *, @@ -231,7 +234,6 @@ def __init__( # Promoted context rows carry no per-sequence extra model inputs. self._context_promotion_supported = context_promotion_supported self._force_lora_graph_for_capture: bool | None = None - # Whether a warmup batch already ran an in-forward Mamba snapshot split (its Triton copy kernels compiled). self._inforward_split_warmed = False def forward_discarded_warmup( diff --git a/tests/unittest/_torch/compilation/test_phase_selective_forward.py b/tests/unittest/_torch/compilation/test_phase_selective_forward.py index 17f7c81fd6eb..7d3f9cd3b5c3 100644 --- a/tests/unittest/_torch/compilation/test_phase_selective_forward.py +++ b/tests/unittest/_torch/compilation/test_phase_selective_forward.py @@ -278,6 +278,7 @@ def forward(*args, **kwargs): ): monkeypatch.setattr(warmup, method, observe(method)) monkeypatch.setattr(graphs, "run_cuda_graph_warmup", observe("_run_cuda_graph_warmup")) + monkeypatch.setattr(graphs, "_warm_inforward_split", Mock()) monkeypatch.setattr(warmup_module, "warmup_sampling_module", Mock()) monkeypatch.setattr(warmup_module, "log_mem_snapshot", Mock()) monkeypatch.setattr(warmup_module.AutoTuner, "get", Mock()) diff --git a/tests/unittest/_torch/modules/mamba/test_gdn_prefill_conv.py b/tests/unittest/_torch/modules/mamba/test_gdn_prefill_conv.py index b8d403ae87e5..dfba8a27ebb8 100644 --- a/tests/unittest/_torch/modules/mamba/test_gdn_prefill_conv.py +++ b/tests/unittest/_torch/modules/mamba/test_gdn_prefill_conv.py @@ -177,8 +177,9 @@ def test_matches_stock_pipeline(num_k_heads, num_v_heads, lens, pad_seqs, extra_ # libdevice expf vs the stock kernel's tl.exp (ex2.approx of g * log2(e), whose error grows with |g|) on the gates -# of these inputs: at most 25 ulp measured on GB300, a relative difference below 3e-6. -_ALPHA_MAX_ULPS = 32 +# of these inputs: at most 25 ulp measured on GB300, 50 on B200 / B300 and 41 on H100 (CI 70254); 128 ulp is a +# relative difference below 1.6e-5. +_ALPHA_MAX_ULPS = 128 @pytest.mark.parametrize("lens,pad_seqs", [([700, 3, 0, 1, 1300], (2,)), ([1, 65], ())]) diff --git a/tests/unittest/_torch/pyexecutor/test_moe_comm_timeout_warmup.py b/tests/unittest/_torch/pyexecutor/test_moe_comm_timeout_warmup.py index 395c5dffc605..7794942e83fa 100644 --- a/tests/unittest/_torch/pyexecutor/test_moe_comm_timeout_warmup.py +++ b/tests/unittest/_torch/pyexecutor/test_moe_comm_timeout_warmup.py @@ -78,6 +78,9 @@ def __init__(self, guard: MoECommTimeoutGuard) -> None: def run_cuda_graph_warmup(self, resource_manager: object) -> None: self.passes.append((self.cuda_graph_runner.is_warmup_only, self._guard.in_warmup)) + def _warm_inforward_split(self, resource_manager: object) -> None: + pass + def test_warmup_scope_switches_the_timeouts_both_ways(guard: MoECommTimeoutGuard) -> None: proxy = _RecordingProxy() diff --git a/tests/unittest/_torch/speculative/hw_agnostic/test_dspark_model_engine_runtime.py b/tests/unittest/_torch/speculative/hw_agnostic/test_dspark_model_engine_runtime.py index 4450c805b208..946936b3d16d 100644 --- a/tests/unittest/_torch/speculative/hw_agnostic/test_dspark_model_engine_runtime.py +++ b/tests/unittest/_torch/speculative/hw_agnostic/test_dspark_model_engine_runtime.py @@ -538,6 +538,7 @@ def warmup(_resources): decoder = object.__new__(DecoderCudaGraphs) decoder.cuda_graph_runner = graph decoder.run_cuda_graph_warmup = warmup + decoder._warm_inforward_split = lambda resource_manager: None decoder.warmup_and_capture(object()) assert calls == [(True, False, True), (False, True, False)] diff --git a/tests/unittest/disaggregated/test_openai_disagg_service.py b/tests/unittest/disaggregated/test_openai_disagg_service.py index 4a7366c57996..a012a9bd3c94 100644 --- a/tests/unittest/disaggregated/test_openai_disagg_service.py +++ b/tests/unittest/disaggregated/test_openai_disagg_service.py @@ -557,10 +557,11 @@ def generate(**kwargs): conversation = kwargs["conversation_params"] scheduling = kwargs["scheduling_params"] item = SimpleNamespace( + id=len(observed[role]), request=SimpleNamespace( py_conversation_params=conversation, py_scheduling_params=scheduling, - ) + ), ) assignments, _ = router.route_requests(states, [item], max_num_active_requests=32) rank = next(rank for rank, items in assignments.items() if items) From d50e88da5ec8efba224054d830ff3da87acf7942 Mon Sep 17 00:00:00 2001 From: Zhenhuan Chen Date: Sat, 14 Nov 2026 10:33:24 -0800 Subject: [PATCH 3/5] [None][fix] main merge follow-ups: home-wait vs strict affinity rule in schemas and docs, steady-spec test stand-in Regenerate the serve schemas for the home-wait / strict-affinity exclusion (AttentionDpConfig) and note it in the field description and the routing guide. Main's OneModelSamplingParams cache reads py_spec_sampling_params from each request; the steady-spec RNG test's fake requests now carry it. Signed-off-by: Zhenhuan Chen --- docs/source/features/subagent-routing.md | 3 ++- tensorrt_llm/llmapi/llm_args.py | 3 ++- .../schemas/trtllm-serve-config.schema.json | 23 ++++++++++++++++++- .../trtllm-serve-disagg-config.schema.json | 23 ++++++++++++++++++- .../pyexecutor/test_steady_spec_prepare.py | 17 +++++++++++++- 5 files changed, 64 insertions(+), 5 deletions(-) diff --git a/docs/source/features/subagent-routing.md b/docs/source/features/subagent-routing.md index f5b944e4c66f..ca86ec7630dd 100644 --- a/docs/source/features/subagent-routing.md +++ b/docs/source/features/subagent-routing.md @@ -127,7 +127,8 @@ stays bound to the home rank. While it waits, later requests can be admitted ahead of it. With `scheduler_config.waiting_queue_policy: priority`, later requests of the same priority can take any rank, and lower-priority requests can take other ranks but not the held request's home rank, so each rank still -admits in priority order. +admits in priority order. It cannot be combined with +`kv_cache_routing_strict_conversation_affinity`. ## Gateway trust boundary diff --git a/tensorrt_llm/llmapi/llm_args.py b/tensorrt_llm/llmapi/llm_args.py index 05a6cfdf7069..8fff025b35a5 100644 --- a/tensorrt_llm/llmapi/llm_args.py +++ b/tensorrt_llm/llmapi/llm_args.py @@ -2557,7 +2557,8 @@ class AttentionDpConfig(StrictBaseModel): "requests of the same admission group (priority) may pass a waiting " "one on any rank; later groups may pass it on other ranks only, not " "into its home rank. None overflows at once. Requires " - "kv_cache_routing_conversation_affinity=True.", + "kv_cache_routing_conversation_affinity=True; not combinable with " + "kv_cache_routing_strict_conversation_affinity.", status="prototype") kv_cache_routing_strict_conversation_affinity: bool = Field( default=False, diff --git a/tensorrt_llm/schemas/trtllm-serve-config.schema.json b/tensorrt_llm/schemas/trtllm-serve-config.schema.json index 9c7e3283a274..0db998fea2b3 100644 --- a/tensorrt_llm/schemas/trtllm-serve-config.schema.json +++ b/tensorrt_llm/schemas/trtllm-serve-config.schema.json @@ -72,6 +72,27 @@ "kv_cache_routing_conversation_affinity" ] } + }, + { + "if": { + "properties": { + "kv_cache_routing_home_wait_rounds": { + "type": "integer" + } + }, + "required": [ + "kv_cache_routing_home_wait_rounds" + ] + }, + "then": { + "properties": { + "kv_cache_routing_strict_conversation_affinity": { + "not": { + "const": true + } + } + } + } } ], "description": "Configuration for attention DP.", @@ -142,7 +163,7 @@ } ], "default": null, - "description": "Conversation-affinity routing: a returning conversation whose home rank is full waits for a slot there for up to this many scheduling rounds in which another rank had room, then overflows by kv_cache_routing_new_conv_placement (keeping its home rank). Later requests of the same admission group (priority) may pass a waiting one on any rank; later groups may pass it on other ranks only, not into its home rank. None overflows at once. Requires kv_cache_routing_conversation_affinity=True.", + "description": "Conversation-affinity routing: a returning conversation whose home rank is full waits for a slot there for up to this many scheduling rounds in which another rank had room, then overflows by kv_cache_routing_new_conv_placement (keeping its home rank). Later requests of the same admission group (priority) may pass a waiting one on any rank; later groups may pass it on other ranks only, not into its home rank. None overflows at once. Requires kv_cache_routing_conversation_affinity=True; not combinable with kv_cache_routing_strict_conversation_affinity.", "status": "prototype", "title": "Kv Cache Routing Home Wait Rounds" }, diff --git a/tensorrt_llm/schemas/trtllm-serve-disagg-config.schema.json b/tensorrt_llm/schemas/trtllm-serve-disagg-config.schema.json index 497deabb9fb3..956fc2523045 100644 --- a/tensorrt_llm/schemas/trtllm-serve-disagg-config.schema.json +++ b/tensorrt_llm/schemas/trtllm-serve-disagg-config.schema.json @@ -72,6 +72,27 @@ "kv_cache_routing_conversation_affinity" ] } + }, + { + "if": { + "properties": { + "kv_cache_routing_home_wait_rounds": { + "type": "integer" + } + }, + "required": [ + "kv_cache_routing_home_wait_rounds" + ] + }, + "then": { + "properties": { + "kv_cache_routing_strict_conversation_affinity": { + "not": { + "const": true + } + } + } + } } ], "description": "Configuration for attention DP.", @@ -142,7 +163,7 @@ } ], "default": null, - "description": "Conversation-affinity routing: a returning conversation whose home rank is full waits for a slot there for up to this many scheduling rounds in which another rank had room, then overflows by kv_cache_routing_new_conv_placement (keeping its home rank). Later requests of the same admission group (priority) may pass a waiting one on any rank; later groups may pass it on other ranks only, not into its home rank. None overflows at once. Requires kv_cache_routing_conversation_affinity=True.", + "description": "Conversation-affinity routing: a returning conversation whose home rank is full waits for a slot there for up to this many scheduling rounds in which another rank had room, then overflows by kv_cache_routing_new_conv_placement (keeping its home rank). Later requests of the same admission group (priority) may pass a waiting one on any rank; later groups may pass it on other ranks only, not into its home rank. None overflows at once. Requires kv_cache_routing_conversation_affinity=True; not combinable with kv_cache_routing_strict_conversation_affinity.", "status": "prototype", "title": "Kv Cache Routing Home Wait Rounds" }, diff --git a/tests/unittest/_torch/pyexecutor/test_steady_spec_prepare.py b/tests/unittest/_torch/pyexecutor/test_steady_spec_prepare.py index d9cadf289b88..3e456ab498e2 100644 --- a/tests/unittest/_torch/pyexecutor/test_steady_spec_prepare.py +++ b/tests/unittest/_torch/pyexecutor/test_steady_spec_prepare.py @@ -204,7 +204,12 @@ def test_populate_before_stage_matches_the_upload(uniform): the staging kernel writes the Philox buffers from the deferred values: over consecutive steps of seeded and unseeded requests, the same buffers and window counters as the uploads of the full pass. A batch whose requests' rows differ is uploaded.""" - from tensorrt_llm._torch.speculative.interface import _RNG_SLOT_SPAN, SpecMetadata + from tensorrt_llm._torch.pyexecutor.sampler.sampler_common import request_random_seed + from tensorrt_llm._torch.speculative.interface import ( + _RNG_SLOT_SPAN, + OneModelSamplingParams, + SpecMetadata, + ) t = 4 seeds = [None, 123, None, (1 << 63) + 5] @@ -216,6 +221,16 @@ def test_populate_before_stage_matches_the_upload(uniform): ) for slot, seed in zip((5, 2, 7, 0), seeds) ] + for request in requests: + # The sampling parameters LlmRequest caches; only the seed is read here. + request.py_spec_sampling_params = OneModelSamplingParams( + temperature=1.0, + top_k=torch.iinfo(torch.int32).max, + top_p=1.0, + min_p=0.0, + is_greedy=False, + seed=request_random_seed(request), + ) b = len(requests) rows = [t] * b if uniform else [t, 1, t, t] normalized = [(1.0, 0, 1.0, 0.0, n) for n in rows] From 85cd43f870edda3694b36d2bb5e655f57860a2b2 Mon Sep 17 00:00:00 2001 From: Zhenhuan Chen Date: Sat, 14 Nov 2026 11:03:50 -0800 Subject: [PATCH 4/5] [None][fix] Deferred-close transcript test: main's idle start_deferred_gen_receives Main's overlap loop starts the deferred generation receives (wait_all=False) before the idle pass flushes the transfer responses; the deferred-close transcript expects it after the first idle flush. Signed-off-by: Zhenhuan Chen --- .../_torch/disaggregation/test_disagg_loop_transcript.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/unittest/_torch/disaggregation/test_disagg_loop_transcript.py b/tests/unittest/_torch/disaggregation/test_disagg_loop_transcript.py index 0b303513cd62..5ce4c7d9dde7 100644 --- a/tests/unittest/_torch/disaggregation/test_disagg_loop_transcript.py +++ b/tests/unittest/_torch/disaggregation/test_disagg_loop_transcript.py @@ -298,6 +298,7 @@ def test_executor_loop_overlap_flushes_deferred_closes(monkeypatch) -> None: idle_pass = _SCHEDULE_HEAD + [ ("flush_deferred_closes",), + ("start_deferred_gen_receives", "wait_all=False"), ("flush_pending_transfer_responses",), ("flush_deferred_closes",), ("handle_timeouts_synced",), From 84575b21dab736cbf231bf43b9a6e7797b69d5b0 Mon Sep 17 00:00:00 2001 From: Zhenhuan Chen Date: Sat, 14 Nov 2026 18:21:48 -0800 Subject: [PATCH 5/5] [None][test] Evict-first tuning test needs a GPU: AutoTuner.get() reads the device name Signed-off-by: Zhenhuan Chen --- .../_torch/moe/fused_moe/test_cutedsl_evict_first_tuning.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unittest/_torch/moe/fused_moe/test_cutedsl_evict_first_tuning.py b/tests/unittest/_torch/moe/fused_moe/test_cutedsl_evict_first_tuning.py index 5fddb7951cd9..f8d1baef4ef6 100644 --- a/tests/unittest/_torch/moe/fused_moe/test_cutedsl_evict_first_tuning.py +++ b/tests/unittest/_torch/moe/fused_moe/test_cutedsl_evict_first_tuning.py @@ -11,8 +11,8 @@ from tensorrt_llm._torch.autotuner import AutoTuner from tensorrt_llm._torch.cute_dsl_utils import IS_CUTLASS_DSL_AVAILABLE +# Not cpu_only: AutoTuner.get() reads the CUDA device name. pytestmark = [ - pytest.mark.cpu_only, pytest.mark.skipif(not IS_CUTLASS_DSL_AVAILABLE, reason="Requires CUTLASS DSL"), ]