From 2214244378bb5babdce7022475aaef9c57d7ab17 Mon Sep 17 00:00:00 2001 From: PixelFlat <329975279+PixelFlat@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:44:15 +0800 Subject: [PATCH 1/6] feat: package the V4.1 sparse attention kernels for Ascend. --- xllm-kernel/csrc/ascendc/CMakeLists.txt | 46 + xllm-kernel/csrc/ascendc/aicpu.cmake | 9 +- .../op_kernel/dequant_swiglu_quant.h | 21 +- .../hc_pre_va/op_host/hc_pre_va_tiling.cpp | 594 ++- .../hc_pre_va/op_host/hc_pre_va_tiling.h | 63 +- .../hc_pre_va/op_kernel/hc_pre_va_base.h | 561 ++- .../op_kernel/hc_pre_va_cube_compute.h | 225 +- .../op_kernel/hc_pre_va_m_k_split_core.h | 1626 ++++++-- .../op_kernel/xllm_kernel_hc_pre_va.cpp | 28 +- ...uant_lightning_indexer_metadata_aicpu.json | 2 +- ...lightning_indexer_v2_metadata_va_proto.cpp | 32 + ...quant_lightning_indexer_v2_metadata_va.cpp | 207 ++ ...n_quant_lightning_indexer_v2_metadata_va.h | 57 + ...quant_lightning_indexer_v2_metadata_va.cpp | 127 + .../quant_lightning_indexer_v2_metadata_va.h | 44 + ...t_lightning_indexer_v2_metadata_va_check.h | 704 ++++ ...ning_indexer_v2_metadata_va_infershape.cpp | 40 + ...lightning_indexer_v2_metadata_va_aicpu.cpp | 1108 ++++++ ...t_lightning_indexer_v2_metadata_va_aicpu.h | 341 ++ ...ightning_indexer_v2_metadata_va_aicpu.json | 15 + .../quant_lightning_indexer_v2_va/SOURCE.txt | 9 + .../quant_lightning_indexer_v2_va_def.cpp | 147 + .../quant_lightning_indexer_v2_va_error_log.h | 167 + ...ant_lightning_indexer_v2_va_infershape.cpp | 177 + .../quant_lightning_indexer_v2_va_tiling.cpp | 1938 ++++++++++ .../quant_lightning_indexer_v2_va_tiling.h | 312 ++ ...nt_lightning_indexer_v2_va_common_arch22.h | 180 + ...nt_lightning_indexer_v2_va_kernel_arch22.h | 1008 +++++ ...htning_indexer_v2_va_service_cube_arch22.h | 753 ++++ ...ning_indexer_v2_va_service_vector_arch22.h | 1370 +++++++ .../quant_lightning_indexer_v2_va_vector.h | 278 ++ .../quant_lightning_indexer_v2_metadata_va.h | 84 + ...htning_indexer_v2_va_template_tiling_key.h | 241 ++ ...m_kernel_quant_lightning_indexer_v2_va.cpp | 92 + .../op_host/rms_norm_cast_va_def.cpp | 39 + .../op_host/rms_norm_cast_va_infershape.cpp | 32 + .../op_host/rms_norm_cast_va_tiling.cpp | 86 + .../op_host/rms_norm_cast_va_tiling.h | 31 + .../op_kernel/rms_norm_cast_va.h | 153 + .../op_kernel/rms_norm_cast_va_base.h | 113 + .../xllm_kernel_rms_norm_cast_va.cpp | 32 + .../sparse_attn_sharedkv_metadata_aicpu.json | 2 +- .../csrc/ascendc/sparse_flash_mla/SOURCE.txt | 7 + .../op_host/checkers/base_checker.cpp | 240 ++ .../checkers/base_checker_sparse_flash_mla.h | 64 + .../op_host/checkers/checker_adapter.h | 103 + .../op_host/checkers/checker_context.h | 108 + .../op_host/checkers/checker_runner.cpp | 63 + .../op_host/checkers/checker_runner.h | 44 + .../op_host/checkers/common_checker.cpp | 366 ++ .../common_checker_sparse_flash_mla.h | 44 + .../op_host/checkers/mask_checker.cpp | 81 + .../checkers/mask_checker_sparse_flash_mla.h | 30 + .../op_host/checkers/metadata_checker.cpp | 53 + .../metadata_checker_sparse_flash_mla.h | 31 + .../checkers/paged_attention_checker.cpp | 138 + ...paged_attention_checker_sparse_flash_mla.h | 37 + .../op_host/checkers/seq_len_checker.cpp | 192 + .../seq_len_checker_sparse_flash_mla.h | 41 + .../op_host/checkers/sinks_checker.cpp | 63 + .../checkers/sinks_checker_sparse_flash_mla.h | 32 + .../op_host/checkers/softmax_lse_checker.cpp | 63 + .../softmax_lse_checker_sparse_flash_mla.h | 30 + .../checkers/sparse_compression_checker.cpp | 323 ++ .../checkers/sparse_compression_checker.h | 47 + .../checkers/sparse_flash_mla_checker.cpp | 38 + .../checkers/sparse_flash_mla_checker.h | 32 + .../sparse_flash_mla/op_host/common/log.h | 776 ++++ .../sparse_flash_mla/op_host/common/ops_err.h | 37 + .../op_host/common/smla_host_common_defs.h | 83 + .../op_host/common/smla_infershape_common.h | 228 ++ .../op_host/sparse_flash_mla_def.cpp | 152 + .../op_host/sparse_flash_mla_infershape.cpp | 56 + .../op_host/sparse_flash_mla_tiling.cpp | 3255 +++++++++++++++++ .../op_host/sparse_flash_mla_tiling.h | 567 +++ .../arch22/sparse_flash_mla_arch22_metadata.h | 85 + .../arch22/sparse_flash_mla_common_arch22.h | 408 +++ .../arch22/sparse_flash_mla_csa_block_cube.h | 1013 +++++ .../sparse_flash_mla_csa_block_vector.h | 1517 ++++++++ .../arch22/sparse_flash_mla_csa_kernel.h | 1123 ++++++ .../arch22/sparse_flash_mla_swa_block_cube.h | 1539 ++++++++ .../sparse_flash_mla_swa_block_vector.h | 1688 +++++++++ .../arch22/sparse_flash_mla_swa_kernel.h | 1238 +++++++ .../arch35/common/smla_metadata_common.h | 75 + .../sparse_flash_mla_kernel_metadata.h | 42 + .../sparse_flash_mla_template_tiling_key.h | 140 + .../xllm_kernel_sparse_flash_mla.cpp | 155 + .../sparse_flash_mla_metadata/SOURCE.txt | 5 + .../sparse_flash_mla_metadata_proto.cpp | 57 + .../aclnn_sparse_flash_mla_metadata.cpp | 319 ++ .../op_api/aclnn_sparse_flash_mla_metadata.h | 65 + .../op_api/sparse_flash_mla_metadata.cpp | 156 + .../op_api/sparse_flash_mla_metadata.h | 55 + .../op_host/sparse_flash_mla_metadata_check.h | 1464 ++++++++ .../sparse_flash_mla_metadata_infershape.cpp | 41 + .../sparse_flash_mla_metadata_aicpu.cpp | 1954 ++++++++++ .../sparse_flash_mla_metadata_aicpu.h | 430 +++ .../sparse_flash_mla_metadata_aicpu.json | 15 + xllm-kernel/csrc/ascendc/v41_sparse_mla.cmake | 48 + 99 files changed, 33560 insertions(+), 590 deletions(-) create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_graph/quant_lightning_indexer_v2_metadata_va_proto.cpp create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.cpp create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.h create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/quant_lightning_indexer_v2_metadata_va.cpp create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/quant_lightning_indexer_v2_metadata_va.h create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/quant_lightning_indexer_v2_metadata_va_check.h create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/quant_lightning_indexer_v2_metadata_va_infershape.cpp create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.cpp create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.h create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.json create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/SOURCE.txt create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_def.cpp create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_error_log.h create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_infershape.cpp create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.cpp create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.h create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_common_arch22.h create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_kernel_arch22.h create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_cube_arch22.h create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_vector_arch22.h create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_vector.h create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_va_template_tiling_key.h create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/xllm_kernel_quant_lightning_indexer_v2_va.cpp create mode 100644 xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_def.cpp create mode 100644 xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_infershape.cpp create mode 100644 xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_tiling.cpp create mode 100644 xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_tiling.h create mode 100644 xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/rms_norm_cast_va.h create mode 100644 xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/rms_norm_cast_va_base.h create mode 100644 xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/xllm_kernel_rms_norm_cast_va.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/SOURCE.txt create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/base_checker.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/base_checker_sparse_flash_mla.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_adapter.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_context.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_runner.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_runner.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/common_checker.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/common_checker_sparse_flash_mla.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/mask_checker.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/mask_checker_sparse_flash_mla.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/metadata_checker.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/metadata_checker_sparse_flash_mla.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/paged_attention_checker.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/paged_attention_checker_sparse_flash_mla.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/seq_len_checker.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/seq_len_checker_sparse_flash_mla.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sinks_checker.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sinks_checker_sparse_flash_mla.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/softmax_lse_checker.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/softmax_lse_checker_sparse_flash_mla.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_compression_checker.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_compression_checker.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_flash_mla_checker.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_flash_mla_checker.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/log.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/ops_err.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/smla_host_common_defs.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/smla_infershape_common.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_def.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_infershape.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_tiling.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_tiling.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_arch22_metadata.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_common_arch22.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_block_cube.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_block_vector.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_kernel.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_block_cube.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_block_vector.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_kernel.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch35/common/smla_metadata_common.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/sparse_flash_mla_kernel_metadata.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/sparse_flash_mla_template_tiling_key.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/xllm_kernel_sparse_flash_mla.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/SOURCE.txt create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_graph/sparse_flash_mla_metadata_proto.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/aclnn_sparse_flash_mla_metadata.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/aclnn_sparse_flash_mla_metadata.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/sparse_flash_mla_metadata.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/sparse_flash_mla_metadata.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/sparse_flash_mla_metadata_check.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/sparse_flash_mla_metadata_infershape.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.json create mode 100644 xllm-kernel/csrc/ascendc/v41_sparse_mla.cmake diff --git a/xllm-kernel/csrc/ascendc/CMakeLists.txt b/xllm-kernel/csrc/ascendc/CMakeLists.txt index eac16ae73d..8635f61dc7 100644 --- a/xllm-kernel/csrc/ascendc/CMakeLists.txt +++ b/xllm-kernel/csrc/ascendc/CMakeLists.txt @@ -52,6 +52,32 @@ set(mega_mtp_host "${CMAKE_CURRENT_SOURCE_DIR}/mega_gdn_mtp_decode/op_host") set(mega_varlen_host "${CMAKE_CURRENT_SOURCE_DIR}/mega_gdn_mtp_decode_varlen/op_host") set(qli "${CMAKE_CURRENT_SOURCE_DIR}/quant_lightning_indexer") set(qli_metadata "${CMAKE_CURRENT_SOURCE_DIR}/quant_lightning_indexer_metadata") +if("ascend910_93" IN_LIST ASCEND_COMPUTE_UNIT) + set(qli_v2 "${CMAKE_CURRENT_SOURCE_DIR}/quant_lightning_indexer_v2_va") + set(qli_v2_metadata "${CMAKE_CURRENT_SOURCE_DIR}/quant_lightning_indexer_v2_metadata_va") + list(APPEND op_definitions "${qli_v2}/op_host/quant_lightning_indexer_v2_va_def.cpp") + set(qli_v2_api + "${ASCEND_AUTOGEN_PATH}/aclnn_xllm_kernel_quant_lightning_indexer_v2_va.cpp" + "${qli_v2_metadata}/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.cpp" + "${qli_v2_metadata}/op_host/op_api/quant_lightning_indexer_v2_metadata_va.cpp" + ) + set_property(SOURCE "${qli_v2_metadata}/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.cpp" + APPEND PROPERTY INCLUDE_DIRECTORIES "${ASCEND_CANN_PACKAGE_PATH}/pkg_inc/op_common") + set_property(SOURCE "${qli_v2_metadata}/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.cpp" + APPEND PROPERTY COMPILE_DEFINITIONS OP_LOG_LIBOPAPI_ONLY) + set(qli_v2_tiling + "${qli_v2}/op_host/quant_lightning_indexer_v2_va_infershape.cpp" + "${qli_v2}/op_host/quant_lightning_indexer_v2_va_tiling.cpp" + "${qli_v2_metadata}/op_host/quant_lightning_indexer_v2_metadata_va_infershape.cpp" + ) + list(APPEND v41_metadata_graph_sources + "${qli_v2_metadata}/op_graph/quant_lightning_indexer_v2_metadata_va_proto.cpp") + list(APPEND v41_aicpu_components quant_lightning_indexer_v2_metadata_va) + list(APPEND v41_aicpu_headers "${qli_v2}/op_kernel/quant_lightning_indexer_v2_metadata_va.h") + install(FILES "${qli_v2_metadata}/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.h" + DESTINATION "packages/vendors/${vendor}/op_api/include" + RENAME aclnn_xllm_kernel_quant_lightning_indexer_v2_metadata_va.h) +endif() set(scatter "${CMAKE_CURRENT_SOURCE_DIR}/scatter_nd_update_v2") set(sas_metadata "${CMAKE_CURRENT_SOURCE_DIR}/sparse_attn_sharedkv_metadata") set(sparse_attention_components compressor sparse_attn_sharedkv sparse_flash_attention_lse) @@ -111,6 +137,7 @@ if("ascend910b" IN_LIST ASCEND_COMPUTE_UNIT OR "ascend910_93" IN_LIST ASCEND_COM endif() # The two quantized projections have device implementations on the A2/A3 targets. if("ascend910b" IN_LIST ASCEND_COMPUTE_UNIT OR "ascend910_93" IN_LIST ASCEND_COMPUTE_UNIT) + set(router_norm_host "${CMAKE_CURRENT_SOURCE_DIR}/rms_norm_cast_va/op_host") set(quant_gemm_host "${CMAKE_CURRENT_SOURCE_DIR}/quant_matmul_nz_decode/op_host") set(mla_host "${CMAKE_CURRENT_SOURCE_DIR}/mla_preprocess_v2/op_host") set(catlass_include "${xllm_kernel_root}/third_party/catlass/include") @@ -119,14 +146,18 @@ if("ascend910b" IN_LIST ASCEND_COMPUTE_UNIT OR "ascend910_93" IN_LIST ASCEND_COM "In a Git checkout run git submodule update --init xllm-kernel/third_party/catlass.") endif() list(APPEND op_definitions + "${router_norm_host}/rms_norm_cast_va_def.cpp" "${quant_gemm_host}/quant_matmul_nz_decode_def.cpp" "${mla_host}/mla_preprocess_v2_def.cpp" ) set(a2_aclnn_sources + "${ASCEND_AUTOGEN_PATH}/aclnn_xllm_kernel_rms_norm_cast_va.cpp" "${ASCEND_AUTOGEN_PATH}/aclnn_xllm_kernel_quant_matmul_nz_decode.cpp" "${ASCEND_AUTOGEN_PATH}/aclnn_xllm_kernel_mla_preprocess_v2.cpp" ) set(a2_tiling_sources + "${router_norm_host}/rms_norm_cast_va_infershape.cpp" + "${router_norm_host}/rms_norm_cast_va_tiling.cpp" "${quant_gemm_host}/quant_matmul_nz_decode_proto.cpp" "${quant_gemm_host}/quant_matmul_nz_decode_tiling.cpp" "${mla_host}/mla_preprocess_tiling.cpp" @@ -163,6 +194,7 @@ foreach(component IN LISTS native_components) list(APPEND native_api "${ASCEND_AUTOGEN_PATH}/aclnn_xllm_kernel_${component}.cpp") endif() endforeach() +include("${CMAKE_CURRENT_SOURCE_DIR}/v41_sparse_mla.cmake") npu_op_code_gen( SRC ${op_definitions} PACKAGE ${vendor} @@ -197,6 +229,7 @@ npu_op_library(cust_opapi ACLNN "${ASCEND_AUTOGEN_PATH}/aclnn_xllm_kernel_quant_lightning_indexer.cpp" "${qli_metadata}/op_api/aclnn_quant_lightning_indexer_metadata.cpp" "${qli_metadata}/op_api/l0_quant_lightning_indexer_metadata.cpp" + ${qli_v2_api} "${scatter}/op_host/op_api/aclnn_scatter_nd_update_v2.cpp" "${scatter}/op_host/op_api/scatter_nd_update_v2.cpp" ${sparse_attention_api} @@ -222,6 +255,7 @@ file(GLOB generated_fallback CONFIGURE_DEPENDS "${ASCEND_AUTOGEN_PATH}/fallback_ npu_op_library(cust_op_proto GRAPH ${generated_proto} "${qli_metadata}/op_graph/quant_lightning_indexer_metadata_proto.cpp" + ${v41_metadata_graph_sources} "${sas_metadata}/op_graph/sparse_attn_sharedkv_metadata_proto.cpp" ) npu_op_library(cust_optiling TILING @@ -266,6 +300,7 @@ npu_op_library(cust_optiling TILING "${qli}/op_host/quant_lightning_indexer_infershape.cpp" "${qli}/op_host/quant_lightning_indexer_tiling.cpp" "${qli_metadata}/op_host/quant_lightning_indexer_metadata_infershape.cpp" + ${qli_v2_tiling} "${scatter}/op_host/scatter_nd_update_infershape.cpp" "${scatter}/op_host/scatter_nd_update_v2_tiling.cpp" ${sparse_attention_tiling} @@ -405,6 +440,8 @@ if("ascend950" IN_LIST ASCEND_COMPUTE_UNIT) endif() if(a2_aclnn_sources) + npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelRmsNormCastVa + KERNEL_DIR rms_norm_cast_va/op_kernel KERNEL_FILE xllm_kernel_rms_norm_cast_va.cpp) npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelQuantMatmulNzDecode KERNEL_DIR quant_matmul_nz_decode/op_kernel KERNEL_FILE xllm_kernel_quant_matmul_nz_decode.cpp) npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelMlaPreprocessV2 @@ -421,6 +458,15 @@ npu_op_kernel_options(ascendc_kernels XllmKernelQuantLightningIndexer OPTIONS --cce-auto-sync=off -Wno-deprecated-declarations -Wno-error -mllvm -cce-vf-remove-membar=false -mllvm -cce-aicore-hoist-movemask=false "-I${CMAKE_CURRENT_SOURCE_DIR}" "-I${qli}/op_kernel") +if("ascend910_93" IN_LIST ASCEND_COMPUTE_UNIT) + v41_sparse_mla_kernel() + npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelQuantLightningIndexerV2Va + KERNEL_DIR quant_lightning_indexer_v2_va/op_kernel KERNEL_FILE xllm_kernel_quant_lightning_indexer_v2_va.cpp) + npu_op_kernel_options(ascendc_kernels XllmKernelQuantLightningIndexerV2Va + OPTIONS --cce-auto-sync=off -Wno-deprecated-declarations -Werror + -mllvm -cce-vf-remove-membar=false -mllvm -cce-aicore-hoist-movemask=false + "-I${qli_v2}/op_kernel") +endif() npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelScatterNdUpdateV2 KERNEL_DIR scatter_nd_update_v2/op_kernel KERNEL_FILE xllm_kernel_scatter_nd_update_v2.cpp) npu_op_kernel_options(ascendc_kernels XllmKernelScatterNdUpdateV2 diff --git a/xllm-kernel/csrc/ascendc/aicpu.cmake b/xllm-kernel/csrc/ascendc/aicpu.cmake index fb29f22fdd..ca07229d58 100644 --- a/xllm-kernel/csrc/ascendc/aicpu.cmake +++ b/xllm-kernel/csrc/ascendc/aicpu.cmake @@ -8,10 +8,12 @@ find_library(aicpu_context NAMES libaicpu_context.a HINTS "${cann}/lib64" "${cann}/ops_base/lib64" NO_DEFAULT_PATH REQUIRED) find_library(aicpu_protobuf NAMES libbase_ascend_protobuf.a HINTS "${cann}/lib64" "${cann}/ops_base/lib64" NO_DEFAULT_PATH REQUIRED) -set(aicpu_library "${CMAKE_CURRENT_BINARY_DIR}/libxllm_kernel_aicpu.so") +# CANN 9 selects the custom AICPU library from the vendor suffix. +set(aicpu_library "${CMAKE_CURRENT_BINARY_DIR}/libmath_aicpu_kernels.so") set(aicpu_config "${CMAKE_CURRENT_BINARY_DIR}/cust_aicpu_kernel.json") set(aicpu_json "{}") -foreach(component quant_lightning_indexer_metadata sparse_attn_sharedkv_metadata) +set(aicpu_components quant_lightning_indexer_metadata sparse_attn_sharedkv_metadata ${v41_aicpu_components}) +foreach(component IN LISTS aicpu_components) set(directory "${CMAKE_CURRENT_LIST_DIR}/${component}/op_kernel_aicpu") list(APPEND aicpu_sources "${directory}/${component}_aicpu.cpp") list(APPEND aicpu_headers "${directory}/${component}_aicpu.h") @@ -40,6 +42,7 @@ add_custom_command( DEPENDS ${aicpu_sources} ${aicpu_headers} + ${v41_aicpu_headers} "${qli_metadata}/op_kernel_aicpu/cpu_context_util.h" "${CMAKE_CURRENT_LIST_DIR}/sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_metadata.h" "${qli}/op_kernel/quant_lightning_indexer_metadata.h" @@ -47,6 +50,6 @@ add_custom_command( VERBATIM ) add_custom_target(xllm_kernel_aicpu ALL DEPENDS "${aicpu_library}") -set(cpu_destination "packages/vendors/${vendor}/op_impl/cpu") +set(cpu_destination "packages/vendors/${vendor}_math/op_impl/cpu") install(FILES "${aicpu_library}" DESTINATION "${cpu_destination}/aicpu_kernel/impl") install(FILES "${aicpu_config}" DESTINATION "${cpu_destination}/config") diff --git a/xllm-kernel/csrc/ascendc/dequant_swiglu_quant/op_kernel/dequant_swiglu_quant.h b/xllm-kernel/csrc/ascendc/dequant_swiglu_quant/op_kernel/dequant_swiglu_quant.h index 8b250f60fb..34940febaf 100644 --- a/xllm-kernel/csrc/ascendc/dequant_swiglu_quant/op_kernel/dequant_swiglu_quant.h +++ b/xllm-kernel/csrc/ascendc/dequant_swiglu_quant/op_kernel/dequant_swiglu_quant.h @@ -871,17 +871,16 @@ __aicore__ inline void DequantSwigluQuantBase::DynamicQuant( for (uint32_t i = 0; i < proDimsx; ++i) { ComputeReduceMax(tmpUbF32Gate[i * tl_->UbFactorDimy], tl_->UbFactorDimy); } - // Calc quant: proDimsx * 64 -> proDimsx - // repeatTimes:proDimsx, dstRepStride:1(dtype), srcBlkStride:1, - // srcRepStride:tl_->UbFactorDimy / 64 * 8 - WholeReduceMax(tmpUbF32Gate, - tmpUbF32Gate, - MASK_NUM_T32, - proDimsx, - 1, - 1, - tl_->UbFactorDimy / MASK_NUM_T32 * MASK_BLK_STRIDE, - ReduceOrder::ORDER_ONLY_VALUE); + // Use the actual row stride and keep the reduction within narrow rows. + WholeReduceMax( + tmpUbF32Gate, + tmpUbF32Gate, + tl_->UbFactorDimy < MASK_NUM_T32 ? tl_->UbFactorDimy : MASK_NUM_T32, + proDimsx, + 1, + 1, + tl_->UbFactorDimy / BLOCK_ELEM, + ReduceOrder::ORDER_ONLY_VALUE); PipeBarrier(); // Calc quant: scaleOut / 127.0 Muls(scaleOut, tmpUbF32Gate, DYNAMIC_QUANT_FACTOR, proDimsx); diff --git a/xllm-kernel/csrc/ascendc/hc_pre_va/op_host/hc_pre_va_tiling.cpp b/xllm-kernel/csrc/ascendc/hc_pre_va/op_host/hc_pre_va_tiling.cpp index f4a6bb5faa..38ef4a6a1b 100644 --- a/xllm-kernel/csrc/ascendc/hc_pre_va/op_host/hc_pre_va_tiling.cpp +++ b/xllm-kernel/csrc/ascendc/hc_pre_va/op_host/hc_pre_va_tiling.cpp @@ -42,8 +42,8 @@ constexpr int64_t BLOCK_SIZE = 32; constexpr int64_t REPEAT_SIZE = 256; constexpr int64_t UB_RESEVED_SIZE = 8192; constexpr int64_t DOUBLE_BUFFER = 2; -constexpr int64_t MAX_VECTOR_REPEAT = 255; constexpr uint64_t M_L1_MAX_SIZE = 256; +constexpr uint64_t CV_LOOP_K_SIZE = 1024; constexpr uint64_t K_MULIT_CORE_SPLIT_BASE_SIZE = 256; constexpr uint64_t A_L1_SIZE = 128 * 256; constexpr uint64_t K_L1_MAX_SIZE = 1024; @@ -53,6 +53,16 @@ constexpr int64_t ITER_TIMES_ATTR_IDX = 1; constexpr int64_t HC_EPS_ATTR_IDX = 2; constexpr int64_t NORM_EPS_ATTR_IDX = 3; constexpr int64_t DEFAULT_ITER_TIMES = 20; +constexpr int64_t SUPPORTED_HC_MULT = 4; +constexpr int64_t SQUARE_SUM_SIZE = 16; +constexpr int64_t MASK_PATTERN_DIM_SIZE = 16; +constexpr int64_t PRE_POST_ROW_WORK_SCALE = 3; +constexpr int64_t SINKHORN_ROW_WORK_SCALE = 64; +constexpr int64_t SINKHORN_SETUP_ITER_EQUIVALENT = 4; +constexpr int64_t SMALL_BS_THRESHOLD = 32; +constexpr uint64_t MPMD_TILING_KEY = 0; +constexpr uint64_t ORIGINAL_TILING_KEY = 1; +constexpr uint64_t PREMIX_TILING_KEY = 2; } // namespace ge::graphStatus HcPreVaTiling::GetPlatformInfo() { @@ -63,7 +73,6 @@ ge::graphStatus HcPreVaTiling::GetPlatformInfo() { OPS_LOG_E(context_, "compile info is null"), return ge::GRAPH_FAILED); aivCoreNum_ = compileInfoPtr->coreNum; - aicCoreNum_ = compileInfoPtr->aicCoreNum; ubSize_ = compileInfoPtr->ubSize; } else { auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo); @@ -73,12 +82,8 @@ ge::graphStatus HcPreVaTiling::GetPlatformInfo() { ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSizePlatForm); ubSize_ = ubSizePlatForm; + socVersion_ = ascendcPlatform.GetSocVersion(); } - OPS_ERR_IF( - aivCoreNum_ == 0 || aicCoreNum_ == 0 || ubSize_ == 0, - OPS_LOG_E(context_->GetNodeName(), - "AIV core count, AIC core count and UB size must be positive"), - return ge::GRAPH_FAILED); return ge::GRAPH_SUCCESS; } @@ -87,67 +92,56 @@ ge::graphStatus HcPreVaTiling::GetAttr() { OPS_LOG_E_IF_NULL(context_, attrs, return ge::GRAPH_FAILED); auto hcMultAttr = attrs->GetAttrPointer(HC_MULT_ATTR_IDX); - const int64_t hc_mult_attribute = hcMultAttr == nullptr ? 4 : *hcMultAttr; - OPS_ERR_IF(hcMult_ != 4 || hc_mult_attribute != hcMult_, - OPS_LOG_E(context_->GetNodeName(), - "x streams and hc_mult must both equal 4"), - return ge::GRAPH_FAILED); + hcMult_ = hcMultAttr == nullptr ? 4 : *hcMultAttr; auto iterTimesAttr = attrs->GetAttrPointer(ITER_TIMES_ATTR_IDX); iterTimes_ = iterTimesAttr == nullptr ? DEFAULT_ITER_TIMES : *iterTimesAttr; - OPS_ERR_IF( - iterTimes_ <= 0, - OPS_LOG_E(context_->GetNodeName(), "hc_sinkhorn_iters must be positive"), - return ge::GRAPH_FAILED); auto hcEpsAttr = attrs->GetAttrPointer(HC_EPS_ATTR_IDX); hcEps_ = hcEpsAttr == nullptr ? 1e-6 : *hcEpsAttr; auto normEpsAttr = attrs->GetAttrPointer(NORM_EPS_ATTR_IDX); normEps_ = normEpsAttr == nullptr ? 1e-6 : *normEpsAttr; - OPS_ERR_IF(!std::isfinite(hcEps_) || hcEps_ <= 0 || - !std::isfinite(normEps_) || normEps_ <= 0, - OPS_LOG_E(context_->GetNodeName(), - "hc_eps and norm_eps must be finite and positive"), - return ge::GRAPH_FAILED); return ge::GRAPH_SUCCESS; } ge::graphStatus HcPreVaTiling::GetShapeAttrsInfoInner() { + OPS_ERR_IF(GetAttr() != ge::GRAPH_SUCCESS, + OPS_LOG_E(context_->GetNodeName(), "get attr failed."), + return ge::GRAPH_FAILED); + // (b, s, hc_mult, d) or (bs, hc_mult, d) auto xShape = context_->GetInputShape(0); OPS_LOG_E_IF_NULL(context_, xShape, return ge::GRAPH_FAILED); size_t xDimNum = xShape->GetStorageShape().GetDimNum(); - OPS_ERR_IF(xDimNum != 3 && xDimNum != 4, - OPS_LOG_E(context_->GetNodeName(), "x rank must be 3 or 4"), - return ge::GRAPH_FAILED); - for (size_t dimension = 0; dimension < xDimNum; ++dimension) { - OPS_ERR_IF( - xShape->GetStorageShape().GetDim(dimension) <= 0, - OPS_LOG_E(context_->GetNodeName(), "x dimensions must be positive"), - return ge::GRAPH_FAILED); - } + int64_t shapeHcMult = 0; if (xDimNum == 3) { bs_ = xShape->GetStorageShape().GetDim(0); - hcMult_ = xShape->GetStorageShape().GetDim(1); + shapeHcMult = xShape->GetStorageShape().GetDim(1); d_ = xShape->GetStorageShape().GetDim(2); } else if (xDimNum == 4) { int64_t b = xShape->GetStorageShape().GetDim(0); int64_t s = xShape->GetStorageShape().GetDim(1); bs_ = b * s; - hcMult_ = xShape->GetStorageShape().GetDim(2); + shapeHcMult = xShape->GetStorageShape().GetDim(2); d_ = xShape->GetStorageShape().GetDim(3); } + OPS_ERR_IF(shapeHcMult != hcMult_, + OPS_LOG_E(context_->GetNodeName(), + "hc_mult attr %ld should match x hc_mult dimension %ld", + hcMult_, + shapeHcMult), + return ge::GRAPH_FAILED); + OPS_ERR_IF( + hcMult_ != SUPPORTED_HC_MULT, + OPS_LOG_E(context_->GetNodeName(), + "XllmKernelHcPreVa only supports hc_mult=%ld, but got %ld", + SUPPORTED_HC_MULT, + hcMult_), + return ge::GRAPH_FAILED); auto shapeHcFn = context_->GetInputShape(1); - OPS_LOG_E_IF_NULL(context_, shapeHcFn, return ge::GRAPH_FAILED); - OPS_ERR_IF(shapeHcFn->GetStorageShape().GetDimNum() != 2, - OPS_LOG_E(context_->GetNodeName(), "hc_fn must have rank 2"), - return ge::GRAPH_FAILED); hcMix_ = shapeHcFn->GetStorageShape().GetDim(0); - OPS_ERR_IF(hcMix_ != 24, - OPS_LOG_E(context_->GetNodeName(), "hc_fn must have 24 rows"), - return ge::GRAPH_FAILED); OPS_ERR_IF( shapeHcFn->GetStorageShape().GetDim(1) != d_ * hcMult_, OPS_LOG_E(context_->GetNodeName(), @@ -157,10 +151,6 @@ ge::graphStatus HcPreVaTiling::GetShapeAttrsInfoInner() { return ge::GRAPH_FAILED); auto shapeHcScale = context_->GetInputShape(2); - OPS_LOG_E_IF_NULL(context_, shapeHcScale, return ge::GRAPH_FAILED); - OPS_ERR_IF(shapeHcScale->GetStorageShape().GetDimNum() != 1, - OPS_LOG_E(context_->GetNodeName(), "hc_scale must have rank 1"), - return ge::GRAPH_FAILED); int64_t scaleFirstDim = shapeHcScale->GetStorageShape().GetDim(0); OPS_ERR_IF(scaleFirstDim != 3, OPS_LOG_E(context_->GetNodeName(), @@ -169,10 +159,6 @@ ge::graphStatus HcPreVaTiling::GetShapeAttrsInfoInner() { return ge::GRAPH_FAILED); auto shapeHcBase = context_->GetInputShape(3); - OPS_LOG_E_IF_NULL(context_, shapeHcBase, return ge::GRAPH_FAILED); - OPS_ERR_IF(shapeHcBase->GetStorageShape().GetDimNum() != 1, - OPS_LOG_E(context_->GetNodeName(), "hc_base must have rank 1"), - return ge::GRAPH_FAILED); int64_t baseFirstDim = shapeHcBase->GetStorageShape().GetDim(0); OPS_ERR_IF(baseFirstDim != hcMix_, OPS_LOG_E(context_->GetNodeName(), @@ -180,33 +166,307 @@ ge::graphStatus HcPreVaTiling::GetShapeAttrsInfoInner() { baseFirstDim), return ge::GRAPH_FAILED); - // 可选输入 pre_mix: [bs, hc_mult] fp32 - tilingData_.set_hasPreMix(context_->GetInputShape(4) != nullptr ? 1 : 0); - auto pre_mix_shape = context_->GetInputShape(4); - if (pre_mix_shape != nullptr) { - OPS_ERR_IF(pre_mix_shape->GetStorageShape().GetDimNum() != xDimNum - 1, + // 可选输入 pre_mix: [bs, hc_mult] fp32; + // gen_placeholder模式下GetInputShape恒非空, 必须用GetOptionalInputTensor判空 + tilingData_.set_hasPreMix(context_->GetOptionalInputTensor(4) != nullptr ? 1 + : 0); + // 可选输出 pre: 无GetOptionalOutputTensor对应API, + // 用shape内容判别(占位shape无有效首维) + auto preOutShape = context_->GetOutputShape(3); + bool hasPreOut = preOutShape != nullptr && + preOutShape->GetStorageShape().GetDimNum() > 0 && + preOutShape->GetStorageShape().GetDim(0) > 0; + tilingData_.set_hasPreOut(hasPreOut ? 1 : 0); + + return ge::GRAPH_SUCCESS; +} + +void HcPreVaTiling::CalcVectorCoreNum() { + int64_t totalCoreNum = static_cast(aivCoreNum_); + int64_t effectiveIterTimes = std::max(iterTimes_, static_cast(1)); + + // Estimate the work per row and test each core split with rounded row counts. + uint64_t prePostRowWork = static_cast(PRE_POST_ROW_WORK_SCALE) * d_; + uint64_t sinkhornRowWork = + static_cast(SINKHORN_ROW_WORK_SCALE) * hcMult_ * + (effectiveIterTimes + SINKHORN_SETUP_ITER_EQUIVALENT); + uint64_t bestLatency = 0; + uint64_t bestImbalance = 0; + bool hasCandidate = false; + + for (int64_t candidatePrePostCoreNum = 1; + candidatePrePostCoreNum < totalCoreNum; + candidatePrePostCoreNum++) { + int64_t candidateSinkhornCoreNum = totalCoreNum - candidatePrePostCoreNum; + uint64_t prePostLatency = + static_cast(CeilDiv(bs_, candidatePrePostCoreNum)) * + prePostRowWork; + uint64_t sinkhornLatency = + static_cast(CeilDiv(bs_, candidateSinkhornCoreNum)) * + sinkhornRowWork; + uint64_t latency = std::max(prePostLatency, sinkhornLatency); + uint64_t imbalance = prePostLatency > sinkhornLatency + ? prePostLatency - sinkhornLatency + : sinkhornLatency - prePostLatency; + if (!hasCandidate || latency < bestLatency || + (latency == bestLatency && imbalance < bestImbalance)) { + hasCandidate = true; + bestLatency = latency; + bestImbalance = imbalance; + prePostCoreNum_ = candidatePrePostCoreNum; + sinkhornCoreNum_ = candidateSinkhornCoreNum; + } + } +} + +ge::graphStatus HcPreVaTiling::CalcMKSplitCoreMembasePart2Tiling() { + // 外部 pre_mix 复用该统一下标 tiling(与旧实现一致), 仅由 kernel 切换 + // y 的权重来源; va 的 premix 专用 tiling/kernel 路径在 A3 上不可用. + bool useOriginal = bs_ <= SMALL_BS_THRESHOLD; + if (useOriginal) { + tilingKey_ = ORIGINAL_TILING_KEY; + rowOfFormerBlock_ = CeilDiv(bs_, static_cast(aivCoreNum_)); + } else { + tilingKey_ = MPMD_TILING_KEY; + OPS_ERR_IF(aivCoreNum_ < 2, OPS_LOG_E(context_->GetNodeName(), - "pre_mix rank must equal x rank minus one"), + "XllmKernelHcPreVa MPMD requires at least two vector " + "cores, but got %lu", + aivCoreNum_), return ge::GRAPH_FAILED); - for (size_t dimension = 0; dimension + 1 < xDimNum; ++dimension) { - OPS_ERR_IF(pre_mix_shape->GetStorageShape().GetDim(dimension) != - xShape->GetStorageShape().GetDim(dimension), - OPS_LOG_E(context_->GetNodeName(), - "pre_mix shape must equal x shape without D"), - return ge::GRAPH_FAILED); + CalcVectorCoreNum(); + rowOfFormerBlock_ = CeilDiv(bs_, prePostCoreNum_); + } + + int64_t stage2CoreNum = + useOriginal ? static_cast(aivCoreNum_) : prePostCoreNum_; + usedAivCoreNums_ = std::min(CeilDiv(bs_, rowOfFormerBlock_), stage2CoreNum); + rowOfTailBlock_ = bs_ - (usedAivCoreNums_ - 1) * rowOfFormerBlock_; + + int64_t minRowPerCore = 1; + int64_t rowOnceLoop = std::min(rowOfFormerBlock_, minRowPerCore); + int64_t kBlockNum = tilingData_.get_cubeBlockDimK(); + + hcMultAlign_ = RoundUp(hcMult_, BLOCK_SIZE / sizeof(float)); + int64_t mix0OriginSize = + kBlockNum * rowOnceLoop * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; + int64_t mix1OriginSize = + kBlockNum * rowOnceLoop * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; + int64_t mix0Size = rowOnceLoop * hcMultAlign_ * sizeof(float); + int64_t mix1Size = rowOnceLoop * hcMultAlign_ * sizeof(float); + int64_t squareSumSize = + kBlockNum * RoundUp(rowOnceLoop * 16, 16) * sizeof(float) * DOUBLE_BUFFER; + int64_t squareReduceSize = rowOnceLoop * SQUARE_SUM_SIZE * sizeof(float); + int64_t rsqrtSize = + RoundUp(rowOnceLoop, BLOCK_SIZE / sizeof(float)) * sizeof(float); + int64_t xSize = rowOnceLoop * hcMult_ * RoundUp(d_, 16) * 2 * + DOUBLE_BUFFER; // x是bfloat16_t 类型 + int64_t ySize = rowOnceLoop * RoundUp(d_, 16) * 2 * DOUBLE_BUFFER; + int64_t postSize = rowOnceLoop * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; + int64_t base0Size = hcMultAlign_ * sizeof(float); + int64_t base1Size = hcMultAlign_ * sizeof(float); + int64_t xCastSize = rowOnceLoop * hcMult_ * RoundUp(d_, 8) * sizeof(float); + int64_t yCastSize = rowOnceLoop * RoundUp(d_, 8) * sizeof(float); + int64_t rowBrcb0Size = RoundUp(rowOnceLoop, 8) * BLOCK_SIZE; + int64_t hcBrcb1Size = RoundUp(rowOnceLoop * hcMultAlign_, 8) * BLOCK_SIZE; + int64_t maskPatternSize = + (rowOnceLoop + MASK_PATTERN_DIM_SIZE - 1) * BLOCK_SIZE; + auto calcOriginalExtraSize = [&](int64_t rowFactor) { + if (!useOriginal) { + return static_cast(0); } + int64_t mix2OriginSize = kBlockNum * rowFactor * hcMult_ * hcMultAlign_ * + sizeof(float) * DOUBLE_BUFFER; + int64_t combFragSize = + rowFactor * hcMult_ * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; + int64_t base2Size = hcMult_ * hcMultAlign_ * sizeof(float); + int64_t reduceBufSize = rowFactor * hcMultAlign_ * sizeof(float); + int64_t mix2Size = rowFactor * hcMult_ * hcMultAlign_ * sizeof(float); + return mix2OriginSize + combFragSize + base2Size + reduceBufSize + mix2Size; + }; + int64_t originalExtraSize = calcOriginalExtraSize(rowOnceLoop); + + int64_t totalSize = mix0OriginSize + mix1OriginSize + mix0Size + mix1Size + + squareSumSize + squareReduceSize + rsqrtSize + xSize + + ySize + postSize + base0Size + base1Size + xCastSize + + yCastSize + rowBrcb0Size + hcBrcb1Size + maskPatternSize + + originalExtraSize; + rowFactor_ = rowOnceLoop; + if (totalSize <= ubSize_) { + // row和d均可以在ub内全载 + dLoop_ = 1; + dFactor_ = d_; + tailDFactor_ = dFactor_; + } else { + int64_t usedUbSize = mix0OriginSize + mix1OriginSize + mix0Size + mix1Size + + squareSumSize + squareReduceSize + rsqrtSize + + postSize + base0Size + base1Size + rowBrcb0Size + + hcBrcb1Size + maskPatternSize + originalExtraSize; + int64_t ubRemain = ubSize_ - usedUbSize; + dFactor_ = d_; + int64_t base = 2; + while (1) { + dFactor_ = CeilDiv(d_, base); + xSize = rowOnceLoop * hcMult_ * RoundUp(dFactor_, 16) * 2 * + DOUBLE_BUFFER; // x是bfloat16_t 类型 + ySize = rowOnceLoop * RoundUp(dFactor_, 16) * 2 * DOUBLE_BUFFER; + xCastSize = rowOnceLoop * hcMult_ * RoundUp(dFactor_, 8) * sizeof(float); + yCastSize = rowOnceLoop * RoundUp(dFactor_, 8) * sizeof(float); + int64_t targetSize = xSize + ySize + xCastSize + yCastSize; + if (targetSize <= ubRemain) { + break; + } + base++; + } + if (dFactor_ > 32) { + dFactor_ = DownAlign(dFactor_, 32); + } + dLoop_ = CeilDiv(d_, dFactor_); + tailDFactor_ = d_ % dFactor_ == 0 ? dFactor_ : d_ % dFactor_; } - // 可选输出 pre: 内部计算的 pre 结果拷出 - tilingData_.set_hasPreOut(context_->GetOutputShape(3) != nullptr ? 1 : 0); - OPS_ERR_IF(GetAttr() != ge::GRAPH_SUCCESS, - OPS_LOG_E(context_->GetNodeName(), "get attr failed."), - return ge::GRAPH_FAILED); + // d全载,尝试搬入更多的bs + if (dFactor_ == d_) { + while (rowFactor_ <= rowOfFormerBlock_) { + mix0OriginSize = + kBlockNum * rowFactor_ * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; + mix1OriginSize = + kBlockNum * rowFactor_ * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; + mix0Size = rowFactor_ * hcMultAlign_ * sizeof(float); + mix1Size = rowFactor_ * hcMultAlign_ * sizeof(float); + squareSumSize = kBlockNum * RoundUp(rowFactor_ * 16, 16) * sizeof(float) * + DOUBLE_BUFFER; + squareReduceSize = rowFactor_ * SQUARE_SUM_SIZE * sizeof(float); + rsqrtSize = + RoundUp(rowFactor_, BLOCK_SIZE / sizeof(float)) * sizeof(float); + xSize = rowFactor_ * hcMult_ * RoundUp(d_, 16) * 2 * + DOUBLE_BUFFER; // x是bfloat16_t 类型 + ySize = rowFactor_ * RoundUp(d_, 16) * 2 * DOUBLE_BUFFER; + postSize = rowFactor_ * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; + xCastSize = rowFactor_ * hcMult_ * RoundUp(d_, 8) * sizeof(float); + yCastSize = rowFactor_ * RoundUp(d_, 8) * sizeof(float); + rowBrcb0Size = RoundUp(rowFactor_, 8) * BLOCK_SIZE; + hcBrcb1Size = RoundUp(rowFactor_ * hcMultAlign_, 8) * BLOCK_SIZE; + maskPatternSize = (rowFactor_ + MASK_PATTERN_DIM_SIZE - 1) * BLOCK_SIZE; + originalExtraSize = calcOriginalExtraSize(rowFactor_); + totalSize = mix0OriginSize + mix1OriginSize + mix0Size + mix1Size + + squareSumSize + squareReduceSize + rsqrtSize + xSize + ySize + + postSize + base0Size + base1Size + xCastSize + yCastSize + + rowBrcb0Size + hcBrcb1Size + maskPatternSize + + originalExtraSize; + if (totalSize > ubSize_) { + rowFactor_ = rowFactor_ - 1; + break; + } + rowFactor_ = rowFactor_ + 1; + } + rowFactor_ = rowFactor_ > rowOfFormerBlock_ ? rowFactor_ - 1 : rowFactor_; + } - return ge::GRAPH_SUCCESS; + // The pre/post transforms only need row-sized state; y still uses the + // full-D buffers above. Give pre/post its own row tile so a full-D shape + // does not force sigmoid and RMSNorm setup to run once per row. + int64_t prePostRowFactor = rowFactor_; + if (!useOriginal) { + auto calcPrePostSize = [&](int64_t candidateRow) { + int64_t originSize = kBlockNum * candidateRow * hcMultAlign_ * + sizeof(float) * DOUBLE_BUFFER; + int64_t reduceSize = candidateRow * hcMultAlign_ * sizeof(float); + int64_t squareSize = kBlockNum * RoundUp(candidateRow * 16, 16) * + sizeof(float) * DOUBLE_BUFFER; + int64_t squareReduce = candidateRow * SQUARE_SUM_SIZE * sizeof(float); + int64_t rsqrt = + RoundUp(candidateRow, BLOCK_SIZE / sizeof(float)) * sizeof(float); + int64_t post = rowFactor_ * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; + int64_t rowBrcb = + RoundUp(candidateRow, BLOCK_SIZE / sizeof(float)) * BLOCK_SIZE; + int64_t hcBrcb = + RoundUp(candidateRow * hcMultAlign_, BLOCK_SIZE / sizeof(float)) * + BLOCK_SIZE; + int64_t mask = (candidateRow + MASK_PATTERN_DIM_SIZE - 1) * BLOCK_SIZE; + int64_t yX = + rowFactor_ * hcMult_ * RoundUp(dFactor_, 16) * 2 * DOUBLE_BUFFER; + int64_t yY = rowFactor_ * RoundUp(dFactor_, 16) * 2 * DOUBLE_BUFFER; + int64_t yXCast = + rowFactor_ * hcMult_ * RoundUp(dFactor_, 8) * sizeof(float); + int64_t yYCast = rowFactor_ * RoundUp(dFactor_, 8) * sizeof(float); + return originSize * 2 + reduceSize * 2 + squareSize + squareReduce + + rsqrt + post + base0Size + base1Size + yX + yY + yXCast + yYCast + + rowBrcb + hcBrcb + mask; + }; + prePostRowFactor = 1; + for (int64_t candidateRow = 1; candidateRow <= rowOfFormerBlock_; + candidateRow++) { + if (calcPrePostSize(candidateRow) > static_cast(ubSize_)) { + break; + } + prePostRowFactor = candidateRow; + } + // Cap the pre/post row batch at four after checking UB capacity. + if (prePostRowFactor > 4) { + prePostRowFactor = 4; + } + } + int64_t prePostRowLoopOfFormerBlock = + CeilDiv(rowOfFormerBlock_, prePostRowFactor); + int64_t prePostRowLoopOfTailBlock = + CeilDiv(rowOfTailBlock_, prePostRowFactor); + int64_t prePostTailRowFactorOfFormerBlock = + rowOfFormerBlock_ % prePostRowFactor == 0 + ? prePostRowFactor + : rowOfFormerBlock_ % prePostRowFactor; + int64_t prePostTailRowFactorOfTailBlock = + rowOfTailBlock_ % prePostRowFactor == 0 + ? prePostRowFactor + : rowOfTailBlock_ % prePostRowFactor; + rowLoopOfFormerBlock_ = CeilDiv(rowOfFormerBlock_, rowFactor_); + rowLoopOfTailBlock_ = CeilDiv(rowOfTailBlock_, rowFactor_); + tailRowFactorOfFormerBlock_ = rowOfFormerBlock_ % rowFactor_ == 0 + ? rowFactor_ + : rowOfFormerBlock_ % rowFactor_; + tailRowFactorOfTailBlock_ = rowOfTailBlock_ % rowFactor_ == 0 + ? rowFactor_ + : rowOfTailBlock_ % rowFactor_; + + tilingData_.set_bs(bs_); + tilingData_.set_hcMix(hcMix_); + tilingData_.set_hcMult(hcMult_); + tilingData_.set_d(d_); + tilingData_.set_hcMultAlign(hcMultAlign_); + tilingData_.set_rowOfFormerBlock(rowOfFormerBlock_); + tilingData_.set_rowOfTailBlock(rowOfTailBlock_); + tilingData_.set_rowLoopOfFormerBlock(rowLoopOfFormerBlock_); + tilingData_.set_rowLoopOfTailBlock(rowLoopOfTailBlock_); + tilingData_.set_stage2RowFactor(rowFactor_); + tilingData_.set_secondUsedCoreNum(usedAivCoreNums_); + tilingData_.set_tailRowFactorOfFormerBlock(tailRowFactorOfFormerBlock_); + tilingData_.set_tailRowFactorOfTailBlock(tailRowFactorOfTailBlock_); + tilingData_.set_dLoop(dLoop_); + tilingData_.set_dFactor(dFactor_); + tilingData_.set_tailDFactor(tailDFactor_); + tilingData_.set_iterTimes(iterTimes_); + tilingData_.set_hcEps(hcEps_); + tilingData_.set_normEps(normEps_); + tilingData_.set_prePostCoreNum(prePostCoreNum_); + tilingData_.set_sinkhornCoreNum(sinkhornCoreNum_); + tilingData_.set_prePostRowOfFormerBlock(rowOfFormerBlock_); + tilingData_.set_prePostRowOfTailBlock(rowOfTailBlock_); + tilingData_.set_prePostRowLoopOfFormerBlock(prePostRowLoopOfFormerBlock); + tilingData_.set_prePostRowLoopOfTailBlock(prePostRowLoopOfTailBlock); + tilingData_.set_prePostRowFactor(prePostRowFactor); + tilingData_.set_prePostTailRowFactorOfFormerBlock( + prePostTailRowFactorOfFormerBlock); + tilingData_.set_prePostTailRowFactorOfTailBlock( + prePostTailRowFactorOfTailBlock); + if (useOriginal) { + return ge::GRAPH_SUCCESS; + } + return CalcSinkhornTiling(); } -ge::graphStatus HcPreVaTiling::CalcMKSplitCoreMembasePart2Tiling() { +// preMix 场景的 Part2 tiling:按行分配,UB 预算包含 mix2、combFrag、base2 和 +// reduceBuf。 +ge::graphStatus HcPreVaTiling::CalcPremixPart2Tiling() { rowOfFormerBlock_ = CeilDiv(bs_, static_cast(aivCoreNum_)); usedAivCoreNums_ = std::min(CeilDiv(bs_, rowOfFormerBlock_), static_cast(aivCoreNum_)); @@ -215,8 +475,6 @@ ge::graphStatus HcPreVaTiling::CalcMKSplitCoreMembasePart2Tiling() { int64_t minRowPerCore = 1; int64_t rowOnceLoop = std::min(rowOfFormerBlock_, minRowPerCore); int64_t kBlockNum = tilingData_.get_cubeBlockDimK(); - const int64_t available_ub_size = - static_cast(ubSize_) - UB_RESEVED_SIZE; hcMultAlign_ = RoundUp(hcMult_, BLOCK_SIZE / sizeof(float)); int64_t mix0OriginSize = @@ -241,38 +499,31 @@ ge::graphStatus HcPreVaTiling::CalcMKSplitCoreMembasePart2Tiling() { int64_t base0Size = hcMultAlign_ * sizeof(float); int64_t base1Size = hcMultAlign_ * sizeof(float); int64_t base2Size = hcMult_ * hcMultAlign_ * sizeof(float); - int64_t xCastSize = rowOnceLoop * hcMult_ * RoundUp(d_, 16) * sizeof(float); - int64_t yCastSize = rowOnceLoop * RoundUp(d_, 16) * sizeof(float); + int64_t xCastSize = rowOnceLoop * hcMult_ * RoundUp(d_, 8) * sizeof(float); + int64_t yCastSize = rowOnceLoop * RoundUp(d_, 8) * sizeof(float); int64_t rowBrcb0Size = RoundUp(rowOnceLoop, 8) * BLOCK_SIZE; int64_t hcBrcb1Size = RoundUp(rowOnceLoop * hcMultAlign_, 8) * BLOCK_SIZE; int64_t reduceBufSize = rowOnceLoop * hcMultAlign_ * sizeof(float); - int64_t maskPatternSize = BLOCK_SIZE * (rowOnceLoop + 15); - int64_t squareReduceSize = rowOnceLoop * 16 * sizeof(float); - int64_t preMixSize = rowOnceLoop * hcMultAlign_ * sizeof(float); - - int64_t totalSize = mix0OriginSize + mix1OriginSize + mix2OriginSize + - mix0Size + mix1Size + mix2Size + squareSumSize + - rsqrtSize + xSize + ySize + postSize + combFragSize + - base0Size + base1Size + base2Size + xCastSize + - yCastSize + rowBrcb0Size + hcBrcb1Size + reduceBufSize + - maskPatternSize + squareReduceSize + preMixSize; + int64_t maskPatternSize = BLOCK_SIZE * 16; + + int64_t totalSize = + mix0OriginSize + mix1OriginSize + mix2OriginSize + mix0Size + mix1Size + + mix2Size + squareSumSize + rsqrtSize + xSize + ySize + postSize + + combFragSize + base0Size + base1Size + base2Size + xCastSize + yCastSize + + rowBrcb0Size + hcBrcb1Size + reduceBufSize + maskPatternSize; rowFactor_ = rowOnceLoop; - if (totalSize <= available_ub_size) { + if (totalSize <= ubSize_) { // row和d均可以在ub内全载 dLoop_ = 1; dFactor_ = d_; tailDFactor_ = dFactor_; } else { - int64_t usedUbSize = - mix0OriginSize + mix1OriginSize + mix2OriginSize + mix0Size + mix1Size + - mix2Size + squareSumSize + rsqrtSize + postSize + combFragSize + - base0Size + base1Size + base2Size + rowBrcb0Size + hcBrcb1Size + - reduceBufSize + maskPatternSize + squareReduceSize + preMixSize; - int64_t ubRemain = available_ub_size - usedUbSize; - OPS_ERR_IF(ubRemain <= 0, - OPS_LOG_E(context_->GetNodeName(), - "stage 2 buffers exceed available UB"), - return ge::GRAPH_FAILED); + int64_t usedUbSize = mix0OriginSize + mix1OriginSize + mix2OriginSize + + mix0Size + mix1Size + mix2Size + squareSumSize + + rsqrtSize + postSize + combFragSize + base0Size + + base1Size + base2Size + rowBrcb0Size + hcBrcb1Size + + reduceBufSize + maskPatternSize; + int64_t ubRemain = ubSize_ - usedUbSize; dFactor_ = d_; int64_t base = 2; while (1) { @@ -280,16 +531,12 @@ ge::graphStatus HcPreVaTiling::CalcMKSplitCoreMembasePart2Tiling() { xSize = rowOnceLoop * hcMult_ * RoundUp(dFactor_, 16) * 2 * DOUBLE_BUFFER; // x是bfloat16_t 类型 ySize = rowOnceLoop * RoundUp(dFactor_, 16) * 2 * DOUBLE_BUFFER; - xCastSize = rowOnceLoop * hcMult_ * RoundUp(dFactor_, 16) * sizeof(float); - yCastSize = rowOnceLoop * RoundUp(dFactor_, 16) * sizeof(float); + xCastSize = rowOnceLoop * hcMult_ * RoundUp(dFactor_, 8) * sizeof(float); + yCastSize = rowOnceLoop * RoundUp(dFactor_, 8) * sizeof(float); int64_t targetSize = xSize + ySize + xCastSize + yCastSize; if (targetSize <= ubRemain) { break; } - OPS_ERR_IF(dFactor_ == 1, - OPS_LOG_E(context_->GetNodeName(), - "a single hidden column does not fit in UB"), - return ge::GRAPH_FAILED); base++; } if (dFactor_ > 32) { @@ -299,12 +546,9 @@ ge::graphStatus HcPreVaTiling::CalcMKSplitCoreMembasePart2Tiling() { tailDFactor_ = d_ % dFactor_ == 0 ? dFactor_ : d_ % dFactor_; } - // Softmax reduces hcMult rows per token; vector repeats are limited to 255. - const int64_t maxRowFactor = - std::min(rowOfFormerBlock_, MAX_VECTOR_REPEAT / hcMult_); // d全载,尝试搬入更多的bs if (dFactor_ == d_) { - while (rowFactor_ <= maxRowFactor) { + while (rowFactor_ <= rowOfFormerBlock_) { mix0OriginSize = kBlockNum * rowFactor_ * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; mix1OriginSize = @@ -324,27 +568,24 @@ ge::graphStatus HcPreVaTiling::CalcMKSplitCoreMembasePart2Tiling() { postSize = rowFactor_ * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; combFragSize = rowFactor_ * hcMult_ * hcMultAlign_ * sizeof(float) * DOUBLE_BUFFER; - xCastSize = rowFactor_ * hcMult_ * RoundUp(d_, 16) * sizeof(float); - yCastSize = rowFactor_ * RoundUp(d_, 16) * sizeof(float); + xCastSize = rowFactor_ * hcMult_ * RoundUp(d_, 8) * sizeof(float); + yCastSize = rowFactor_ * RoundUp(d_, 8) * sizeof(float); rowBrcb0Size = RoundUp(rowFactor_, 8) * BLOCK_SIZE; hcBrcb1Size = RoundUp(rowFactor_ * hcMultAlign_, 8) * BLOCK_SIZE; reduceBufSize = rowFactor_ * hcMultAlign_ * sizeof(float); - maskPatternSize = BLOCK_SIZE * (rowFactor_ + 15); - squareReduceSize = rowFactor_ * 16 * sizeof(float); - preMixSize = rowFactor_ * hcMultAlign_ * sizeof(float); + maskPatternSize = BLOCK_SIZE * MASK_PATTERN_DIM_SIZE; totalSize = mix0OriginSize + mix1OriginSize + mix2OriginSize + mix0Size + mix1Size + mix2Size + squareSumSize + rsqrtSize + xSize + ySize + postSize + combFragSize + base0Size + base1Size + base2Size + xCastSize + yCastSize + rowBrcb0Size + - hcBrcb1Size + reduceBufSize + maskPatternSize + - squareReduceSize + preMixSize; - if (totalSize > available_ub_size) { + hcBrcb1Size + reduceBufSize + maskPatternSize; + if (totalSize > ubSize_) { rowFactor_ = rowFactor_ - 1; break; } rowFactor_ = rowFactor_ + 1; } - rowFactor_ = rowFactor_ > maxRowFactor ? rowFactor_ - 1 : rowFactor_; + rowFactor_ = rowFactor_ > rowOfFormerBlock_ ? rowFactor_ - 1 : rowFactor_; } rowLoopOfFormerBlock_ = CeilDiv(rowOfFormerBlock_, rowFactor_); rowLoopOfTailBlock_ = CeilDiv(rowOfTailBlock_, rowFactor_); @@ -355,6 +596,7 @@ ge::graphStatus HcPreVaTiling::CalcMKSplitCoreMembasePart2Tiling() { ? rowFactor_ : rowOfTailBlock_ % rowFactor_; + tilingKey_ = PREMIX_TILING_KEY; tilingData_.set_bs(bs_); tilingData_.set_hcMix(hcMix_); tilingData_.set_hcMult(hcMult_); @@ -377,14 +619,112 @@ ge::graphStatus HcPreVaTiling::CalcMKSplitCoreMembasePart2Tiling() { return ge::GRAPH_SUCCESS; } +ge::graphStatus HcPreVaTiling::CalcSinkhornTiling() { + sinkhornRowOfFormerBlock_ = CeilDiv(bs_, sinkhornCoreNum_); + sinkhornUsedCoreNum_ = + std::min(CeilDiv(bs_, sinkhornRowOfFormerBlock_), sinkhornCoreNum_); + sinkhornRowOfTailBlock_ = + bs_ - (sinkhornUsedCoreNum_ - 1) * sinkhornRowOfFormerBlock_; + + int64_t kBlockNum = tilingData_.get_cubeBlockDimK(); + auto calcTotalSize = [&](int64_t rowFactor) { + int64_t rowFactorAlign = RoundUp(rowFactor, BLOCK_SIZE / sizeof(float)); + int64_t matrixSize = hcMult_ * hcMult_; + int64_t mix2OriginSize = + kBlockNum * rowFactor * matrixSize * sizeof(float) * DOUBLE_BUFFER; + int64_t combFragSize = + rowFactor * matrixSize * sizeof(float) * DOUBLE_BUFFER; + int64_t squareSumSize = + kBlockNum * RoundUp(rowFactor * SQUARE_SUM_SIZE, SQUARE_SUM_SIZE) * + sizeof(float) * DOUBLE_BUFFER; + int64_t rsqrtSize = + RoundUp(rowFactor, BLOCK_SIZE / sizeof(float)) * sizeof(float); + int64_t squareReduceSize = rowFactor * SQUARE_SUM_SIZE * sizeof(float); + int64_t mixes02ReduceSize = matrixSize * rowFactorAlign * sizeof(float); + int64_t reduceBufSize = hcMult_ * rowFactorAlign * sizeof(float); + int64_t rowBrcb0Size = + RoundUp(rowFactor, BLOCK_SIZE / sizeof(float)) * BLOCK_SIZE; + int64_t hcBrcb1Size = matrixSize * BLOCK_SIZE; + int64_t maskPatternSize = + (rowFactor + MASK_PATTERN_DIM_SIZE - 1) * BLOCK_SIZE; + return mix2OriginSize + combFragSize + squareSumSize + rsqrtSize + + squareReduceSize + mixes02ReduceSize + reduceBufSize + rowBrcb0Size + + hcBrcb1Size + maskPatternSize; + }; + + int64_t base2Size = hcMult_ * hcMult_ * sizeof(float); + + int64_t maxSinkhornRowFactor = + std::min(sinkhornRowOfFormerBlock_, static_cast(64)); + // Keep double buffering for generalized batch sizes. The row-factor search + // accounts for both queue slots so the allocation stays in UB. + sinkhornRowFactor_ = 1; + while (sinkhornRowFactor_ <= maxSinkhornRowFactor) { + if (calcTotalSize(sinkhornRowFactor_) + base2Size > + static_cast(ubSize_)) { + sinkhornRowFactor_--; + break; + } + sinkhornRowFactor_++; + } + sinkhornRowFactor_ = std::min(sinkhornRowFactor_, maxSinkhornRowFactor); + OPS_ERR_IF(sinkhornRowFactor_ < 1, + OPS_LOG_E(context_->GetNodeName(), + "XllmKernelHcPreVa sinkhorn buffers exceed UB size %lu", + ubSize_), + return ge::GRAPH_FAILED); + + sinkhornRowLoopOfFormerBlock_ = + CeilDiv(sinkhornRowOfFormerBlock_, sinkhornRowFactor_); + sinkhornRowLoopOfTailBlock_ = + CeilDiv(sinkhornRowOfTailBlock_, sinkhornRowFactor_); + sinkhornTailRowFactorOfFormerBlock_ = + sinkhornRowOfFormerBlock_ % sinkhornRowFactor_ == 0 + ? sinkhornRowFactor_ + : sinkhornRowOfFormerBlock_ % sinkhornRowFactor_; + sinkhornTailRowFactorOfTailBlock_ = + sinkhornRowOfTailBlock_ % sinkhornRowFactor_ == 0 + ? sinkhornRowFactor_ + : sinkhornRowOfTailBlock_ % sinkhornRowFactor_; + + tilingData_.set_sinkhornUsedCoreNum(sinkhornUsedCoreNum_); + tilingData_.set_sinkhornRowOfFormerBlock(sinkhornRowOfFormerBlock_); + tilingData_.set_sinkhornRowOfTailBlock(sinkhornRowOfTailBlock_); + tilingData_.set_sinkhornRowLoopOfFormerBlock(sinkhornRowLoopOfFormerBlock_); + tilingData_.set_sinkhornRowLoopOfTailBlock(sinkhornRowLoopOfTailBlock_); + tilingData_.set_sinkhornRowFactor(sinkhornRowFactor_); + tilingData_.set_sinkhornTailRowFactorOfFormerBlock( + sinkhornTailRowFactorOfFormerBlock_); + tilingData_.set_sinkhornTailRowFactorOfTailBlock( + sinkhornTailRowFactorOfTailBlock_); + return ge::GRAPH_SUCCESS; +} + ge::graphStatus HcPreVaTiling::CalcOpTiling() { uint64_t kSize = hcMult_ * d_; tilingData_.set_k(kSize); // 计算bs_轴切核 uint64_t mDimNum = std::min(aicCoreNum_, static_cast(CeilDiv(bs_, M_L1_MAX_SIZE))); - uint64_t singleCoreM = RoundUp(CeilDiv(bs_, mDimNum), AscendC::BLOCK_CUBE); uint64_t kDimNum = aicCoreNum_ / mDimNum; + if (kDimNum == 1) { + // K cannot use the remaining AICs, so distribute M across all cores. + mDimNum = aicCoreNum_; + } else if (aicCoreNum_ % mDimNum != 0) { + // Align mDimNum up to the nearest factor of aicCoreNum_ so that + // mDimNum * kDimNum == aicCoreNum_ holds exactly. Without this the + // integer division truncates kDimNum and the trailing AIC cores idle + // (e.g. bs=2024: mDimNum=8, kDimNum=2, only 16 of 20 AICs run). + for (uint64_t factor = mDimNum; factor <= aicCoreNum_; ++factor) { + if (aicCoreNum_ % factor == 0) { + mDimNum = factor; + break; + } + } + } + uint64_t singleCoreM = + RoundUp(CeilDiv(bs_, static_cast(mDimNum)), AscendC::BLOCK_CUBE); + kDimNum = aicCoreNum_ / mDimNum; uint64_t splitKSize = RoundUp(CeilDiv(kSize, kDimNum), K_MULIT_CORE_SPLIT_BASE_SIZE); @@ -397,7 +737,7 @@ ge::graphStatus HcPreVaTiling::CalcOpTiling() { static_cast(K_L1_MAX_SIZE)) / K_L1_ALIGN_SIZE * K_L1_ALIGN_SIZE); - tilingData_.set_cvLoopKSize(1024); + tilingData_.set_cvLoopKSize(CV_LOOP_K_SIZE); // vector stage1 tiling tilingData_.set_cubeCoreNum(static_cast(aicCoreNum_)); @@ -461,8 +801,16 @@ ge::graphStatus HcPreVaTiling::GetWorkspaceSize() { } ge::graphStatus HcPreVaTiling::PostTiling() { - context_->SetTilingKey(0); + context_->SetTilingKey(tilingKey_); context_->SetBlockDim(aicCoreNum_); + if (tilingKey_ == MPMD_TILING_KEY) { + auto ret = context_->SetScheduleMode(1); + OPS_ERR_IF( + ret != ge::GRAPH_SUCCESS, + OPS_LOG_E(context_, + "Failed to set schedule mode to 1 for XllmKernelHcPreVa."), + return ge::GRAPH_FAILED); + } size_t* workspaces = context_->GetWorkspaceSizes(1); workspaces[0] = workspaceSize_; tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), @@ -472,25 +820,7 @@ ge::graphStatus HcPreVaTiling::PostTiling() { } ge::graphStatus TilingPrepareForHcPreVa(gert::TilingParseContext* context) { - OPS_ERR_IF(context == nullptr, - OPS_REPORT_VECTOR_INNER_ERR("XllmKernelHcPreVa", - "Tiling parse context is null"), - return ge::GRAPH_FAILED); - auto compileInfo = context->GetCompiledInfo(); - OPS_LOG_E_IF_NULL(context, compileInfo, return ge::GRAPH_FAILED); - auto platformInfo = context->GetPlatformInfo(); - OPS_LOG_E_IF_NULL(context, platformInfo, return ge::GRAPH_FAILED); - auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo); - compileInfo->coreNum = ascendcPlatform.GetCoreNumAiv(); - compileInfo->aicCoreNum = ascendcPlatform.GetCoreNumAic(); - ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, - compileInfo->ubSize); - OPS_ERR_IF( - compileInfo->coreNum == 0 || compileInfo->aicCoreNum == 0 || - compileInfo->ubSize == 0, - OPS_LOG_E(context->GetNodeName(), - "AIV core count, AIC core count and UB size must be positive"), - return ge::GRAPH_FAILED); + (void)context; return ge::GRAPH_SUCCESS; } diff --git a/xllm-kernel/csrc/ascendc/hc_pre_va/op_host/hc_pre_va_tiling.h b/xllm-kernel/csrc/ascendc/hc_pre_va/op_host/hc_pre_va_tiling.h index 478f86f0a9..69466f1987 100644 --- a/xllm-kernel/csrc/ascendc/hc_pre_va/op_host/hc_pre_va_tiling.h +++ b/xllm-kernel/csrc/ascendc/hc_pre_va/op_host/hc_pre_va_tiling.h @@ -53,6 +53,7 @@ TILING_DATA_FIELD_DEF(int64_t, rowOfFormerBlock); TILING_DATA_FIELD_DEF(int64_t, rowOfTailBlock); TILING_DATA_FIELD_DEF(int64_t, rowLoopOfFormerBlock); TILING_DATA_FIELD_DEF(int64_t, rowLoopOfTailBlock); +TILING_DATA_FIELD_DEF(int64_t, rowFactor); TILING_DATA_FIELD_DEF(int64_t, tailRowFactorOfFormerBlock); TILING_DATA_FIELD_DEF(int64_t, tailRowFactorOfTailBlock); TILING_DATA_FIELD_DEF(int64_t, dLoop); @@ -61,25 +62,67 @@ TILING_DATA_FIELD_DEF(int64_t, tailDFactor); TILING_DATA_FIELD_DEF(int64_t, iterTimes); TILING_DATA_FIELD_DEF(float, hcEps); TILING_DATA_FIELD_DEF(float, normEps); +TILING_DATA_FIELD_DEF(int64_t, kBlockFactor); +TILING_DATA_FIELD_DEF(int64_t, kFactor); +TILING_DATA_FIELD_DEF(int64_t, tailKFactor); +TILING_DATA_FIELD_DEF(int64_t, kLoop); TILING_DATA_FIELD_DEF(int64_t, stage2RowFactor); TILING_DATA_FIELD_DEF(int64_t, k); +TILING_DATA_FIELD_DEF(int64_t, kLoopOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, kLoopOfTailBlock); +TILING_DATA_FIELD_DEF(int64_t, stage1KFactor); +TILING_DATA_FIELD_DEF(int64_t, kFactorOfFormerBlock); TILING_DATA_FIELD_DEF(int64_t, kL1Size); TILING_DATA_FIELD_DEF(int64_t, mL1Size); TILING_DATA_FIELD_DEF(int64_t, cubeBlockDimM); TILING_DATA_FIELD_DEF(int64_t, cubeBlockDimK); +TILING_DATA_FIELD_DEF(int64_t, kUbSize); // ub一次处理k的size TILING_DATA_FIELD_DEF(int64_t, cvLoopKSize); // cv同步使用的k轴长度 TILING_DATA_FIELD_DEF(int64_t, multCoreSplitKSize); // 多核切K后的单核k处理长度 -TILING_DATA_FIELD_DEF(int64_t, multCoreSplitMSize); // 多核切K后的单核k处理长度 - +TILING_DATA_FIELD_DEF(int64_t, + multCoreSplitMSize); // 多核切 M 后单核处理的 M 轴长度 +TILING_DATA_FIELD_DEF(int64_t, tailKSizeOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, tailKSizeOfTailBlock); + +TILING_DATA_FIELD_DEF(int64_t, mLoopOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, mLoopOfTailBlock); +TILING_DATA_FIELD_DEF(int64_t, formerMSize); +TILING_DATA_FIELD_DEF(int64_t, tailMSizeOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, tailMSizeOfTailBlock); + +TILING_DATA_FIELD_DEF(int64_t, firstUsedCoreNum); TILING_DATA_FIELD_DEF(int64_t, secondUsedCoreNum); +TILING_DATA_FIELD_DEF(int64_t, rowInnerFactor); + TILING_DATA_FIELD_DEF(int64_t, cubeCoreNum); TILING_DATA_FIELD_DEF(int64_t, stage1MFactor); +TILING_DATA_FIELD_DEF(int64_t, bufferPool0Size); +TILING_DATA_FIELD_DEF(int64_t, bufferPool1Size); +TILING_DATA_FIELD_DEF(int64_t, mUbSize); TILING_DATA_FIELD_DEF(int64_t, hasPreMix); TILING_DATA_FIELD_DEF(int64_t, hasPreOut); +TILING_DATA_FIELD_DEF(int64_t, prePostCoreNum); +TILING_DATA_FIELD_DEF(int64_t, sinkhornCoreNum); +TILING_DATA_FIELD_DEF(int64_t, prePostRowOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, prePostRowOfTailBlock); +TILING_DATA_FIELD_DEF(int64_t, prePostRowLoopOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, prePostRowLoopOfTailBlock); +TILING_DATA_FIELD_DEF(int64_t, prePostRowFactor); +TILING_DATA_FIELD_DEF(int64_t, prePostTailRowFactorOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, prePostTailRowFactorOfTailBlock); +TILING_DATA_FIELD_DEF(int64_t, sinkhornUsedCoreNum); +TILING_DATA_FIELD_DEF(int64_t, sinkhornRowOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, sinkhornRowOfTailBlock); +TILING_DATA_FIELD_DEF(int64_t, sinkhornRowLoopOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, sinkhornRowLoopOfTailBlock); +TILING_DATA_FIELD_DEF(int64_t, sinkhornRowFactor); +TILING_DATA_FIELD_DEF(int64_t, sinkhornTailRowFactorOfFormerBlock); +TILING_DATA_FIELD_DEF(int64_t, sinkhornTailRowFactorOfTailBlock); + END_TILING_DATA_DEF; REGISTER_TILING_DATA_CLASS(XllmKernelHcPreVa, HcPreVaTilingData) @@ -87,7 +130,6 @@ REGISTER_TILING_DATA_CLASS(XllmKernelHcPreVa, HcPreVaTilingData) // ----------算子CompileInfo定义---------- struct HcPreVaCompileInfo { uint64_t coreNum = 0; - uint64_t aicCoreNum = 0; uint64_t ubSize = 0; }; @@ -105,7 +147,10 @@ class HcPreVaTiling { ge::graphStatus GetAttr(); ge::graphStatus GetShapeAttrsInfoInner(); ge::graphStatus CalcOpTiling(); + void CalcVectorCoreNum(); ge::graphStatus CalcMKSplitCoreMembasePart2Tiling(); + ge::graphStatus CalcPremixPart2Tiling(); + ge::graphStatus CalcSinkhornTiling(); private: gert::TilingContext* context_ = nullptr; @@ -134,6 +179,18 @@ class HcPreVaTiling { int64_t iterTimes_ = 0; double hcEps_ = 0.0; double normEps_ = 0.0; + platform_ascendc::SocVersion socVersion_ = + platform_ascendc::SocVersion::ASCEND910B; + int64_t prePostCoreNum_ = 0; + int64_t sinkhornCoreNum_ = 0; + int64_t sinkhornUsedCoreNum_ = 0; + int64_t sinkhornRowOfFormerBlock_ = 0; + int64_t sinkhornRowOfTailBlock_ = 0; + int64_t sinkhornRowLoopOfFormerBlock_ = 0; + int64_t sinkhornRowLoopOfTailBlock_ = 0; + int64_t sinkhornRowFactor_ = 0; + int64_t sinkhornTailRowFactorOfFormerBlock_ = 0; + int64_t sinkhornTailRowFactorOfTailBlock_ = 0; }; } // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_base.h b/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_base.h index 942e7771c1..4d7f7560ca 100644 --- a/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_base.h +++ b/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_base.h @@ -22,25 +22,35 @@ namespace XllmKernelHcPreVa { using namespace AscendC; -constexpr int32_t BLOCK_SIZE = 32; -constexpr int32_t DEFAULT_BLOCK_STRIDE = 1; -constexpr int32_t DEFAULT_REPEAT_STRIDE = 8; -constexpr int32_t ONE_REPEAT_BLOCK_NUMS = 8; -constexpr int32_t REPEAT_SIZE = 256; -constexpr int32_t MAX_REPEAT_STRIDE = 255; -constexpr int32_t WORKSPACE_ALIGN_SIZE = 512; -constexpr uint32_t ONE = 1; -constexpr uint32_t SHIFT_COEFF = 17; -constexpr int32_t DOUBLE_BUFFER = 2; -constexpr int32_t CV_RATIO = 2; + +// ==================== A3架构常量定义 ==================== +// 以下常量用于AscendC A3架构的Vector API参数配置 +constexpr int32_t BLOCK_SIZE = 32; // 一个Block的字节数(32 Bytes) +constexpr int32_t DEFAULT_BLOCK_STRIDE = + 1; // 默认Block步长(相邻两个Block间隔1个Block) +constexpr int32_t DEFAULT_REPEAT_STRIDE = + 8; // 默认Repeat步长(8个Block = 256 Bytes = 1个Repeat) +constexpr int32_t ONE_REPEAT_BLOCK_NUMS = + 8; // 一个Repeat包含8个Block(256/32=8) +constexpr int32_t REPEAT_SIZE = 256; // 一个Repeat的字节大小(256 Bytes) +constexpr int32_t MAX_REPEAT_STRIDE = 255; // Repeat步长最大值(255个Block) +constexpr int32_t WORKSPACE_ALIGN_SIZE = + 512; // Workspace地址对齐大小(512 Bytes) +constexpr uint32_t ONE = 1; // GatherMask掩码基础值(bit[0]=1) +constexpr uint32_t SHIFT_COEFF = 17; // 移位系数 +constexpr int32_t DOUBLE_BUFFER = 2; // 双缓冲数量 +constexpr int32_t CV_RATIO = 2; // Cube:Vector核数比 = 1:2(1个AIC配2个AIV) constexpr uint64_t N_SIZE = 24; -constexpr uint64_t NUM_TWO = 2; -constexpr uint64_t SQUARE_SUM_SIZE = 16; -constexpr uint64_t MASK_PATTERN_BASE_SIZE = 16; -constexpr uint64_t MASK_PATTERN_REPEAT_SIZE = 8; -constexpr uint64_t MASK_PATTERN_DIM_SIZE = 16; -constexpr uint64_t MM_CACHE_LINE_BYTES = 512; +constexpr uint64_t NUM_TWO = 2; // 常量2 +constexpr uint64_t SQUARE_SUM_SIZE = 16; // 平方和输出大小(NZ格式下M×M=16×16) +constexpr uint64_t MASK_PATTERN_BASE_SIZE = 16; // GatherMask掩码基础维度大小 +constexpr uint64_t MASK_PATTERN_REPEAT_SIZE = 8; // 掩码重复子大小 +constexpr uint64_t MASK_PATTERN_DIM_SIZE = 16; // 掩码单次处理的维度大小 +constexpr uint64_t MM_CACHE_LINE_BYTES = 512; // MatMul缓存行大小(512 Bytes) + +// ==================== 对齐工具函数 ==================== +// 向上取整除法:返回(a + b - 1) / b __aicore__ inline int32_t CeilDiv(int32_t a, int32_t b) { if (b == 0) { return a; @@ -48,47 +58,70 @@ __aicore__ inline int32_t CeilDiv(int32_t a, int32_t b) { return (a + b - 1) / b; } +// 向上对齐:将a向上对齐到b的倍数 __aicore__ inline int32_t CeilAlign(int32_t a, int32_t b) { return CeilDiv(a, b) * b; } +// 按类型T的Block元素数向上对齐:用于确保元素数满足32字节Block对齐要求 template __aicore__ inline int32_t RoundUp(int32_t num) { - int32_t elemNum = BLOCK_SIZE / sizeof(T); + int32_t elemNum = BLOCK_SIZE / sizeof(T); // 每个Block中T类型元素的个数 return CeilAlign(num, elemNum); } +// ==================== GatherMask对角提取(用于RMSNorm平方和) +// ==================== + +// 设置GatherMask的循环对角掩码:生成 patternRows 行,第 i 行 base = 1 << (i % +// 16) 调用方按 rowFactor + MASK_PATTERN_DIM_SIZE - 1 行生成循环模式, 保证后续 +// GatherMask 单次调用中所有操作数保持 32 字节对齐 __aicore__ inline void SetGatherMaskPattern( - const LocalTensor& mask_pattern, - uint32_t rows) { - for (uint32_t row = 0; row < rows; ++row) { - Duplicate(mask_pattern[row * MASK_PATTERN_REPEAT_SIZE], - ONE << (row % MASK_PATTERN_DIM_SIZE), - MASK_PATTERN_REPEAT_SIZE); + const LocalTensor& maskPattern, + uint16_t patternRows) { + for (uint32_t i = 0; i < patternRows; i++) { + uint32_t base = ONE << (i % MASK_PATTERN_DIM_SIZE); + Duplicate(maskPattern[i * 8], base, 8); } PipeBarrier(); } +// 使用循环对角掩码从NZ格式的平方和结果中提取对角线元素(单次GatherMask完成dim0行) +// 输入input: NZ格式的平方和矩阵(dim0×16行×16列) +// 输出output: 提取的对角线元素(dim0个) +// maskPattern: 由SetGatherMaskPattern生成的循环对角掩码 +// dim0: 需要处理的行数 +// diagonalOffset: 当前行块在16×16 NZ块中的对角相位(globalRowOffset % +// SQUARE_SUM_SIZE) __aicore__ inline void GatherMaskByDiagonal( const LocalTensor& output, const LocalTensor& input, - const LocalTensor& mask_pattern, - uint16_t rows, - uint16_t diagonal_offset) { - // Each source row contains sixteen adjacent diagonal candidates. A cyclic - // pattern per row keeps the source and destination operands aligned. - uint64_t reserved_count = 0; + const LocalTensor maskPattern, + uint16_t dim0, + uint16_t diagonalOffset) { + uint16_t patternIdx = diagonalOffset % MASK_PATTERN_DIM_SIZE; + uint64_t rsvdCnt = 0; + // The caller provides dim0 + 15 cyclic patterns so all operands stay 32-byte + // aligned in one call. GatherMask(output, input, - mask_pattern[(diagonal_offset % MASK_PATTERN_DIM_SIZE) * - MASK_PATTERN_REPEAT_SIZE], + maskPattern[patternIdx * MASK_PATTERN_REPEAT_SIZE], true, MASK_PATTERN_DIM_SIZE, - {1, rows, 2, 1}, - reserved_count); + {1, dim0, 2, 1}, + rsvdCnt); PipeBarrier(); } +// ==================== 末维广播乘法 ==================== + +// output[dim0, dim1] = input0[dim0, dim1] * broadcast(input1[1, dim1]) +// 将一维向量input1沿第0维广播后与input0逐元素相乘 +// 参数: curRowNum=行数(dim0), curColNum=列数(dim1) +// tmpBuffer用于存放Brcb广播后的input1 +// needBrc: 是否需要执行Brcb广播(false时input1已广播好) +// 策略选择: +// 当列数较大时,根据dstRepStride是否超255来选择Col方向或Row方向开Repeat template __aicore__ inline void MulABLastDimBrcInline(const LocalTensor& output, const LocalTensor& input0, @@ -96,6 +129,7 @@ __aicore__ inline void MulABLastDimBrcInline(const LocalTensor& output, const LocalTensor& tmpBuffer, const int32_t curRowNum, const int32_t curColNum) { + // 第一步:通过Brcb将input1沿第0维广播到curRowNum行 if constexpr (needBrc) { uint32_t repeatTimes = CeilDiv(curRowNum, ONE_REPEAT_BLOCK_NUMS); Brcb(tmpBuffer, @@ -104,24 +138,30 @@ __aicore__ inline void MulABLastDimBrcInline(const LocalTensor& output, {DEFAULT_BLOCK_STRIDE, DEFAULT_REPEAT_STRIDE}); } PipeBarrier(); - uint32_t elemInOneBlock = BLOCK_SIZE / sizeof(T); - uint32_t elemInOneRepeat = REPEAT_SIZE / sizeof(T); - uint32_t curColNumAlign = RoundUp(curColNum); + uint32_t elemInOneBlock = BLOCK_SIZE / sizeof(T); // 一个Block中T类型元素个数 + uint32_t elemInOneRepeat = + REPEAT_SIZE / sizeof(T); // 一个Repeat中T类型元素个数 + uint32_t curColNumAlign = RoundUp(curColNum); // 列数向上对齐到Block + // 简单场景:列数不超过一个Block,直接连续乘法 if (curColNum <= elemInOneBlock) { Mul(output, input0, tmpBuffer, curRowNum * curColNumAlign); } else { - int32_t numRepeatPerLine = curColNum / elemInOneRepeat; - int32_t numRemainPerLine = curColNum % elemInOneRepeat; - int32_t dstRepStridePerLine = CeilDiv(curColNum, elemInOneBlock); + // 复杂场景:列数超过一个Block,需要分Repeat处理 + int32_t numRepeatPerLine = curColNum / elemInOneRepeat; // 每行完整Repeat数 + int32_t numRemainPerLine = + curColNum % elemInOneRepeat; // 每行尾部剩余元素数 + int32_t dstRepStridePerLine = + CeilDiv(curColNum, elemInOneBlock); // 每行占多少个Block BinaryRepeatParams instrParams; if (numRepeatPerLine > 0) { + // 判断是否可以用Row方向Repeat(条件:步长不超255且行数>=每行Repeat数) if (dstRepStridePerLine > MAX_REPEAT_STRIDE || curRowNum < numRepeatPerLine) { - // 在Col方向开Repeat, 并且Repeat小于255 + // 策略1:在Col方向开Repeat(逐行处理),适用于步长超限或行数较少的场景 instrParams.dstBlkStride = 1; instrParams.src0BlkStride = 1; - instrParams.src1BlkStride = 0; + instrParams.src1BlkStride = 0; // src1(广播向量)不随行移动 instrParams.dstRepStride = DEFAULT_REPEAT_STRIDE; instrParams.src0RepStride = DEFAULT_REPEAT_STRIDE; instrParams.src1RepStride = 0; @@ -134,13 +174,13 @@ __aicore__ inline void MulABLastDimBrcInline(const LocalTensor& output, instrParams); } } else { - // 在Row方向开Repeat + // 策略2:在Row方向开Repeat(逐Repeat处理),利用repeatTimes=curRowNum提高指令并行度 instrParams.dstBlkStride = 1; instrParams.src0BlkStride = 1; - instrParams.src1BlkStride = 0; + instrParams.src1BlkStride = 0; // src1(广播向量)固定不变 instrParams.dstRepStride = dstRepStridePerLine; instrParams.src0RepStride = dstRepStridePerLine; - instrParams.src1RepStride = 1; + instrParams.src1RepStride = 1; // src1按Block递增跟随 for (uint32_t i = 0; i < numRepeatPerLine; i++) { Mul(output[i * elemInOneRepeat], input0[i * elemInOneRepeat], @@ -152,8 +192,10 @@ __aicore__ inline void MulABLastDimBrcInline(const LocalTensor& output, } } + // 处理每行尾部不足一个Repeat的剩余元素 if (numRemainPerLine > 0) { if (dstRepStridePerLine > MAX_REPEAT_STRIDE) { + // 步长超限:逐行处理尾部元素 instrParams.dstBlkStride = 1; instrParams.src0BlkStride = 1; instrParams.src1BlkStride = 0; @@ -169,12 +211,13 @@ __aicore__ inline void MulABLastDimBrcInline(const LocalTensor& output, instrParams); } } else { + // 步长不超限:一次性处理所有行的尾部元素 instrParams.dstBlkStride = 1; instrParams.src0BlkStride = 1; instrParams.src1BlkStride = 0; instrParams.dstRepStride = dstRepStridePerLine; instrParams.src0RepStride = dstRepStridePerLine; - instrParams.src1RepStride = 1; + instrParams.src1RepStride = 0; Mul(output[numRepeatPerLine * elemInOneRepeat], input0[numRepeatPerLine * elemInOneRepeat], tmpBuffer, @@ -187,6 +230,9 @@ __aicore__ inline void MulABLastDimBrcInline(const LocalTensor& output, PipeBarrier(); } +// ==================== 末维广播减法 ==================== +// 与MulABLastDimBrcInline结构完全相同,仅将Mul替换为Sub +// output[dim0, dim1] = input0[dim0, dim1] - broadcast(input1[1, dim1]) template __aicore__ inline void SubABLastDimBrcInline(const LocalTensor& output, const LocalTensor& input0, @@ -285,6 +331,9 @@ __aicore__ inline void SubABLastDimBrcInline(const LocalTensor& output, PipeBarrier(); } +// ==================== 末维广播除法 ==================== +// 与MulABLastDimBrcInline结构完全相同,仅将Mul替换为Div +// output[dim0, dim1] = input0[dim0, dim1] / broadcast(input1[1, dim1]) template __aicore__ inline void DivABLastDimBrcInline(const LocalTensor& output, const LocalTensor& input0, @@ -383,6 +432,12 @@ __aicore__ inline void DivABLastDimBrcInline(const LocalTensor& output, PipeBarrier(); } +// ==================== 首维广播加法 ==================== + +// output[dim0, dim1] = input0[dim0, dim1] + broadcast(input1[1, dim1]) +// 将一维向量input1沿第0维广播后加到input0的每一行 +// 与MulABLastDimBrcInline不同:此处input1不需要Brcb预广播,直接作为src1(src1BlkStride=1) +// 参数: curRowNum=行数(dim0), curColNum=列数(dim1) template __aicore__ inline void AddBAFirstDimBrcInline(const LocalTensor& output, const LocalTensor& input0, @@ -467,43 +522,56 @@ __aicore__ inline void AddBAFirstDimBrcInline(const LocalTensor& output, PipeBarrier(); } +// ==================== Sigmoid优化实现 ==================== + +// 计算sigmoid分母: output = 1 + exp(-x) +// 分三步: x取负(-1*x) → exp(-x) → +1 +// 用于后续SigmoidPerf中的除法计算: sigmoid(x) = 1 / (1 + exp(-x)) template __aicore__ inline void CalcDenominator(const LocalTensor& output, const LocalTensor& input, const uint32_t calCount) { - Muls(output, input, static_cast(-1.0), calCount); + Muls(output, input, static_cast(-1.0), calCount); // output = -x PipeBarrier(); - Exp(output, output, calCount); + Exp(output, output, calCount); // output = exp(-x) PipeBarrier(); - Adds(output, output, static_cast(1.0), calCount); + Adds(output, output, static_cast(1.0), calCount); // output = 1 + exp(-x) PipeBarrier(); } +// 优化版sigmoid: sigmoid(x) = 1 / (1 + exp(-x)) +// 相比原生Exp+Div实现,利用Duplicate生成常数1再用Div计算,减少一次标量运算 // 暂时不处理repeat超限场景 +// 参数: calCount=元素总数, tmpBuffer用于存放常数1.0 template __aicore__ inline void SigmoidPerf(const LocalTensor& output, const LocalTensor& input, const LocalTensor& tmpBuffer, const int64_t calCount) { uint32_t elemInOneBlock = BLOCK_SIZE / sizeof(T); - Duplicate(tmpBuffer, static_cast(1.0), elemInOneBlock); - CalcDenominator(output, input, calCount); + Duplicate(tmpBuffer, + static_cast(1.0), + elemInOneBlock); // 生成常数1.0(只需一个Block大小) + CalcDenominator(output, input, calCount); // output = 1 + exp(-x) uint32_t elemInOneRepeat = REPEAT_SIZE / sizeof(T); - int32_t numRepeatPerLine = calCount / elemInOneRepeat; - int32_t numRemainPerLine = calCount % elemInOneRepeat; + int32_t numRepeatPerLine = calCount / elemInOneRepeat; // 完整Repeat数 + int32_t numRemainPerLine = calCount % elemInOneRepeat; // 尾部剩余元素数 BinaryRepeatParams instrParams; + // src0(常数1)的Block步长=0, Repeat步长=0 → 保持固定;src1(分母)正常递进 instrParams.dstBlkStride = 1; instrParams.src0BlkStride = 0; instrParams.src1BlkStride = 1; instrParams.dstRepStride = DEFAULT_REPEAT_STRIDE; instrParams.src0RepStride = 0; instrParams.src1RepStride = DEFAULT_REPEAT_STRIDE; + // 整除部分: output = 1 / (1 + exp(-x)) Div(output, tmpBuffer, output, elemInOneRepeat, numRepeatPerLine, instrParams); + // 尾部剩余部分 if (numRemainPerLine != 0) { Div(output[numRepeatPerLine * elemInOneRepeat], tmpBuffer, @@ -515,6 +583,17 @@ __aicore__ inline void SigmoidPerf(const LocalTensor& output, PipeBarrier(); } +// ==================== 超连接前处理核心计算 ==================== + +// 计算pre = sigmoid(mix * rsqrt * scale + base) + eps +// 参数说明: +// mixLocal: 输入混合向量(M×N),输出为中间结果 +// rsqrtLocal: RMSNorm的1/sqrt(mean+eps)值,沿行广播 +// hcBaseLocal: base偏置值(base0),沿行广播 +// scale: hc_scale[0]标量缩放系数 +// eps: 防止分母为0的小量 +// curRowNum, curColNum: 行数和列数 +// 计算步骤: mix *= rsqrt → mix *= scale → mix += base → sigmoid → pre += eps __aicore__ inline void ProcessPre(const LocalTensor& preLocal, const LocalTensor& mixLocal, const LocalTensor& hcBaseLocal, @@ -526,17 +605,30 @@ __aicore__ inline void ProcessPre(const LocalTensor& preLocal, const int32_t curRowNum, const int32_t curColNum) { int32_t curColNumAlign = RoundUp(curColNum); - MulABLastDimBrcInline( - mixLocal, mixLocal, rsqrtLocal, tmpBuffer0, curRowNum, curColNum); - Muls(mixLocal, mixLocal, scale, curRowNum * curColNumAlign); + MulABLastDimBrcInline(mixLocal, + mixLocal, + rsqrtLocal, + tmpBuffer0, + curRowNum, + curColNum); // mix *= rsqrt + Muls(mixLocal, mixLocal, scale, curRowNum * curColNumAlign); // mix *= scale PipeBarrier(); AddBAFirstDimBrcInline( - mixLocal, mixLocal, hcBaseLocal, curRowNum, curColNum); - SigmoidPerf(preLocal, mixLocal, tmpBuffer1, curRowNum * curColNumAlign); - Adds(preLocal, preLocal, eps, curRowNum * curColNumAlign); + mixLocal, mixLocal, hcBaseLocal, curRowNum, curColNum); // mix += base + SigmoidPerf(preLocal, + mixLocal, + tmpBuffer1, + curRowNum * curColNumAlign); // pre = sigmoid(mix) + Adds(preLocal, preLocal, eps, curRowNum * curColNumAlign); // pre += eps PipeBarrier(); } +// ==================== 沿dim1轴归约求和 ==================== + +// All-Reduce-Along dim1: output[dim0, dim2] = Σ_j input[dim0, j, dim2] +// 将3D张量(dim0, dim1, dim2)沿中间维度dim1求和,输出2D张量(dim0, dim2) +// 用于K-split多核归约:多个核各算一部分K,最后在此求和合并 +// 参数: dim0=批次, dim1=K-split核数(归约轴), dim2=每核输出大小 __aicore__ inline void ReduceSumARAPerf(const LocalTensor& output, const LocalTensor& input, const uint32_t dim0, @@ -546,17 +638,18 @@ __aicore__ inline void ReduceSumARAPerf(const LocalTensor& output, uint32_t elemInOneRepeat = REPEAT_SIZE / sizeof(float); uint32_t dim2Align = RoundUp(dim2); - // 拷贝第一个R到output上 + // 拷贝第一个R到output上(作为累加初始值) DataCopyParams copyParams; copyParams.blockCount = dim0; copyParams.blockLen = dim2Align / elemInOneBlock; - copyParams.srcStride = (dim1 - 1) * (dim2Align / elemInOneBlock); + copyParams.srcStride = + (dim1 - 1) * (dim2Align / elemInOneBlock); // 跳过dim1-1个dim2块 copyParams.dstStride = 0; DataCopy(output, input, copyParams); PipeBarrier(); uint32_t dim2RepeatTimes = dim2 / elemInOneRepeat; uint32_t dim2Reminder = dim2 % elemInOneRepeat; - // 沿着dim2方向开repeat + // 沿着dim2方向开repeat(每个元素累加) BinaryRepeatParams instrParams; instrParams.dstBlkStride = 1; instrParams.src0BlkStride = 1; @@ -564,6 +657,9 @@ __aicore__ inline void ReduceSumARAPerf(const LocalTensor& output, instrParams.dstRepStride = DEFAULT_REPEAT_STRIDE; instrParams.src0RepStride = DEFAULT_REPEAT_STRIDE; instrParams.src1RepStride = DEFAULT_REPEAT_STRIDE; + // 对每个dim0批次,遍历dim1(从1开始)累加到output。 + // 连续 Add 对同一 output 读改写时,后一条指令可能在前一条写回前读取数据。 + // 每轮累加后同步 Vector 流水,避免归约结果错误。 for (uint32_t i = 0; i < dim0; i++) { for (uint32_t j = 1; j < dim1; j++) { Add(output[i * dim2Align], @@ -587,15 +683,62 @@ __aicore__ inline void ReduceSumARAPerf(const LocalTensor& output, PipeBarrier(); } +// Sinkhorn 的列归约固定为 4x4。专用路径保持与通用归约相同的 +// 左到右累加顺序,但省去首行 DataCopy 和每个加数后的 barrier。 +__aicore__ inline void ReduceSum4x4Perf(const LocalTensor& output, + const LocalTensor& input, + const uint32_t dim0) { + constexpr uint32_t dim2 = 4; + const uint32_t dim2Align = RoundUp(dim2); + for (uint32_t i = 0; i < dim0; i++) { + const uint32_t inOffset = i * dim2 * dim2Align; + const uint32_t outOffset = i * dim2Align; + Add(output[outOffset], input[inOffset], input[inOffset + dim2Align], dim2); + Add(output[outOffset], + output[outOffset], + input[inOffset + 2 * dim2Align], + dim2); + Add(output[outOffset], + output[outOffset], + input[inOffset + 3 * dim2Align], + dim2); + } + PipeBarrier(); +} + +// ==================== 二维Cast类型转换 ==================== + +// 将2D张量从T1类型转换到T0类型,逐行处理 +// 参数: dim0=行数, dim1=列数 +// bfloat16→float使用CAST_NONE(无损),其他类型使用CAST_RINT(四舍五入) +// syncAfter=false: 跳过尾部PipeBarrier, 由调用方合并同步点或依赖队列 +// 事件(EnQue的V_MTE3)兜底——用于连续Cast与Brcb等dst互不重叠的指令 +// 并行发射后统一一次屏障(见ProcessYHc4), 减少热路径屏障密度. template __aicore__ inline void CastTwoDim(const LocalTensor& output, const LocalTensor& input, const uint32_t dim0, - const uint32_t dim1) { - uint32_t dim1AlignT0 = RoundUp(dim1); - uint32_t dim1AlignT1 = RoundUp(dim1); + const uint32_t dim1, + const bool syncAfter = true) { + uint32_t dim1AlignT0 = RoundUp(dim1); // 输出类型对齐后的列数 + uint32_t dim1AlignT1 = RoundUp(dim1); // 输入类型对齐后的列数 + // 对齐的连续二维 tile 可以一次完成 Cast,避免在 Stage1 和 ProcessY + // 中为每一行生成独立的 Vector 指令与循环控制。 + if (dim1AlignT0 == dim1 && dim1AlignT1 == dim1) { + if constexpr (IsSameType::value && + IsSameType::value) { + Cast(output, input, AscendC::RoundMode::CAST_NONE, dim0 * dim1); + } else { + Cast(output, input, AscendC::RoundMode::CAST_RINT, dim0 * dim1); + } + if (syncAfter) { + PipeBarrier(); + } + return; + } if constexpr (IsSameType::value && IsSameType::value) { + // bf16→fp32: 无需舍入模式,直接转换(无损扩展) for (uint32_t i = 0; i < dim0; i++) { Cast(output[i * dim1AlignT0], input[i * dim1AlignT1], @@ -603,6 +746,7 @@ __aicore__ inline void CastTwoDim(const LocalTensor& output, dim1); } } else { + // 其他类型转换: 使用CAST_RINT(四舍五入到最近偶数) for (uint32_t i = 0; i < dim0; i++) { Cast(output[i * dim1AlignT0], input[i * dim1AlignT1], @@ -610,7 +754,108 @@ __aicore__ inline void CastTwoDim(const LocalTensor& output, dim1); } } + if (syncAfter) { + PipeBarrier(); + } +} + +// ==================== 计算输出y ==================== + +// 计算 y = Σ_{j=0}^{hc_mult-1} (weight[:,j] * x[:,j,:]) +// 权重由调用方传入:普通路径使用 pre,preMix 路径使用 preMix。 +// hc_mult=4 时使用融合乘加;其他情况逐元素乘权重后沿 hc_mult 维度归约。 +// 参数: dim0=batch数, dim1=hc_mult, dim2=d_factor +// Brcb 后每路权重仅占一个 Block;src1BlkStride=0 使权重在整行内复用, +// 避免按连续地址读取时跨入下一路权重。 +// 每个 pass 处理一路权重;pass 间用 PipeBarrier 同步对 y 的读改写。 +template +__aicore__ void inline ProcessYHc4(const LocalTensor& yLocal, + const LocalTensor& xLocal, + const LocalTensor& mix01Local, + const LocalTensor& hcBrcbLocal1, + const LocalTensor& xCastLocal, + const LocalTensor& yCastLocal, + const uint32_t dim0, + const uint32_t dim2, + const bool needBrc = true) { + const uint32_t rows = dim0 * 4; + const uint32_t dim2Align = RoundUp(dim2); + const uint32_t elemInOneBlock = BLOCK_SIZE / sizeof(float); + const uint32_t elemInOneRepeat = REPEAT_SIZE / sizeof(float); + const uint32_t repeatTimes = CeilDiv(rows, ONE_REPEAT_BLOCK_NUMS); + + // Cast(xCast)与Brcb(hcBrcbLocal1)写不同dst, 可并行发射, 合并为一个 + // 同步点(Mul需两者都完成才可取数)——相比各自屏障省一次V流水排空. + // 尾部Cast(yLocal)同样免屏障: Pass3后的屏障已保证MulAddDst写回, + // yLocal→CopyOut的可见性由yQue.EnQue的V_MTE3事件保证. + CastTwoDim(xCastLocal, xLocal, rows, dim2, /*syncAfter=*/false); + if (needBrc) { + Brcb(hcBrcbLocal1, + mix01Local, + repeatTimes, + {DEFAULT_BLOCK_STRIDE, DEFAULT_REPEAT_STRIDE}); + } + PipeBarrier(); + BinaryRepeatParams instrParams; + instrParams.dstBlkStride = 1; + instrParams.src0BlkStride = 1; + instrParams.src1BlkStride = 0; // 权重块(8个相同值)在行内所有Block间复用 + instrParams.dstRepStride = DEFAULT_REPEAT_STRIDE; // repeat 沿列方向连续推进 + instrParams.src0RepStride = DEFAULT_REPEAT_STRIDE; + instrParams.src1RepStride = 0; + const uint32_t nRep = dim2 / elemInOneRepeat; + const uint32_t rem = dim2 % elemInOneRepeat; + + // Pass 0: 第0路乘法 y = x0 * w0 + for (uint32_t i = 0; i < dim0; i++) { + const uint32_t xOffset = i * 4 * dim2Align; + const uint32_t yOffset = i * dim2Align; + const uint32_t weightOffset = i * 4 * elemInOneBlock; + if (nRep > 0) { + Mul(yCastLocal[yOffset], + xCastLocal[xOffset], + hcBrcbLocal1[weightOffset], + elemInOneRepeat, + nRep, + instrParams); + } + if (rem > 0) { + Mul(yCastLocal[yOffset + nRep * elemInOneRepeat], + xCastLocal[xOffset + nRep * elemInOneRepeat], + hcBrcbLocal1[weightOffset], + rem, + 1, + instrParams); + } + } PipeBarrier(); + // Pass k=1..3: 乘加 y += xk * wk (pass 内各行独立, pass 间屏障隔离读改写) + for (uint32_t k = 1; k < 4; k++) { + for (uint32_t i = 0; i < dim0; i++) { + const uint32_t xOffset = i * 4 * dim2Align + k * dim2Align; + const uint32_t yOffset = i * dim2Align; + const uint32_t weightOffset = i * 4 * elemInOneBlock + k * elemInOneBlock; + if (nRep > 0) { + MulAddDst(yCastLocal[yOffset], + xCastLocal[xOffset], + hcBrcbLocal1[weightOffset], + static_cast(elemInOneRepeat), + nRep, + instrParams); + } + if (rem > 0) { + MulAddDst(yCastLocal[yOffset + nRep * elemInOneRepeat], + xCastLocal[xOffset + nRep * elemInOneRepeat], + hcBrcbLocal1[weightOffset], + static_cast(rem), + 1, + instrParams); + } + } + PipeBarrier(); + } + // 尾Cast免屏障(见函数头说明): yLocal的GM可见性由yQue.EnQue事件保证. + CastTwoDim(yLocal, yCastLocal, dim0, dim2, /*syncAfter=*/false); } template @@ -623,74 +868,43 @@ __aicore__ void inline ProcessY(const LocalTensor& yLocal, const uint32_t dim0, const uint32_t dim1, const uint32_t dim2, - const uint32_t mixRowStride) { + const bool needBrc = true) { if (dim1 == 4) { - // Match the four-stream collapse: retain the accumulator through each - // multiply-add instead of rounding four products before the reduction. - CastTwoDim(xCastLocal, xLocal, dim0 * dim1, dim2); - const uint32_t hidden_stride = RoundUp(dim2); - BinaryRepeatParams params; - params.dstBlkStride = 1; - params.src0BlkStride = 1; - params.src1BlkStride = 0; - params.dstRepStride = DEFAULT_REPEAT_STRIDE; - params.src0RepStride = DEFAULT_REPEAT_STRIDE; - params.src1RepStride = 0; - const bool packed_mix = mixRowStride == 4; - if (packed_mix) { - Brcb(hcBrcbLocal1, - mix01Local, - CeilDiv(dim0 * 4, 8), - {DEFAULT_BLOCK_STRIDE, DEFAULT_REPEAT_STRIDE}); - PipeBarrier(); - } - for (uint32_t row = 0; row < dim0; ++row) { - if (!packed_mix) { - Brcb(hcBrcbLocal1, - mix01Local[row * mixRowStride], - 1, - {DEFAULT_BLOCK_STRIDE, DEFAULT_REPEAT_STRIDE}); - PipeBarrier(); - } - for (uint32_t stream = 0; stream < 4; ++stream) { - for (uint32_t offset = 0; offset < dim2; offset += 64) { - const uint32_t remaining = dim2 - offset; - const uint64_t count = remaining < 64 ? remaining : 64; - auto destination = yCastLocal[row * hidden_stride + offset]; - auto source = xCastLocal[(row * 4 + stream) * hidden_stride + offset]; - auto weight = - hcBrcbLocal1[(packed_mix ? row * 4 * 8 : 0) + stream * 8]; - if (stream == 0) { - Mul(destination, source, weight, count, 1, params); - } else { - MulAddDst(destination, source, weight, count, 1, params); - } - } - PipeBarrier(); - } - } - CastTwoDim(yLocal, yCastLocal, dim0, dim2); + ProcessYHc4(yLocal, + xLocal, + mix01Local, + hcBrcbLocal1, + xCastLocal, + yCastLocal, + dim0, + dim2, + needBrc); return; } - CastTwoDim(xCastLocal, xLocal, dim0 * dim1, dim2); - if (mixRowStride == dim1) { - MulABLastDimBrcInline( - xCastLocal, xCastLocal, mix01Local, hcBrcbLocal1, dim0 * dim1, dim2); - } else { - const uint32_t hiddenRowStride = dim1 * RoundUp(dim2); - for (uint32_t row = 0; row < dim0; ++row) { - MulABLastDimBrcInline(xCastLocal[row * hiddenRowStride], - xCastLocal[row * hiddenRowStride], - mix01Local[row * mixRowStride], - hcBrcbLocal1, - dim1, - dim2); - } - } - ReduceSumARAPerf(yCastLocal, xCastLocal, dim0, dim1, dim2); - CastTwoDim(yLocal, yCastLocal, dim0, dim2); + CastTwoDim(xCastLocal, xLocal, dim0 * dim1, dim2); // 1. x bf16→fp32 + MulABLastDimBrcInline(xCastLocal, + xCastLocal, + mix01Local, + hcBrcbLocal1, + dim0 * dim1, + dim2); // 2. x_cast *= 输入权重 + ReduceSumARAPerf( + yCastLocal, xCastLocal, dim0, dim1, dim2); // 3. Σ沿hc_mult维度 + CastTwoDim(yLocal, yCastLocal, dim0, dim2); // 4. y fp32→bf16 } +// ==================== 计算输出post ==================== + +// 计算post = sigmoid(mix * rsqrt * scale + base) * 2 +// 对应计算公式步骤4中的post部分 +// 与ProcessPre结构相同,但最终是*2而非+eps +// 参数说明: +// mixLocal: 输入混合向量(M×N),输出为中间结果 +// rsqrtLocal: RMSNorm的1/sqrt(mean+eps)值,沿行广播 +// hcBaseLocal: base偏置值(base1),沿行广播 +// scale: hc_scale[1]标量缩放系数 +// needBrc=false: rsqrtLocal已由ProcessPre阶段广播好,无需再次Brcb +// 计算步骤: mix *= rsqrt → mix *= scale → mix += base → sigmoid → post *= 2 __aicore__ inline void ProcessPost(const LocalTensor& postLocal, const LocalTensor& mixLocal, const LocalTensor& hcBaseLocal, @@ -701,20 +915,31 @@ __aicore__ inline void ProcessPost(const LocalTensor& postLocal, const int32_t curRowNum, const int32_t curColNum) { int32_t curColNumAlign = RoundUp(curColNum); - MulABLastDimBrcInline( - mixLocal, mixLocal, rsqrtLocal, tmpBuffer0, curRowNum, curColNum); - Muls(mixLocal, mixLocal, scale, curRowNum * curColNumAlign); + MulABLastDimBrcInline(mixLocal, + mixLocal, + rsqrtLocal, + tmpBuffer0, + curRowNum, + curColNum); // mix *= rsqrt (无需Brcb) + Muls(mixLocal, mixLocal, scale, curRowNum * curColNumAlign); // mix *= scale PipeBarrier(); AddBAFirstDimBrcInline( - mixLocal, mixLocal, hcBaseLocal, curRowNum, curColNum); - SigmoidPerf(postLocal, mixLocal, tmpBuffer1, curRowNum * curColNumAlign); + mixLocal, mixLocal, hcBaseLocal, curRowNum, curColNum); // mix += base + SigmoidPerf(postLocal, + mixLocal, + tmpBuffer1, + curRowNum * curColNumAlign); // post = sigmoid(mix) Muls(postLocal, postLocal, static_cast(2.0f), - curRowNum * curColNumAlign); + curRowNum * curColNumAlign); // post *= 2 PipeBarrier(); } +// ==================== 末维归约Max/Sum ==================== + +// 沿最后一维求最大值: output[curRowNum] = max(input[curRowNum, curColNum]) +// 使用WholeReduceMax,输出仅为值(不含索引) __aicore__ inline void LastDimReduceMaxPerf(const LocalTensor& output, const LocalTensor& input, const uint32_t curRowNum, @@ -731,6 +956,8 @@ __aicore__ inline void LastDimReduceMaxPerf(const LocalTensor& output, PipeBarrier(); } +// 沿最后一维求和: output[curRowNum] = Σ input[curRowNum, curColNum] +// 使用WholeReduceSum __aicore__ inline void LastDimReduceSumPerf(const LocalTensor& output, const LocalTensor& input, const uint32_t curRowNum, @@ -746,7 +973,13 @@ __aicore__ inline void LastDimReduceSumPerf(const LocalTensor& output, PipeBarrier(); } -// 暂时只支持R轴小于64,既curColNum不能超过64 +// ==================== FP32 Softmax ==================== + +// 沿最后一维计算softmax: output = softmax(input) + eps +// 对应计算公式步骤4中的comb_frag部分(softmax+Sinkhorn迭代的第一步) +// 暂时只支持R轴(末维)小于64, 即curColNum不能超过64 +// 计算步骤: max → sub(max) → exp → sum → div(sum) → +eps +// 参数: curRowNum=行数, curColNum=列数(=hc_mult), eps=防0小量 __aicore__ inline void SoftmaxFP32Perf( const LocalTensor& output, const LocalTensor& input, @@ -755,21 +988,38 @@ __aicore__ inline void SoftmaxFP32Perf( const int32_t curRowNum, const int32_t curColNum, float eps) { - LastDimReduceMaxPerf(tmpReduceBuffer, input, curRowNum, curColNum); - SubABLastDimBrcInline( - output, input, tmpReduceBuffer, tmpBrcbBuffer, curRowNum, curColNum); + LastDimReduceMaxPerf( + tmpReduceBuffer, input, curRowNum, curColNum); // 1. 求每行最大值 + SubABLastDimBrcInline(output, + input, + tmpReduceBuffer, + tmpBrcbBuffer, + curRowNum, + curColNum); // 2. 减去最大值(数值稳定) uint32_t curColNumAlign = RoundUp(curColNum); - Exp(output, output, curRowNum * curColNumAlign); + Exp(output, output, curRowNum * curColNumAlign); // 3. 求exp PipeBarrier(); - LastDimReduceSumPerf(tmpReduceBuffer, output, curRowNum, curColNum); - DivABLastDimBrcInline( - output, output, tmpReduceBuffer, tmpBrcbBuffer, curRowNum, curColNum); - Adds(output, output, eps, curRowNum * curColNumAlign); + LastDimReduceSumPerf( + tmpReduceBuffer, output, curRowNum, curColNum); // 4. 求每行和 + DivABLastDimBrcInline(output, + output, + tmpReduceBuffer, + tmpBrcbBuffer, + curRowNum, + curColNum); // 5. 除以和(归一化) + Adds(output, + output, + eps, + curRowNum * curColNumAlign); // 6. +eps(用于Sinkhorn迭代防0) PipeBarrier(); } -// (bs, hc_mult, hc_mult) = (bs, hc_mult, hc_mult) + (bs, 1, hc_mult) +// ==================== 三维广播除法(用于Sinkhorn迭代) ==================== +// output[dim0, dim1, dim2] = input0[dim0, dim1, dim2] / input1[dim0, 1, dim2] +// input1沿dim1方向广播后与input0逐元素相除 +// 用于Sinkhorn迭代的行归一化: comb_frag(bs, hc_mult, hc_mult) /= row_sum(bs, 1, +// hc_mult) 参数: dim0=bs, dim1=hc_mult, dim2=hc_mult template __aicore__ inline void DivABABrcInline(const LocalTensor& output, const LocalTensor& input0, @@ -786,12 +1036,13 @@ __aicore__ inline void DivABABrcInline(const LocalTensor& output, // 在dim1方向开repeat BinaryRepeatParams instrParams; if (dim1 >= dim2RepeatTimes) { + // 策略1:在dim1方向开Repeat(src1的Repeat步长=0,沿dim1不移动) instrParams.dstBlkStride = 1; instrParams.src0BlkStride = 1; instrParams.src1BlkStride = 1; instrParams.dstRepStride = dim2RepeatStride; instrParams.src0RepStride = dim2RepeatStride; - instrParams.src1RepStride = 0; + instrParams.src1RepStride = 0; // src1沿dim1不移动(广播) for (uint32_t i = 0; i < dim0; i++) { for (uint32_t j = 0; j < dim2RepeatTimes; j++) { Div(output[i * dim1 * dim2Align + j * elemInOneRepeat], @@ -811,7 +1062,7 @@ __aicore__ inline void DivABABrcInline(const LocalTensor& output, } } } else { - // 在dim2方向开repeat + // 策略2:在dim2方向开repeat(逐dim1行处理,src1固定为对应dim0的行向量) instrParams.dstBlkStride = 1; instrParams.src0BlkStride = 1; instrParams.src1BlkStride = 1; @@ -830,6 +1081,12 @@ __aicore__ inline void DivABABrcInline(const LocalTensor& output, PipeBarrier(); } +// ==================== GM↔UB数据搬运工具 ==================== + +// 从Global Memory拷贝数据到UB(LocalTensor) +// 使用DataCopyPad支持非对齐长度的数据拷贝 +// 参数: nBurst=数据块数(行数), copyLen=每行元素数, srcStride=源行间间隔, +// dstStride=目的行间间隔(以Block为单位) template __aicore__ inline void CopyIn(const GlobalTensor& inputGm, const LocalTensor& inputTensor, @@ -852,7 +1109,9 @@ __aicore__ inline void CopyIn(const GlobalTensor& inputGm, DataCopyPad(inputTensor, inputGm, dataCoptExtParams, dataCopyPadExtParams); } -// (bs, hc_mult, hc_mult) --> (bs, hc_mult, hc_mult_align) +// 3D数据拷贝: (outerLoop, nBurst, gmLastDim) → UB (outerLoop, nBurst, +// ubLastDimAlign) 外层循环按outerLoop遍历,每层调用CopyIn拷贝nBurst行 +// 适用于GM和UB最后一维长度不同(UB有对齐padding)的场景 template __aicore__ inline void CopyInWithOuterFor(const GlobalTensor& inputGm, const LocalTensor& inputTensor, @@ -871,6 +1130,11 @@ __aicore__ inline void CopyInWithOuterFor(const GlobalTensor& inputGm, } } +// 4D数据拷贝: (outerLoop, gmFirstDim, gmLastDim) → UB (outerLoop, nBurst, +// ubLastDimAlign) +// 支持非连续内存访问模式,根据outerLoop与nBurst的大小关系选择不同遍历策略 +// 当outerLoop <= nBurst时:按outerLoop遍历,每次取nBurst行 +// 当outerLoop > nBurst时:按nBurst遍历,每次取outerLoop个分散数据段 template __aicore__ inline void CopyInWithOuterFor(const GlobalTensor& inputGm, const LocalTensor& inputTensor, @@ -903,6 +1167,9 @@ __aicore__ inline void CopyInWithOuterFor(const GlobalTensor& inputGm, } } +// 从UB(LocalTensor)拷贝数据到Global Memory +// 参数: nBurst=数据块数(行数), copyLen=每行元素数, +// dstStride=目的行间间隔(以字节为单位) template __aicore__ inline void CopyOut(const LocalTensor& outputTensor, const GlobalTensor& outputGm, diff --git a/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_cube_compute.h b/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_cube_compute.h index 2b0079a853..eaf93574c4 100644 --- a/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_cube_compute.h +++ b/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_cube_compute.h @@ -61,13 +61,21 @@ class HcCubeCompute { TPipe* tpipe); __aicore__ inline void ComputeDecode( const AscendC::GlobalTensor& xGm, + const AscendC::GlobalTensor& nextXGm, const AscendC::GlobalTensor& workspaceGlobalA2, const AscendC::GlobalTensor& workspaceGlobalAB, - const MmParams& mmParams); + const MmParams& mmParams, + bool a1Preloaded, + bool preloadNextTile, + uint64_t nextB1Offset, + uint64_t nextB1Size); __aicore__ inline void CopyInB1(uint64_t mGmOffset, uint64_t kGmOffset, uint64_t kL1Size, const MmParams& mmParams); + __aicore__ inline void PreloadNextB1(uint64_t kGmOffset, + uint64_t kL1Size, + const MmParams& mmParams); __aicore__ inline void SetBL1Mte1ToMte2Flag(); __aicore__ inline void WaitBL1Mte1ToMte2Flag(); __aicore__ inline void End(); @@ -108,6 +116,10 @@ class HcCubeCompute { uint64_t kL0Size, bool isLastK, const MmParams& mmParams); + __aicore__ inline void ComputeL0Pairs(uint64_t l1BaseKOffset, + uint64_t curKL1Size, + bool closeAccumulator, + const MmParams& mmParams); TPipe* pipe_; const HcPreVaTilingData* tiling_; @@ -124,11 +136,16 @@ class HcCubeCompute { GlobalTensor yGm_; static constexpr uint64_t MM1_MTE2_MTE1_EVENT = 2; + static constexpr uint64_t B_MTE2_MTE1_EVENT = 4; static constexpr uint64_t X_MTE1_MTE2_EVENT = 2; static constexpr uint64_t B_MTE1_MTE2_EVENT = 4; static constexpr uint64_t M_MTE1_EVENT_L0A = 3; static constexpr uint64_t M_MTE1_EVENT_L0B = 5; + // Keep the MTE1->M flag tied to the L0B slot. A2 and AB use different + // double-buffer slots, so sharing one event serializes otherwise + // independent Mmad launches. static constexpr uint64_t MTE1_M_EVENT = 2; + static constexpr uint64_t SYNC_AIV_TO_AIC_FLAG = 8; static constexpr uint64_t L1_BUF_NUM = 2; static constexpr uint64_t L0A_BUF_NUM = 2; @@ -202,6 +219,7 @@ __aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::Init( SetFlag(X_MTE1_MTE2_EVENT + i); SetFlag(B_MTE1_MTE2_EVENT + i); } + AscendC::SetHF32TransMode(1); } HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_PARAM @@ -242,6 +260,28 @@ __aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::CopyInB1( DataCopy(l1b_[(l1bLoopIdx_ % L1_BUF_NUM) * L1_BUF_OFFSET], fnGm_[kGmOffset], nd2nzParams); + SetFlag(B_MTE2_MTE1_EVENT + l1bLoopIdx_ % L1_BUF_NUM); +} + +HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_PARAM +__aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::PreloadNextB1( + uint64_t kGmOffset, + uint64_t kL1Size, + const MmParams& mmParams) { + uint64_t nextB1Idx = (l1bLoopIdx_ + 1) % L1_BUF_NUM; + WaitFlag(B_MTE1_MTE2_EVENT + nextB1Idx); + + AscendC::Nd2NzParams nd2nzParams; + nd2nzParams.ndNum = 1; + nd2nzParams.nValue = mmParams.curNL1; + nd2nzParams.dValue = kL1Size; + nd2nzParams.srcNdMatrixStride = 1; + nd2nzParams.srcDValue = mmParams.kGmSize; + nd2nzParams.dstNzC0Stride = CeilAlign(mmParams.curNL1, BLOCK_CUBE); + nd2nzParams.dstNzNStride = 1; + nd2nzParams.dstNzMatrixStride = 1; + DataCopy(l1b_[nextB1Idx * L1_BUF_OFFSET], fnGm_[kGmOffset], nd2nzParams); + SetFlag(B_MTE2_MTE1_EVENT + nextB1Idx); } HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_PARAM @@ -291,7 +331,7 @@ __aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::Fixp( mmParams.curML1, mmParams.curNL1, true, - mmParams.nOutSize); // ND M/N are 512B aligned. + mmParams.nOutSize); // ND row stride is aligned to 512B. } HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_PARAM @@ -307,23 +347,95 @@ HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::WaitBL1Mte1ToMte2Flag() { WaitFlag(B_MTE1_MTE2_EVENT + l1bLoopIdx_ % L1_BUF_NUM); } +HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_PARAM +__aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::ComputeL0Pairs( + uint64_t l1BaseKOffset, + uint64_t curKL1Size, + bool closeAccumulator, + const MmParams& mmParams) { + for (uint64_t kL1Offset = 0; kL1Offset < curKL1Size; + kL1Offset += K_L0_SIZE * 2) { + uint64_t firstKOffset = l1BaseKOffset + kL1Offset; + bool firstIsLast = closeAccumulator && kL1Offset + K_L0_SIZE >= curKL1Size; + + WaitFlag(M_MTE1_EVENT_L0A + l0aLoopIdx_ % L0A_BUF_NUM); + LoadAToL0A(kL1Offset, K_L0_SIZE, l1aLoopIdx_, mmParams); + + WaitFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); + LoadAToL0B(kL1Offset, K_L0_SIZE, l1aLoopIdx_, mmParams); + MmadA2(firstKOffset, K_L0_SIZE, firstIsLast, mmParams); + SetFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); + l0bLoopIdx_++; + + WaitFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); + LoadBToL0B( + firstKOffset % mmParams.xWsKSize, K_L0_SIZE, l1bLoopIdx_, mmParams); + AscendC::SetHF32Mode(1); + MmadAB(firstKOffset, K_L0_SIZE, firstIsLast, mmParams); + AscendC::SetHF32Mode(0); + SetFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); + l0bLoopIdx_++; + SetFlag(M_MTE1_EVENT_L0A + l0aLoopIdx_ % L0A_BUF_NUM); + l0aLoopIdx_++; + + uint64_t secondKL1Offset = kL1Offset + K_L0_SIZE; + if (secondKL1Offset >= curKL1Size) { + AscendC::SetHF32Mode(0); + continue; + } + + uint64_t secondKOffset = l1BaseKOffset + secondKL1Offset; + bool secondIsLast = + closeAccumulator && secondKL1Offset + K_L0_SIZE >= curKL1Size; + WaitFlag(M_MTE1_EVENT_L0A + l0aLoopIdx_ % L0A_BUF_NUM); + LoadAToL0A(secondKL1Offset, K_L0_SIZE, l1aLoopIdx_, mmParams); + + WaitFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); + LoadAToL0B(secondKL1Offset, K_L0_SIZE, l1aLoopIdx_, mmParams); + MmadA2(secondKOffset, K_L0_SIZE, secondIsLast, mmParams); + SetFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); + l0bLoopIdx_++; + + WaitFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); + LoadBToL0B( + secondKOffset % mmParams.xWsKSize, K_L0_SIZE, l1bLoopIdx_, mmParams); + AscendC::SetHF32Mode(1); + MmadAB(secondKOffset, K_L0_SIZE, secondIsLast, mmParams); + SetFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); + l0bLoopIdx_++; + AscendC::SetHF32Mode(0); + SetFlag(M_MTE1_EVENT_L0A + l0aLoopIdx_ % L0A_BUF_NUM); + l0aLoopIdx_++; + } +} + HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_PARAM __aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::ComputeDecode( const AscendC::GlobalTensor& xGm, + const AscendC::GlobalTensor& nextXGm, const AscendC::GlobalTensor& workspaceGlobalA2, const AscendC::GlobalTensor& workspaceGlobalAB, - const MmParams& mmParams) { - WaitFlag(X_MTE1_MTE2_EVENT + l1aLoopIdx_ % L1_BUF_NUM); + const MmParams& mmParams, + bool a1Preloaded, + bool preloadNextTile, + uint64_t nextB1Offset, + uint64_t nextB1Size) { + WaitFlag(B_MTE2_MTE1_EVENT + l1bLoopIdx_ % L1_BUF_NUM); uint64_t kGmOffset = 0; + bool nextB1Issued = false; uint64_t curKL1Size = (kGmOffset + mmParams.curKL1 >= mmParams.singleCoreK) ? (mmParams.singleCoreK - kGmOffset) : mmParams.curKL1; - CopyInA1(curKL1Size, - xGm[kGmOffset], - l1a_[(l1aLoopIdx_ % DOUBLE_BUFFER) * L1_BUF_OFFSET], - mmParams); - - SetFlag(MM1_MTE2_MTE1_EVENT + l1aLoopIdx_ % L1_BUF_NUM); + if (!a1Preloaded) { + WaitFlag(X_MTE1_MTE2_EVENT + + l1aLoopIdx_ % L1_BUF_NUM); + CopyInA1(curKL1Size, + xGm[kGmOffset], + l1a_[(l1aLoopIdx_ % DOUBLE_BUFFER) * L1_BUF_OFFSET], + mmParams); + SetFlag(MM1_MTE2_MTE1_EVENT + + l1aLoopIdx_ % L1_BUF_NUM); + } kGmOffset += mmParams.curKL1; while (kGmOffset < mmParams.singleCoreK) { WaitFlag(X_MTE1_MTE2_EVENT + @@ -338,77 +450,43 @@ __aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::ComputeDecode( SetFlag(MM1_MTE2_MTE1_EVENT + (l1aLoopIdx_ + 1) % L1_BUF_NUM); + if (preloadNextTile && kGmOffset + nextKL1Size >= mmParams.singleCoreK) { + // Queue the next B1 behind the final current-tile A1. + PreloadNextB1(nextB1Offset, nextB1Size, mmParams); + nextB1Issued = true; + } WaitFlag(MM1_MTE2_MTE1_EVENT + l1aLoopIdx_ % L1_BUF_NUM); - for (uint64_t kL1Offset = 0; kL1Offset < curKL1Size; - kL1Offset += K_L0_SIZE) { // K_L0_SIZE 32 - WaitFlag(M_MTE1_EVENT_L0A + l0aLoopIdx_ % L0A_BUF_NUM); - LoadAToL0A(kL1Offset, K_L0_SIZE, l1aLoopIdx_, mmParams); - - WaitFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); - LoadAToL0B(kL1Offset, K_L0_SIZE, l1aLoopIdx_, mmParams); - MmadA2( - kGmOffset + kL1Offset - mmParams.curKL1, K_L0_SIZE, false, mmParams); - SetFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); - l0bLoopIdx_++; - - WaitFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); - LoadBToL0B((kGmOffset + kL1Offset - mmParams.curKL1) % mmParams.xWsKSize, - K_L0_SIZE, - l1bLoopIdx_, - mmParams); - MmadAB( - kGmOffset + kL1Offset - mmParams.curKL1, K_L0_SIZE, false, mmParams); - SetFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); - l0bLoopIdx_++; - - SetFlag(M_MTE1_EVENT_L0A + l0aLoopIdx_ % L0A_BUF_NUM); - l0aLoopIdx_++; - } + ComputeL0Pairs(kGmOffset - mmParams.curKL1, curKL1Size, false, mmParams); SetFlag(X_MTE1_MTE2_EVENT + l1aLoopIdx_ % L1_BUF_NUM); l1aLoopIdx_++; kGmOffset += mmParams.curKL1; curKL1Size = nextKL1Size; } + if (preloadNextTile) { + // Keep the shared MTE2 queue bounded to the next B1 transfer and first + // A1 tile. Single-L1 tiles use this fallback to issue B1 here. + if (!nextB1Issued) { + PreloadNextB1(nextB1Offset, nextB1Size, mmParams); + } + CrossCoreWaitFlag(SYNC_AIV_TO_AIC_FLAG); + uint64_t nextA1Idx = (l1aLoopIdx_ + 1) % L1_BUF_NUM; + WaitFlag(X_MTE1_MTE2_EVENT + nextA1Idx); + uint64_t nextA1Size = + nextB1Size < mmParams.curKL1 ? nextB1Size : mmParams.curKL1; + CopyInA1(nextA1Size, nextXGm, l1a_[nextA1Idx * L1_BUF_OFFSET], mmParams); + SetFlag(MM1_MTE2_MTE1_EVENT + nextA1Idx); + } WaitFlag(MM1_MTE2_MTE1_EVENT + l1aLoopIdx_ % L1_BUF_NUM); - for (uint64_t kL1Offset = 0; kL1Offset < curKL1Size; kL1Offset += K_L0_SIZE) { - const uint64_t curKL0Size = - AscendC::Std::min(K_L0_SIZE, curKL1Size - kL1Offset); - const uint64_t loadKL0Size = CeilAlign(curKL0Size, 8); - WaitFlag(M_MTE1_EVENT_L0A + l0aLoopIdx_ % L0A_BUF_NUM); - LoadAToL0A(kL1Offset, loadKL0Size, l1aLoopIdx_, mmParams); - - WaitFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); - LoadAToL0B(kL1Offset, loadKL0Size, l1aLoopIdx_, mmParams); - MmadA2(kGmOffset + kL1Offset - mmParams.curKL1, - curKL0Size, - mmParams.isLastK && kL1Offset + K_L0_SIZE >= curKL1Size, - mmParams); - SetFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); - l0bLoopIdx_++; - - WaitFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); - LoadBToL0B((kGmOffset + kL1Offset - mmParams.curKL1) % mmParams.xWsKSize, - curKL0Size, - l1bLoopIdx_, - mmParams); // to l0b - MmadAB(kGmOffset + kL1Offset - mmParams.curKL1, - curKL0Size, - mmParams.isLastK && kL1Offset + K_L0_SIZE >= curKL1Size, - mmParams); - SetFlag(M_MTE1_EVENT_L0B + l0bLoopIdx_ % L0B_BUF_NUM); - l0bLoopIdx_++; - - SetFlag(M_MTE1_EVENT_L0A + l0aLoopIdx_ % L0A_BUF_NUM); - l0aLoopIdx_++; - } + ComputeL0Pairs( + kGmOffset - mmParams.curKL1, curKL1Size, mmParams.isLastK, mmParams); SetFlag(X_MTE1_MTE2_EVENT + l1aLoopIdx_ % L1_BUF_NUM); l1aLoopIdx_++; if (mmParams.isLastK) { - Fixp(workspaceGlobalA2, workspaceGlobalAB, mmParams); // l0cLoopIdx_++; + Fixp(workspaceGlobalA2, workspaceGlobalAB, mmParams); } } @@ -498,8 +576,9 @@ __aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::MmadA2( uint64_t kL0Size, bool isLastK, const MmParams& mmParams) { - SetFlag(MTE1_M_EVENT); - WaitFlag(MTE1_M_EVENT); + uint64_t mte1MEvent = MTE1_M_EVENT + (l0bLoopIdx_ % L0B_BUF_NUM); + SetFlag(mte1MEvent); + WaitFlag(mte1MEvent); for (uint64_t mL0Offset = 0; mL0Offset < mmParams.curML1; mL0Offset += BLOCK_CUBE) { MmadParams mmadParams; @@ -547,10 +626,9 @@ __aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::MmadAB( uint64_t kL0Size, bool isLastK, const MmParams& mmParams) { - SetFlag(MTE1_M_EVENT); - WaitFlag(MTE1_M_EVENT); - AscendC::SetHF32Mode(1); - AscendC::SetHF32TransMode(1); + uint64_t mte1MEvent = MTE1_M_EVENT + (l0bLoopIdx_ % L0B_BUF_NUM); + SetFlag(mte1MEvent); + WaitFlag(mte1MEvent); MmadParams mmadParams; mmadParams.m = CeilAlign(mmParams.curML1, BLOCK_CUBE); mmadParams.n = mmParams.curNL1; @@ -564,7 +642,6 @@ __aicore__ inline void HC_PRE_VA_CUBE_COMPUTE_TEMPLATE_CLASS::MmadAB( l0a_[(l0aLoopIdx_ % L0A_BUF_NUM) * L0AB_BUF_OFFSET], l0b_[(l0bLoopIdx_ % L0AB_BUF_NUM) * L0AB_BUF_OFFSET], mmadParams); - AscendC::SetHF32Mode(0); } } // namespace XllmKernelHcPreVa diff --git a/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_m_k_split_core.h b/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_m_k_split_core.h index 0f3f31c4c6..83dc4c261a 100644 --- a/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_m_k_split_core.h +++ b/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/hc_pre_va_m_k_split_core.h @@ -11,12 +11,12 @@ */ /*! - * \file hc_pre_va_m_k_split_core.h + * \file hc_pre_va_m_split_core.h * \brief */ -#ifndef HC_PRE_VA_M_K_SPLIT_CORE_H -#define HC_PRE_VA_M_K_SPLIT_CORE_H +#ifndef HC_PRE_VA_M_K_SPLIT_A3_CORE_H +#define HC_PRE_VA_M_K_SPLIT_A3_CORE_H #include "hc_pre_va_base.h" #include "hc_pre_va_cube_compute.h" @@ -78,121 +78,178 @@ class HcPreVaMembaseKSplitCorePart1 { pipe->InitBuffer(mmInQue, NUM_TWO, xQueNum * sizeof(float)); } - __aicore__ inline void Process() { - if ASCEND_IS_AIC { - // 初始设置 - CrossCoreSetFlag(SYNC_AIC_TO_AIV_FLAG); - CrossCoreSetFlag(SYNC_AIC_TO_AIV_FLAG); - } - + // 计算 (m,k) 网格分块索引与 GM 范围; curVectorBlockIdx 为 AIV 原始 + // blockIdx(奇偶分半用) + __aicore__ inline void GetMkBlockInfo(uint64_t& mGmBaseOffset, + uint64_t& mGmEndOffset, + uint64_t& kGmStartOffset, + uint64_t& kGmEndOffset, + uint64_t& curVectorBlockIdx) { uint64_t curBlockIdx = GetBlockIdx(); - uint64_t curVectorBlockIdx = curBlockIdx; + curVectorBlockIdx = curBlockIdx; if ASCEND_IS_AIV { curBlockIdx = curBlockIdx / NUM_TWO; } uint64_t mBlkDimIdx = curBlockIdx / tilingData->cubeBlockDimK; uint64_t kBlkDimIdx = curBlockIdx % tilingData->cubeBlockDimK; - uint64_t kGmStartOffset = tilingData->multCoreSplitKSize * kBlkDimIdx; - uint64_t kGmEndOffset = kGmStartOffset + tilingData->multCoreSplitKSize; - if (kGmEndOffset > tilingData->k) { - kGmEndOffset = tilingData->k; + kBlkDimIdx_ = kBlkDimIdx; + kGmStartOffset = tilingData->multCoreSplitKSize * kBlkDimIdx; + kGmEndOffset = kGmStartOffset + tilingData->multCoreSplitKSize; + if (kGmEndOffset > static_cast(tilingData->k)) { + kGmEndOffset = static_cast(tilingData->k); } - - uint64_t mGmBaseOffset = mBlkDimIdx * tilingData->multCoreSplitMSize; - uint64_t mGmEndOffset = mGmBaseOffset + tilingData->multCoreSplitMSize; - if (mGmEndOffset > tilingData->bs) { - mGmEndOffset = tilingData->bs; + mGmBaseOffset = mBlkDimIdx * tilingData->multCoreSplitMSize; + mGmEndOffset = mGmBaseOffset + tilingData->multCoreSplitMSize; + if (mGmEndOffset > static_cast(tilingData->bs)) { + mGmEndOffset = static_cast(tilingData->bs); } - for (uint64_t mGmOffset = mGmBaseOffset; mGmOffset < mGmEndOffset; - mGmOffset += tilingData->mL1Size) { - uint64_t realMSize = mGmOffset + tilingData->mL1Size > mGmEndOffset - ? mGmEndOffset - mGmOffset - : tilingData->mL1Size; - for (uint64_t kGmBaseOffset = kGmStartOffset; - kGmBaseOffset < kGmEndOffset; - kGmBaseOffset += tilingData->cvLoopKSize) { - uint64_t realKGmSize = - kGmBaseOffset + tilingData->cvLoopKSize > kGmEndOffset - ? kGmEndOffset - kGmBaseOffset - : tilingData->cvLoopKSize; - if ASCEND_IS_AIC { - MmParams mmParams; - mmParams.curML1 = realMSize; - mmParams.curKL1 = tilingData->kL1Size; - mmParams.curNL1 = N_SIZE; - mmParams.singleCoreK = realKGmSize; - mmParams.xWsKSize = tilingData->cvLoopKSize; - mmParams.nOutSize = mmOuterInnerSize_; - mmParams.kGmBaseOffset = kGmBaseOffset; - mmParams.nGmSize = N_SIZE; - mmParams.kGmSize = tilingData->k; - mmParams.isLastK = - kGmBaseOffset + tilingData->cvLoopKSize >= kGmEndOffset; - mmParams.isFirstK = kGmBaseOffset == kGmStartOffset; + } + + // 单个 m-chunk 的完整 k 循环(原 Process 的 m 循环体). b1/a1 预取状态每 chunk + // 组重置, 跨 m-chunk 调用间不残留预取依赖. cvLoopIdx_ 跨调用连续, 维持 ws1 双 + // buffer 槽位交替. + __aicore__ inline void ProcessMChunk(uint64_t mGmOffset, + uint64_t mGmEndOffset, + uint64_t kGmStartOffset, + uint64_t kGmEndOffset, + uint64_t curVectorBlockIdx) { + uint64_t realMSize = + mGmOffset + static_cast(tilingData->mL1Size) > mGmEndOffset + ? mGmEndOffset - mGmOffset + : static_cast(tilingData->mL1Size); + bool b1Prefetched = false; + bool a1Prefetched = false; + for (uint64_t kGmBaseOffset = kGmStartOffset; kGmBaseOffset < kGmEndOffset; + kGmBaseOffset += tilingData->cvLoopKSize) { + uint64_t realKGmSize = + kGmBaseOffset + tilingData->cvLoopKSize > kGmEndOffset + ? kGmEndOffset - kGmBaseOffset + : tilingData->cvLoopKSize; + if ASCEND_IS_AIC { + MmParams mmParams; + mmParams.curML1 = realMSize; + mmParams.curKL1 = tilingData->kL1Size; + mmParams.curNL1 = N_SIZE; + mmParams.singleCoreK = realKGmSize; + mmParams.xWsKSize = tilingData->cvLoopKSize; + mmParams.nOutSize = mmOuterInnerSize_; + mmParams.kGmBaseOffset = kGmBaseOffset; + mmParams.nGmSize = N_SIZE; + mmParams.kGmSize = tilingData->k; + mmParams.isLastK = + kGmBaseOffset + tilingData->cvLoopKSize >= kGmEndOffset; + mmParams.isFirstK = kGmBaseOffset == kGmStartOffset; + if (!b1Prefetched) { cubeCompute_.WaitBL1Mte1ToMte2Flag(); cubeCompute_.CopyInB1( mGmOffset, kGmBaseOffset, realKGmSize, mmParams); + } + + uint64_t nextB1Offset = kGmBaseOffset + tilingData->cvLoopKSize; + bool preloadNextB1 = nextB1Offset < kGmEndOffset; + uint64_t nextB1Size = 0; + if (preloadNextB1) { + uint64_t nextB1Remain = kGmEndOffset - nextB1Offset; + nextB1Size = + nextB1Remain < static_cast(tilingData->cvLoopKSize) + ? nextB1Remain + : static_cast(tilingData->cvLoopKSize); + } + if (!a1Prefetched) { CrossCoreWaitFlag(SYNC_AIV_TO_AIC_FLAG); - cubeCompute_.ComputeDecode( - xCastFp32WsGm[cvLoopIdx_ % DOUBLE_BUFFER * xCastFp32BufSize_], - squareSumFp32WsGm[kBlkDimIdx * squareSumFp32BufSize_ + - mGmOffset * BLOCK_CUBE], - mmOutFp32WsGm[kBlkDimIdx * mmOutFp32BufSize_ + - mGmOffset * mmOuterInnerSize_], - mmParams); - cubeCompute_.SetBL1Mte1ToMte2Flag(); - CrossCoreSetFlag(SYNC_AIC_TO_AIV_FLAG); - } else { - CrossCoreWaitFlag(SYNC_AIC_TO_AIV_FLAG); - // vec.compute(); - int64_t mVectorOffset = mGmOffset; - int64_t mVectorLength = (realMSize + 1) / NUM_TWO; - if ((curVectorBlockIdx % NUM_TWO) == 1) { - mVectorOffset = mGmOffset + (realMSize + 1) / NUM_TWO; - mVectorLength = realMSize - mVectorLength; - } - int64_t curUbLoops = (mVectorLength + tilingData->stage1MFactor - 1) / - tilingData->stage1MFactor; - int64_t curUbMfactorTail = - mVectorLength - ((curUbLoops - 1) * tilingData->stage1MFactor); - for (int64_t i = 0; i < curUbLoops; ++i) { - int64_t curUbMFactor = (i != (curUbLoops - 1)) - ? tilingData->stage1MFactor - : curUbMfactorTail; - xLocal = xQue.template AllocTensor(); - int64_t curGlobalxOffset = - (mVectorOffset + i * tilingData->stage1MFactor) * - tilingData->k + - kGmBaseOffset; - CopyIn(xGm[curGlobalxOffset], - xLocal, - curUbMFactor, - realKGmSize, - tilingData->k - realKGmSize); - xQue.template EnQue(xLocal); - xLocal = xQue.template DeQue(); - xCastLocal = mmInQue.AllocTensor(); - CastTwoDim(xCastLocal, xLocal, curUbMFactor, realKGmSize); - xQue.template FreeTensor(xLocal); - mmInQue.template EnQue(xCastLocal); - xCastLocal = mmInQue.template DeQue(); - int64_t cutMmInOffset = - cvLoopIdx_ % DOUBLE_BUFFER * xCastFp32BufSize_ + - (i * tilingData->stage1MFactor + mVectorOffset - mGmOffset) * - tilingData->cvLoopKSize; - CopyOut(xCastLocal, - xCastFp32WsGm[cutMmInOffset], - curUbMFactor, - realKGmSize, - tilingData->cvLoopKSize - realKGmSize); - mmInQue.FreeTensor(xCastLocal); - } - CrossCoreSetFlag(SYNC_AIV_TO_AIC_FLAG); } - cvLoopIdx_++; + cubeCompute_.ComputeDecode( + xCastFp32WsGm[cvLoopIdx_ % DOUBLE_BUFFER * xCastFp32BufSize_], + xCastFp32WsGm[(cvLoopIdx_ + 1) % DOUBLE_BUFFER * xCastFp32BufSize_], + squareSumFp32WsGm[kBlkDimIdx_ * squareSumFp32BufSize_ + + mGmOffset * BLOCK_CUBE], + mmOutFp32WsGm[kBlkDimIdx_ * mmOutFp32BufSize_ + + mGmOffset * mmOuterInnerSize_], + mmParams, + a1Prefetched, + preloadNextB1, + nextB1Offset, + nextB1Size); + cubeCompute_.SetBL1Mte1ToMte2Flag(); + b1Prefetched = preloadNextB1; + a1Prefetched = preloadNextB1; + CrossCoreSetFlag(SYNC_AIC_TO_AIV_FLAG); + } else { + CrossCoreWaitFlag(SYNC_AIC_TO_AIV_FLAG); + // vec.compute(); + int64_t mVectorOffset = mGmOffset; + int64_t mVectorLength = (realMSize + 1) / NUM_TWO; + if ((curVectorBlockIdx % NUM_TWO) == 1) { + mVectorOffset = mGmOffset + (realMSize + 1) / NUM_TWO; + mVectorLength = realMSize - mVectorLength; + } + int64_t curUbLoops = (mVectorLength + tilingData->stage1MFactor - 1) / + tilingData->stage1MFactor; + int64_t curUbMfactorTail = + mVectorLength - ((curUbLoops - 1) * tilingData->stage1MFactor); + for (int64_t i = 0; i < curUbLoops; ++i) { + int64_t curUbMFactor = (i != (curUbLoops - 1)) + ? tilingData->stage1MFactor + : curUbMfactorTail; + xLocal = xQue.template AllocTensor(); + int64_t curGlobalxOffset = + (mVectorOffset + i * tilingData->stage1MFactor) * tilingData->k + + kGmBaseOffset; + CopyIn(xGm[curGlobalxOffset], + xLocal, + curUbMFactor, + realKGmSize, + tilingData->k - realKGmSize); + xQue.template EnQue(xLocal); + xLocal = xQue.template DeQue(); + xCastLocal = mmInQue.AllocTensor(); + CastTwoDim(xCastLocal, xLocal, curUbMFactor, realKGmSize); + xQue.template FreeTensor(xLocal); + mmInQue.template EnQue(xCastLocal); + xCastLocal = mmInQue.template DeQue(); + int64_t cutMmInOffset = + cvLoopIdx_ % DOUBLE_BUFFER * xCastFp32BufSize_ + + (i * tilingData->stage1MFactor + mVectorOffset - mGmOffset) * + tilingData->cvLoopKSize; + CopyOut(xCastLocal, + xCastFp32WsGm[cutMmInOffset], + curUbMFactor, + realKGmSize, + tilingData->cvLoopKSize - realKGmSize); + mmInQue.FreeTensor(xCastLocal); + } + CrossCoreSetFlag(SYNC_AIV_TO_AIC_FLAG); } + cvLoopIdx_++; + } + } + + __aicore__ inline void Process() { + if ASCEND_IS_AIC { + // 初始设置 + CrossCoreSetFlag(SYNC_AIC_TO_AIV_FLAG); + CrossCoreSetFlag(SYNC_AIC_TO_AIV_FLAG); + } + + uint64_t mGmBaseOffset = 0; + uint64_t mGmEndOffset = 0; + uint64_t kGmStartOffset = 0; + uint64_t kGmEndOffset = 0; + uint64_t curVectorBlockIdx = 0; + GetMkBlockInfo(mGmBaseOffset, + mGmEndOffset, + kGmStartOffset, + kGmEndOffset, + curVectorBlockIdx); + for (uint64_t mGmOffset = mGmBaseOffset; mGmOffset < mGmEndOffset; + mGmOffset += tilingData->mL1Size) { + ProcessMChunk(mGmOffset, + mGmEndOffset, + kGmStartOffset, + kGmEndOffset, + curVectorBlockIdx); } if ASCEND_IS_AIC { cubeCompute_.End(); @@ -228,13 +285,14 @@ class HcPreVaMembaseKSplitCorePart1 { static constexpr uint64_t SYNC_MODE2 = NUM_TWO; uint64_t cvLoopIdx_ = 0; + uint64_t kBlkDimIdx_ = 0; uint64_t xCastFp32BufSize_; uint64_t mmOuterInnerSize_; uint64_t mmOutFp32BufSize_; uint64_t squareSumFp32BufSize_; }; -template +template class HcPreVaMembaseKSplitCorePart2 { public: __aicore__ inline HcPreVaMembaseKSplitCorePart2() {} @@ -259,6 +317,1214 @@ class HcPreVaMembaseKSplitCorePart2 { workspaceGm.SetGlobalBuffer((__gm__ float*)workspace); } + __aicore__ inline void InitCommonBuffers(int64_t stage1UsedCoreNum, + int64_t rowFactor) { + pipe->InitBuffer( + squareSumQue, + NUM_TWO, + stage1UsedCoreNum * rowFactor * SQUARE_SUM_SIZE * sizeof(float)); + pipe->InitBuffer(squareReduceBuf, + rowFactor * SQUARE_SUM_SIZE * sizeof(float)); + pipe->InitBuffer(rsqrtBuf, RoundUp(rowFactor) * sizeof(float)); + pipe->InitBuffer(rowBrcbBuf0, RoundUp(rowFactor) * BLOCK_SIZE); + pipe->InitBuffer(maskPatternBuf, + RoundUp((rowFactor + MASK_PATTERN_DIM_SIZE - 1) * + MASK_PATTERN_REPEAT_SIZE) * + sizeof(uint32_t)); + + pipe->InitBuffer( + preMixBuf, + RoundUp(rowFactor * tilingData->hcMultAlign) * sizeof(float)); + preMixLocal = preMixBuf.Get(); + + squareReduceLocal = squareReduceBuf.Get(); + rsqrtLocal = rsqrtBuf.Get(); + rowBrcbLocal0 = rowBrcbBuf0.Get(); + maskPatternLocal = maskPatternBuf.Get(); + SetGatherMaskPattern( + maskPatternLocal, + static_cast(rowFactor + MASK_PATTERN_DIM_SIZE - 1)); + } + + __aicore__ inline void InitPrePostBuffers(int64_t stage1UsedCoreNum) { + int64_t rowFactor = tilingData->prePostRowFactor; + // Pre/post and y have different working-set shapes. Keep the y + // buffers at the stage2 row factor (normally one row for full-D + // tiles), while batching the row-only pre/post path separately. + int64_t yRowFactor = tilingData->stage2RowFactor; + int64_t xQueSize = + yRowFactor * tilingData->hcMult * RoundUp(tilingData->dFactor); + InitCommonBuffers(stage1UsedCoreNum, rowFactor); + pipe->InitBuffer(mixesQue01, + NUM_TWO, + stage1UsedCoreNum * rowFactor * tilingData->hcMultAlign * + NUM_TWO * sizeof(float)); + pipe->InitBuffer(xQue, NUM_TWO, xQueSize * sizeof(T)); + pipe->InitBuffer(yQue, + NUM_TWO, + yRowFactor * RoundUp(tilingData->dFactor) * sizeof(T)); + // ProcessPost 按 prePostRowFactor 批量处理行,postQue 需容纳整个批次。 + pipe->InitBuffer( + postQue, + NUM_TWO, + tilingData->prePostRowFactor * tilingData->hcMultAlign * sizeof(float)); + pipe->InitBuffer(hcBaseBuf0, tilingData->hcMultAlign * sizeof(float)); + pipe->InitBuffer(hcBaseBuf1, tilingData->hcMultAlign * sizeof(float)); + pipe->InitBuffer( + hcBrcbBuf1, + RoundUp(rowFactor * tilingData->hcMultAlign) * BLOCK_SIZE); + pipe->InitBuffer( + mixes01ReduceBuf, + rowFactor * tilingData->hcMultAlign * NUM_TWO * sizeof(float)); + pipe->InitBuffer(xCastBuf, xQueSize * sizeof(float)); + pipe->InitBuffer( + yCastBuf, yRowFactor * RoundUp(tilingData->dFactor) * sizeof(float)); + + hcBase0Local = hcBaseBuf0.Get(); + hcBase1Local = hcBaseBuf1.Get(); + hcBrcbLocal1 = hcBrcbBuf1.Get(); + mixes01ReduceLocal = mixes01ReduceBuf.Get(); + xCastLocal = xCastBuf.Get(); + yCastLocal = yCastBuf.Get(); + } + + __aicore__ inline void InitSinkhornBuffers(int64_t stage1UsedCoreNum) { + int64_t rowFactor = tilingData->sinkhornRowFactor; + int64_t rowFactorAlign = RoundUp(rowFactor); + InitCommonBuffers(stage1UsedCoreNum, rowFactor); + pipe->InitBuffer( + mixesQue2, + DOUBLE_BUFFER, + stage1UsedCoreNum * rowFactor * COMPACT_MATRIX_SIZE * sizeof(float)); + pipe->InitBuffer(combFragQue, + DOUBLE_BUFFER, + rowFactor * COMPACT_MATRIX_SIZE * sizeof(float)); + pipe->InitBuffer(hcBaseBuf2, COMPACT_MATRIX_SIZE * sizeof(float)); + pipe->InitBuffer(hcBrcbBuf1, COMPACT_MATRIX_SIZE * BLOCK_SIZE); + pipe->InitBuffer(reduceBuf, + COMPACT_HC_MULT * rowFactorAlign * sizeof(float)); + pipe->InitBuffer(mixes02ReduceBuf, + COMPACT_MATRIX_SIZE * rowFactorAlign * sizeof(float)); + + hcBase2Local = hcBaseBuf2.Get(); + hcBrcbLocal1 = hcBrcbBuf1.Get(); + reduceLocal = reduceBuf.Get(); + mixes02ReduceLocal = mixes02ReduceBuf.Get(); + } + + __aicore__ inline void InitOriginalBuffers(int64_t stage1UsedCoreNum) { + int64_t rowFactor = tilingData->stage2RowFactor; + int64_t xQueSize = + rowFactor * tilingData->hcMult * RoundUp(tilingData->dFactor); + InitCommonBuffers(stage1UsedCoreNum, rowFactor); + + pipe->InitBuffer(mixesQue01, + NUM_TWO, + stage1UsedCoreNum * rowFactor * tilingData->hcMultAlign * + NUM_TWO * sizeof(float)); + pipe->InitBuffer(mixesQue2, + NUM_TWO, + stage1UsedCoreNum * rowFactor * tilingData->hcMult * + tilingData->hcMultAlign * sizeof(float)); + pipe->InitBuffer(xQue, NUM_TWO, xQueSize * sizeof(T)); + pipe->InitBuffer( + yQue, NUM_TWO, rowFactor * RoundUp(tilingData->dFactor) * sizeof(T)); + pipe->InitBuffer( + postQue, NUM_TWO, rowFactor * tilingData->hcMultAlign * sizeof(float)); + pipe->InitBuffer(combFragQue, + NUM_TWO, + rowFactor * tilingData->hcMult * tilingData->hcMultAlign * + sizeof(float)); + + pipe->InitBuffer(hcBaseBuf0, tilingData->hcMultAlign * sizeof(float)); + pipe->InitBuffer(hcBaseBuf1, tilingData->hcMultAlign * sizeof(float)); + pipe->InitBuffer( + hcBaseBuf2, + tilingData->hcMult * tilingData->hcMultAlign * sizeof(float)); + pipe->InitBuffer( + hcBrcbBuf1, + RoundUp(rowFactor * tilingData->hcMultAlign) * BLOCK_SIZE); + pipe->InitBuffer(reduceBuf, + rowFactor * tilingData->hcMultAlign * sizeof(float)); + pipe->InitBuffer( + mixes01ReduceBuf, + rowFactor * tilingData->hcMultAlign * NUM_TWO * sizeof(float)); + pipe->InitBuffer(mixes02ReduceBuf, + rowFactor * tilingData->hcMult * tilingData->hcMultAlign * + sizeof(float)); + pipe->InitBuffer(xCastBuf, xQueSize * sizeof(float)); + pipe->InitBuffer( + yCastBuf, rowFactor * RoundUp(tilingData->dFactor) * sizeof(float)); + + hcBase0Local = hcBaseBuf0.Get(); + hcBase1Local = hcBaseBuf1.Get(); + hcBase2Local = hcBaseBuf2.Get(); + hcBrcbLocal1 = hcBrcbBuf1.Get(); + reduceLocal = reduceBuf.Get(); + mixes01ReduceLocal = mixes01ReduceBuf.Get(); + mixes02ReduceLocal = mixes02ReduceBuf.Get(); + xCastLocal = xCastBuf.Get(); + yCastLocal = yCastBuf.Get(); + } + + __aicore__ inline void Init(GM_ADDR x, + GM_ADDR hcScale, + GM_ADDR hcBase, + GM_ADDR y, + GM_ADDR post, + GM_ADDR combFrag, + GM_ADDR preMix, + GM_ADDR pre, + GM_ADDR workspace, + const HcPreVaTilingData* tilingDataPtr, + TPipe* pipePtr) { + pipe = pipePtr; + tilingData = tilingDataPtr; + InitGlobalBuffers( + x, hcScale, hcBase, y, post, combFrag, preMix, pre, workspace); + if ASCEND_IS_AIC { + return; + } + int64_t stage1UsedCoreNum = tilingData->cubeBlockDimK; + if constexpr (useOriginal) { + InitOriginalBuffers(stage1UsedCoreNum); + } else { + if (GetBlockIdx() < tilingData->prePostCoreNum) { + InitPrePostBuffers(stage1UsedCoreNum); + } else { + InitSinkhornBuffers(stage1UsedCoreNum); + } + } + } + + // pre 在 UB 中按 hcMultAlign 行距存放, GM 按 hcMult 行距紧凑存放, 逐行写出. + __aicore__ inline void CopyOutPre(const LocalTensor& src, + int64_t globalRowOffset, + int64_t curRowFactor) { + if (tilingData->hasPreOut == 0) { + return; + } + event_t eventIdVToMte3 = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_MTE3)); + SetFlag(eventIdVToMte3); + WaitFlag(eventIdVToMte3); + for (int64_t rowIdx = 0; rowIdx < curRowFactor; rowIdx++) { + CopyOut(src[rowIdx * tilingData->hcMultAlign], + preGm[(globalRowOffset + rowIdx) * tilingData->hcMult], + 1, + tilingData->hcMult); + } + event_t eventIdMte3ToV = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE3_V)); + SetFlag(eventIdMte3ToV); + WaitFlag(eventIdMte3ToV); + } + + // 外部 pre_mix 按 hcMultAlign 行距暂存到 UB, 供 y 复用. + __aicore__ inline void LoadPreMix(int64_t globalRowOffset, + int64_t curRowFactor) { + if (tilingData->hasPreMix == 0) { + return; + } + for (int64_t rowIdx = 0; rowIdx < curRowFactor; rowIdx++) { + CopyIn(preMixGm[(globalRowOffset + rowIdx) * tilingData->hcMult], + preMixLocal[rowIdx * tilingData->hcMultAlign], + 1, + tilingData->hcMult); + } + event_t eventIdMte2ToV = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(eventIdMte2ToV); + WaitFlag(eventIdMte2ToV); + } + + __aicore__ inline void CalcRsqrt(int64_t stage1UsedCoreNum, + int64_t globalRowOffset, + int64_t curRowFactor, + int64_t workspaceSize1, + int64_t workspaceSize2) { + squareSumOutLocal = squareSumQue.AllocTensor(); + CopyIn(workspaceGm[workspaceSize1 + workspaceSize2 + + globalRowOffset * SQUARE_SUM_SIZE], + squareSumOutLocal, + stage1UsedCoreNum, + curRowFactor * SQUARE_SUM_SIZE, + CeilAlign(tilingData->bs, SQUARE_SUM_SIZE) * SQUARE_SUM_SIZE - + curRowFactor * SQUARE_SUM_SIZE); + squareSumQue.EnQue(squareSumOutLocal); + squareSumOutLocal = squareSumQue.DeQue(); + ReduceSumARAPerf(squareReduceLocal, + squareSumOutLocal, + 1, + stage1UsedCoreNum, + curRowFactor * SQUARE_SUM_SIZE); + GatherMaskByDiagonal(rsqrtLocal, + squareReduceLocal, + maskPatternLocal, + curRowFactor, + globalRowOffset % SQUARE_SUM_SIZE); + float coeff = 1.0f / static_cast(tilingData->k); + Muls(rsqrtLocal, rsqrtLocal, coeff, curRowFactor); + PipeBarrier(); + Adds(rsqrtLocal, rsqrtLocal, tilingData->normEps, curRowFactor); + PipeBarrier(); + Sqrt(rsqrtLocal, rsqrtLocal, curRowFactor); + Duplicate(rowBrcbLocal0, static_cast(1.0f), curRowFactor); + PipeBarrier(); + Div(rsqrtLocal, rowBrcbLocal0, rsqrtLocal, curRowFactor); + } + + __aicore__ inline void CopyInPartialCombCompact(int64_t stage1UsedCoreNum, + int64_t workspaceSize1, + int64_t mmLastAxisSize, + int64_t globalRowOffset, + int64_t curRowFactor) { + int64_t combOffset = tilingData->hcMult * NUM_TWO; + for (int64_t kBlockIdx = 0; kBlockIdx < stage1UsedCoreNum; kBlockIdx++) { + int64_t gmOffset = workspaceSize1 + + kBlockIdx * tilingData->bs * mmLastAxisSize + + globalRowOffset * mmLastAxisSize + combOffset; + int64_t ubOffset = kBlockIdx * curRowFactor * COMPACT_MATRIX_SIZE; + CopyIn(workspaceGm[gmOffset], + mixes2Local[ubOffset], + curRowFactor, + COMPACT_MATRIX_SIZE, + mmLastAxisSize - COMPACT_MATRIX_SIZE); + } + } + + __aicore__ inline void GatherCompactToElementMajor( + const LocalTensor& output, + const LocalTensor& input, + int64_t curRowFactor) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + Duplicate(output, 0.0f, COMPACT_MATRIX_SIZE * rowFactorAlign); + PipeBarrier(); + for (int64_t matrixElement = 0; matrixElement < COMPACT_MATRIX_SIZE; + matrixElement++) { + uint64_t rsvdCnt = 0; + GatherMask(output[matrixElement * rowFactorAlign], + input, + maskPatternLocal[matrixElement * MASK_PATTERN_REPEAT_SIZE], + true, + COMPACT_MATRIX_SIZE, + {1, static_cast(curRowFactor), 2, 0}, + rsvdCnt); + } + PipeBarrier(); + } + + __aicore__ inline void GatherElementMajorToCompact( + const LocalTensor& output, + const LocalTensor& input, + int64_t curRowFactor) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + int64_t rowStride = rowFactorAlign / (BLOCK_SIZE / sizeof(float)); + for (int64_t rowIdx = 0; rowIdx < curRowFactor; rowIdx++) { + int64_t rowGroupOffset = + rowIdx / MASK_PATTERN_DIM_SIZE * MASK_PATTERN_DIM_SIZE; + int64_t rowInGroup = rowIdx % MASK_PATTERN_DIM_SIZE; + int64_t rowsInGroup = curRowFactor - rowGroupOffset; + if (rowsInGroup > MASK_PATTERN_DIM_SIZE) { + rowsInGroup = MASK_PATTERN_DIM_SIZE; + } + uint64_t rsvdCnt = 0; + // GatherMask patterns repeat every 16 elements. For row factors above 16, + // advance the source to the current group instead of aliasing row 16 to + // row 0. + GatherMask(output[rowIdx * COMPACT_MATRIX_SIZE], + input[rowGroupOffset], + maskPatternLocal[rowInGroup * MASK_PATTERN_REPEAT_SIZE], + true, + rowsInGroup, + {1, COMPACT_MATRIX_SIZE, static_cast(rowStride), 0}, + rsvdCnt); + } + PipeBarrier(); + } + + template + __aicore__ inline void ReduceCompactRows(const LocalTensor& output, + const LocalTensor& input, + int64_t curRowFactor) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + int64_t rowStride = rowFactorAlign / (BLOCK_SIZE / sizeof(float)); + BinaryRepeatParams params; + params.dstBlkStride = 1; + params.src0BlkStride = 1; + params.src1BlkStride = 1; + params.dstRepStride = rowStride; + params.src0RepStride = COMPACT_HC_MULT * rowStride; + params.src1RepStride = COMPACT_HC_MULT * rowStride; + if constexpr (reduceMax) { + Max(output, + input, + input[rowFactorAlign], + curRowFactor, + COMPACT_HC_MULT, + params); + PipeBarrier(); + params.src0RepStride = rowStride; + Max(output, + output, + input[NUM_TWO * rowFactorAlign], + curRowFactor, + COMPACT_HC_MULT, + params); + PipeBarrier(); + Max(output, + output, + input[3 * rowFactorAlign], + curRowFactor, + COMPACT_HC_MULT, + params); + } else { + Add(output, + input, + input[rowFactorAlign], + curRowFactor, + COMPACT_HC_MULT, + params); + PipeBarrier(); + params.src0RepStride = rowStride; + Add(output, + output, + input[NUM_TWO * rowFactorAlign], + curRowFactor, + COMPACT_HC_MULT, + params); + PipeBarrier(); + Add(output, + output, + input[3 * rowFactorAlign], + curRowFactor, + COMPACT_HC_MULT, + params); + } + PipeBarrier(); + } + + __aicore__ inline void ReduceCompactCols(const LocalTensor& output, + const LocalTensor& input, + int64_t curRowFactor) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + int64_t rowStride = rowFactorAlign / (BLOCK_SIZE / sizeof(float)); + BinaryRepeatParams params; + params.dstBlkStride = 1; + params.src0BlkStride = 1; + params.src1BlkStride = 1; + params.dstRepStride = rowStride; + params.src0RepStride = rowStride; + params.src1RepStride = rowStride; + Add(output, + input, + input[COMPACT_HC_MULT * rowFactorAlign], + curRowFactor, + COMPACT_HC_MULT, + params); + PipeBarrier(); + Add(output, + output, + input[NUM_TWO * COMPACT_HC_MULT * rowFactorAlign], + curRowFactor, + COMPACT_HC_MULT, + params); + PipeBarrier(); + Add(output, + output, + input[3 * COMPACT_HC_MULT * rowFactorAlign], + curRowFactor, + COMPACT_HC_MULT, + params); + PipeBarrier(); + } + + template + __aicore__ inline void ApplyCompactRowValues( + const LocalTensor& output, + const LocalTensor& input, + const LocalTensor& rowValues, + int64_t curRowFactor) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + int64_t rowStride = rowFactorAlign / (BLOCK_SIZE / sizeof(float)); + BinaryRepeatParams params; + params.dstBlkStride = 1; + params.src0BlkStride = 1; + params.src1BlkStride = 1; + params.dstRepStride = COMPACT_HC_MULT * rowStride; + params.src0RepStride = COMPACT_HC_MULT * rowStride; + params.src1RepStride = rowStride; + for (int64_t colIdx = 0; colIdx < COMPACT_HC_MULT; colIdx++) { + if constexpr (divide) { + Div(output[colIdx * rowFactorAlign], + input[colIdx * rowFactorAlign], + rowValues, + curRowFactor, + COMPACT_HC_MULT, + params); + } else { + Sub(output[colIdx * rowFactorAlign], + input[colIdx * rowFactorAlign], + rowValues, + curRowFactor, + COMPACT_HC_MULT, + params); + } + } + PipeBarrier(); + } + + __aicore__ inline void ApplyCompactColValues( + const LocalTensor& output, + const LocalTensor& input, + const LocalTensor& colValues, + int64_t curRowFactor) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + int64_t rowStride = rowFactorAlign / (BLOCK_SIZE / sizeof(float)); + BinaryRepeatParams params; + params.dstBlkStride = 1; + params.src0BlkStride = 1; + params.src1BlkStride = 1; + params.dstRepStride = rowStride; + params.src0RepStride = rowStride; + params.src1RepStride = rowStride; + for (int64_t matrixRow = 0; matrixRow < COMPACT_HC_MULT; matrixRow++) { + Div(output[matrixRow * COMPACT_HC_MULT * rowFactorAlign], + input[matrixRow * COMPACT_HC_MULT * rowFactorAlign], + colValues, + curRowFactor, + COMPACT_HC_MULT, + params); + } + PipeBarrier(); + } + + __aicore__ inline void NormalizeCompactRows(const LocalTensor& data, + int64_t curRowFactor) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + ReduceCompactRows(reduceLocal, data, curRowFactor); + Adds(reduceLocal, + reduceLocal, + tilingData->hcEps, + COMPACT_HC_MULT * rowFactorAlign); + PipeBarrier(); + ApplyCompactRowValues(data, data, reduceLocal, curRowFactor); + } + + __aicore__ inline void NormalizeCompactCols(const LocalTensor& data, + int64_t curRowFactor) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + ReduceCompactCols(reduceLocal, data, curRowFactor); + Adds(reduceLocal, + reduceLocal, + tilingData->hcEps, + COMPACT_HC_MULT * rowFactorAlign); + PipeBarrier(); + ApplyCompactColValues(data, data, reduceLocal, curRowFactor); + } + + __aicore__ inline void SoftmaxCompactRows(const LocalTensor& data, + int64_t curRowFactor) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + ReduceCompactRows(reduceLocal, data, curRowFactor); + ApplyCompactRowValues(data, data, reduceLocal, curRowFactor); + Exp(data, data, COMPACT_MATRIX_SIZE * rowFactorAlign); + PipeBarrier(); + ReduceCompactRows(reduceLocal, data, curRowFactor); + ApplyCompactRowValues(data, data, reduceLocal, curRowFactor); + Adds(data, data, tilingData->hcEps, COMPACT_MATRIX_SIZE * rowFactorAlign); + PipeBarrier(); + } + + __aicore__ inline void ProcessCompactSinkhorn(const LocalTensor& data, + int64_t curRowFactor, + float hcScale) { + int64_t rowFactorAlign = RoundUp(curRowFactor); + int64_t rowStride = rowFactorAlign / (BLOCK_SIZE / sizeof(float)); + Brcb(hcBrcbLocal1, + hcBase2Local, + NUM_TWO, + {DEFAULT_BLOCK_STRIDE, DEFAULT_REPEAT_STRIDE}); + PipeBarrier(); + + BinaryRepeatParams mulParams; + mulParams.dstBlkStride = 1; + mulParams.src0BlkStride = 1; + mulParams.src1BlkStride = 1; + mulParams.dstRepStride = rowStride; + mulParams.src0RepStride = rowStride; + mulParams.src1RepStride = 0; + Mul(data, data, rsqrtLocal, curRowFactor, COMPACT_MATRIX_SIZE, mulParams); + PipeBarrier(); + Muls(data, data, hcScale, COMPACT_MATRIX_SIZE * rowFactorAlign); + PipeBarrier(); + + BinaryRepeatParams biasParams = mulParams; + biasParams.src1BlkStride = 0; + biasParams.src1RepStride = 1; + Add(data, + data, + hcBrcbLocal1, + curRowFactor, + COMPACT_MATRIX_SIZE, + biasParams); + PipeBarrier(); + + SoftmaxCompactRows(data, curRowFactor); + NormalizeCompactCols(data, curRowFactor); + for (int64_t iter = 0; iter < tilingData->iterTimes - 1; iter++) { + NormalizeCompactRows(data, curRowFactor); + NormalizeCompactCols(data, curRowFactor); + } + } + + __aicore__ inline void PrePostLoadBase(float& hcScale0, float& hcScale1) { + CopyIn(hcBaseGm, hcBase0Local, 1, tilingData->hcMult); + CopyIn(hcBaseGm[tilingData->hcMult], hcBase1Local, 1, tilingData->hcMult); + event_t eventId = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(eventId); + WaitFlag(eventId); + hcScale0 = hcScaleGm.GetValue(0); + hcScale1 = hcScaleGm.GetValue(1); + } + + // 连续 actualRow 行的一批 pre/post 处理(原 ProcessPrePost 行循环体主体) + __aicore__ inline void ProcessPrePostBatch(int64_t stage1UsedCoreNum, + int64_t workspaceSize1, + int64_t workspaceSize2, + int64_t mmLastAxisSize, + int64_t globalRowOffset, + int64_t curRowFactor, + float hcScale0, + float hcScale1) { + CalcRsqrt(stage1UsedCoreNum, + globalRowOffset, + curRowFactor, + workspaceSize1, + workspaceSize2); + + mixes01Local = mixesQue01.AllocTensor(); + + uint64_t mixBaseOffset = workspaceSize1 + globalRowOffset * mmLastAxisSize; + CopyInWithOuterFor(workspaceGm[mixBaseOffset], + mixes01Local, + stage1UsedCoreNum, + curRowFactor, + tilingData->hcMult, + tilingData->bs, + mmLastAxisSize); + CopyInWithOuterFor(workspaceGm[mixBaseOffset + tilingData->hcMult], + mixes01Local[stage1UsedCoreNum * curRowFactor * + tilingData->hcMultAlign], + stage1UsedCoreNum, + curRowFactor, + tilingData->hcMult, + tilingData->bs, + mmLastAxisSize); + + mixesQue01.EnQue(mixes01Local); + mixes01Local = mixesQue01.DeQue(); + ReduceSumARAPerf(mixes01ReduceLocal, + mixes01Local, + NUM_TWO, + stage1UsedCoreNum, + curRowFactor * tilingData->hcMultAlign); + ProcessPre(mixes01ReduceLocal, + mixes01ReduceLocal, + hcBase0Local, + rsqrtLocal, + rowBrcbLocal0, + hcBrcbLocal1, + hcScale0, + tilingData->hcEps, + curRowFactor, + tilingData->hcMult); + CopyOutPre(mixes01ReduceLocal, globalRowOffset, curRowFactor); + LoadPreMix(globalRowOffset, curRowFactor); + mixesQue01.template FreeTensor(mixes01Local); + squareSumQue.template FreeTensor(squareSumOutLocal); + + // Keep the D tile resident for each row. This lets the row-only + // pre/post transforms run in a larger batch without inflating the + // x/y UB buffers that are sized for one full-D row. + for (int64_t rowIdx = 0; rowIdx < curRowFactor; rowIdx++) { + int64_t rowOffset = globalRowOffset + rowIdx; + const LocalTensor preRow = + tilingData->hasPreMix != 0 + ? preMixLocal[rowIdx * tilingData->hcMultAlign] + : mixes01ReduceLocal[rowIdx * tilingData->hcMultAlign]; + for (int64_t dLoopIdx = 0; dLoopIdx < tilingData->dLoop; dLoopIdx++) { + int64_t curDFactor = dLoopIdx == tilingData->dLoop - 1 + ? tilingData->tailDFactor + : tilingData->dFactor; + xLocal = xQue.template AllocTensor(); + CopyIn(xGm[rowOffset * tilingData->hcMult * tilingData->d + + dLoopIdx * tilingData->dFactor], + xLocal, + tilingData->hcMult, + curDFactor, + tilingData->d - curDFactor); + xQue.template EnQue(xLocal); + xLocal = xQue.template DeQue(); + yLocal = yQue.template AllocTensor(); + ProcessY(yLocal, + xLocal, + preRow, + hcBrcbLocal1, + xCastLocal, + yCastLocal, + 1, + tilingData->hcMult, + curDFactor); + xQue.template FreeTensor(xLocal); + yQue.template EnQue(yLocal); + yLocal = yQue.template DeQue(); + CopyOut(yLocal, + yGm[rowOffset * tilingData->d + dLoopIdx * tilingData->dFactor], + 1, + curDFactor, + tilingData->d - curDFactor); + yQue.template FreeTensor(yLocal); + } + } + + // 在行循环外批量处理 post,减少 sigmoid/mul 链的逐行同步开销。 + // rowBrcbLocal0 已按行广播;rsqrtLocal 在行循环中保持不变。 + postLocal = postQue.AllocTensor(); + ProcessPost(postLocal, + mixes01ReduceLocal[curRowFactor * tilingData->hcMultAlign], + hcBase1Local, + rsqrtLocal, + rowBrcbLocal0, + hcBrcbLocal1, + hcScale1, + curRowFactor, + tilingData->hcMult); + postQue.EnQue(postLocal); + postLocal = postQue.template DeQue(); + // post的UB布局行距hcMultAlign(列4 pad到8), GM布局行距hcMult, 非整 + // block倍数关系, 保留逐行CopyOut. + for (int64_t rowIdx = 0; rowIdx < curRowFactor; rowIdx++) { + int64_t rowOffset = globalRowOffset + rowIdx; + CopyOut(postLocal[rowIdx * tilingData->hcMultAlign], + postGm[rowOffset * tilingData->hcMult], + 1, + tilingData->hcMult); + } + postQue.FreeTensor(postLocal); + } + + __aicore__ inline void ProcessPrePost(int64_t stage1UsedCoreNum, + int64_t workspaceSize1, + int64_t workspaceSize2, + int64_t mmLastAxisSize) { + int64_t blockIdx = GetBlockIdx(); + if (blockIdx >= tilingData->secondUsedCoreNum) { + return; + } + float hcScale0 = 0.0f; + float hcScale1 = 0.0f; + PrePostLoadBase(hcScale0, hcScale1); + + int64_t rowOuterLoop = blockIdx == tilingData->secondUsedCoreNum - 1 + ? tilingData->prePostRowLoopOfTailBlock + : tilingData->prePostRowLoopOfFormerBlock; + int64_t tailRowFactor = blockIdx == tilingData->secondUsedCoreNum - 1 + ? tilingData->prePostTailRowFactorOfTailBlock + : tilingData->prePostTailRowFactorOfFormerBlock; + + for (int64_t rowOuterIdx = 0; rowOuterIdx < rowOuterLoop; rowOuterIdx++) { + int64_t curRowFactor = rowOuterIdx == rowOuterLoop - 1 + ? tailRowFactor + : tilingData->prePostRowFactor; + int64_t globalRowOffset = blockIdx * tilingData->prePostRowOfFormerBlock + + rowOuterIdx * tilingData->prePostRowFactor; + ProcessPrePostBatch(stage1UsedCoreNum, + workspaceSize1, + workspaceSize2, + mmLastAxisSize, + globalRowOffset, + curRowFactor, + hcScale0, + hcScale1); + } + } + + // 连续 actualRow 行的一批 sinkhorn 处理(原 ProcessSinkhorn 行循环体原样抽出) + __aicore__ inline void ProcessSinkhornBatch(int64_t stage1UsedCoreNum, + int64_t workspaceSize1, + int64_t workspaceSize2, + int64_t mmLastAxisSize, + int64_t globalRowOffset, + int64_t curRowFactor, + float hcScale2) { + CalcRsqrt(stage1UsedCoreNum, + globalRowOffset, + curRowFactor, + workspaceSize1, + workspaceSize2); + + mixes2Local = mixesQue2.AllocTensor(); + CopyInPartialCombCompact(stage1UsedCoreNum, + workspaceSize1, + mmLastAxisSize, + globalRowOffset, + curRowFactor); + mixesQue2.EnQue(mixes2Local); + mixes2Local = mixesQue2.DeQue(); + combFragLocal = combFragQue.AllocTensor(); + + ReduceSumARAPerf(combFragLocal, + mixes2Local, + 1, + stage1UsedCoreNum, + curRowFactor * COMPACT_MATRIX_SIZE); + GatherCompactToElementMajor( + mixes02ReduceLocal, combFragLocal, curRowFactor); + ProcessCompactSinkhorn(mixes02ReduceLocal, curRowFactor, hcScale2); + GatherElementMajorToCompact( + combFragLocal, mixes02ReduceLocal, curRowFactor); + mixesQue2.FreeTensor(mixes2Local); + squareSumQue.template FreeTensor(squareSumOutLocal); + + combFragQue.EnQue(combFragLocal); + combFragLocal = combFragQue.DeQue(); + CopyOut(combFragLocal, + combFragGm[globalRowOffset * COMPACT_MATRIX_SIZE], + 1, + curRowFactor * COMPACT_MATRIX_SIZE); + combFragQue.FreeTensor(combFragLocal); + } + + __aicore__ inline void ProcessSinkhorn(int64_t stage1UsedCoreNum, + int64_t workspaceSize1, + int64_t workspaceSize2, + int64_t mmLastAxisSize) { + int64_t blockIdx = GetBlockIdx() - tilingData->prePostCoreNum; + if (blockIdx < 0 || blockIdx >= tilingData->sinkhornUsedCoreNum) { + return; + } + CopyIn(hcBaseGm[COMPACT_HC_MULT * NUM_TWO], + hcBase2Local, + 1, + COMPACT_MATRIX_SIZE); + event_t eventId = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(eventId); + WaitFlag(eventId); + float hcScale2 = hcScaleGm.GetValue(NUM_TWO); + + int64_t rowOuterLoop = blockIdx == tilingData->sinkhornUsedCoreNum - 1 + ? tilingData->sinkhornRowLoopOfTailBlock + : tilingData->sinkhornRowLoopOfFormerBlock; + int64_t tailRowFactor = + blockIdx == tilingData->sinkhornUsedCoreNum - 1 + ? tilingData->sinkhornTailRowFactorOfTailBlock + : tilingData->sinkhornTailRowFactorOfFormerBlock; + + for (int64_t rowOuterIdx = 0; rowOuterIdx < rowOuterLoop; rowOuterIdx++) { + int64_t curRowFactor = rowOuterIdx == rowOuterLoop - 1 + ? tailRowFactor + : tilingData->sinkhornRowFactor; + int64_t globalRowOffset = + blockIdx * tilingData->sinkhornRowOfFormerBlock + + rowOuterIdx * tilingData->sinkhornRowFactor; + ProcessSinkhornBatch(stage1UsedCoreNum, + workspaceSize1, + workspaceSize2, + mmLastAxisSize, + globalRowOffset, + curRowFactor, + hcScale2); + } + } + + __aicore__ inline void ProcessOriginal() { + if ASCEND_IS_AIC { + return; + } + int64_t blockIdx = GetBlockIdx(); + if (blockIdx >= tilingData->secondUsedCoreNum) { + return; + } + + int64_t stage1UsedCoreNum = tilingData->cubeBlockDimK; + int64_t mmLastAxisSize = + CeilAlign(tilingData->hcMix, MM_CACHE_LINE_BYTES / sizeof(float)); + int64_t xCastFp32BufSize = + tilingData->mL1Size * + CeilAlign(tilingData->cvLoopKSize, MM_CACHE_LINE_BYTES / sizeof(float)); + int64_t workspaceSize1 = + tilingData->cubeCoreNum * DOUBLE_BUFFER * xCastFp32BufSize; + int64_t workspaceSize2 = CeilAlign(stage1UsedCoreNum * tilingData->bs * + mmLastAxisSize * sizeof(float), + WORKSPACE_ALIGN_SIZE) / + sizeof(float); + + CopyIn(hcBaseGm, hcBase0Local, 1, tilingData->hcMult); + CopyIn(hcBaseGm[tilingData->hcMult], hcBase1Local, 1, tilingData->hcMult); + CopyIn(hcBaseGm[tilingData->hcMult * NUM_TWO], + hcBase2Local, + tilingData->hcMult, + tilingData->hcMult); + event_t eventId = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(eventId); + WaitFlag(eventId); + float hcScale0 = hcScaleGm.GetValue(0); + float hcScale1 = hcScaleGm.GetValue(1); + float hcScale2 = hcScaleGm.GetValue(NUM_TWO); + + int64_t rowOuterLoop = blockIdx == tilingData->secondUsedCoreNum - 1 + ? tilingData->rowLoopOfTailBlock + : tilingData->rowLoopOfFormerBlock; + int64_t tailRowFactor = blockIdx == tilingData->secondUsedCoreNum - 1 + ? tilingData->tailRowFactorOfTailBlock + : tilingData->tailRowFactorOfFormerBlock; + + for (int64_t rowOuterIdx = 0; rowOuterIdx < rowOuterLoop; rowOuterIdx++) { + int64_t curRowFactor = rowOuterIdx == rowOuterLoop - 1 + ? tailRowFactor + : tilingData->stage2RowFactor; + int64_t globalRowOffset = blockIdx * tilingData->rowOfFormerBlock + + rowOuterIdx * tilingData->stage2RowFactor; + CalcRsqrt(stage1UsedCoreNum, + globalRowOffset, + curRowFactor, + workspaceSize1, + workspaceSize2); + + mixes01Local = mixesQue01.AllocTensor(); + uint64_t mixBaseOffset = + workspaceSize1 + globalRowOffset * mmLastAxisSize; + CopyInWithOuterFor(workspaceGm[mixBaseOffset], + mixes01Local, + stage1UsedCoreNum, + curRowFactor, + tilingData->hcMult, + tilingData->bs, + mmLastAxisSize); + CopyInWithOuterFor( + workspaceGm[mixBaseOffset + tilingData->hcMult], + mixes01Local[stage1UsedCoreNum * tilingData->stage2RowFactor * + tilingData->hcMultAlign], + stage1UsedCoreNum, + curRowFactor, + tilingData->hcMult, + tilingData->bs, + mmLastAxisSize); + mixesQue01.EnQue(mixes01Local); + mixes01Local = mixesQue01.DeQue(); + ReduceSumARAPerf(mixes01ReduceLocal, + mixes01Local, + NUM_TWO, + stage1UsedCoreNum, + curRowFactor * tilingData->hcMultAlign); + + ProcessPre(mixes01ReduceLocal, + mixes01ReduceLocal, + hcBase0Local, + rsqrtLocal, + rowBrcbLocal0, + hcBrcbLocal1, + hcScale0, + tilingData->hcEps, + curRowFactor, + tilingData->hcMult); + CopyOutPre(mixes01ReduceLocal, globalRowOffset, curRowFactor); + LoadPreMix(globalRowOffset, curRowFactor); + for (int64_t dLoopIdx = 0; dLoopIdx < tilingData->dLoop; dLoopIdx++) { + int64_t curDFactor = dLoopIdx == tilingData->dLoop - 1 + ? tilingData->tailDFactor + : tilingData->dFactor; + xLocal = xQue.template AllocTensor(); + CopyIn(xGm[globalRowOffset * tilingData->hcMult * tilingData->d + + dLoopIdx * tilingData->dFactor], + xLocal, + curRowFactor * tilingData->hcMult, + curDFactor, + tilingData->d - curDFactor); + xQue.template EnQue(xLocal); + xLocal = xQue.template DeQue(); + yLocal = yQue.template AllocTensor(); + ProcessY(yLocal, + xLocal, + tilingData->hasPreMix != 0 ? preMixLocal : mixes01ReduceLocal, + hcBrcbLocal1, + xCastLocal, + yCastLocal, + curRowFactor, + tilingData->hcMult, + curDFactor); + xQue.template FreeTensor(xLocal); + yQue.template EnQue(yLocal); + yLocal = yQue.template DeQue(); + CopyOut(yLocal, + yGm[globalRowOffset * tilingData->d + + dLoopIdx * tilingData->dFactor], + curRowFactor, + curDFactor, + tilingData->d - curDFactor); + yQue.template FreeTensor(yLocal); + } + + postLocal = postQue.AllocTensor(); + ProcessPost(postLocal, + mixes01ReduceLocal[curRowFactor * tilingData->hcMultAlign], + hcBase1Local, + rsqrtLocal, + rowBrcbLocal0, + hcBrcbLocal1, + hcScale1, + curRowFactor, + tilingData->hcMult); + mixesQue01.template FreeTensor(mixes01Local); + postQue.EnQue(postLocal); + postLocal = postQue.DeQue(); + CopyOut(postLocal, + postGm[globalRowOffset * tilingData->hcMult], + curRowFactor, + tilingData->hcMult); + postQue.FreeTensor(postLocal); + + mixes2Local = mixesQue2.AllocTensor(); + for (int64_t kBlockIdx = 0; kBlockIdx < stage1UsedCoreNum; kBlockIdx++) { + for (int64_t rowIdx = 0; rowIdx < curRowFactor; rowIdx++) { + int64_t gmOffset = workspaceSize1 + + kBlockIdx * tilingData->bs * mmLastAxisSize + + (globalRowOffset + rowIdx) * mmLastAxisSize + + tilingData->hcMult * NUM_TWO; + int64_t ubOffset = (kBlockIdx * curRowFactor + rowIdx) * + tilingData->hcMult * tilingData->hcMultAlign; + CopyIn(workspaceGm[gmOffset], + mixes2Local[ubOffset], + tilingData->hcMult, + tilingData->hcMult); + } + } + mixesQue2.EnQue(mixes2Local); + mixes2Local = mixesQue2.DeQue(); + ReduceSumARAPerf( + mixes02ReduceLocal, + mixes2Local, + 1, + stage1UsedCoreNum, + curRowFactor * tilingData->hcMult * tilingData->hcMultAlign); + combFragLocal = combFragQue.AllocTensor(); + + MulABLastDimBrcInline( + mixes02ReduceLocal, + mixes02ReduceLocal, + rsqrtLocal, + rowBrcbLocal0, + curRowFactor, + tilingData->hcMult * tilingData->hcMultAlign); + Muls(mixes02ReduceLocal, + mixes02ReduceLocal, + hcScale2, + curRowFactor * tilingData->hcMult * tilingData->hcMultAlign); + PipeBarrier(); + AddBAFirstDimBrcInline( + mixes02ReduceLocal, + mixes02ReduceLocal, + hcBase2Local, + curRowFactor, + tilingData->hcMult * tilingData->hcMultAlign); + SoftmaxFP32Perf(mixes02ReduceLocal, + mixes02ReduceLocal, + reduceLocal, + hcBrcbLocal1, + curRowFactor * tilingData->hcMult, + tilingData->hcMult, + tilingData->hcEps); + ReduceSumARAPerf(reduceLocal, + mixes02ReduceLocal, + curRowFactor, + tilingData->hcMult, + tilingData->hcMult); + Adds(reduceLocal, + reduceLocal, + tilingData->hcEps, + curRowFactor * tilingData->hcMultAlign); + PipeBarrier(); + DivABABrcInline(combFragLocal, + mixes02ReduceLocal, + reduceLocal, + curRowFactor, + tilingData->hcMult, + tilingData->hcMult); + for (int64_t iter = 0; iter < tilingData->iterTimes - 1; iter++) { + LastDimReduceSumPerf(reduceLocal, + combFragLocal, + curRowFactor * tilingData->hcMult, + tilingData->hcMult); + Adds(reduceLocal, + reduceLocal, + tilingData->hcEps, + curRowFactor * tilingData->hcMult); + PipeBarrier(); + DivABLastDimBrcInline(combFragLocal, + combFragLocal, + reduceLocal, + hcBrcbLocal1, + curRowFactor * tilingData->hcMult, + tilingData->hcMult); + ReduceSumARAPerf(reduceLocal, + combFragLocal, + curRowFactor, + tilingData->hcMult, + tilingData->hcMult); + Adds(reduceLocal, + reduceLocal, + tilingData->hcEps, + curRowFactor * tilingData->hcMultAlign); + PipeBarrier(); + DivABABrcInline(combFragLocal, + combFragLocal, + reduceLocal, + curRowFactor, + tilingData->hcMult, + tilingData->hcMult); + } + mixesQue2.FreeTensor(mixes2Local); + squareSumQue.template FreeTensor(squareSumOutLocal); + + combFragQue.EnQue(combFragLocal); + combFragLocal = combFragQue.DeQue(); + CopyOut( + combFragLocal, + combFragGm[globalRowOffset * tilingData->hcMult * tilingData->hcMult], + curRowFactor * tilingData->hcMult, + tilingData->hcMult); + combFragQue.FreeTensor(combFragLocal); + } + } + + __aicore__ inline void Process() { + if constexpr (useOriginal) { + ProcessOriginal(); + return; + } + if ASCEND_IS_AIC { + return; + } + int64_t stage1UsedCoreNum = tilingData->cubeBlockDimK; + int64_t mmLastAxisSize = + CeilAlign(tilingData->hcMix, MM_CACHE_LINE_BYTES / sizeof(float)); + int64_t xCastFp32BufSize = + tilingData->mL1Size * + CeilAlign(tilingData->cvLoopKSize, MM_CACHE_LINE_BYTES / sizeof(float)); + int64_t workspaceSize1 = + tilingData->cubeCoreNum * DOUBLE_BUFFER * xCastFp32BufSize; + int64_t workspaceSize2 = CeilAlign(stage1UsedCoreNum * tilingData->bs * + mmLastAxisSize * sizeof(float), + WORKSPACE_ALIGN_SIZE) / + sizeof(float); + if (GetBlockIdx() < tilingData->prePostCoreNum) { + ProcessPrePost( + stage1UsedCoreNum, workspaceSize1, workspaceSize2, mmLastAxisSize); + } else { + ProcessSinkhorn( + stage1UsedCoreNum, workspaceSize1, workspaceSize2, mmLastAxisSize); + } + } + + private: + static constexpr int64_t COMPACT_HC_MULT = 4; + static constexpr int64_t COMPACT_MATRIX_SIZE = + COMPACT_HC_MULT * COMPACT_HC_MULT; + + TPipe* pipe; + const HcPreVaTilingData* tilingData; + GlobalTensor mixesGm; + GlobalTensor rsqrtGm; + GlobalTensor hcScaleGm; + GlobalTensor hcBaseGm; + GlobalTensor workspaceGm; + GlobalTensor xGm; + GlobalTensor yGm; + GlobalTensor postGm; + GlobalTensor combFragGm; + GlobalTensor preMixGm; + GlobalTensor preGm; + + TQue mixesQue01; + TQue mixesQue2; + TQue xQue; + TQue yQue; + TQue postQue; + TQue combFragQue; + + TQue squareSumQue; + + TBuf hcBaseBuf0; + TBuf hcBaseBuf1; + TBuf hcBaseBuf2; + + TBuf rowBrcbBuf0; + TBuf hcBrcbBuf1; + TBuf reduceBuf; + + TBuf rsqrtBuf; + TBuf squareReduceBuf; + TBuf mixes01ReduceBuf; + TBuf mixes02ReduceBuf; + + TBuf xCastBuf; + TBuf yCastBuf; + TBuf maskPatternBuf; + TBuf preMixBuf; + + LocalTensor mixes01Local; + LocalTensor mixes2Local; + LocalTensor rsqrtLocal; + LocalTensor xLocal; + LocalTensor yLocal; + LocalTensor postLocal; + LocalTensor combFragLocal; + LocalTensor hcBase0Local; + LocalTensor hcBase1Local; + LocalTensor hcBase2Local; + LocalTensor rowBrcbLocal0; + LocalTensor hcBrcbLocal1; + LocalTensor reduceLocal; + LocalTensor squareReduceLocal; + LocalTensor mixes01ReduceLocal; + LocalTensor mixes02ReduceLocal; + LocalTensor xCastLocal; + LocalTensor yCastLocal; + LocalTensor squareSumOutLocal; + LocalTensor maskPatternLocal; + LocalTensor preMixLocal; +}; + +// preMix 场景专用的 Part2 实现,对应 tilingKey=2。 +template +class HcPreVaMembaseKSplitCorePremixPart2 { + public: + __aicore__ inline HcPreVaMembaseKSplitCorePremixPart2() {} + + __aicore__ inline void InitGlobalBuffers(GM_ADDR x, + GM_ADDR hcScale, + GM_ADDR hcBase, + GM_ADDR y, + GM_ADDR post, + GM_ADDR combFrag, + GM_ADDR preMix, + GM_ADDR pre, + GM_ADDR workspace) { + xGm.SetGlobalBuffer((__gm__ T*)x); + hcScaleGm.SetGlobalBuffer((__gm__ float*)hcScale); + hcBaseGm.SetGlobalBuffer((__gm__ float*)hcBase); + yGm.SetGlobalBuffer((__gm__ T*)y); + postGm.SetGlobalBuffer((__gm__ float*)post); + combFragGm.SetGlobalBuffer((__gm__ float*)combFrag); + preMixGm.SetGlobalBuffer((__gm__ float*)preMix); + preGm.SetGlobalBuffer((__gm__ float*)pre); + workspaceGm.SetGlobalBuffer((__gm__ float*)workspace); + } + __aicore__ inline void InitQueBuffers(int64_t stage1UsedCoreNum, int64_t xQueNum2) { int64_t mixesQue01Size = stage1UsedCoreNum * tilingData->stage2RowFactor * @@ -311,18 +1577,17 @@ class HcPreVaMembaseKSplitCorePart2 { tilingData->hcMult * sizeof(float)); pipe->InitBuffer( squareReduceBuf, - tilingData->stage2RowFactor * SQUARE_SUM_SIZE * sizeof(float)); + tilingData->stage2RowFactor * tilingData->hcMultAlign * sizeof(float)); pipe->InitBuffer(xCastBuf, xQueNum2 * sizeof(float)); pipe->InitBuffer(yCastBuf, tilingData->stage2RowFactor * RoundUp(tilingData->dFactor) * sizeof(float)); pipe->InitBuffer( rsqrtBuf, RoundUp(tilingData->stage2RowFactor) * sizeof(float)); - pipe->InitBuffer(maskPatternBuf, - RoundUp((tilingData->stage2RowFactor + - MASK_PATTERN_DIM_SIZE - 1) * - MASK_PATTERN_REPEAT_SIZE) * - sizeof(uint32_t)); + pipe->InitBuffer( + maskPatternBuf, + RoundUp(MASK_PATTERN_DIM_SIZE * MASK_PATTERN_REPEAT_SIZE) * + sizeof(uint32_t)); pipe->InitBuffer( preMixBuf, tilingData->stage2RowFactor * tilingData->hcMultAlign * sizeof(float)); @@ -343,9 +1608,8 @@ class HcPreVaMembaseKSplitCorePart2 { rsqrtLocal = rsqrtBuf.Get(); maskPatternLocal = maskPatternBuf.Get(); preMixLocal = preMixBuf.Get(); - SetGatherMaskPattern( - maskPatternLocal, - tilingData->stage2RowFactor + MASK_PATTERN_DIM_SIZE - 1); + SetGatherMaskPattern(maskPatternLocal, + static_cast(MASK_PATTERN_DIM_SIZE)); } __aicore__ inline void Init(GM_ADDR x, @@ -359,9 +1623,6 @@ class HcPreVaMembaseKSplitCorePart2 { GM_ADDR workspace, const HcPreVaTilingData* tilingDataPtr, TPipe* pipePtr) { - if ASCEND_IS_AIC { - return; - } pipe = pipePtr; tilingData = tilingDataPtr; InitGlobalBuffers( @@ -374,63 +1635,9 @@ class HcPreVaMembaseKSplitCorePart2 { GetLocalTensors(); } - // Match the four-stream Sinkhorn reduction order used by HcPre's - // compact layout above 32 tokens. The small-token path uses - // WholeReduceSum and its pairwise addition tree. - __aicore__ inline void ReduceSinkhornRows(const LocalTensor& output, - const LocalTensor& input, - int64_t rowCount) { - if (tilingData->hcMult != 4 || tilingData->bs <= 32) { - LastDimReduceSumPerf(output, input, rowCount, tilingData->hcMult); - return; - } - // One eight-word mask covers 256 source elements (32 padded rows). - // Longer counter masks would read the next column's different pattern. - for (int64_t first = 0; first < rowCount; first += 32) { - const int64_t remaining = rowCount - first; - const int64_t rows = remaining < 32 ? remaining : 32; - uint64_t selected = 0; - GatherMask(output[first], - input[first * tilingData->hcMultAlign], - maskPatternLocal, - true, - rows * tilingData->hcMultAlign, - {1, 1, 8, 0}, - selected); - PipeBarrier(); - for (int64_t column = 1; column < 4; ++column) { - GatherMask(hcBrcbLocal1, - input[first * tilingData->hcMultAlign], - maskPatternLocal[column * MASK_PATTERN_REPEAT_SIZE], - true, - rows * tilingData->hcMultAlign, - {1, 1, 8, 0}, - selected); - PipeBarrier(); - Add(output[first], output[first], hcBrcbLocal1, rows); - PipeBarrier(); - } - } - } - - __aicore__ inline void SoftmaxSinkhornRows(const LocalTensor& data, - int64_t rowCount) { - LastDimReduceMaxPerf(reduceLocal, data, rowCount, tilingData->hcMult); - SubABLastDimBrcInline( - data, data, reduceLocal, hcBrcbLocal1, rowCount, tilingData->hcMult); - Exp(data, data, rowCount * tilingData->hcMultAlign); - PipeBarrier(); - ReduceSinkhornRows(reduceLocal, data, rowCount); - DivABLastDimBrcInline( - data, data, reduceLocal, hcBrcbLocal1, rowCount, tilingData->hcMult); - Adds(data, data, tilingData->hcEps, rowCount * tilingData->hcMultAlign); - PipeBarrier(); - } - __aicore__ inline void Process() { if ASCEND_IS_AIV { - int64_t stage1UsedCoreNum = - tilingData->cubeBlockDimK; // todo check 此处不应该写死32 + int64_t stage1UsedCoreNum = tilingData->cubeBlockDimK; int64_t stage2BlockIdx = GetBlockIdx(); int64_t stage2UsedCoreNum = tilingData->secondUsedCoreNum; if (stage2BlockIdx >= stage2UsedCoreNum) { @@ -475,11 +1682,7 @@ class HcPreVaMembaseKSplitCorePart2 { int64_t curRowFactor = (rowOuterIdx == rowOuterLoop - 1) ? tailRowFactor : tilingData->stage2RowFactor; - SetGatherMaskPattern( - maskPatternLocal, - tilingData->stage2RowFactor + MASK_PATTERN_DIM_SIZE - 1); squareSumOutLocal = squareSumQue.AllocTensor(); - // todo CopyIn(workspaceGm[workspaceSize1 + workspaceSize2 + stage2BlockIdx * tilingData->rowOfFormerBlock * SQUARE_SUM_SIZE + @@ -497,13 +1700,15 @@ class HcPreVaMembaseKSplitCorePart2 { 1, stage1UsedCoreNum, curRowFactor * SQUARE_SUM_SIZE); - int64_t curBsIdxForAll = stage2BlockIdx * tilingData->rowOfFormerBlock + - rowOuterIdx * tilingData->stage2RowFactor; - GatherMaskByDiagonal(rsqrtLocal, - squareReduceLocal, - maskPatternLocal, - curRowFactor, - curBsIdxForAll % SQUARE_SUM_SIZE); + int64_t curBsIdxForAll = + (stage2BlockIdx * tilingData->rowLoopOfFormerBlock + rowOuterIdx) * + tilingData->stage2RowFactor; + GatherMaskByDiagonal( + rsqrtLocal, + squareReduceLocal, + maskPatternLocal, + curRowFactor, + static_cast(curBsIdxForAll % SQUARE_SUM_SIZE)); float coeff = 1.0f / static_cast(tilingData->k); Muls(rsqrtLocal, rsqrtLocal, coeff, curRowFactor); PipeBarrier(); @@ -564,17 +1769,18 @@ class HcPreVaMembaseKSplitCorePart2 { GetTPipePtr()->FetchEventID(HardEvent::V_MTE3)); SetFlag(eventIdPreOut); WaitFlag(eventIdPreOut); - CopyOut(mixes01ReduceLocal, - preGm[stage2BlockIdx * tilingData->rowOfFormerBlock * - tilingData->hcMult + - rowOuterIdx * tilingData->stage2RowFactor * - tilingData->hcMult], - curRowFactor, - tilingData->hcMult); - event_t eventIdPreDone = static_cast( + int64_t preRowBase = stage2BlockIdx * tilingData->rowOfFormerBlock + + rowOuterIdx * tilingData->stage2RowFactor; + for (int64_t rowIdx = 0; rowIdx < curRowFactor; rowIdx++) { + CopyOut(mixes01ReduceLocal[rowIdx * tilingData->hcMultAlign], + preGm[(preRowBase + rowIdx) * tilingData->hcMult], + 1, + tilingData->hcMult); + } + event_t eventIdPreOutBack = static_cast( GetTPipePtr()->FetchEventID(HardEvent::MTE3_V)); - SetFlag(eventIdPreDone); - WaitFlag(eventIdPreDone); + SetFlag(eventIdPreOutBack); + WaitFlag(eventIdPreOutBack); } if (tilingData->hasPreMix != 0) { CopyIn(preMixGm[stage2BlockIdx * tilingData->rowOfFormerBlock * @@ -597,7 +1803,7 @@ class HcPreVaMembaseKSplitCorePart2 { CopyIn(xGm[xGmBlockBaseOffsetPart2 + xGmBsBaseOffsetPart2 + dLoopIdx * tilingData->dFactor], xLocal, - curRowFactor * tilingData->hcMult, + tilingData->stage2RowFactor * tilingData->hcMult, curDFactor, tilingData->d - curDFactor); xQue.template EnQue(xLocal); @@ -612,9 +1818,7 @@ class HcPreVaMembaseKSplitCorePart2 { yCastLocal, curRowFactor, tilingData->hcMult, - curDFactor, - tilingData->hasPreMix != 0 ? tilingData->hcMult - : tilingData->hcMultAlign); + curDFactor); xQue.template FreeTensor(xLocal); yQue.template EnQue(yLocal); yLocal = yQue.template DeQue(); @@ -698,31 +1902,18 @@ class HcPreVaMembaseKSplitCorePart2 { hcBase2Local, curRowFactor, tilingData->hcMult * tilingData->hcMultAlign); - const int64_t sinkhornRows = curRowFactor * tilingData->hcMult; - if (tilingData->hcMult == 4) { - const event_t vectorEvent = - static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_S)); - SetFlag(vectorEvent); - WaitFlag(vectorEvent); - for (int64_t column = 0; column < 4; ++column) { - for (int64_t word = 0; word < MASK_PATTERN_REPEAT_SIZE; ++word) { - maskPatternLocal.SetValue( - column * MASK_PATTERN_REPEAT_SIZE + word, - 0x01010101u << column); - } - } - const event_t indexEvent = - static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); - SetFlag(indexEvent); - WaitFlag(indexEvent); - } - SoftmaxSinkhornRows(mixes02ReduceLocal, sinkhornRows); + SoftmaxFP32Perf(mixes02ReduceLocal, + mixes02ReduceLocal, + reduceLocal, + hcBrcbLocal1, + curRowFactor * tilingData->hcMult, + tilingData->hcMult, + tilingData->hcEps); ReduceSumARAPerf(reduceLocal, mixes02ReduceLocal, curRowFactor, tilingData->hcMult, tilingData->hcMult); - // Column sums retain the block-aligned stride from ReduceSumARAPerf. Adds(reduceLocal, reduceLocal, tilingData->hcEps, @@ -735,7 +1926,10 @@ class HcPreVaMembaseKSplitCorePart2 { tilingData->hcMult, tilingData->hcMult); for (int64_t iter = 0; iter < tilingData->iterTimes - 1; iter++) { - ReduceSinkhornRows(reduceLocal, combFragLocal, sinkhornRows); + LastDimReduceSumPerf(reduceLocal, + combFragLocal, + curRowFactor * tilingData->hcMult, + tilingData->hcMult); Adds(reduceLocal, reduceLocal, tilingData->hcEps, diff --git a/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/xllm_kernel_hc_pre_va.cpp b/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/xllm_kernel_hc_pre_va.cpp index 866db5b305..cd22a55312 100644 --- a/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/xllm_kernel_hc_pre_va.cpp +++ b/xllm-kernel/csrc/ascendc/hc_pre_va/op_kernel/xllm_kernel_hc_pre_va.cpp @@ -46,7 +46,6 @@ extern "C" __global__ __aicore__ void xllm_kernel_hc_pre_va(GM_ADDR x, } TPipe pipe; - // A3 if (TILING_KEY_IS(0)) { GET_TILING_DATA_WITH_STRUCT(HcPreVaTilingData, tiling_data_in, tiling); const HcPreVaTilingData* __restrict tilingData = &tiling_data_in; @@ -57,7 +56,32 @@ extern "C" __global__ __aicore__ void xllm_kernel_hc_pre_va(GM_ADDR x, pipe.Destroy(); TPipe pipeStage2; - XllmKernelHcPreVa::HcPreVaMembaseKSplitCorePart2 op2; + XllmKernelHcPreVa::HcPreVaMembaseKSplitCorePart2 op2; + op2.Init(x, + hc_scale, + hc_base, + y, + post, + comb_frag, + pre_mix, + pre, + userWs, + tilingData, + &pipeStage2); + op2.Process(); + + pipeStage2.Destroy(); + } else if (TILING_KEY_IS(1)) { + GET_TILING_DATA_WITH_STRUCT(HcPreVaTilingData, tiling_data_in, tiling); + const HcPreVaTilingData* __restrict tilingData = &tiling_data_in; + XllmKernelHcPreVa::HcPreVaMembaseKSplitCorePart1 op; + op.Init(x, hc_fn, userWs, tilingData, &pipe); + op.Process(); + + pipe.Destroy(); + + TPipe pipeStage2; + XllmKernelHcPreVa::HcPreVaMembaseKSplitCorePart2 op2; op2.Init(x, hc_scale, hc_base, diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_metadata/op_kernel_aicpu/quant_lightning_indexer_metadata_aicpu.json b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_metadata/op_kernel_aicpu/quant_lightning_indexer_metadata_aicpu.json index 2e5db434e8..e9c4973ba2 100644 --- a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_metadata/op_kernel_aicpu/quant_lightning_indexer_metadata_aicpu.json +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_metadata/op_kernel_aicpu/quant_lightning_indexer_metadata_aicpu.json @@ -6,7 +6,7 @@ "flagAsync":"False", "flagPartial":"False", "functionName":"RunCpuKernel", - "kernelSo":"libxllm_kernel_aicpu.so", + "kernelSo":"libmath_aicpu_kernels.so", "opKernelLib":"CUSTAICPUKernel", "userDefined":"True", "workspaceSize":"100" diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_graph/quant_lightning_indexer_v2_metadata_va_proto.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_graph/quant_lightning_indexer_v2_metadata_va_proto.cpp new file mode 100644 index 0000000000..8e6319a8e5 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_graph/quant_lightning_indexer_v2_metadata_va_proto.cpp @@ -0,0 +1,32 @@ +// Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. + +#include "graph/operator_reg.h" +#include "graph/types.h" + +namespace ge { + +REG_OP(XllmKernelQuantLightningIndexerV2MetadataVa) + .OPTIONAL_INPUT(cu_seqlens_q, TensorType({DT_INT32})) + .OPTIONAL_INPUT(cu_seqlens_k, TensorType({DT_INT32})) + .OPTIONAL_INPUT(seqused_q, TensorType({DT_INT32})) + .OPTIONAL_INPUT(seqused_k, TensorType({DT_INT32})) + .OPTIONAL_INPUT(cmp_residual_k, TensorType({DT_INT32})) + .OUTPUT(metadata, TensorType({DT_INT32})) + .REQUIRED_ATTR(num_heads_q, Int) + .REQUIRED_ATTR(num_heads_k, Int) + .REQUIRED_ATTR(head_dim, Int) + .REQUIRED_ATTR(topk, Int) + .REQUIRED_ATTR(quant_mode, Int) + .ATTR(batch_size, Int, 0) + .ATTR(max_seqlen_q, Int, 0) + .ATTR(max_seqlen_k, Int, 0) + .ATTR(layout_q, String, "BSND") + .ATTR(layout_k, String, "BSND") + .ATTR(mask_mode, Int, 0) + .ATTR(cmp_ratio, Int, 1) + .REQUIRED_ATTR(aic_core_num, Int) + .REQUIRED_ATTR(aiv_core_num, Int) + .REQUIRED_ATTR(soc_version, String) + .OP_END_FACTORY_REG(XllmKernelQuantLightningIndexerV2MetadataVa) + +} // namespace ge diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.cpp new file mode 100644 index 0000000000..3a8609ff7d --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.cpp @@ -0,0 +1,207 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file aclnn_quant_lightning_indexer_v2_metadata_va.cpp + * \brief + */ + +#include "aclnn_quant_lightning_indexer_v2_metadata_va.h" + +#include "../quant_lightning_indexer_v2_metadata_va_check.h" +#include "aclnn/aclnn_base.h" +#include "aclnn_kernels/common/op_error_check.h" +#include "aclnn_kernels/contiguous.h" +#include "aclnn_kernels/reshape.h" +#include "opdev/common_types.h" +#include "opdev/data_type_utils.h" +#include "opdev/format_utils.h" +#include "opdev/make_op_executor.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "opdev/op_log.h" +#include "opdev/platform.h" +#include "opdev/tensor_view_utils.h" +#include "quant_lightning_indexer_v2_metadata_va.h" + +#ifdef __cplusplus +extern "C" { +#endif + +aclnnStatus aclnnXllmKernelQuantLightningIndexerV2MetadataVaGetWorkspaceSize( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + const aclTensor* metadata, + uint64_t* workspaceSize, + aclOpExecutor** executor) { + if (workspaceSize == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "workspaceSize is nullptr"); + return ACLNN_ERR_INNER_NULLPTR; + } + if (executor == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "executor is nullptr"); + return ACLNN_ERR_INNER_NULLPTR; + } + L2_DFX_PHASE_1(aclnnXllmKernelQuantLightningIndexerV2MetadataVa, + DFX_IN(cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio), + DFX_OUT(metadata)); + + auto uniqueExecutor = CREATE_EXECUTOR(); + CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + + const op::PlatformInfo& npuInfo = op::GetCurrentPlatformInfo(); + uint32_t aicCoreNum = npuInfo.GetCubeCoreNum(); + uint32_t aivCoreNum = npuInfo.GetVectorCoreNum(); + const std::string socVersion = npuInfo.GetSocLongVersion(); + + auto ret = ParamsCheckQliV2Va(cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + metadata, + aicCoreNum, + aivCoreNum, + socVersion); + CHECK_RET(ret == ACLNN_SUCCESS, ret); + + const aclTensor* cuSeqlensQOptionalContiguous = nullptr; + if (cuSeqlensQOptional != nullptr) { + cuSeqlensQOptionalContiguous = + l0op::Contiguous(cuSeqlensQOptional, uniqueExecutor.get()); + if (cuSeqlensQOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "cu_seqlens_q contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* cuSeqlensKOptionalContiguous = nullptr; + if (cuSeqlensKOptional != nullptr) { + cuSeqlensKOptionalContiguous = + l0op::Contiguous(cuSeqlensKOptional, uniqueExecutor.get()); + if (cuSeqlensKOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "cu_seqlens_k contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* sequsedQOptionalContiguous = nullptr; + if (sequsedQOptional != nullptr) { + sequsedQOptionalContiguous = + l0op::Contiguous(sequsedQOptional, uniqueExecutor.get()); + if (sequsedQOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "seqused_q contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* sequsedKOptionalContiguous = nullptr; + if (sequsedKOptional != nullptr) { + sequsedKOptionalContiguous = + l0op::Contiguous(sequsedKOptional, uniqueExecutor.get()); + if (sequsedKOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "seqused_k contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* cmpResidualLKOptionalContiguous = nullptr; + if (cmpResidualKOptional != nullptr) { + cmpResidualLKOptionalContiguous = + l0op::Contiguous(cmpResidualKOptional, uniqueExecutor.get()); + if (cmpResidualLKOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "cmp_residual_k contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + + auto output = l0op::XllmKernelQuantLightningIndexerV2MetadataVa( + cuSeqlensQOptionalContiguous, + cuSeqlensKOptionalContiguous, + sequsedQOptionalContiguous, + sequsedKOptionalContiguous, + cmpResidualLKOptionalContiguous, + numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + aicCoreNum, + aivCoreNum, + socVersion.c_str(), + metadata, + uniqueExecutor.get()); + CHECK_RET(output != nullptr, ACLNN_ERR_INNER_NULLPTR); + + *workspaceSize = uniqueExecutor->GetWorkspaceSize(); + uniqueExecutor.ReleaseTo(executor); + return ACLNN_SUCCESS; +} + +aclnnStatus aclnnXllmKernelQuantLightningIndexerV2MetadataVa( + void* workspace, + uint64_t workspaceSize, + aclOpExecutor* executor, + aclrtStream stream) { + L2_DFX_PHASE_2(aclnnXllmKernelQuantLightningIndexerV2MetadataVa); + return CommonOpExecutorRun(workspace, workspaceSize, executor, stream); +} + +#ifdef __cplusplus +} +#endif diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.h new file mode 100644 index 0000000000..509e015fd2 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.h @@ -0,0 +1,57 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef ACLNN_QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_H +#define ACLNN_QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_H + +#include + +#include "aclnn/aclnn_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +__attribute__((visibility("default"))) aclnnStatus +aclnnXllmKernelQuantLightningIndexerV2MetadataVaGetWorkspaceSize( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + const aclTensor* metadata, + uint64_t* workspaceSize, + aclOpExecutor** executor); + +__attribute__((visibility("default"))) aclnnStatus +aclnnXllmKernelQuantLightningIndexerV2MetadataVa(void* workspace, + uint64_t workspaceSize, + aclOpExecutor* executor, + aclrtStream stream); + +#ifdef __cplusplus +} +#endif + +#endif // ACLNN_QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/quant_lightning_indexer_v2_metadata_va.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/quant_lightning_indexer_v2_metadata_va.cpp new file mode 100644 index 0000000000..39bec2a403 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/quant_lightning_indexer_v2_metadata_va.cpp @@ -0,0 +1,127 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_lightning_indexer_v2_metadata_va.cpp + * \brief + */ + +#include "quant_lightning_indexer_v2_metadata_va.h" + +#include "opdev/aicpu/aicpu_task.h" +#include "opdev/make_op_executor.h" +#include "opdev/op_def.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "opdev/op_log.h" +#include "opdev/shape_utils.h" + +using namespace op; +namespace l0op { +OP_TYPE_REGISTER(XllmKernelQuantLightningIndexerV2MetadataVa); + +const aclTensor* XllmKernelQuantLightningIndexerV2MetadataVa( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + int64_t aicCoreNum, + int64_t aivCoreNum, + const char* socVersion, + const aclTensor* metadata, + aclOpExecutor* executor) { + L0_DFX(XllmKernelQuantLightningIndexerV2MetadataVa, + cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + aicCoreNum, + aivCoreNum, + socVersion, + metadata); + + static internal::AicpuTaskSpace space( + "XllmKernelQuantLightningIndexerV2MetadataVa"); + + auto ret = + ADD_TO_LAUNCHER_LIST_AICPU(XllmKernelQuantLightningIndexerV2MetadataVa, + OP_ATTR_NAMES({"num_heads_q", + "num_heads_k", + "head_dim", + "topk", + "quant_mode", + "batch_size", + "max_seqlen_q", + "max_seqlen_k", + "layout_q", + "layout_k", + "mask_mode", + "cmp_ratio", + "aic_core_num", + "aiv_core_num", + "soc_version"}), + OP_INPUT(cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional), + OP_OUTPUT(metadata), + OP_ATTR(numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + aicCoreNum, + aivCoreNum, + socVersion)); + + OP_CHECK(ret == ACL_SUCCESS, + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, + "XllmKernelQuantLightningIndexerV2MetadataVa " + "ADD_TO_LAUNCHER_LIST_AICPU failed."), + return nullptr); + return metadata; +} +} // namespace l0op diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/quant_lightning_indexer_v2_metadata_va.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/quant_lightning_indexer_v2_metadata_va.h new file mode 100644 index 0000000000..36e412584e --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/op_api/quant_lightning_indexer_v2_metadata_va.h @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef L0_QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_H +#define L0_QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_H + +#include "opdev/op_executor.h" + +namespace l0op { +const aclTensor* XllmKernelQuantLightningIndexerV2MetadataVa( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + int64_t aicCoreNum, + int64_t aivCoreNum, + const char* socVersion, + const aclTensor* metadata, + aclOpExecutor* executor); +} // namespace l0op + +#endif diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/quant_lightning_indexer_v2_metadata_va_check.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/quant_lightning_indexer_v2_metadata_va_check.h new file mode 100644 index 0000000000..4d15639820 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/quant_lightning_indexer_v2_metadata_va_check.h @@ -0,0 +1,704 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_lightning_indexer_v2_metadata_va_check.h + * \brief + */ + +#include "../../quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_error_log.h" +#include "../../quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h" +#include "log/log.h" +#include "opdev/data_type_utils.h" +#include "opdev/format_utils.h" +#include "opdev/op_log.h" +#include "opdev/tensor_view_utils.h" + +#ifdef __cplusplus +extern "C" { +#endif + +namespace { + +static constexpr const char* QLI_V2_ACLNN_OP_NAME = + "XllmKernelQuantLightningIndexerV2MetadataVa"; + +inline constexpr int64_t QLI_V2_QUANT_MODE_1 = 1; +inline constexpr int64_t QLI_V2_QUANT_MODE_2 = 2; +inline constexpr int64_t QLI_V2_QUANT_MODE_3 = 3; +inline constexpr int64_t QLI_V2_QUANT_MODE_4 = 4; +inline constexpr int64_t QLI_V2_QUANT_MODE_5 = 5; +inline constexpr int64_t QLI_V2_NO_MASK_MODE = 0; +inline constexpr int64_t QLI_V2_CAUSAL_MASK_MODE = 3; +inline constexpr int64_t QLI_V2_CMP_RATIO_LOWER_BOUND = 1; +inline constexpr int64_t QLI_V2_CMP_RATIO_UPPER_BOUND = 128; +inline constexpr int64_t QLI_V2_NUM_HEADS_Q_LOWER_BOUND = 1; +inline constexpr int64_t QLI_V2_NUM_HEADS_Q_UPPER_BOUND = 64; +inline constexpr int64_t QLI_V2_NUM_HEADS_Q_G32 = + 32; // g=32 支持 (A1 对齐 v1 推导) +inline constexpr int64_t QLI_V2_TOPK_LOWER_BOUND = 1; +inline constexpr int64_t QLI_V2_A5_TOPK_UPPER_BOUND = 8192; +inline constexpr int64_t QLI_V2_A3_TOPK_UPPER_BOUND = 2048; + +inline bool IsTensorExistQliV2Va(const aclTensor* tensor) { + return (tensor != nullptr) && (tensor->GetViewShape().GetDimNum() > 0) && + (tensor->GetViewShape().GetDim(0) > 0); +} + +int64_t GetDimNumQliV2Va(const aclTensor* tensor) { + if (tensor == nullptr) { + return -1; + } + return tensor->GetViewShape().GetDimNum(); +} + +aclDataType GetDataTypeQliV2Va(const aclTensor* tensor) { + aclDataType dataType = aclDataType::ACL_DT_UNDEFINED; + if (tensor == nullptr) { + return dataType; + } + aclGetDataType(tensor, &dataType); + return dataType; +} + +inline bool IsTensorSourceQLiV2(const std::string& source) { + return source != "batch_size"; +} + +inline int64_t GetRawShapeSizeQLiV2(const std::string& source, + int64_t batchValue) { + if (source.find("cu_seqlens") != std::string::npos) { + return batchValue + 1; + } + return batchValue; +} + +int64_t GetQueryBatchSizeQliV2Va(int64_t batchSize, + const aclTensor* cuSeqlensQOptional, + const aclTensor* sequsedQOptional, + const char* layoutQOptional, + std::string& source) { + // 1. 如果sequsedQOptional 传了,使用sequsedQOptional获取BatchSize + if (IsTensorExistQliV2Va(sequsedQOptional)) { + source = "seqused_q"; + return sequsedQOptional->GetViewShape().GetDim(0); + } + // 2. 如果sequsedQOptional 没传,使用cuSeqlensQOptional获取BatchSize + if (strcmp(layoutQOptional, "TND") == 0) { + if (IsTensorExistQliV2Va( + cuSeqlensQOptional)) { // 前序校验已保证layout_q = + // TND时,cu_seqlens_q必须传入,此通路必达 + source = "cu_seqlens_q"; + return cuSeqlensQOptional->GetViewShape().GetDim(0) - 1; + } + } + source = "batch_size"; + // 3. 使用batchSize + return batchSize; +} + +int64_t GetKeyBatchSizeQliV2Va(int64_t batchSize, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedKOptional, + const char* layoutKOptional, + std::string& source) { + // 1. 如果sequsedKOptional 传了,使用sequsedKOptional获取BatchSize + if (IsTensorExistQliV2Va(sequsedKOptional)) { + source = "seqused_k"; + return sequsedKOptional->GetViewShape().GetDim(0); + } + // 如果是 TND,必须使用 cuSeqlensKOptional获取BatchSize + if (strcmp(layoutKOptional, "TND") == 0) { + if (IsTensorExistQliV2Va( + cuSeqlensKOptional)) { // 前序校验已保证layout_k = + // TND时,cu_seqlens_k必须传入,此通路必达 + source = "cu_seqlens_k"; + return cuSeqlensKOptional->GetViewShape().GetDim(0) - 1; + } + } + source = "batch_size"; + // 3. 使用batchSize + return batchSize; +} + +aclnnStatus CheckSingleParamQliV2Va(int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + const char* layoutQOptional, + const char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + uint32_t aicCoreNum, + uint32_t aivCoreNum, + const std::string& socVersion) { + // num_heads_k 校验 + if (numHeadsK != 1) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "num_heads_kv", + std::to_string(numHeadsK), + "The value of num_heads_kv should be 1"); + return ACLNN_ERR_PARAM_INVALID; + } + // head_dim 校验 + if (headDim != 128) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "head_dim", + std::to_string(headDim), + "The value of head_dim should be 128"); + return ACLNN_ERR_PARAM_INVALID; + } + // batch_size 非负校验 + if (batchSize < 0) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "batch_size", + std::to_string(batchSize), + "The value of batch_size should not be negative"); + return ACLNN_ERR_PARAM_INVALID; + } + // max_seqlen_q 校验 + if (maxSeqlenQ < -1) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_q", + std::to_string(maxSeqlenQ), + "The value of max_seqlen_q should be >= -1"); + return ACLNN_ERR_PARAM_INVALID; + } + // max_seqlen_k 校验 + if (maxSeqlenK < -1) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_k", + std::to_string(maxSeqlenK), + "The value of max_seqlen_k should be >= -1"); + return ACLNN_ERR_PARAM_INVALID; + } + // mask_mode 校验 + if ((maskMode != QLI_V2_NO_MASK_MODE) && + (maskMode != QLI_V2_CAUSAL_MASK_MODE)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "mask_mode", + std::to_string(maskMode), + "The value of mask_mode should be " + + std::to_string(QLI_V2_NO_MASK_MODE) + " or " + + std::to_string(QLI_V2_CAUSAL_MASK_MODE)); + return ACLNN_ERR_PARAM_INVALID; + } + // layout_q 校验 + if (layoutQOptional == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, "layout_q", "Layout_q is null"); + return ACLNN_ERR_PARAM_INVALID; + } + if ((strcmp(layoutQOptional, "TND") != 0) && + (strcmp(layoutQOptional, "BSND") != 0)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "layout_q", + layoutQOptional, + "The value of layout_q must be TND or BSND"); + return ACLNN_ERR_PARAM_INVALID; + } + // layout_k 校验 + if (layoutKOptional == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, "layout_k", "Layout_k is null"); + return ACLNN_ERR_PARAM_INVALID; + } + if ((strcmp(layoutKOptional, "PA_BBND") != 0) && + (strcmp(layoutQOptional, layoutKOptional) != 0)) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "layout_q and layout_k", + std::string(layoutQOptional) + " and " + std::string(layoutKOptional), + "For layout_k != PA_BBND, layout_q and layout_k must be the same"); + return ACLNN_ERR_PARAM_INVALID; + } + // num_heads_q 校验 (g=64/32, 32 参照 v1 对齐 mBaseSize=4*g 推导) + CHECK_COND((numHeadsQ == QLI_V2_NUM_HEADS_Q_UPPER_BOUND) || + (numHeadsQ == QLI_V2_NUM_HEADS_Q_G32), + ACLNN_ERR_PARAM_INVALID, + "num_heads_q should be %lld or %lld, but got %lld", + QLI_V2_NUM_HEADS_Q_UPPER_BOUND, + QLI_V2_NUM_HEADS_Q_G32, + numHeadsQ); + // topk 校验 + CHECK_COND( + topk >= QLI_V2_TOPK_LOWER_BOUND && topk <= QLI_V2_A3_TOPK_UPPER_BOUND, + ACLNN_ERR_PARAM_INVALID, + "topk should be [%lld, %lld], but got %lld", + QLI_V2_TOPK_LOWER_BOUND, + QLI_V2_A3_TOPK_UPPER_BOUND, + topk); + // quant_mode 校验 + CHECK_COND(quantMode == QLI_V2_QUANT_MODE_2, + ACLNN_ERR_PARAM_INVALID, + "quant_mode should be 2, but got %lld", + quantMode); + // cmp_ratio 校验 + CHECK_COND((cmpRatio >= QLI_V2_CMP_RATIO_LOWER_BOUND) && + (cmpRatio <= QLI_V2_CMP_RATIO_UPPER_BOUND) && + ((cmpRatio & (cmpRatio - 1)) == 0), + ACLNN_ERR_PARAM_INVALID, + "cmp_ratio should be 1/2/4/8/16/32/64/128, but got %lld", + cmpRatio); + CHECK_COND(strcmp(layoutKOptional, "PA_BBND") == 0, + ACLNN_ERR_PARAM_INVALID, + "layout_k must be PA_BBND, but got %s", + layoutKOptional); + // 校验 layout_q 为 BSND 时,max_seqlen_q 必须大于 0 + if ((strcmp(layoutQOptional, "BSND") == 0) && (maxSeqlenQ <= 0)) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_q", + std::to_string(maxSeqlenQ), + "When layout_q is BSND, the value of max_seqlen_q " + "must be equal to the size of the second axis of q"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 layout_k 为 BSND 时,max_seqlen_k 必须大于 0 + if ((strcmp(layoutKOptional, "BSND") == 0) && (maxSeqlenK <= 0)) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_k", + std::to_string(maxSeqlenK), + "When layout_k is BSND, the value of max_seqlen_k " + "must be equal to the size of the second axis of k"); + return ACLNN_ERR_PARAM_INVALID; + } + // 核心数校验 + CHECK_COND(aicCoreNum > 0, + ACLNN_ERR_PARAM_INVALID, + "AIC num should be larger than 0, but got %u", + aicCoreNum); + CHECK_COND(aicCoreNum <= optiling::AIC_CORE_MAX_NUM, + ACLNN_ERR_PARAM_INVALID, + "The maximum supported AIC num is %u, but got %u", + optiling::AIC_CORE_MAX_NUM, + aicCoreNum); + CHECK_COND(aivCoreNum > 0, + ACLNN_ERR_PARAM_INVALID, + "AIV num should be larger than 0, but got %u", + aivCoreNum); + CHECK_COND(aivCoreNum <= optiling::AIV_CORE_MAX_NUM, + ACLNN_ERR_PARAM_INVALID, + "The maximum supported AIV num is %u, but got %u", + optiling::AIV_CORE_MAX_NUM, + aivCoreNum); + return ACLNN_SUCCESS; +} + +aclnnStatus CheckExistenceQliV2Va(int64_t maskMode, + int64_t cmpRatio, + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + const char* layoutQOptional, + const char* layoutKOptional, + const aclTensor* metadata) { + // cu_seqlens_q 存在性校验 + if ((strcmp(layoutQOptional, "TND") == 0) && + !IsTensorExistQliV2Va(cuSeqlensQOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_q", + "When layout_q is TND, cu_seqlens_q must be provided"); + return ACLNN_ERR_PARAM_INVALID; + } + // layout_q BSND, seqused_q 不存在时,max_seqlen_q 不能为-1 + if (strcmp(layoutQOptional, "BSND") == 0 && + !IsTensorExistQliV2Va(sequsedQOptional) && (maxSeqlenQ <= -1)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_q", + std::to_string(maxSeqlenQ), + "When layout_q is BSND and seqused_q is not provided, max_seqlen_q can " + "not be -1"); + return ACLNN_ERR_PARAM_INVALID; + } + // cu_seqlens_k 存在性校验 + if ((strcmp(layoutKOptional, "TND") == 0) && + !IsTensorExistQliV2Va(cuSeqlensKOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_k", + "When layout_k is TND, cu_seqlens_k must be provided"); + return ACLNN_ERR_PARAM_INVALID; + } + // seqused_k 存在性校验 + if ((strcmp(layoutKOptional, "PA_BBND") == 0) && + !IsTensorExistQliV2Va(sequsedKOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "seqused_k", + "When layout_k is PA_BBND, seqused_k must be provided"); + return ACLNN_ERR_PARAM_INVALID; + } + // layout_k BSND, seqused_k 不存在时,max_seqlen_k 不能为-1 + if (strcmp(layoutKOptional, "BSND") == 0 && + !IsTensorExistQliV2Va(sequsedKOptional) && maxSeqlenK <= -1) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_k", + std::to_string(maxSeqlenK), + "When layout_k is BSND and seqused_k is not provided, max_seqlen_k can " + "not be -1"); + return ACLNN_ERR_PARAM_INVALID; + } + // cmp_residual_k 存在性校验 + if ((cmpRatio != QLI_V2_CMP_RATIO_LOWER_BOUND) && + (maskMode == QLI_V2_CAUSAL_MASK_MODE) && + !IsTensorExistQliV2Va(cmpResidualKOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cmp_residual_k", + "When cmp_ratio is not 1 and mask_mode is CAUSAL, cmp_residual_k must " + "be provided"); + return ACLNN_ERR_PARAM_INVALID; + } + // metadata 存在性校验 + if (!IsTensorExistQliV2Va(metadata)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, "metadata", "Metadata is nullptr"); + return ACLNN_ERR_PARAM_INVALID; + } + return ACLNN_SUCCESS; +} + +aclnnStatus CheckConsistencyQliV2Va(int64_t batchSize, + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + const char* layoutQOptional, + const char* layoutKOptional, + const aclTensor* metadata) { + int64_t dimNum = -1; + aclDataType dataType = aclDataType::ACL_DT_UNDEFINED; + + // 校验 cu_seqlens_q + if (IsTensorExistQliV2Va(cuSeqlensQOptional)) { + dimNum = GetDimNumQliV2Va(cuSeqlensQOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "cu_seqlens_q", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQliV2Va(cuSeqlensQOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_q", + ToString(dataType).GetString(), + "The dtype of cu_seqlens_q must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 cu_seqlens_k + if (IsTensorExistQliV2Va(cuSeqlensKOptional)) { + dimNum = GetDimNumQliV2Va(cuSeqlensKOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "cu_seqlens_k", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQliV2Va(cuSeqlensKOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_k", + ToString(dataType).GetString(), + "The dtype of cu_seqlens_k must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 seqused_q + if (IsTensorExistQliV2Va(sequsedQOptional)) { + dimNum = GetDimNumQliV2Va(sequsedQOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "seqused_q", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQliV2Va(sequsedQOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "seqused_q", + ToString(dataType).GetString(), + "The dtype of seqused_q must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 seqused_k + if (IsTensorExistQliV2Va(sequsedKOptional)) { + dimNum = GetDimNumQliV2Va(sequsedKOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "seqused_k", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQliV2Va(sequsedKOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "seqused_k", + ToString(dataType).GetString(), + "The dtype of seqused_k must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 cmp_residual_k + if (IsTensorExistQliV2Va(cmpResidualKOptional)) { + dimNum = GetDimNumQliV2Va(cmpResidualKOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "cmp_residual_k", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQliV2Va(cmpResidualKOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cmp_residual_k", + ToString(dataType).GetString(), + "The dtype of cmp_residual_k must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 metadata + if (IsTensorExistQliV2Va(metadata)) { + dimNum = GetDimNumQliV2Va(metadata); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "metadata", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQliV2Va(metadata); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "metadata", + ToString(dataType).GetString(), + "The dtype of metadata must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 metadata 元素数 + if (metadata->GetViewShape().GetDim(0) != + optiling::QLI_V2_METADATA_TOTAL_SIZE) { + OP_LOGE(ACLNN_ERR_PARAM_INVALID, + "The element num of metadata must be %u, but got %lld", + optiling::QLI_V2_METADATA_TOTAL_SIZE, + metadata->GetViewShape().GetDim(0)); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验batch + std::string querySource; + std::string keySource; + int64_t queryBatchSize = GetQueryBatchSizeQliV2Va(batchSize, + cuSeqlensQOptional, + sequsedQOptional, + layoutQOptional, + querySource); + int64_t keyBatchSize = GetKeyBatchSizeQliV2Va(batchSize, + cuSeqlensKOptional, + sequsedKOptional, + layoutKOptional, + keySource); + if (queryBatchSize != keyBatchSize) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + querySource + " and " + keySource, + std::to_string(GetRawShapeSizeQLiV2(querySource, queryBatchSize)) + + " and " + + std::to_string(GetRawShapeSizeQLiV2(keySource, keyBatchSize)), + "The batch_size obtained from query should be the same as that " + "obtained from key"); + if (IsTensorSourceQLiV2(querySource) && IsTensorSourceQLiV2(keySource)) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + querySource + " and " + keySource, + std::to_string(GetRawShapeSizeQLiV2(querySource, queryBatchSize)) + + " and " + + std::to_string(GetRawShapeSizeQLiV2(keySource, keyBatchSize)), + "The batch_size obtained from query should be the same as that " + "obtained from key"); + } else if (IsTensorSourceQLiV2(querySource)) { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + querySource, + std::to_string(GetRawShapeSizeQLiV2(querySource, queryBatchSize)), + "The batch_size obtained from query should be the same as that " + "obtained from key"); + } else { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + keySource, + std::to_string(GetRawShapeSizeQLiV2(keySource, keyBatchSize)), + "The batch_size obtained from query should be the same as that " + "obtained from key"); + } + return ACLNN_ERR_PARAM_INVALID; + } + // 校验TND场景q维度一致性 + if (strcmp(layoutQOptional, "TND") == 0 && + IsTensorExistQliV2Va(sequsedQOptional)) { + int64_t cuSeqlensQBatchSize = + cuSeqlensQOptional->GetViewShape().GetDim(0) - 1; + CHECK_COND(cuSeqlensQBatchSize == queryBatchSize, + ACLNN_ERR_PARAM_INVALID, + "When layout_q is TND and seqused_q is passed, The batch_size " + "obtained from cu_seqlens_q should be the " + "same as that obtained from seqused_q, but got %lld and %lld", + cuSeqlensQBatchSize, + queryBatchSize); + if (cuSeqlensQBatchSize != queryBatchSize) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_q and seqused_q", + std::to_string(cuSeqlensQBatchSize) + " and " + + std::to_string(queryBatchSize), + "When layout_q is TND and seqused_q is passed, " + "the shape size of cu_seqlens_q minus 1 must be equal to " + "the shape size of seqused_q"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验TND场景k维度一致性 + if (strcmp(layoutKOptional, "TND") == 0 && + IsTensorExistQliV2Va(sequsedKOptional)) { + int64_t cuSeqlensKBatchSize = + cuSeqlensKOptional->GetViewShape().GetDim(0) - 1; + if (cuSeqlensKBatchSize != keyBatchSize) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_k and seqused_k", + std::to_string(cuSeqlensKBatchSize) + " and " + + std::to_string(keyBatchSize), + "When layout_k is TND and seqused_k is passed, " + "the shape size of cu_seqlens_k minus 1 must be equal to " + "the shape size of seqused_k"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 cmp_residual_k 元素数 + if (IsTensorExistQliV2Va(cmpResidualKOptional)) { + auto cmpResidualKBatch = cmpResidualKOptional->GetViewShape().GetDim(0); + if (cmpResidualKBatch != queryBatchSize) { + if (IsTensorSourceQLiV2(querySource)) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cmp_residual_k and " + querySource, + std::to_string(cmpResidualKBatch) + " and " + + std::to_string( + GetRawShapeSizeQLiV2(querySource, queryBatchSize)), + "The batch_size of cmp_residual_k should match the valid batch " + "size"); + } else { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cmp_residual_k", + std::to_string(cmpResidualKBatch), + "The batch_size of cmp_residual_k should match the valid batch " + "size"); + } + return ACLNN_ERR_PARAM_INVALID; + } + } + return ACLNN_SUCCESS; +} + +aclnnStatus ParamsCheckQliV2Va(const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + const aclTensor* metadata, + uint32_t aicCoreNum, + uint32_t aivCoreNum, + const std::string& socVersion) { + auto ret = CheckSingleParamQliV2Va(numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + aicCoreNum, + aivCoreNum, + socVersion); + CHECK_RET(ret == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); + + ret = CheckExistenceQliV2Va(maskMode, + cmpRatio, + cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + metadata); + CHECK_RET(ret == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); + + ret = CheckConsistencyQliV2Va(batchSize, + cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + layoutQOptional, + layoutKOptional, + metadata); + CHECK_RET(ret == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); + + return ACLNN_SUCCESS; +} +} // namespace + +#ifdef __cplusplus +} +#endif diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/quant_lightning_indexer_v2_metadata_va_infershape.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/quant_lightning_indexer_v2_metadata_va_infershape.cpp new file mode 100644 index 0000000000..790d94f6e9 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_host/quant_lightning_indexer_v2_metadata_va_infershape.cpp @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_lightning_indexer_v2_metadata_va_infershape.cpp + * \brief + */ +#include "../../quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h" +#include "register/op_impl_registry.h" + +using namespace ge; + +namespace ops { +static ge::graphStatus InferShapeXllmKernelQuantLightningIndexerV2MetadataVa( + gert::InferShapeContext* context) { + gert::Shape* oShape = context->GetOutputShape(0); + oShape->SetDimNum(1); + oShape->SetDim(0, optiling::QLI_V2_METADATA_TOTAL_SIZE); + return GRAPH_SUCCESS; +} + +static ge::graphStatus InferDtypeXllmKernelQuantLightningIndexerV2MetadataVa( + gert::InferDataTypeContext* context) { + context->SetOutputDataType(0, DT_INT32); + return GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(XllmKernelQuantLightningIndexerV2MetadataVa) + .InferShape(InferShapeXllmKernelQuantLightningIndexerV2MetadataVa) + .InferDataType(InferDtypeXllmKernelQuantLightningIndexerV2MetadataVa); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.cpp new file mode 100644 index 0000000000..085d768cbc --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.cpp @@ -0,0 +1,1108 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#include "quant_lightning_indexer_v2_metadata_va_aicpu.h" + +#include +#include +#include +// KERNEL_STATUS_OK / KERNEL_STATUS_PARAM_INVALID 由 cpu_context_util.h (经 +// aicpu.h) 提供; 不 include status.h, 其 constexpr 与 cpu_context_util.h +// 的同名宏冲突。 + +using namespace optiling; + +namespace aicpu::xllm_qli_v2 { +uint32_t XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::Compute( + CpuKernelContext& ctx) { + bool success = Prepare(ctx); + if (!success) { + return KERNEL_STATUS_PARAM_INVALID; + } + SplitResult splitRes{aicCoreNum_, aivCoreNum_}; + success = BalanceSchedule(splitRes) && GenMetadata(splitRes); + return success ? KERNEL_STATUS_OK : KERNEL_STATUS_PARAM_INVALID; +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::Prepare( + CpuKernelContext& ctx) { + // input + cuSeqlensQ_ = ctx.Input(static_cast(ParamId::actSeqLenQ)); + cuSeqlensK_ = ctx.Input(static_cast(ParamId::actSeqLenK)); + sequsedQ_ = ctx.Input(static_cast(ParamId::seqUsedQ)); + sequsedK_ = ctx.Input(static_cast(ParamId::seqUsedK)); + cmpResidualK_ = ctx.Input(static_cast(ParamId::cmpResidualK)); + // output + metadata_ = ctx.Output(static_cast(ParamId::metadata)); + + bool requiredAttrs = GetAttrValue(ctx, "aic_core_num", aicCoreNum_) && + GetAttrValue(ctx, "aiv_core_num", aivCoreNum_) && + GetAttrValue(ctx, "soc_version", socVersion_) && + GetAttrValue(ctx, "num_heads_q", numHeadsQ_) && + GetAttrValue(ctx, "num_heads_k", numHeadsK_) && + GetAttrValue(ctx, "head_dim", headDim_) && + GetAttrValue(ctx, "topk", topk_); + if (!requiredAttrs) { + return false; + } + + // attributes optional + GetAttrValueOpt(ctx, "batch_size", batchSize_); + GetAttrValueOpt(ctx, "max_seqlen_q", maxSeqlenQ_); + GetAttrValueOpt(ctx, "max_seqlen_k", maxSeqlenK_); + GetAttrValueOpt(ctx, "layout_q", layoutQ_); + GetAttrValueOpt(ctx, "layout_k", layoutK_); + GetAttrValueOpt(ctx, "mask_mode", maskMode_); + GetAttrValueOpt(ctx, "cmp_ratio", cmpRatio_); + + return (ParamsCheck() && ParamsInit()); +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::ParamsCheck() { + if (metadata_ == nullptr) { + KERNEL_LOG_ERROR("Output metadata is nullptr"); + return false; + } else if (metadata_->GetData() == nullptr) { + KERNEL_LOG_ERROR("Output metadata data is nullptr"); + return false; + } + const int32_t batchSize = GetQueryBatchSize(); + return CheckCuSeqlensQ(batchSize) && CheckCuSeqlensK(batchSize) && + CheckSequsedQ(batchSize) && CheckSequsedK(batchSize) && + CheckCmpResidualK(batchSize); +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CheckCuSeqlensQ( + int32_t batchSize) const { + if (layoutQ_ != "TND" || cuSeqlensQ_ == nullptr || + cuSeqlensQ_->GetData() == nullptr) { + return true; + } + const int32_t* cuSeqlensQPtr = + static_cast(cuSeqlensQ_->GetData()); + if (cuSeqlensQPtr[0] != 0) { + KERNEL_LOG_ERROR( + "The first element of cu_seqlens_q should be 0, but got %d", + cuSeqlensQPtr[0]); + return false; + } + for (int32_t i = 1; i < batchSize + 1; ++i) { + if (cuSeqlensQPtr[i - 1] > cuSeqlensQPtr[i]) { + KERNEL_LOG_ERROR( + "The elements in cu_seqlens_q must be in ascending order, " + "but got cu_seqlens_q[%d] = %d, cu_seqlens_q[%d] = %d", + i - 1, + cuSeqlensQPtr[i - 1], + i, + cuSeqlensQPtr[i]); + return false; + } + } + return true; +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CheckCuSeqlensK( + int32_t batchSize) const { + if (layoutK_ != "TND" || cuSeqlensK_ == nullptr || + cuSeqlensK_->GetData() == nullptr) { + return true; + } + const int32_t* cuSeqlensKPtr = + static_cast(cuSeqlensK_->GetData()); + if (cuSeqlensKPtr[0] != 0) { + KERNEL_LOG_ERROR( + "The first element of cu_seqlens_k should be 0, but got %d", + cuSeqlensKPtr[0]); + return false; + } + for (int32_t i = 1; i < batchSize + 1; ++i) { + if (cuSeqlensKPtr[i - 1] > cuSeqlensKPtr[i]) { + KERNEL_LOG_ERROR( + "The elements in cu_seqlens_k must be in ascending order, " + "but got cu_seqlens_k[%d] = %d, cu_seqlens_k[%d] = %d", + i - 1, + cuSeqlensKPtr[i - 1], + i, + cuSeqlensKPtr[i]); + return false; + } + } + return true; +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CheckSequsedQ( + int32_t batchSize) const { + if (sequsedQ_ == nullptr || sequsedQ_->GetData() == nullptr) { + return true; + } + const int32_t* sequsedQPtr = + static_cast(sequsedQ_->GetData()); + const int32_t* cuSeqlensQPtr = + (layoutQ_ == "TND" && cuSeqlensQ_ != nullptr && + cuSeqlensQ_->GetData() != nullptr) + ? static_cast(cuSeqlensQ_->GetData()) + : nullptr; + for (int32_t i = 0; i < batchSize; ++i) { + if (sequsedQPtr[i] < 0) { + KERNEL_LOG_ERROR( + "The elements in seqused_q should be >= 0, but got seqused_q[%d] = " + "%d", + i, + sequsedQPtr[i]); + return false; + } + if (layoutQ_ == "BSND" && sequsedQPtr[i] > maxSeqlenQ_) { + KERNEL_LOG_ERROR( + "The elements in seqused_q should not be greater than max_seqlen_q " + "%d, " + "but got seqused_q[%d] = %d", + maxSeqlenQ_, + i, + sequsedQPtr[i]); + return false; + } + if (cuSeqlensQPtr != nullptr) { + const int32_t seqLen = cuSeqlensQPtr[i + 1] - cuSeqlensQPtr[i]; + if (sequsedQPtr[i] > seqLen) { + KERNEL_LOG_ERROR( + "The elements in seqused_q should not be greater than the sequence " + "length " + "from cu_seqlens_q %d, but got seqused_q[%d] = %d", + seqLen, + i, + sequsedQPtr[i]); + return false; + } + } + } + return true; +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CheckSequsedK( + int32_t batchSize) const { + if (sequsedK_ == nullptr || sequsedK_->GetData() == nullptr) { + return true; + } + const int32_t* sequsedKPtr = + static_cast(sequsedK_->GetData()); + const int32_t* cuSeqlensKPtr = + (layoutK_ == "TND" && cuSeqlensK_ != nullptr && + cuSeqlensK_->GetData() != nullptr) + ? static_cast(cuSeqlensK_->GetData()) + : nullptr; + for (int32_t i = 0; i < batchSize; ++i) { + if (sequsedKPtr[i] < 0) { + KERNEL_LOG_ERROR( + "The elements in seqused_k should be >= 0, but got seqused_k[%d] = " + "%d", + i, + sequsedKPtr[i]); + return false; + } + if (layoutK_ == "BSND" && sequsedKPtr[i] > maxSeqlenK_) { + KERNEL_LOG_ERROR( + "The elements in seqused_k should not be greater than max_seqlen_k " + "%d, " + "but got seqused_k[%d] = %d", + maxSeqlenK_, + i, + sequsedKPtr[i]); + return false; + } + if (cuSeqlensKPtr != nullptr) { + const int32_t seqLen = cuSeqlensKPtr[i + 1] - cuSeqlensKPtr[i]; + if (sequsedKPtr[i] > seqLen) { + KERNEL_LOG_ERROR( + "The elements in seqused_k should not be greater than the sequence " + "length " + "from cu_seqlens_k %d, but got seqused_k[%d] = %d", + seqLen, + i, + sequsedKPtr[i]); + return false; + } + } + } + return true; +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CheckCmpResidualK( + int32_t batchSize) const { + if (cmpResidualK_ == nullptr || cmpResidualK_->GetData() == nullptr) { + return true; + } + const int32_t* cmpResidualKPtr = + static_cast(cmpResidualK_->GetData()); + for (int32_t i = 0; i < batchSize; ++i) { + if (cmpResidualKPtr[i] < 0 || cmpResidualKPtr[i] >= cmpRatio_) { + KERNEL_LOG_ERROR( + "The elements in cmp_residual_k should be in [0, cmpRatio_(%d)), but " + "got " + "cmp_residual_k[%d] = %d", + cmpRatio_, + i, + cmpResidualKPtr[i]); + return false; + } + } + return true; +} + +int32_t +XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::GetQueryBatchSize() { + // 1. 如果sequsedQ_传了,使用sequsedQ_获取BatchSize + if (sequsedQ_ != nullptr && sequsedQ_->GetData() != nullptr) { + if (sequsedQ_->GetTensorShape() != nullptr) { + return sequsedQ_->GetTensorShape()->GetDimSize(0); + } + } + // 2. sequsedQ_ 没传,判断 Layout + if (layoutQ_ == "TND") { + // 如果是 TND,尝试使用 cuSeqlensQ_获取BatchSize + if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { + if (cuSeqlensQ_->GetTensorShape() != nullptr) { + return cuSeqlensQ_->GetTensorShape()->GetDimSize(0) - 1; + } + } + } + // 3. 如果不是 TND,或者 cuSeqlensQ_ 为空,使用batchSize_ + return batchSize_; +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::ParamsInit() { + batchSize_ = GetQueryBatchSize(); + auto mode = static_cast(maskMode_); + if (mode == SparseMode::RIGHT_DOWN_CAUSAL) { + attentionMode_ = 1; + preToken_ = INT64_MAX; + } else if (mode == SparseMode::DEFAULT_MASK) { + attentionMode_ = 0; + } else if (mode == SparseMode::BAND) { + attentionMode_ = 1; + } + groupSize_ = + static_cast(numHeadsQ_) / static_cast(numHeadsK_); + mBaseSize_ = s1BaseSize_ * groupSize_; + s2BaseSize_ = 2048U; + return true; +} + +uint32_t XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::GetS1SeqSize( + uint32_t bIdx) { + // 1. 如果 sequsedQ_ 传了,直接使用 + if (sequsedQ_ != nullptr && sequsedQ_->GetData() != nullptr) { + const int32_t* seqUsedPtr = + static_cast(sequsedQ_->GetData()); + return static_cast(seqUsedPtr[bIdx]); + } + // 2. sequsedQ_ 没传,判断 Layout + if (layoutQ_ == "TND") { + // 如果是 TND,尝试使用 cuSeqlensQ_ + if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { + const int32_t* s1Ptr = + static_cast(cuSeqlensQ_->GetData()); + return static_cast(s1Ptr[bIdx + 1U] - s1Ptr[bIdx]); + } + } + // 3. 如果不是 TND,或者 cuSeqlensQ_ 为空,使用 querySeqSize_ + return static_cast(maxSeqlenQ_); +} + +uint32_t XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::GetS2SeqSize( + uint32_t bIdx) { + // 如果 seqUsedKv_ 传了,直接使用 + if (sequsedK_ != nullptr && sequsedK_->GetData() != nullptr) { + const int32_t* seqUsedPtr = + static_cast(sequsedK_->GetData()); + return static_cast(seqUsedPtr[bIdx]); + } + // seqUsedKv_ 没传,判断 Layout + if (layoutK_ == "TND") { + // 如果是 TND,尝试使用 actSeqLenOriKv_ + if (cuSeqlensK_ != nullptr && cuSeqlensK_->GetData() != nullptr) { + const int32_t* s2Ptr = + static_cast(cuSeqlensK_->GetData()); + return static_cast(s2Ptr[bIdx + 1U] - s2Ptr[bIdx]); + } + } + // 使用 max_seqlen_k + return static_cast(maxSeqlenK_); +} + +uint64_t XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::GetRevertS2Size( + uint32_t bIdx) { + uint32_t cmpS2Size = GetS2SeqSize(bIdx); + if (cmpResidualK_ != nullptr && cmpResidualK_->GetData() != nullptr) { + const int32_t* residualPtr = + static_cast(cmpResidualK_->GetData()); + return static_cast(cmpS2Size) * static_cast(cmpRatio_) + + static_cast(residualPtr[bIdx]); + } else { + return static_cast(cmpS2Size) * static_cast(cmpRatio_); + } +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcSplitInfo( + SplitContext& splitContext) { + // 计算每个batch的切分,统计是否为空batch,记录最后有效batch(每个batch的每个N2切分是一样的) + SplitInfo& splitInfo = splitContext.splitInfo; + for (uint32_t bIdx = 0; bIdx < static_cast(batchSize_); bIdx++) { + uint32_t s1Size = GetS1SeqSize(bIdx); + uint32_t s2Size = GetS2SeqSize(bIdx); + maxS2Size_ = std::max(maxS2Size_, s2Size); + splitInfo.s1GBaseNum[bIdx] = + (static_cast(s1Size) * groupSize_ + (mBaseSize_ - 1U)) / + mBaseSize_; + splitInfo.s1GTailSize[bIdx] = + (static_cast(s1Size) * groupSize_) % mBaseSize_; + splitInfo.s2BaseNum[bIdx] = (s2Size + s2BaseSize_ - 1U) / s2BaseSize_; + splitInfo.s2TailSize[bIdx] = s2Size % s2BaseSize_; + if (splitInfo.s1GBaseNum[bIdx] != 0U && splitInfo.s2BaseNum[bIdx] != 0U) { + splitInfo.isKvSeqAllZero = false; + } + } +} + +int64_t +XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcPreTokenLeftUp( + uint32_t s1Size, + uint64_t s2Size) const { + auto mode = static_cast(maskMode_); + if (mode == SparseMode::BAND) { + return static_cast(s1Size) - static_cast(s2Size) + + preToken_; + } + return preToken_; +} + +int64_t +XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcNextTokenLeftUp( + uint32_t s1Size, + uint64_t s2Size) const { + auto mode = static_cast(maskMode_); + switch (mode) { + case SparseMode::DEFAULT_MASK: + case SparseMode::ALL_MASK: + case SparseMode::LEFT_UP_CAUSAL: + return nextToken_; + case SparseMode::RIGHT_DOWN_CAUSAL: + return static_cast(s2Size) - static_cast(s1Size); + case SparseMode::BAND: + return static_cast(s2Size) - static_cast(s1Size) + + nextToken_; + default: + return nextToken_; + } +} + +int64_t XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcCost( + uint32_t basicM, + uint32_t basicS2) const { + uint32_t alignCoefM = 16U; + uint32_t alignCoefS2 = 64U; + uint32_t alignBasicM = (basicM + alignCoefM - 1U) >> + 4U; // 按alignCoefM对齐,向上取整,4:移位操作实现除16 + uint32_t alignBasicS2 = + (basicS2 + alignCoefS2 - 1U) >> + 6U; // 按alignCoefS2对齐,向上取整,6:移位操作实现除64 + return static_cast(COST_WEIGHT_M * alignBasicM + + COST_WEIGHT_S2 * alignBasicS2); +} + +BlockCost +XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcCostTable( + uint32_t s1NormalSize, + uint32_t s2NormalSize, + uint32_t s1GTailSize, + uint32_t s2TailSize) const { + BlockCost typeCost{}; + typeCost[NORMAL_BLOCK][NORMAL_BLOCK] = CalcCost(s1NormalSize, s2NormalSize); + typeCost[TAIL_BLOCK][NORMAL_BLOCK] = + (s1GTailSize == 0U) ? 0U : CalcCost(s1GTailSize, s2NormalSize); + typeCost[NORMAL_BLOCK][TAIL_BLOCK] = + (s2TailSize == 0U) ? 0U : CalcCost(s1NormalSize, s2TailSize); + typeCost[TAIL_BLOCK][TAIL_BLOCK] = (s1GTailSize == 0U || s2TailSize == 0U) + ? 0U + : CalcCost(s1GTailSize, s2TailSize); + return typeCost; +} + +Range +XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcS2TokenRange( + uint32_t s1GIdx, + const BatchCache& batchCache) { + // no mask + if (!attentionMode_) { + return std::make_pair(0, static_cast(batchCache.revertS2Size)); + } + + // 1. calc index of s2FirstToken, s2LastToken by index of s1GFirstToken, + // s1GLastToken + int64_t s1GFirstToken = + static_cast(s1GIdx) * static_cast(mBaseSize_); + int64_t s1GLastToken = + std::min(s1GFirstToken + static_cast(mBaseSize_), + static_cast(batchCache.s1Size) * + static_cast(groupSize_)) - + 1; + int64_t s1FirstToken = 0; + int64_t s1LastToken = 0; + if (isS1G_) { + s1FirstToken = s1GFirstToken / static_cast(groupSize_); + s1LastToken = s1GLastToken / static_cast(groupSize_); + } else { + if (s1GFirstToken / batchCache.s1Size == s1GLastToken / batchCache.s1Size) { + // start and end locate in one G + s1FirstToken = s1GFirstToken % static_cast(batchCache.s1Size); + s1LastToken = s1GLastToken % static_cast(batchCache.s1Size); + } else { + // start and end locate in two or more G, but working same as crossing a + // complete block + s1FirstToken = 0; + s1LastToken = batchCache.s1Size; + } + } + + int64_t s2FirstToken = s1FirstToken - batchCache.preTokenLeftUp; + int64_t s2LastToken = s1LastToken + batchCache.nextTokenLeftUp; + + return std::make_pair(s2FirstToken, s2LastToken); +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcBatchCache( + uint32_t bIdx, + const SplitContext& splitContext, + BatchCache& batchCache) { + const SplitInfo& splitInfo = splitContext.splitInfo; + + batchCache.bIdx = bIdx; + batchCache.s1Size = GetS1SeqSize(bIdx); + batchCache.revertS2Size = GetRevertS2Size(bIdx); + batchCache.preTokenLeftUp = + CalcPreTokenLeftUp(batchCache.s1Size, batchCache.revertS2Size); + batchCache.nextTokenLeftUp = + CalcNextTokenLeftUp(batchCache.s1Size, batchCache.revertS2Size); +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcS1GCache( + uint32_t s1GIdx, + const SplitContext& splitContext, + const BatchCache& batchCache, + S1GCache& s1GCache) { + const SplitInfo& splitInfo = splitContext.splitInfo; + + s1GCache.bIdx = batchCache.bIdx; + s1GCache.s1GIdx = s1GIdx; + + if (splitInfo.s1GBaseNum[batchCache.bIdx] == 0 || + splitInfo.s2BaseNum[batchCache.bIdx] == 0) { + s1GCache.s1GBlock = 0; + s1GCache.s1GCost = 0; + s1GCache.s1GLastBlockCost = 0; + s1GCache.s1GNormalBlockCost = 0; + return; + } + + auto s2TokenRange = CalcS2TokenRange(s1GIdx, batchCache); + int64_t s2FirstToken = s2TokenRange.first; + int64_t s2LastToken = s2TokenRange.second; + // get valid range + s2FirstToken = Clip(s2FirstToken, + static_cast(0), + static_cast(batchCache.revertS2Size - 1U)); + s2LastToken = Clip(s2LastToken, + static_cast(0), + static_cast(batchCache.revertS2Size - 1U)); + + // get block start & end + int64_t s2CmpLength = (s2LastToken - s2FirstToken + 1) / cmpRatio_; + if (s2CmpLength <= 0) { + s1GCache.s2Start = 0U; + s1GCache.s2End = 0U; + } else { + s1GCache.s2Start = 0U; + // end of block index, Right-open interval + s1GCache.s2End = + (static_cast(s2CmpLength) + s2BaseSize_ - 1) / s2BaseSize_; + } + + if (s1GCache.s2Start >= s1GCache.s2End) { + s1GCache.s1GBlock = 0; + s1GCache.s1GCost = 0; + s1GCache.s1GLastBlockCost = 0; + s1GCache.s1GNormalBlockCost = 0; + return; + } + + uint32_t s2TailSize = static_cast(s2CmpLength) % s2BaseSize_; + + // 计算S2方向满块、尾块数量 + s1GCache.s1GBlock = s1GCache.s2End - s1GCache.s2Start; + uint32_t curTailS2Num = s2TailSize != 0 ? 1U : 0U; + uint32_t curNormalS2Num = s1GCache.s1GBlock - curTailS2Num; + + BlockCost typeCost = + CalcCostTable(mBaseSize_, + s2BaseSize_, + splitInfo.s1GTailSize[batchCache.bIdx], + s2TailSize); + + if (s1GIdx == (splitInfo.s1GBaseNum[batchCache.bIdx] - 1U) && + splitInfo.s1GTailSize[batchCache.bIdx] != 0U) { + s1GCache.s1GCost = typeCost[TAIL_BLOCK][NORMAL_BLOCK] * curNormalS2Num + + typeCost[TAIL_BLOCK][TAIL_BLOCK] * curTailS2Num; + s1GCache.s1GLastBlockCost = curTailS2Num > 0U + ? typeCost[TAIL_BLOCK][TAIL_BLOCK] + : typeCost[TAIL_BLOCK][NORMAL_BLOCK]; + s1GCache.s1GNormalBlockCost = typeCost[TAIL_BLOCK][NORMAL_BLOCK]; + } else { + s1GCache.s1GCost = typeCost[NORMAL_BLOCK][NORMAL_BLOCK] * curNormalS2Num + + typeCost[NORMAL_BLOCK][TAIL_BLOCK] * curTailS2Num; + s1GCache.s1GLastBlockCost = curTailS2Num > 0U + ? typeCost[NORMAL_BLOCK][TAIL_BLOCK] + : typeCost[NORMAL_BLOCK][NORMAL_BLOCK]; + s1GCache.s1GNormalBlockCost = typeCost[NORMAL_BLOCK][NORMAL_BLOCK]; + } +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcBatchCost( + uint32_t bIdx, + const SplitContext& splitContext, + CostInfo& costInfo) { + const SplitInfo& splitInfo = splitContext.splitInfo; + + costInfo.bN2CostOfEachBatch[bIdx] = 0; + costInfo.bN2BlockOfEachBatch[bIdx] = 0U; + costInfo.bN2LastBlockCostOfEachBatch[bIdx] = 0U; + + if (GetS1SeqSize(bIdx) == 0U || GetS2SeqSize(bIdx) == 0U) { + return; + } + + BatchCache bCache; + S1GCache s1GCache; + CalcBatchCache(bIdx, splitContext, bCache); + for (uint32_t s1GIdx = 0; s1GIdx < splitInfo.s1GBaseNum[bIdx]; s1GIdx++) { + CalcS1GCache(s1GIdx, splitContext, bCache, s1GCache); + costInfo.bN2CostOfEachBatch[bIdx] += s1GCache.s1GCost; + costInfo.bN2BlockOfEachBatch[bIdx] += s1GCache.s1GBlock; + // 更新最大S1G行开销 + if (s1GCache.s1GCost > costInfo.maxS1GCost) { + costInfo.maxS1GCost = s1GCache.s1GCost; + } + + if (s1GCache.s1GBlock > 0) { + costInfo.bN2LastBlockCostOfEachBatch[bIdx] = s1GCache.s1GLastBlockCost; + } + } +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcCostInfo( + SplitContext& splitContext) { + const SplitInfo& splitInfo = splitContext.splitInfo; + CostInfo& costInfo = splitContext.costInfo; + + if (splitInfo.isKvSeqAllZero) { + costInfo.totalCost = 0; + costInfo.totalBlockNum = 0U; + return; + } + + // 计算batch的负载并记录,用于按batch分配,需要按行计算起止点,统计块数、负载 + for (uint32_t bIdx = 0; bIdx < static_cast(batchSize_); bIdx++) { + CalcBatchCost(bIdx, splitContext, costInfo); + costInfo.totalCost += costInfo.bN2CostOfEachBatch[bIdx] * numHeadsK_; + costInfo.totalBlockNum += + costInfo.bN2BlockOfEachBatch[bIdx] * static_cast(numHeadsK_); + } +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::UpdateCursor( + const SplitContext& splitContext, + AssignContext& assignContext) { + const SplitInfo& splitInfo = splitContext.splitInfo; + const CostInfo& costInfo = splitContext.costInfo; + + bool UpdateS1G = false; + bool UpdateBatch = false; + + // Update S2 + if (assignContext.curS2Idx >= + assignContext.s1GCache.s2End) { // 边界assignInfo.s2End是取不到的开区间 + assignContext.curS2Idx = 0U; + assignContext.curS1GIdx++; + UpdateS1G = true; + } + + // Update S1G + if (assignContext.curS1GIdx >= splitInfo.s1GBaseNum[assignContext.curBIdx]) { + assignContext.curS1GIdx = 0U; + assignContext.curBN2Idx++; + } + + // Update Batch + if (assignContext.curBN2Idx == + static_cast(batchSize_) * + static_cast(numHeadsK_)) { // 所有负载全部分配完 + assignContext.curS1GIdx = 0U; + assignContext.curS2Idx = 0U; + assignContext.isFinished = true; + return; + } + + if (assignContext.curBN2Idx / static_cast(numHeadsK_) != + assignContext.curBIdx) { + assignContext.curBIdx = + assignContext.curBN2Idx / static_cast(numHeadsK_); + assignContext.curS1GIdx = 0U; + UpdateBatch = true; + UpdateS1G = true; + } + + // Update Cache + if (UpdateBatch) { + CalcBatchCache( + assignContext.curBIdx, splitContext, assignContext.batchCache); + assignContext.bN2Cost = costInfo.bN2CostOfEachBatch[assignContext.curBIdx]; + assignContext.bN2Block = + costInfo.bN2BlockOfEachBatch[assignContext.curBIdx]; + } + if (UpdateS1G) { + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + } +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::AssignByBatch( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + const CostInfo& costInfo = splitContext.costInfo; + while (assignContext.bN2Cost == 0 || + IsWithinTolerance( + assignContext.coreCache.costLimit, + costInfo.bN2LastBlockCostOfEachBatch[assignContext.curBIdx] / + FA_TOLERANCE_RATIO, + assignContext.coreCache.cost + assignContext.bN2Cost)) { + assignContext.coreCache.cost += assignContext.bN2Cost; + assignContext.coreCache.block += assignContext.bN2Block; + assignContext.curBN2Idx++; + + // to the end + if (assignContext.curBN2Idx == + static_cast(batchSize_) * static_cast(numHeadsK_)) { + assignContext.curS1GIdx = 0U; + assignContext.curS2Idx = 0U; + assignContext.isFinished = true; + return; + } + + // next batch + if (assignContext.curBN2Idx / static_cast(numHeadsK_) != + assignContext.curBIdx) { + assignContext.curBIdx = + assignContext.curBN2Idx / static_cast(numHeadsK_); + CalcBatchCache( + assignContext.curBIdx, splitContext, assignContext.batchCache); + } + + assignContext.bN2Cost = costInfo.bN2CostOfEachBatch[assignContext.curBIdx]; + assignContext.bN2Block = + costInfo.bN2BlockOfEachBatch[assignContext.curBIdx]; + assignContext.curS1GIdx = 0U; + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + } +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::AssignByRow( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + + while (IsWithinTolerance( + assignContext.coreCache.costLimit, + assignContext.s1GCache.s1GLastBlockCost / FA_TOLERANCE_RATIO, + assignContext.coreCache.cost + assignContext.s1GCache.s1GCost)) { + assignContext.coreCache.cost += assignContext.s1GCache.s1GCost; + assignContext.coreCache.block += assignContext.s1GCache.s1GBlock; + + // 当前batch被分配一行出去,更新剩余负载 + assignContext.bN2Cost = + assignContext.bN2Cost > assignContext.s1GCache.s1GCost + ? assignContext.bN2Cost - assignContext.s1GCache.s1GCost + : 0; + assignContext.bN2Block = + assignContext.bN2Block > assignContext.s1GCache.s1GBlock + ? assignContext.bN2Block - assignContext.s1GCache.s1GBlock + : 0U; + // 计算新一行的信息 + do { + assignContext.curS1GIdx++; + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + } while (assignContext.s1GCache.s1GBlock == 0); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + } +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::AssignByBlock( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + + int64_t curCost = assignContext.s1GCache.s1GNormalBlockCost; + if (assignContext.curS2Idx == (assignContext.s1GCache.s2End - 1U)) { + curCost = assignContext.s1GCache.s1GLastBlockCost; + } + + // (costLimit - curCostOnCore) * FA_TOLERANCE_RATIO > curCost;至少分配1块 + while (IsWithinTolerance(assignContext.coreCache.costLimit, + curCost / FA_TOLERANCE_RATIO, + assignContext.coreCache.cost + curCost)) { + assignContext.coreCache.cost += curCost; + assignContext.coreCache.block++; + assignContext.curS2Idx++; + // 当前batch被分配一块出去,更新剩余负载 + assignContext.bN2Cost = assignContext.bN2Cost - curCost; + // 当前行被分配一块出去,更新剩余负载 + assignContext.s1GCache.s1GCost = assignContext.s1GCache.s1GCost - curCost; + assignContext.bN2Block--; + assignContext.s1GCache.s1GBlock--; + } +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::ForceAssign( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + + int64_t curCost = assignContext.s1GCache.s1GNormalBlockCost; + if (assignContext.curS2Idx == (assignContext.s1GCache.s2End - 1U)) { + curCost = assignContext.s1GCache.s1GLastBlockCost; + } + + assignContext.coreCache.cost += curCost; + assignContext.coreCache.block++; + assignContext.curS2Idx++; + // 当前batch被分配一块出去,更新剩余负载 + assignContext.bN2Cost = assignContext.bN2Cost - curCost; + assignContext.bN2Block--; + // 当前行被分配一块出去,更新剩余负载 + assignContext.s1GCache.s1GCost = assignContext.s1GCache.s1GCost - curCost; + assignContext.s1GCache.s1GBlock--; + UpdateCursor(splitContext, assignContext); +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::IsNeedRecordFDInfo( + const AssignContext& assignContext, + const SplitResult& splitRes) { + // 切分点大概率不会刚好在行尾,因此滞后处理归约信息的统计,到下一个切分点再判断是否需要归约 + // 核0无需处理 + if (assignContext.curCoreIdx == 0U) { + return false; + } + // 无跨核行,无需处理 + if (assignContext.curKvSplitPart <= 1U) { + return false; + } + // 需要归约的行还未处理完 + if (assignContext.curBN2Idx == + splitRes.bN2End[assignContext.curCoreIdx - 1U] && + assignContext.curS1GIdx == + splitRes.gS1End[assignContext.curCoreIdx - 1U]) { + return false; + } + return true; +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::RecordFDInfo( + const SplitContext& splitContext, + const AssignContext& assignContext, + SplitResult& result) { + const SplitInfo& splitInfo = splitContext.splitInfo; + // 需要规约的行是上一个核的切分点所在位置 + uint32_t splitBIdx = result.bN2End[assignContext.curCoreIdx - 1U] / + static_cast(numHeadsK_); + uint32_t splitS1GIdx = result.gS1End[assignContext.curCoreIdx - 1U]; + uint32_t s1Size = GetS1SeqSize(splitBIdx); + + // 计算归约数据的FD均衡划分信息 + uint32_t curFdS1gSize = + (splitS1GIdx == splitInfo.s1GBaseNum[splitBIdx] - 1U) + ? (static_cast(s1Size) * groupSize_ - + static_cast(splitS1GIdx) * mBaseSize_) + : mBaseSize_; + // 记录 + result.maxS2SplitNum = + std::max(result.maxS2SplitNum, assignContext.curKvSplitPart); + // 若存在头归约,则切分点一定为上一个核结束的位置 + result.fdRes.fdBN2Idx[result.numOfFdHead] = + result.bN2End[assignContext.curCoreIdx - 1U]; + result.fdRes.fdMIdx[result.numOfFdHead] = + result.gS1End[assignContext.curCoreIdx - 1U]; + result.fdRes.fdWorkspaceIdx[result.numOfFdHead] = assignContext.preFdDataNum; + result.fdRes.fdS2SplitNum[result.numOfFdHead] = assignContext.curKvSplitPart; + result.fdRes.fdMSize[result.numOfFdHead] = curFdS1gSize / groupSize_; + result.numOfFdHead++; +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::AssignBlockToCore( + const SplitContext& splitContext, + AssignContext& assignContext, + SplitResult& result) { + const CostInfo& costInfo = splitContext.costInfo; + result.firstFdDataWorkspaceIdx[assignContext.curCoreIdx] = + assignContext.preFdDataNum + assignContext.curKvSplitPart - 1U; + assignContext.coreCache = {}; + assignContext.coreCache.costLimit = + assignContext.unassignedCost / (aicCoreNum_ - assignContext.curCoreIdx); + if (!supportFd_) { + assignContext.coreCache.costLimit = + costInfo.maxS1GCost > assignContext.coreCache.costLimit + ? costInfo.maxS1GCost + : assignContext.coreCache.costLimit; + } + // 1、按整batch分配 + AssignByBatch(splitContext, assignContext); + // 2、按行分配 + AssignByRow(splitContext, assignContext); + // 3、按块分配 + if (supportFd_) { + AssignByBlock(splitContext, assignContext); + // 4、强制分配 + if (assignContext.coreCache.block == 0) { + ForceAssign(splitContext, assignContext); + } + } + result.bN2End[assignContext.curCoreIdx] = assignContext.curBN2Idx; + result.gS1End[assignContext.curCoreIdx] = assignContext.curS1GIdx; + result.s2End[assignContext.curCoreIdx] = assignContext.curS2Idx; + result.maxCost = std::max(result.maxCost, assignContext.coreCache.cost); + assignContext.unassignedCost -= assignContext.coreCache.cost; + // 对之前的归约信息进行记录并清理 + if (supportFd_ && IsNeedRecordFDInfo(assignContext, result)) { + RecordFDInfo(splitContext, assignContext, result); + assignContext.preFdDataNum += assignContext.curKvSplitPart; + assignContext.curKvSplitPart = 1U; + } + // 更新S2切分信息 + if (supportFd_ && assignContext.curS2Idx > assignContext.s1GCache.s2Start && + assignContext.curS2Idx <= assignContext.s1GCache.s2End) { + assignContext.curKvSplitPart++; + } +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcSplitPlan( + int64_t costLimit, + const SplitContext& splitContext, + SplitResult& result) { + const CostInfo& costInfo = splitContext.costInfo; + if (aicCoreNum_ == 0U) { + return; + } + result.maxCost = 0U; + result.usedCoreNum = 0U; + AssignContext assignContext{}; + assignContext.curBIdx = 0U; + assignContext.curS1GIdx = 0U; + assignContext.unassignedCost = costInfo.totalCost; + assignContext.bN2Cost = costInfo.bN2CostOfEachBatch[assignContext.curBIdx]; + assignContext.bN2Block = costInfo.bN2BlockOfEachBatch[assignContext.curBIdx]; + CalcBatchCache(assignContext.curBIdx, splitContext, assignContext.batchCache); + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + for (uint32_t i = 0; i < aicCoreNum_; ++i) { + if (result.maxCost > costLimit) { + return; + } + if (assignContext.isFinished || assignContext.unassignedCost <= 0) { + break; + } + assignContext.curCoreIdx = i; + AssignBlockToCore(splitContext, assignContext, result); + // Keep trailing zero-cost batches in the last AIC range so their outputs + // are initialized. + if (!assignContext.isFinished && assignContext.unassignedCost <= 0) { + result.bN2End[i] = + static_cast(batchSize_) * static_cast(numHeadsK_); + result.gS1End[i] = 0U; + result.s2End[i] = 0U; + assignContext.isFinished = true; + } + } + result.usedCoreNum = assignContext.curCoreIdx + 1; +} + +void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::SplitFD( + SplitResult& splitRes) { + // 计算FD的总数据量 + uint64_t totalFDLoad = 0; + for (uint32_t i = 0; i < splitRes.numOfFdHead; i++) { + totalFDLoad += splitRes.fdRes.fdS2SplitNum[i] * splitRes.fdRes.fdMSize[i]; + } + // 计算当前最大冗余vec核数 + uint32_t emptyVectorNum = aivCoreNum_ - splitRes.numOfFdHead; + // 计算每个核处理的load + // 向上取整,避免核负载为0 + uint64_t averageLoad = (totalFDLoad + aivCoreNum_ - 1U) / aivCoreNum_; + uint32_t curCoreIndex = 0; + for (uint32_t i = 0; i < splitRes.numOfFdHead; i++) { + // 冗余vec核数为0,此时规约任务无法进行更小的切分,只能1个vec核计算1个规约任务 + if (emptyVectorNum == 0U) { + splitRes.fdRes.fdIdx[curCoreIndex] = i; + splitRes.fdRes.fdMStart[curCoreIndex] = 0U; + splitRes.fdRes.fdMNum[curCoreIndex] = splitRes.fdRes.fdMSize[i]; + curCoreIndex++; + continue; + } + // 计算当前归约任务所用核数,向下取整,避免使用核数超出总核数 + uint32_t curFDVectorNum = splitRes.fdRes.fdS2SplitNum[i] * + splitRes.fdRes.fdMSize[i] / averageLoad; + curFDVectorNum = std::max(1U, curFDVectorNum); + // 计算当前归约任务每个核的行数,向上取整,避免行数为0 + uint32_t curAveMSize = + (splitRes.fdRes.fdMSize[i] + curFDVectorNum - 1U) / curFDVectorNum; + curFDVectorNum = + (splitRes.fdRes.fdMSize[i] + curAveMSize - 1U) / curAveMSize; + // 需要使用的vec核数与当前剩余可用vec核数取最小 + curFDVectorNum = + std::min(curFDVectorNum, emptyVectorNum + 1U); // 1: Fd任务自身带一个核 + // FD负载分配 + for (uint32_t vid = 0; vid < curFDVectorNum; vid++) { + splitRes.fdRes.fdIdx[curCoreIndex] = i; + splitRes.fdRes.fdMStart[curCoreIndex] = vid * curAveMSize; + splitRes.fdRes.fdMNum[curCoreIndex] = + (vid < curFDVectorNum - 1) + ? curAveMSize + : (splitRes.fdRes.fdMSize[i] - vid * curAveMSize); + curCoreIndex++; + } + // 更新冗余vec核数 + emptyVectorNum -= (curFDVectorNum - 1U); // 1: 空余核不包含FD自身的核,要-1 + } + splitRes.fdRes.fdUsedVecNum = curCoreIndex; +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::BalanceSchedule( + SplitResult& splitRes) { + SplitContext splitContext(batchSize_); + // 1、划分基本块,统计信息 + CalcSplitInfo(splitContext); + // 全空case + if (splitContext.splitInfo.isKvSeqAllZero) { + splitRes.usedCoreNum = 1U; + splitRes.bN2End[0] = + static_cast(batchSize_) * static_cast(numHeadsK_); + splitRes.gS1End[0] = 0U; + splitRes.s2End[0] = 0U; + return true; + } + CalcCostInfo(splitContext); + + splitRes.maxCost = INT64_MAX; + splitRes.usedCoreNum = 1U; + CalcSplitPlan(splitRes.maxCost, splitContext, splitRes); + // 3、存在FD任务,对FD进行负载均衡分配 + if (supportFd_ && splitRes.numOfFdHead > 0U) { + SplitFD(splitRes); + } + splitRes.usedCoreNum = std::max(splitRes.usedCoreNum, 1U); // 至少使用1个core + return true; +} + +bool XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::GenMetadata( + SplitResult& splitRes) { + optiling::detail::QliV2Metadata* metadataPtr = + static_cast(metadata_->GetData()); + // 结构体仅覆盖 864 个 int32 (3456B),输出张量共 1024 个 int32 (4096B); + // 尾部 864..1023 从未写入,全量清零避免 aclnn/图模式读到未初始化垃圾。 + std::memset( + metadataPtr, 0, QLI_V2_METADATA_TOTAL_SIZE * sizeof(QLI_V2_METADATA_T)); + // LI Metadata Generate + for (size_t i = 0; i < aicCoreNum_; ++i) { + if (i >= splitRes.usedCoreNum) { + metadataPtr->qliV2Metadata[i][QLI_V2_CORE_ENABLE_INDEX] = + 0; // AIC disenable + continue; + } + metadataPtr->qliV2Metadata[i][QLI_V2_CORE_ENABLE_INDEX] = 1; // AIC enable + // FA START + metadataPtr->qliV2Metadata[i][QLI_V2_BN2_START_INDEX] = + i == 0 ? 0 : splitRes.bN2End[i - 1]; + metadataPtr->qliV2Metadata[i][QLI_V2_M_START_INDEX] = + i == 0 ? 0 : splitRes.gS1End[i - 1]; + metadataPtr->qliV2Metadata[i][QLI_V2_S2_START_INDEX] = + i == 0 ? 0 : splitRes.s2End[i - 1]; + // FA END + metadataPtr->qliV2Metadata[i][QLI_V2_BN2_END_INDEX] = splitRes.bN2End[i]; + metadataPtr->qliV2Metadata[i][QLI_V2_M_END_INDEX] = splitRes.gS1End[i]; + metadataPtr->qliV2Metadata[i][QLI_V2_S2_END_INDEX] = splitRes.s2End[i]; + metadataPtr + ->qliV2Metadata[i][QLI_V2_FIRST_QLD_V2_DATA_WORKSPACE_IDX_INDEX] = + splitRes.firstFdDataWorkspaceIdx[i]; + } + + // LD Metadata Generate + for (size_t i = 0; i < aivCoreNum_; ++i) { + if (i >= splitRes.fdRes.fdUsedVecNum) { + metadataPtr->qldV2Metadata[i][QLD_V2_CORE_ENABLE_INDEX] = + 0; // AIV disenable + continue; + } + metadataPtr->qldV2Metadata[i][QLD_V2_CORE_ENABLE_INDEX] = 1; // AIV enable + uint32_t curFdIdx = splitRes.fdRes.fdIdx[i]; + metadataPtr->qldV2Metadata[i][QLD_V2_BN2_IDX_INDEX] = + splitRes.fdRes.fdBN2Idx[curFdIdx]; + metadataPtr->qldV2Metadata[i][QLD_V2_M_IDX_INDEX] = + splitRes.fdRes.fdMIdx[curFdIdx]; + metadataPtr->qldV2Metadata[i][QLD_V2_WORKSPACE_IDX_INDEX] = + splitRes.fdRes.fdWorkspaceIdx[curFdIdx]; + metadataPtr->qldV2Metadata[i][QLD_V2_WORKSPACE_NUM_INDEX] = + splitRes.fdRes.fdS2SplitNum[curFdIdx]; + metadataPtr->qldV2Metadata[i][QLD_V2_M_START_INDEX] = + splitRes.fdRes.fdMStart[i]; + metadataPtr->qldV2Metadata[i][QLD_V2_M_NUM_INDEX] = + splitRes.fdRes.fdMNum[i]; + } + return true; +} + +} // namespace aicpu::xllm_qli_v2 + +namespace aicpu { +namespace { +using xllm_qli_v2::XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel; +static const char* kernelType = "XllmKernelQuantLightningIndexerV2MetadataVa"; +REGISTER_CPU_KERNEL(kernelType, + XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel); +} // namespace +} // namespace aicpu diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.h new file mode 100644 index 0000000000..809e5edc1e --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.h @@ -0,0 +1,341 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_lightning_indexer_v2_metadata_va_aicpu.h + * \brief + */ + +#ifndef QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_AICPU_H +#define QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_AICPU_H + +#include +#include +#include + +#include "../../quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h" +#include "cpu_context.h" +#include "cpu_kernel.h" +#include "cpu_tensor.h" +#include "log.h" +#include "quant_lightning_indexer_metadata/op_kernel_aicpu/cpu_context_util.h" + +namespace aicpu::xllm_qli_v2 { +constexpr int64_t FA_TOLERANCE_RATIO = 2; +constexpr uint32_t COST_WEIGHT_M = 6U; +constexpr uint32_t COST_WEIGHT_S2 = 10U; + +enum BlockType : uint32_t { NORMAL_BLOCK = 0, TAIL_BLOCK, BLOCK_MAX_TYPE }; + +enum class SparseMode : uint8_t { + DEFAULT_MASK = 0, + ALL_MASK, + LEFT_UP_CAUSAL, + RIGHT_DOWN_CAUSAL, + BAND, + SPARSE_BUTT, +}; + +template +using Range = std::pair; + +template +using BlockCost = std::array(BLOCK_MAX_TYPE)>, + static_cast(BLOCK_MAX_TYPE)>; + +template +T Clip(T value, T minValue, T maxValue) { + if (value < minValue) { + return minValue; + } + if (value > maxValue) { + return maxValue; + } + return value; +} + +template +inline bool IsWithinTolerance(T limit, T tolerance, T value) { + return limit + tolerance >= value; +} + +// 分核功能模块输出:FD信息,包含需要归约的数据索引及其分核信息 +struct FlashDecodeResult { + uint32_t fdUsedVecNum{0U}; // 归约过程使用的vector数量 + // 1、归约任务的索引信息 + std::vector + fdBN2Idx{}; // 每个归约任务的BN2索引,脚标为归约任务的序号,最大为核数-1 + std::vector + fdMIdx{}; // 每个归约任务的GS1索引,脚标为归约任务的序号 + std::vector + fdWorkspaceIdx{}; // 每个归约任务在workspace中的存放位置 + std::vector + fdS2SplitNum{}; // 每个归约任务的S2核间切分份数,脚标为归约任务的序号 + std::vector fdMSize{}; // 每个归约任务m轴大小,脚标为归约任务的序号 + // 2、FD负载均衡阶段,归约任务的分核(vec)信息 + std::vector + fdIdx{}; // FD负载均衡阶段,每个vector处理的归约任务对应ID + std::vector + fdMStart{}; // FD负载均衡阶段,每个vector处理的归约任务的m轴起点 + std::vector + fdMNum{}; // FD负载均衡阶段,每个vector处理的归约任务的m轴行数 + + FlashDecodeResult(uint32_t aicNum, uint32_t aivNum) + : fdBN2Idx(aicNum), + fdMIdx(aicNum), + fdWorkspaceIdx(aicNum), + fdS2SplitNum(aicNum), + fdMSize(aicNum), + fdIdx(aivNum), + fdMStart(aivNum), + fdMNum(aivNum) {} +}; + +// 分核功能模块输出:FA阶段的核间分核信息 +struct SplitResult { + uint32_t usedCoreNum{0U}; // 使用的核数量 + std::vector bN2End{}; // 每个核处理数据的BN2结束点 + std::vector gS1End{}; // 每个核处理数据的GS1结束点 + std::vector s2End{}; // 每个核处理数据的S2结束点 + std::vector + firstFdDataWorkspaceIdx{}; // 每个核第一份归约任务的存放位置 + int64_t maxCost{0}; // 慢核开销 + uint32_t numOfFdHead{0U}; // 归约任务数量 + uint32_t maxS2SplitNum{0U}; // 单个归约任务最大分核数量 + FlashDecodeResult fdRes{0U, 0U}; // FD信息 + + SplitResult(uint32_t aicNum, uint32_t aivNum) + : bN2End(aicNum), + gS1End(aicNum), + s2End(aicNum), + firstFdDataWorkspaceIdx(aicNum), + fdRes(aicNum, aivNum) {}; +}; + +// 分核功能模块内部使用:记录切分信息 +struct SplitInfo { + std::vector s1GBaseNum{}; // S1G方向,切了多少个基本块 + std::vector s2BaseNum{}; // S2方向,切了多少个基本块 + std::vector s1GTailSize{}; // S1G方向,尾块size + std::vector s2TailSize{}; // S2方向,尾块size + bool isKvSeqAllZero{true}; + + explicit SplitInfo(uint32_t batchSize) + : s1GBaseNum(batchSize), + s2BaseNum(batchSize), + s1GTailSize(batchSize), + s2TailSize(batchSize) {} +}; + +// 分核功能模块内部使用:记录batch的开销信息 +struct CostInfo { + std::vector bN2CostOfEachBatch{}; // 整个batch的开销 + std::vector bN2BlockOfEachBatch{}; // 整个batch的开销 + std::vector bN2LastBlockCostOfEachBatch{}; // batch最后一块的开销 + uint32_t totalBlockNum{0U}; + int64_t totalCost{0}; + uint64_t maxS1GCost{0}; // 新增 + + explicit CostInfo(uint32_t batchSize) + : bN2CostOfEachBatch(batchSize), + bN2BlockOfEachBatch(batchSize), + bN2LastBlockCostOfEachBatch(batchSize) {} +}; + +// 分核功能模块内部使用:分核过程中,case基本信息的上下文信息,组合以减少接口传参数量 +struct SplitContext { + SplitInfo splitInfo{0U}; + CostInfo costInfo{0U}; + + explicit SplitContext(uint32_t batchSize) + : splitInfo(batchSize), costInfo(batchSize) {} +}; + +// 分核功能模块内部使用:记录batch相关的临时信息 +struct BatchCache { + uint32_t bIdx{0U}; + uint32_t s1Size{0U}; + uint64_t revertS2Size{0U}; + int64_t preTokenLeftUp{0}; + int64_t nextTokenLeftUp{0}; + BlockCost typeCost{}; +}; + +// 分核功能模块内部使用:记录当前行(S1G)的临时信息 +struct S1GCache { + uint32_t bIdx{0U}; + uint32_t s1GIdx{0U}; + uint32_t s2Start{0U}; + uint32_t s2End{0U}; + int64_t s1GCost{0}; + int64_t s1GLastBlockCost{0}; + uint32_t s1GBlock{0U}; + int64_t s1GNormalBlockCost{0}; +}; + +// 分核功能模块内部使用:记录分配过程中,当前核的负载信息 +struct CoreCache { + int64_t costLimit{0}; // 负载上限 + int64_t cost{0}; // 已分配负载 + uint32_t block{0U}; // 已分配块数 +}; + +// 分核功能模块内部使用:记录分配过程中的上下文信息 +struct AssignContext { + uint32_t curBIdx{0U}; + uint32_t curBN2Idx{0U}; + uint32_t curS1GIdx{0U}; + uint32_t curS2Idx{0U}; + uint32_t curCoreIdx{0U}; + int64_t unassignedCost{0}; + uint32_t curKvSplitPart{1U}; + uint32_t preFdDataNum{0U}; + + int64_t bN2Cost{0}; + uint32_t bN2Block{0U}; + bool isFinished{false}; + BatchCache batchCache{}; + S1GCache s1GCache{}; + CoreCache coreCache{}; +}; +class XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel : public CpuKernel { + public: + XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel() = default; + ~XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel() = default; + uint32_t Compute(CpuKernelContext& ctx) override; + + private: + bool Prepare(CpuKernelContext& ctx); + bool ParamsCheck(); + bool CheckCuSeqlensQ(int32_t batchSize) const; + bool CheckCuSeqlensK(int32_t batchSize) const; + bool CheckSequsedQ(int32_t batchSize) const; + bool CheckSequsedK(int32_t batchSize) const; + bool CheckCmpResidualK(int32_t batchSize) const; + int32_t GetQueryBatchSize(); + bool ParamsInit(); + bool BalanceSchedule(SplitResult& splitRes); + bool GenMetadata(SplitResult& splitRes); + + // util + uint32_t GetS1SeqSize(uint32_t bIdx); + uint32_t GetS2SeqSize(uint32_t bIdx); + uint64_t GetRevertS2Size(uint32_t bIdx); + int64_t CalcPreTokenLeftUp(uint32_t s1Size, uint64_t s2Size) const; + int64_t CalcNextTokenLeftUp(uint32_t s1Size, uint64_t s2Size) const; + Range CalcS2TokenRange(uint32_t s1GIdx, + const BatchCache& batchCache); + int64_t CalcCost(uint32_t basicM, uint32_t basicS2) const; + BlockCost CalcCostTable(uint32_t s1NormalSize, + uint32_t s2NormalSize, + uint32_t s1GTailSize, + uint32_t s2TailSize) const; + + // cache calculation + void CalcBatchCache(uint32_t bIdx, + const SplitContext& splitContext, + BatchCache& batchCache); + void CalcS1GCache(uint32_t s1GIdx, + const SplitContext& splitContext, + const BatchCache& batchCache, + S1GCache& s1GCache); + + // preprocess + void CalcSplitInfo(SplitContext& splitContext); + void CalcBatchCost(uint32_t bIdx, + const SplitContext& splitContext, + CostInfo& costInfo); + void CalcCostInfo(SplitContext& splitContext); + + // assign + void UpdateCursor(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignByBatch(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignByRow(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignByBlock(const SplitContext& splitContext, + AssignContext& assignContext); + void ForceAssign(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignBlockToCore(const SplitContext& splitContext, + AssignContext& assignContext, + SplitResult& result); + + // FD + bool IsNeedRecordFDInfo(const AssignContext& assignContext, + const SplitResult& splitRes); + void RecordFDInfo(const SplitContext& splitContext, + const AssignContext& assignContext, + SplitResult& result); + + // main + void SplitFD(SplitResult& splitRes); + void CalcSplitPlan(int64_t costLimit, + const SplitContext& splitContext, + SplitResult& result); + + private: + // input + Tensor* cuSeqlensQ_ = nullptr; + Tensor* cuSeqlensK_ = nullptr; + Tensor* sequsedQ_ = nullptr; + Tensor* sequsedK_ = nullptr; + Tensor* cmpResidualK_ = nullptr; + // output + Tensor* metadata_ = nullptr; + // attributes + std::string socVersion_ = ""; + // FD/LD 归约路径(SplitFD/IsNeedRecordFDInfo 等)与 base v2 + // 对齐保留但未启用: 当前场景不产生 FD 任务,恒为 + // false,相关分支为休眠代码,勿据此误判为缺陷。 + bool supportFd_ = false; + uint32_t aicCoreNum_ = optiling::AIC_CORE_MAX_NUM; + uint32_t aivCoreNum_ = optiling::AIV_CORE_MAX_NUM; + int32_t batchSize_ = 0; + int32_t maxSeqlenQ_ = 0; + int32_t maxSeqlenK_ = 0; + int32_t numHeadsQ_ = 0; + int32_t numHeadsK_ = 0; + int32_t headDim_ = 0; + int32_t quantMode_ = 0; + int32_t topk_ = 0; + std::string layoutQ_ = "BSND"; + std::string layoutK_ = "BSND"; + int32_t maskMode_ = 0; + int32_t cmpRatio_ = 1; + uint32_t attentionMode_ = 0; + + // SplitParams + int64_t preToken_ = INT64_MAX; + int64_t nextToken_ = INT64_MAX; + uint32_t groupSize_ = 0; + uint32_t mBaseSize_ = 256; + uint32_t s1BaseSize_ = 4; + uint32_t s2BaseSize_ = 128; + bool isS1G_ = true; + uint32_t maxS2Size_ = 0; + + private: + enum class ParamId : uint32_t { + // input + actSeqLenQ = 0, + actSeqLenK = 1, + seqUsedQ = 2, + seqUsedK = 3, + cmpResidualK = 4, + // output + metadata = 0, + }; +}; +} // namespace aicpu::xllm_qli_v2 +#endif diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.json b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.json new file mode 100644 index 0000000000..549d0b4a49 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.json @@ -0,0 +1,15 @@ +{ + "XllmKernelQuantLightningIndexerV2MetadataVa":{ + "opInfo":{ + "computeCost":"100", + "engine":"DNN_VM_AICPU", + "flagAsync":"False", + "flagPartial":"False", + "functionName":"RunCpuKernel", + "kernelSo":"libmath_aicpu_kernels.so", + "opKernelLib":"CUSTAICPUKernel", + "userDefined":"True", + "workspaceSize":"100" + } + } +} diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/SOURCE.txt b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/SOURCE.txt new file mode 100644 index 0000000000..8e150ec1fa --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/SOURCE.txt @@ -0,0 +1,9 @@ +The AscendC QLI V2 and AICPU metadata implementations originate from xllm_ops +revision 8bd2b014c38fec33ecf14dd33e05e8ad792ec5c8, under +xllm_ops/attention/quant_lightning_indexer_v2_va and +xllm_ops/attention/quant_lightning_indexer_v2_metadata_va. Their original +source headers and CANN Open Software License Agreement Version 2.0 apply. +The license is included in ../gamma_add_rms_norm/CANN_LICENSE.txt. + +xLLM registers the two operators with XllmKernel-prefixed names and packages +them in the xllm-kernel vendor, using its shared AICPU library. diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_def.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_def.cpp new file mode 100644 index 0000000000..ae4652dfe4 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_def.cpp @@ -0,0 +1,147 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va_def.cpp + * \brief + */ + +#include "register/op_def_registry.h" + +namespace ops { +class XllmKernelQuantLightningIndexerV2Va : public OpDef { + public: + explicit XllmKernelQuantLightningIndexerV2Va(const char* name) : OpDef(name) { + this->Input("q") + .ParamType(REQUIRED) + .DataType({ge::DT_INT8}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("k") + .ParamType(REQUIRED) + .DataType({ge::DT_INT8}) + .FormatList({ge::FORMAT_ND}) + .IgnoreContiguous(); + this->Input("w") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("q_descale") + .ParamType(REQUIRED) + .DataTypeList({ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("k_descale") + .ParamType(REQUIRED) + .DataTypeList({ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}) + .IgnoreContiguous(); + this->Input("cu_seqlens_q") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cu_seqlens_k") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("seqused_q") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("seqused_k") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cmp_residual_k") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("block_table") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("output_idx_offset") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("metadata") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("candidate_topk_index") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Output("sparse_indices") + .ParamType(REQUIRED) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}); + this->Output("sparse_values") + .ParamType(REQUIRED) + .DataTypeList({ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}); + this->Output("candidate_topk_index_out") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}); + this->Attr("topk").AttrType(REQUIRED).Int( + 2048); // 2048: 筛选前2048个作为输出index + this->Attr("quant_mode") + .AttrType(REQUIRED) + .Int(2); // 2: int8 per-token-head (仅支持2) + this->Attr("max_seqlen_q") + .AttrType(OPTIONAL) + .Int(-1); // -1: 默认值,表示任意可能长度 + this->Attr("layout_q").AttrType(OPTIONAL).String("BSND"); + this->Attr("layout_k").AttrType(OPTIONAL).String("BSND"); + this->Attr("mask_mode").AttrType(OPTIONAL).Int(0); // 0: 默认值,无mask + this->Attr("cmp_ratio").AttrType(OPTIONAL).Int(1); + this->Attr("return_value").AttrType(OPTIONAL).Int(0); // 0: 默认值 + this->Attr("candidate_mode") + .AttrType(OPTIONAL) + .Int(3); // 3: 默认关闭candidate + this->Attr("candidate_topk_blocks") + .AttrType(OPTIONAL) + .Int(2048); // 块级topk个数, 支持(0, 2048]内64的倍数 + this->Attr("candidate_block_size") + .AttrType(OPTIONAL) + .Int(8); // 候选块大小(位置数) + this->Attr("key_stride0") + .AttrType(OPTIONAL) + .Int(0); // A11: key 第0维 stride (0=紧凑; aclnn 动态调用下 tiling + // 拿不到 tensor stride, 由 csrc 自动传入) + this->Attr("key_dequant_scale_stride0") + .AttrType(OPTIONAL) + .Int(0); // A11: k_scale 第0维 stride + OpAICoreConfig aicore_config; + aicore_config.DynamicCompileStaticFlag(true) + .DynamicFormatFlag(true) + .DynamicRankSupportFlag(true) + .DynamicShapeSupportFlag(true) + .NeedCheckSupportFlag(false) + .PrecisionReduceFlag(true) + .ExtendCfgInfo("opFile.value", + "xllm_kernel_quant_lightning_indexer_v2_va"); + this->AICore().AddConfig("ascend910_93", aicore_config); + } +}; +OP_ADD(XllmKernelQuantLightningIndexerV2Va); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_error_log.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_error_log.h new file mode 100644 index 0000000000..b67792ab8c --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_error_log.h @@ -0,0 +1,167 @@ +/** + * Copyright (c) 2025 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#pragma once + +#include + +// 说明: 这些错误日志宏不依赖 OP_LOGE。opdev/op_log.h (经 opdev/format_utils.h +// 传递包含) 会把 OP_LOGE 重定义为 errno 语义 (std::to_string(errno)), 与 opname +// 语义冲突; 故此处直接用 std::cerr 输出, 自包含、不受宏遮蔽影响, 且能正确处理 +// std::string / const char* / 数值等各类实参 (operator<< 重载)。 + +#ifndef OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON +#define OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opname, param, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid argument for " \ + << (param) << ", reason: " << (reason) << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_DTYPE +#define OP_LOGE_FOR_INVALID_DTYPE(opname, param, actual, expected) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid dtype for " << (param) \ + << ", actual: " << (actual) << ", expected: " << (expected) \ + << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON +#define OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON(opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid dtype for " << (param) \ + << ", actual: " << (actual) << ", reason: " << (reason) \ + << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON +#define OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON(opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid dtypes for " << (param) \ + << ", actual: " << (actual) << ", reason: " << (reason) \ + << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_SHAPE +#define OP_LOGE_FOR_INVALID_SHAPE(opname, param, actual, expected) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid shape for " << (param) \ + << ", actual: " << (actual) << ", expected: " << (expected) \ + << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON +#define OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid shape for " << (param) \ + << ", actual: " << (actual) << ", reason: " << (reason) \ + << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON +#define OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid shapes for " << (param) \ + << ", actual: " << (actual) << ", reason: " << (reason) \ + << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_SHAPEDIM +#define OP_LOGE_FOR_INVALID_SHAPEDIM(opname, param, actual, expected) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid shape dim for " \ + << (param) << ", actual: " << (actual) \ + << ", expected: " << (expected) << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON +#define OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( \ + opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid shape dim for " \ + << (param) << ", actual: " << (actual) \ + << ", reason: " << (reason) << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_SHAPEDIMS_WITH_REASON +#define OP_LOGE_FOR_INVALID_SHAPEDIMS_WITH_REASON( \ + opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid shape dims for " \ + << (param) << ", actual: " << (actual) \ + << ", reason: " << (reason) << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_SHAPESIZE +#define OP_LOGE_FOR_INVALID_SHAPESIZE(opname, param, actual, expected) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid shape size for " \ + << (param) << ", actual: " << (actual) \ + << ", expected: " << (expected) << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON +#define OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( \ + opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid shape size for " \ + << (param) << ", actual: " << (actual) \ + << ", reason: " << (reason) << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON +#define OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( \ + opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid shape sizes for " \ + << (param) << ", actual: " << (actual) \ + << ", reason: " << (reason) << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_VALUE +#define OP_LOGE_FOR_INVALID_VALUE(opname, param, actual, expected) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid value for " << (param) \ + << ", actual: " << (actual) << ", expected: " << (expected) \ + << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_VALUE_WITH_REASON +#define OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid value for " << (param) \ + << ", actual: " << (actual) << ", reason: " << (reason) \ + << std::endl; \ + } while (0) +#endif + +#ifndef OP_LOGE_FOR_INVALID_VALUES_WITH_REASON +#define OP_LOGE_FOR_INVALID_VALUES_WITH_REASON(opname, param, actual, reason) \ + do { \ + std::cerr << "[ERROR] [" << (opname) << "] Invalid values for " << (param) \ + << ", actual: " << (actual) << ", reason: " << (reason) \ + << std::endl; \ + } while (0) +#endif \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_infershape.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_infershape.cpp new file mode 100644 index 0000000000..ba04f4378c --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_infershape.cpp @@ -0,0 +1,177 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va_infershape.cpp + * \brief + */ +#include +#include + +#include "err/ops_err.h" +#include "log/log.h" +#include "quant_lightning_indexer_v2_va_error_log.h" + +using namespace ge; + +namespace ops { +constexpr uint32_t QUERY_INDEX = 0; +constexpr uint32_t KEY_INDEX = 1; +constexpr uint32_t ATTR_SPARSE_COUNT_INDEX = 0; +constexpr uint32_t ATTR_QUERY_LAYOUT_INDEX = 3; +constexpr uint32_t ATTR_KV_LAYOUT_INDEX = 4; +constexpr uint32_t ATTR_RETURN_VALUE_INDEX = 7; +constexpr uint32_t ATTR_CANDIDATE_MODE_INDEX = 8; +constexpr uint32_t ATTR_CANDIDATE_TOPK_BLOCKS_INDEX = 9; +constexpr uint32_t CANDIDATE_MODE_SOURCE = 1; +constexpr uint32_t CU_SEQLENS_Q_INDEX = 5; +constexpr uint32_t SPARSE_VALUES_OUTPUT_INDEX = 1; +constexpr uint32_t CANDIDATE_TOPK_INDEX_OUTPUT_INDEX = 2; +constexpr uint32_t CANDIDATE_TOPK_BLOCKS_FIX = 2048; +constexpr uint32_t DIM_NUM_3 = 3; +constexpr uint32_t DIM_NUM_4 = 4; + +static ge::graphStatus InferShapeXllmKernelQuantLightningIndexerV2Va( + gert::InferShapeContext* context) { + if (context == nullptr) { + OP_LOGE("XllmKernelQuantLightningIndexerV2Va", "context is nullptr!"); + return ge::GRAPH_FAILED; + } + const gert::Shape* queryShape = context->GetInputShape(QUERY_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, queryShape); + const gert::Shape* keyShape = context->GetInputShape(KEY_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, keyShape); + gert::Shape* sparseIndicesShape = context->GetOutputShape(0); + OP_CHECK_NULL_WITH_CONTEXT(context, sparseIndicesShape); + gert::Shape* sparseValuesShape = context->GetOutputShape(1); + OP_CHECK_NULL_WITH_CONTEXT(context, sparseValuesShape); + + auto attrs = context->GetAttrs(); + OP_CHECK_NULL_WITH_CONTEXT(context, attrs); + const char* inputLayoutQueryPtr = + attrs->GetAttrPointer(ATTR_QUERY_LAYOUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, inputLayoutQueryPtr); + const char* inputLayoutKeyPtr = + attrs->GetAttrPointer(ATTR_KV_LAYOUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, inputLayoutKeyPtr); + const int64_t* sparse_count = attrs->GetInt(ATTR_SPARSE_COUNT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, sparse_count); + + std::string inputLayoutQueryPtrStr = std::string(inputLayoutQueryPtr); + std::string inputLayoutKeyPtrStr = std::string(inputLayoutKeyPtr); + if (inputLayoutQueryPtrStr != "TND" && inputLayoutQueryPtrStr != "BSND") { + OP_LOGE_FOR_INVALID_VALUE("XllmKernelQuantLightningIndexerV2Va", + "layout_q", + inputLayoutQueryPtrStr.c_str(), + "BSND or TND"); + return GRAPH_FAILED; + } + + int64_t keyHeadNum = (inputLayoutKeyPtrStr == "TND") ? keyShape->GetDim(1) + : keyShape->GetDim(2); + if (inputLayoutQueryPtrStr == "BSND") { + sparseIndicesShape->SetDimNum(DIM_NUM_4); + sparseIndicesShape->SetDim(0, queryShape->GetDim(0)); // 0:Dim B + sparseIndicesShape->SetDim(1, queryShape->GetDim(1)); // 1:Dim S + sparseIndicesShape->SetDim(2, keyHeadNum); // 2:Dim N + sparseIndicesShape->SetDim(3, *sparse_count); // 3:Dim K + } else { + sparseIndicesShape->SetDimNum(DIM_NUM_3); + sparseIndicesShape->SetDim(0, queryShape->GetDim(0)); // 0:Dim T + sparseIndicesShape->SetDim( + 1, keyHeadNum); // 1:output shape's N Dim, 2: key shape's N Dim + sparseIndicesShape->SetDim(2, *sparse_count); // 2:Dim K + } + const int32_t* return_value = + attrs->GetAttrPointer(ATTR_RETURN_VALUE_INDEX); + bool returnValueFlag = + (return_value != nullptr) ? (*return_value != 0) : false; + if (returnValueFlag) { + *sparseValuesShape = *sparseIndicesShape; + } else { + sparseValuesShape->SetDimNum(1); + sparseValuesShape->SetDim(0, 0); + } + + // candidate_topk_index: 仅 candidate_mode=1(source) 时输出。 + // gate 与 tiling (quant_lightning_indexer_v2_va_tiling.cpp CheckAttrParaInfo) + // 保持一致: BSND 直接放行; TND 需 layout_k=PA_BBND 且 cu_seqlens_q 存在 + // (候选路径下 K 仅支持分页布局)。 + gert::Shape* candidateTopkIndexShape = + context->GetOutputShape(CANDIDATE_TOPK_INDEX_OUTPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, candidateTopkIndexShape); + const int32_t* candidate_mode = + attrs->GetAttrPointer(ATTR_CANDIDATE_MODE_INDEX); + uint32_t candidateMode = + (candidate_mode != nullptr) ? static_cast(*candidate_mode) : 3U; + if (candidateMode == CANDIDATE_MODE_SOURCE) { + bool tndGateOk = false; + if (inputLayoutQueryPtrStr == "TND") { + const gert::Shape* cuSeqlensQShape = + context->GetOptionalInputShape(CU_SEQLENS_Q_INDEX); + tndGateOk = + (inputLayoutKeyPtrStr == "PA_BBND") && (cuSeqlensQShape != nullptr); + } + OP_CHECK_IF((inputLayoutQueryPtrStr != "BSND") && !tndGateOk, + OP_LOGE("XllmKernelQuantLightningIndexerV2Va", + "candidate_mode=1 only supports layout_q=BSND, or " + "layout_q=TND with " + "layout_k=PA_BBND and cu_seqlens_q provided; but got " + "layout_q=%s, layout_k=%s.", + inputLayoutQueryPtrStr.c_str(), + inputLayoutKeyPtrStr.c_str()), + return GRAPH_FAILED); + const int64_t* candidate_topk_blocks = + attrs->GetAttrPointer(ATTR_CANDIDATE_TOPK_BLOCKS_INDEX); + int64_t candBlocks = (candidate_topk_blocks != nullptr) + ? *candidate_topk_blocks + : CANDIDATE_TOPK_BLOCKS_FIX; + // TND 语义: 保持 sparseIndices 的 3 维 [T, N2, topk] 形状, 仅末维替换为 + // candidate_topk_blocks; BSND 则为 4 维 [B, S1, N2, candidate_topk_blocks] + // (SetDim 用 GetDimNum()-1, 布局无关)。 + *candidateTopkIndexShape = *sparseIndicesShape; + candidateTopkIndexShape->SetDim(sparseIndicesShape->GetDimNum() - 1, + candBlocks); + } else { + candidateTopkIndexShape->SetDimNum(1); + candidateTopkIndexShape->SetDim(0, 0); + } + + OP_LOGD(context->GetNodeName(), + "XllmKernelQuantLightningIndexerV2Va InferShape end."); + return ge::GRAPH_SUCCESS; +} + +static ge::graphStatus InferDataTypeXllmKernelQuantLightningIndexerV2Va( + gert::InferDataTypeContext* context) { + if (context == nullptr) { + OP_LOGE("XllmKernelQuantLightningIndexerV2Va", + "InferDataTypeContext context is nullptr!"); + return ge::GRAPH_FAILED; + } + OP_LOGD(context->GetNodeName(), + "Enter XllmKernelQuantLightningIndexerV2Va InferDataType impl."); + // default index data type is int32 + ge::DataType outputType = ge::DT_INT32; + context->SetOutputDataType(0, outputType); + // sparse_values (output 1) 为 bfloat16, 与 tiling GetAndCheckInOutDataType + // 的校验一致 + context->SetOutputDataType(SPARSE_VALUES_OUTPUT_INDEX, ge::DT_BF16); + context->SetOutputDataType(CANDIDATE_TOPK_INDEX_OUTPUT_INDEX, outputType); + OP_LOGD(context->GetNodeName(), + "XllmKernelQuantLightningIndexerV2Va InferDataType end."); + return GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(XllmKernelQuantLightningIndexerV2Va) + .InferShape(InferShapeXllmKernelQuantLightningIndexerV2Va) + .InferDataType(InferDataTypeXllmKernelQuantLightningIndexerV2Va); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.cpp new file mode 100644 index 0000000000..a0be78adef --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.cpp @@ -0,0 +1,1938 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va_tiling.cpp + * \brief + */ + +#include "quant_lightning_indexer_v2_va_tiling.h" + +#include "../op_kernel/quant_lightning_indexer_v2_va_template_tiling_key.h" +#include "quant_lightning_indexer_v2_va_error_log.h" + +using namespace ge; +using namespace AscendC; +using std::map; +using std::string; +namespace optiling { + +static const std::map DATATYPE_TO_STRING_MAP = { + {ge::DT_UNDEFINED, + "DT_UNDEFINED"}, // Used to indicate a DataType field has not been set. + {ge::DT_FLOAT, "DT_FLOAT"}, // float type + {ge::DT_FLOAT16, "DT_FLOAT16"}, // fp16 type + {ge::DT_INT8, "DT_INT8"}, // int8 type + {ge::DT_INT16, "DT_INT16"}, // int16 type + {ge::DT_UINT16, "DT_UINT16"}, // uint16 type + {ge::DT_UINT8, "DT_UINT8"}, // uint8 type + {ge::DT_INT32, "DT_INT32"}, // uint32 type + {ge::DT_INT64, "DT_INT64"}, // int64 type + {ge::DT_UINT32, "DT_UINT32"}, // unsigned int32 + {ge::DT_UINT64, "DT_UINT64"}, // unsigned int64 + {ge::DT_BOOL, "DT_BOOL"}, // bool type + {ge::DT_DOUBLE, "DT_DOUBLE"}, // double type + {ge::DT_DUAL, "DT_DUAL"}, // dual output type + {ge::DT_DUAL_SUB_INT8, "DT_DUAL_SUB_INT8"}, // dual output int8 type + {ge::DT_DUAL_SUB_UINT8, "DT_DUAL_SUB_UINT8"}, // dual output uint8 type + {ge::DT_COMPLEX32, "DT_COMPLEX32"}, // complex32 type + {ge::DT_COMPLEX64, "DT_COMPLEX64"}, // complex64 type + {ge::DT_COMPLEX128, "DT_COMPLEX128"}, // complex128 type + {ge::DT_QINT8, "DT_QINT8"}, // qint8 type + {ge::DT_QINT16, "DT_QINT16"}, // qint16 type + {ge::DT_QINT32, "DT_QINT32"}, // qint32 type + {ge::DT_QUINT8, "DT_QUINT8"}, // quint8 type + {ge::DT_QUINT16, "DT_QUINT16"}, // quint16 type + {ge::DT_RESOURCE, "DT_RESOURCE"}, // resource type + {ge::DT_STRING_REF, "DT_STRING_REF"}, // string ref type + {ge::DT_STRING, "DT_STRING"}, // string type + {ge::DT_VARIANT, "DT_VARIANT"}, // dt_variant type + {ge::DT_BF16, "DT_BFLOAT16"}, // dt_bfloat16 type + {ge::DT_INT4, "DT_INT4"}, // dt_variant type + {ge::DT_UINT1, "DT_UINT1"}, // dt_variant type + {ge::DT_INT2, "DT_INT2"}, // dt_variant type + {ge::DT_UINT2, "DT_UINT2"}, // dt_variant type + {ge::DT_HIFLOAT8, "DT_HIFLOAT8"}, + {ge::DT_FLOAT8_E4M3FN, "DT_FLOAT8_E4M3FN"}, + {ge::DT_FLOAT8_E8M0, "DT_FLOAT8_E8M0"}, + {ge::DT_FLOAT4_E2M1, "DT_FLOAT4_E2M1"}}; + +std::string QLIV2VaDataTypeToSerialString(ge::DataType type) { + const auto it = DATATYPE_TO_STRING_MAP.find(type); + if (it != DATATYPE_TO_STRING_MAP.end()) { + return it->second; + } else { + OP_LOGE("QLIV2VaDataTypeToSerialString ", "datatype %d not support", type); + return "UNDEFINED"; + } +} + +static std::vector ToVector(const gert::Shape& shape) { + size_t shapeSize = shape.GetDimNum(); + std::vector shapeVec(shapeSize, 0); + + for (size_t i = 0; i < shapeSize; i++) { + shapeVec[i] = shape.GetDim(i); + } + return shapeVec; +} + +static std::string ToStringRaw(const gert::Shape& shape) { + std::ostringstream oss; + auto v = ToVector(shape); + if (v.size() > 0) { + for (size_t i = 0; i < v.size() - 1; ++i) { + oss << v[i] << ", "; + } + oss << v[v.size() - 1]; + } + return oss.str(); +} + +// A5 Host tiling libraries must not depend on the external opsbase formatter. +// Preserve its bracketed diagnostics using the existing local formatter. +static std::string ShapeToStringForLog(const gert::Shape& shape) { + return "[" + ToStringRaw(shape) + "]"; +} + +// --------------------------QLIV2VaInfoParser类成员函数定义------------------------------------- +ge::graphStatus QLIV2VaInfoParser::CheckRequiredInOutExistence() const { + OP_CHECK_IF(opParamInfo_.query.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "q", "The shape of q is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.query.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "q", "The desc of q is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.key.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "k", "The shape of k is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.key.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "k", "The desc of k is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.weights.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "w", "The shape of w is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.weights.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "w", "The desc of w is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.query_dequant_scale.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "query_dequant_scale", + "The shape of query_dequant_scale is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.query_dequant_scale.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "query_dequant_scale", + "The desc of query_dequant_scale is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.key_dequant_scale.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "key_dequant_scale", + "The shape of key_dequant_scale is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.key_dequant_scale.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "key_dequant_scale", + "The desc of key_dequant_scale is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.attenOut.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "sparse_indices", "The shape of sparse_indices is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.attenOut.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "sparse_indices", "The desc of sparse_indices is nullptr"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::CheckRequiredAttrExistence() const { + OP_CHECK_IF(opParamInfo_.layOutQuery == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "layout_q", "Layout_q is nullptr"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(opParamInfo_.layOutKey == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "layout_k", "Layout_k is nullptr"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(opParamInfo_.sparseCount == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "sparse_count", "Sparse_count is nullptr"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(opParamInfo_.sparseMode == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "sparse_mode", "Sparse_mode is nullptr"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(opParamInfo_.quantMode == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "query_quant_mode", "Query_quant_mode is nullptr"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::CheckRequiredParaExistence() const { + if (CheckRequiredInOutExistence() != ge::GRAPH_SUCCESS || + CheckRequiredAttrExistence() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetOpName() { + if (context_->GetNodeName() == nullptr) { + OP_LOGE("LightningIndexerV2", "opName got from TilingContext is nullptr"); + return ge::GRAPH_FAILED; + } + opName_ = context_->GetNodeName(); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetNpuInfo() { + platformInfo_ = context_->GetPlatformInfo(); + OP_CHECK_IF(platformInfo_ == nullptr, + OP_LOGE(opName_, "GetPlatformInfo is nullptr."), + return ge::GRAPH_FAILED); + + auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo_); + uint32_t aivNum = ascendcPlatform.GetCoreNumAiv(); + uint32_t aicNum = ascendcPlatform.GetCoreNumAic(); + OP_CHECK_IF(aicNum == 0 || aivNum == 0, + OP_LOGE(opName_, "num of core obtained is 0."), + return GRAPH_FAILED); + + socVersion_ = ascendcPlatform.GetSocVersion(); + npuArch_ = ascendcPlatform.GetCurNpuArch(); + if (npuArch_ != NpuArch::DAV_2201) { + OP_LOGE( + opName_, "NpuArch[%d] is not support.", static_cast(npuArch_)); + return GRAPH_FAILED; + } + OP_CHECK_IF(context_->GetWorkspaceSizes(1) == nullptr, + OP_LOGE(opName_, "workSpaceSize got from ge is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->GetRawTilingData() == nullptr, + OP_LOGE(context_->GetNodeName(), + "RawTilingData got from GE context is nullptr."), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +void QLIV2VaInfoParser::GetOptionalInputParaInfo() { + opParamInfo_.cuSeqLensQ.tensor = + context_->GetOptionalInputTensor(CU_SEQLENS_Q_INDEX); + opParamInfo_.cuSeqLensQ.desc = + context_->GetOptionalInputDesc(CU_SEQLENS_Q_INDEX); + opParamInfo_.cuSeqLensK.tensor = + context_->GetOptionalInputTensor(CU_SEQLENS_K_INDEX); + opParamInfo_.cuSeqLensK.desc = + context_->GetOptionalInputDesc(CU_SEQLENS_K_INDEX); + opParamInfo_.sequsedQ.tensor = + context_->GetOptionalInputTensor(SEQUSED_Q_INDEX); + opParamInfo_.sequsedQ.desc = context_->GetOptionalInputDesc(SEQUSED_Q_INDEX); + opParamInfo_.sequsedK.tensor = + context_->GetOptionalInputTensor(SEQUSED_K_INDEX); + opParamInfo_.sequsedK.desc = context_->GetOptionalInputDesc(SEQUSED_K_INDEX); + opParamInfo_.cmpResidualK.tensor = + context_->GetOptionalInputTensor(CMP_RESIDUAL_K_INDEX); + opParamInfo_.cmpResidualK.desc = + context_->GetOptionalInputDesc(CMP_RESIDUAL_K_INDEX); + opParamInfo_.blockTable.tensor = + context_->GetOptionalInputTensor(BLOCK_TABLE_INDEX); + opParamInfo_.blockTable.desc = + context_->GetOptionalInputDesc(BLOCK_TABLE_INDEX); + opParamInfo_.outputIdxOffset.tensor = + context_->GetOptionalInputTensor(OUTPUT_IDX_OFFSET_INDEX); + opParamInfo_.outputIdxOffset.desc = + context_->GetOptionalInputDesc(OUTPUT_IDX_OFFSET_INDEX); + opParamInfo_.metadata.tensor = + context_->GetOptionalInputTensor(METADATA_INDEX); + opParamInfo_.metadata.desc = context_->GetOptionalInputDesc(METADATA_INDEX); + opParamInfo_.candidateTopkIndex.tensor = + context_->GetOptionalInputTensor(CANDIDATE_TOPK_INDEX_INPUT_INDEX); + opParamInfo_.candidateTopkIndex.desc = + context_->GetOptionalInputDesc(CANDIDATE_TOPK_INDEX_INPUT_INDEX); +} + +void QLIV2VaInfoParser::GetInputParaInfo() { + opParamInfo_.query.desc = context_->GetInputDesc(QUERY_INDEX); + opParamInfo_.query.shape = context_->GetInputShape(QUERY_INDEX); + opParamInfo_.key.desc = context_->GetInputDesc(KEY_INDEX); + opParamInfo_.key.shape = context_->GetInputShape(KEY_INDEX); + opParamInfo_.weights.desc = context_->GetInputDesc(WEIGTHS_INDEX); + opParamInfo_.weights.shape = context_->GetInputShape(WEIGTHS_INDEX); + opParamInfo_.query_dequant_scale.desc = + context_->GetInputDesc(QUERY_DEQUANT_SCALE_INDEX); + opParamInfo_.query_dequant_scale.shape = + context_->GetInputShape(QUERY_DEQUANT_SCALE_INDEX); + opParamInfo_.key_dequant_scale.desc = + context_->GetInputDesc(KEY_DEQUANT_SCALE_INDEX); + opParamInfo_.key_dequant_scale.shape = + context_->GetInputShape(KEY_DEQUANT_SCALE_INDEX); + GetOptionalInputParaInfo(); +} + +void QLIV2VaInfoParser::GetOutputParaInfo() { + opParamInfo_.attenOut.desc = context_->GetOutputDesc(SPARSE_INDICES_INDEX); + opParamInfo_.attenOut.shape = context_->GetOutputShape(SPARSE_INDICES_INDEX); + opParamInfo_.sparseValues.desc = context_->GetOutputDesc(SPARSE_VALUES_INDEX); + opParamInfo_.sparseValues.shape = + context_->GetOutputShape(SPARSE_VALUES_INDEX); +} + +ge::graphStatus QLIV2VaInfoParser::GetAttrParaInfo() { + auto attrs = context_->GetAttrs(); + OP_CHECK_IF(attrs == nullptr, + OP_LOGE(context_->GetNodeName(), "attrs got from ge is nullptr"), + return ge::GRAPH_FAILED); + + OP_LOGI(context_->GetNodeName(), "GetAttrParaInfo start"); + + opParamInfo_.quantMode = + attrs->GetAttrPointer(ATTR_QUANT_MODE_INDEX); + opParamInfo_.maxSeqlenQ = + attrs->GetAttrPointer(ATTR_MAX_SEQLEN_Q_INDEX); + opParamInfo_.layOutQuery = attrs->GetStr(ATTR_QUERY_LAYOUT_INDEX); + opParamInfo_.layOutKey = attrs->GetStr(ATTR_KEY_LAYOUT_INDEX); + opParamInfo_.sparseCount = attrs->GetAttrPointer(ATTR_TOPK_INDEX); + opParamInfo_.sparseMode = + attrs->GetAttrPointer(ATTR_MASK_MODE_INDEX); + opParamInfo_.cmpRatio = attrs->GetAttrPointer(ATTR_CMP_RATIO_INDEX); + opParamInfo_.returnValue = + attrs->GetAttrPointer(ATTR_RETURN_VALUE_INDEX); + opParamInfo_.candidateMode = + attrs->GetAttrPointer(ATTR_CANDIDATE_MODE_INDEX); + opParamInfo_.candidateTopkBlocks = + attrs->GetAttrPointer(ATTR_CANDIDATE_TOPK_BLOCKS_INDEX); + opParamInfo_.candidateBlockSize = + attrs->GetAttrPointer(ATTR_CANDIDATE_BLOCK_SIZE_INDEX); + // A11: key 0 轴非连续 — tiling 侧 stride 来源优先级: + // 1) GetDynamicInputStride (仅 TensorV2/图模式携带非连续描述时有值) + // 2) 显式属性 key_stride0/key_dequant_scale_stride0 (aclnn 动态调用下 1) + // 恒为空, csrc 从 tensor.stride() 自动传入) 两路都空 = 紧凑存储 + opParamInfo_.keyStride0Attr = + attrs->GetAttrPointer(ATTR_KEY_STRIDE0_INDEX); + opParamInfo_.keyDequantScaleStride0Attr = + attrs->GetAttrPointer(ATTR_KEY_DEQUANT_SCALE_STRIDE0_INDEX); + auto keyStrides = context_->GetDynamicInputStride(KEY_INDEX, 0); + auto keyDequantScaleStrides = + context_->GetDynamicInputStride(KEY_DEQUANT_SCALE_INDEX, 0); + if (keyStrides != nullptr && keyStrides->GetDimNum() > 0) { + for (size_t i = 0; i < keyStrides->GetDimNum(); i++) { + keyStridesVec_.push_back(keyStrides->GetStride(i)); + } + } + if (keyDequantScaleStrides != nullptr && + keyDequantScaleStrides->GetDimNum() > 0) { + for (size_t i = 0; i < keyDequantScaleStrides->GetDimNum(); i++) { + keyDequantScaleStridesVec_.push_back( + keyDequantScaleStrides->GetStride(i)); + } + } + + if (opParamInfo_.layOutQuery != nullptr) { + OP_LOGI(context_->GetNodeName(), + "layout_query is:%s", + opParamInfo_.layOutQuery); + } + if (opParamInfo_.layOutKey != nullptr) { + OP_LOGI( + context_->GetNodeName(), "layout_key is:%s", opParamInfo_.layOutKey); + } + if (opParamInfo_.sparseCount != nullptr) { + OP_LOGI(context_->GetNodeName(), + "selscted count is:%d", + *opParamInfo_.sparseCount); + } + if (opParamInfo_.sparseMode != nullptr) { + OP_LOGI( + context_->GetNodeName(), "sparse mode is:%d", *opParamInfo_.sparseMode); + } + if (opParamInfo_.cmpRatio != nullptr) { + OP_LOGI(context_->GetNodeName(), "cmpRatio is:%d", *opParamInfo_.cmpRatio); + } + if (opParamInfo_.returnValue != nullptr) { + OP_LOGI(context_->GetNodeName(), + "returnValue is:%s", + *opParamInfo_.returnValue ? "true" : "false"); + } + if (opParamInfo_.maxSeqlenQ != nullptr) { + OP_LOGI( + context_->GetNodeName(), "maxSeqlenQ is:%d", *opParamInfo_.maxSeqlenQ); + } + if (opParamInfo_.quantMode != nullptr) { + OP_LOGI(context_->GetNodeName(), + "query_quant_mode mode is:%d", + *opParamInfo_.quantMode); + } + OP_LOGI(context_->GetNodeName(), "GetAttrParaInfo end"); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::CheckAttrParaInfo() { + std::string layout_key(opParamInfo_.layOutKey); + std::string layout_query(opParamInfo_.layOutQuery); + + OP_CHECK_IF((std::string(opParamInfo_.layOutKey) != "PA_BBND"), + OP_LOGE(opName_, + "input attr layout_key only supported PA_BBND," + "but now layout_key is %s.", + layout_key.c_str()), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(!((*opParamInfo_.sparseCount > 0) && + (*opParamInfo_.sparseCount <= SPARSE_LIMIT)), + OP_LOGE(opName_, + "input attr sparse_count must > 0 and <= %d, but now " + "sparse_count is %d", + SPARSE_LIMIT, + *opParamInfo_.sparseCount), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (*opParamInfo_.cmpRatio <= 0) || (*opParamInfo_.cmpRatio > 128) || + ((*opParamInfo_.cmpRatio & (*opParamInfo_.cmpRatio - 1)) != 0), + OP_LOGE( + opName_, + "input attr cmpRatio must > 0 and <= 128 and should be powers of 2," + " but now cmpRatio is %ld.", + *opParamInfo_.cmpRatio), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(((std::string(opParamInfo_.layOutQuery) != "BSND") && + (std::string(opParamInfo_.layOutQuery) != "TND")), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "layout_q", + std::string(opParamInfo_.layOutQuery).c_str(), + "Layout_q only supports BSND or TND"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(!((*opParamInfo_.sparseMode == 0) || + (*opParamInfo_.sparseMode == SPARSE_MODE_LOWER)), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "sparse_mode", + std::to_string(*opParamInfo_.sparseMode).c_str(), + "Sparse_mode only supports 0 or 3"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(*opParamInfo_.quantMode != 2, + OP_LOGE(opName_, "input attr quant_mode only supported 2."), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(*opParamInfo_.returnValue, + OP_LOGE(opName_, "input attr returnValue only supported False."), + return ge::GRAPH_FAILED); + OP_CHECK_IF((*opParamInfo_.maxSeqlenQ < -1), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "max_seqlen_q", + std::to_string(*opParamInfo_.maxSeqlenQ).c_str(), + "Max_seqlen_q must >= -1"), + return ge::GRAPH_FAILED); + + // -------------------candidate (two-level topk) 校验------------------- + uint32_t candidateMode = + (opParamInfo_.candidateMode != nullptr) + ? static_cast(*opParamInfo_.candidateMode) + : CANDIDATE_MODE_OFF; + OP_CHECK_IF( + (candidateMode != CANDIDATE_MODE_SOURCE) && + (candidateMode != CANDIDATE_MODE_CONSUMER) && + (candidateMode != CANDIDATE_MODE_OFF), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "candidate_mode", + std::to_string(candidateMode), + "Candidate_mode only supports 1(source), 2(consumer) or 3(off)"), + return ge::GRAPH_FAILED); + if (candidateMode != CANDIDATE_MODE_OFF) { + // A12: layout_q 支持 BSND 与 TND (TND 需 cu_seqlens_q; layout_k 固定 + // PA_BBND — K 仅支持分页布局) + OP_CHECK_IF( + std::string(opParamInfo_.layOutQuery) != "BSND" && + std::string(opParamInfo_.layOutQuery) != "TND", + OP_LOGE(opName_, + "candidate_mode only supports layout_q=BSND/TND, but got %s.", + layout_query.c_str()), + return ge::GRAPH_FAILED); + if (std::string(opParamInfo_.layOutQuery) == "TND") { + OP_CHECK_IF(std::string(opParamInfo_.layOutKey) != "PA_BBND", + OP_LOGE(opName_, + "candidate_mode with layout_q=TND requires " + "layout_k=PA_BBND, but got %s.", + layout_key.c_str()), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.cuSeqLensQ.tensor == nullptr, + OP_LOGE(opName_, + "candidate_mode with layout_q=TND requires cu_seqlens_q."), + return ge::GRAPH_FAILED); + } + uint32_t candBlocks = + (opParamInfo_.candidateTopkBlocks != nullptr) + ? static_cast(*opParamInfo_.candidateTopkBlocks) + : CANDIDATE_TOPK_BLOCKS_FIX; + // 放宽为 (0, 2048] 内 64 的倍数: 累加器/抽取/拷出逻辑均按 64 对齐设计 + OP_CHECK_IF( + candBlocks == 0 || candBlocks > CANDIDATE_TOPK_BLOCKS_FIX || + (candBlocks % 64) != 0, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "candidate_topk_blocks", + std::to_string(candBlocks), + "Candidate_topk_blocks must be a multiple of 64 in (0, 2048]"), + return ge::GRAPH_FAILED); + uint32_t candBlkSize = + (opParamInfo_.candidateBlockSize != nullptr) + ? static_cast(*opParamInfo_.candidateBlockSize) + : CANDIDATE_BLOCK_SIZE_DEFAULT; + // 当前仅支持 8: BlockReduceMax 以 32B 块 (8 fp32) 为归约粒度 + OP_CHECK_IF(candBlkSize != CANDIDATE_BLOCK_SIZE_DEFAULT, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "candidate_block_size", + std::to_string(candBlkSize), + "Candidate_block_size only supports 8 currently"), + return ge::GRAPH_FAILED); + if (candidateMode == CANDIDATE_MODE_CONSUMER) { + OP_CHECK_IF(opParamInfo_.candidateTopkIndex.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "candidate_topk_index", + "candidate_topk_index input is required when " + "candidate_mode=2(consumer)"), + return ge::GRAPH_FAILED); + } + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetOpParaInfo() { + GetInputParaInfo(); + GetOutputParaInfo(); + if (ge::GRAPH_SUCCESS != GetAttrParaInfo()) { + return ge::GRAPH_FAILED; + } + if (ge::GRAPH_SUCCESS != CheckAttrParaInfo()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetAndCheckInOutDataType() { + inputQType_ = opParamInfo_.query.desc->GetDataType(); + inputKType_ = opParamInfo_.key.desc->GetDataType(); + weightsType_ = opParamInfo_.weights.desc->GetDataType(); + inputQueryScaleType_ = opParamInfo_.query_dequant_scale.desc->GetDataType(); + inputKeyScaleType_ = opParamInfo_.key_dequant_scale.desc->GetDataType(); + outputType_ = opParamInfo_.attenOut.desc->GetDataType(); + valuesOutType_ = opParamInfo_.sparseValues.desc->GetDataType(); + + OP_CHECK_IF(!(inputQType_ == inputKType_), + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( + opName_, + "q and k", + QLIV2VaDataTypeToSerialString(inputQType_) + " and " + + QLIV2VaDataTypeToSerialString(inputKType_), + "The dtype of q and k must be same"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF( + !(inputQueryScaleType_ == inputKeyScaleType_), + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( + opName_, + "q_descale and k_descale", + QLIV2VaDataTypeToSerialString(inputQueryScaleType_) + " and " + + QLIV2VaDataTypeToSerialString(inputKeyScaleType_), + "The dtype of q_descale and k_descale must be same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + inputQType_ != ge::DT_INT8, + OP_LOGE(opName_, + "The data types of the input query and key must be int8."), + return ge::GRAPH_FAILED); + OP_CHECK_IF(inputQueryScaleType_ != ge::DT_FLOAT16, + OP_LOGE(opName_, + "The data types of the input query_dequant_scale and " + "key_dequant_scale must be float16."), + return ge::GRAPH_FAILED); + + OP_CHECK_IF( + weightsType_ != ge::DT_FLOAT16, + OP_LOGE(opName_, "The data types of the input weights must be float16."), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(outputType_ != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "sparse_indices", + QLIV2VaDataTypeToSerialString(outputType_).c_str(), + "The dtype of sparse_indices must be int32"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(valuesOutType_ != ge::DT_BF16, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "sparse_values", + QLIV2VaDataTypeToSerialString(valuesOutType_).c_str(), + "The dtype of sparse_values must be bfloat16"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetQueryKeyAndOutLayout() { + // 获取query,key的Layout基准值 + const map layoutQueryMap = { + {"BSND", QliV2DataLayout::BSND}, {"TND", QliV2DataLayout::TND}}; + + std::string layout_query(opParamInfo_.layOutQuery); + auto QLayout_ = layoutQueryMap.find(layout_query); + if (QLayout_ != layoutQueryMap.end()) { + qLayout_ = QLayout_->second; + } + + const map layoutKeyMap = { + {"BSND", QliV2DataLayout::BSND}, + {"TND", QliV2DataLayout::TND}, + {"PA_BSND", QliV2DataLayout::PA_BBND}, + {"PA_BBND", QliV2DataLayout::PA_BBND}}; + std::string layout_key(opParamInfo_.layOutKey); + auto KLayout = layoutKeyMap.find(layout_key); + if (KLayout != layoutKeyMap.end()) { + kLayout_ = KLayout->second; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetAndCheckOptionalInput() { + // =============== K 侧校验 =============== + if (kLayout_ == QliV2DataLayout::PA_BBND) { + // PA_BBND: block_table 必传, seqused_k 必传, cu_seqlens_k 不传 + OP_CHECK_IF(opParamInfo_.blockTable.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "block_table", + "When layout_k is PA_BBND, block_table must not be null"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.sequsedK.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "seqused_k", + "When layout_k is PA_BBND, seqused_k must not be null"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.cuSeqLensK.tensor != nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cu_seqlens_k", + "When layout_k is PA_BBND, cu_seqlens_k must not be provided"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.blockTable.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "block_table", + QLIV2VaDataTypeToSerialString( + opParamInfo_.blockTable.desc->GetDataType()) + .c_str(), + "The dtype of block_table only supports int32"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.sequsedK.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "seqused_k", + QLIV2VaDataTypeToSerialString( + opParamInfo_.sequsedK.desc->GetDataType()) + .c_str(), + "The dtype of seqused_k only supports int32"), + return ge::GRAPH_FAILED); + } else if (kLayout_ == QliV2DataLayout::TND) { + // TND: cu_seqlens_k 必传, seqused_k 可选, cu_seqlens_k 不传 + OP_CHECK_IF(opParamInfo_.cuSeqLensK.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cu_seqlens_k", + "When layout_k is TND, cu_seqlens_k must not be null"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.cuSeqLensK.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "cu_seqlens_k", + QLIV2VaDataTypeToSerialString( + opParamInfo_.cuSeqLensK.desc->GetDataType()) + .c_str(), + "The dtype of cu_seqlens_k only supports int32"), + return ge::GRAPH_FAILED); + // seqused_k 可选 - 仅校验数据类型 + if (opParamInfo_.sequsedK.tensor != nullptr) { + OP_CHECK_IF(opParamInfo_.sequsedK.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "seqused_k", + QLIV2VaDataTypeToSerialString( + opParamInfo_.sequsedK.desc->GetDataType()) + .c_str(), + "The dtype of seqused_k only supports int32"), + return ge::GRAPH_FAILED); + } + } else { + // BSND: cu_seqlens_k 不传, seqused_k 可选 + OP_CHECK_IF(opParamInfo_.cuSeqLensK.tensor != nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cu_seqlens_k", + "When layout_k is BSND, cu_seqlens_k must not be null"), + return ge::GRAPH_FAILED); + if (opParamInfo_.sequsedK.tensor != nullptr) { + OP_CHECK_IF(opParamInfo_.sequsedK.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "seqused_k", + QLIV2VaDataTypeToSerialString( + opParamInfo_.sequsedK.desc->GetDataType()) + .c_str(), + "The dtype of seqused_k only supports int32"), + return ge::GRAPH_FAILED); + } + } + + // block_table 非 PA 场景必须为空 + if (kLayout_ != QliV2DataLayout::PA_BBND) { + OP_CHECK_IF( + opParamInfo_.blockTable.tensor != nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "block_table", + "When layout_k is not PA_BBND, block_table must not be null"), + return ge::GRAPH_FAILED); + } + + // =============== cmpResidualK 校验 =============== + // cmpRatio 不等于 1 且 sparseMode 不等于 0 时 cmpResidualK 必传 + if (opParamInfo_.cmpRatio != nullptr && *opParamInfo_.cmpRatio != 1 && + opParamInfo_.sparseMode != nullptr && *opParamInfo_.sparseMode != 0) { + OP_CHECK_IF(opParamInfo_.cmpResidualK.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cmp_residual_k", + "Cmp_ratio is not 1 and sparse_mode is not 0, " + "cmp_residual_k must not be null"), + return ge::GRAPH_FAILED); + // cmpResidualK 传入时校验维度 & 数据类型 + if (qLayout_ == QliV2DataLayout::BSND) { + OP_CHECK_IF( + opParamInfo_.query.shape->GetStorageShape().GetDim(DIM_IDX_ZERO) != + opParamInfo_.cmpResidualK.tensor->GetStorageShape() + .GetShapeSize(), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "cmp_residual_k", + ToStringRaw(opParamInfo_.cmpResidualK.tensor->GetStorageShape()) + .c_str(), + "When layout_q is BSND, the shape of cmp_residual_k must be " + "(B,)"), + return ge::GRAPH_FAILED); + } else if (qLayout_ == QliV2DataLayout::TND) { + OP_CHECK_IF( + opParamInfo_.cmpResidualK.tensor->GetStorageShape().GetShapeSize() != + opParamInfo_.cuSeqLensQ.tensor->GetStorageShape().GetShapeSize() - + 1, + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "cmp_residual_k", + std::to_string(opParamInfo_.cmpResidualK.tensor->GetStorageShape() + .GetShapeSize()), + "When layout_q is TND, the shape size of cmp_residual_k " + "must equal the shape size - 1 of cu_seqlens_q"), + return ge::GRAPH_FAILED); + } + } else { + OP_CHECK_IF( + opParamInfo_.cmpResidualK.tensor != nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cmp_residual_k", + "Cmp_ratio is 1 or sparse_mode is 0, cmp_residual_k must be null"), + return ge::GRAPH_FAILED); + } + // cmpResidualK 传入时校验数据类型 + if (opParamInfo_.cmpResidualK.tensor != nullptr) { + OP_CHECK_IF(opParamInfo_.cmpResidualK.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "cmp_residual_k", + QLIV2VaDataTypeToSerialString( + opParamInfo_.cmpResidualK.desc->GetDataType()) + .c_str(), + "The dtype of cmp_residual_k supports int32"), + return ge::GRAPH_FAILED); + } + + // =============== Q 侧校验 =============== + if (qLayout_ == QliV2DataLayout::TND) { + // TND: cu_seqlens_q 必传, seqused_q 可选 + OP_CHECK_IF(opParamInfo_.cuSeqLensQ.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cu_seqlens_q", + "When layout_q is TND, cu_seqlens_q must not be null"), + return ge::GRAPH_FAILED); + if (kLayout_ == QliV2DataLayout::PA_BBND) { + // k为PA_BBND必传sequsedK, 用sequsedK的维度校验 + OP_CHECK_IF( + opParamInfo_.cuSeqLensQ.tensor->GetStorageShape().GetShapeSize() != + opParamInfo_.sequsedK.tensor->GetStorageShape().GetShapeSize() + + 1, + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "cmp_residual_k", + std::to_string(opParamInfo_.cmpResidualK.tensor->GetStorageShape() + .GetShapeSize()), + "When layout_q is TND and layout_k is PA_BBND, " + "the shape size of cu_seqlens_q must equal the shape size + 1 of " + "seqused_k"), + return ge::GRAPH_FAILED); + } else if (kLayout_ == QliV2DataLayout::TND) { + // q、k都为TND, cuSeqlensQ与cuSeqlensK维度一致校验 + OP_CHECK_IF( + opParamInfo_.cuSeqLensQ.tensor->GetStorageShape().GetShapeSize() != + opParamInfo_.cuSeqLensK.tensor->GetStorageShape().GetShapeSize(), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "cu_seqlens_q and cu_seqlens_k", + ShapeToStringForLog( + opParamInfo_.cuSeqLensQ.tensor->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.cuSeqLensK.tensor->GetStorageShape()), + "When layout_q is TND and layout_k is TND, " + "the shape of cu_seqlens_q must equal the shape of cu_seqlens_k"), + return ge::GRAPH_FAILED); + } + OP_CHECK_IF(opParamInfo_.cuSeqLensQ.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "cu_seqlens_q", + QLIV2VaDataTypeToSerialString( + opParamInfo_.cuSeqLensK.desc->GetDataType()) + .c_str(), + "The dtype of cu_seqlens_q only supports int32"), + return ge::GRAPH_FAILED); + // seqused_q 可选 - 仅校验数据类型 + if (opParamInfo_.sequsedQ.tensor != nullptr) { + OP_CHECK_IF(opParamInfo_.sequsedQ.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "seqused_q", + QLIV2VaDataTypeToSerialString( + opParamInfo_.sequsedQ.desc->GetDataType()) + .c_str(), + "The dtype of seqused_q only supports int32"), + return ge::GRAPH_FAILED); + } + } else { + // BSND: cu_seqlens_q 不传, seqused_q 可选 + OP_CHECK_IF(opParamInfo_.cuSeqLensQ.tensor != nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cu_seqlens_q", + "When layout_q is BSND, cu_seqlens_q must not be provided"), + return ge::GRAPH_FAILED); + if (opParamInfo_.sequsedQ.tensor != nullptr) { + OP_CHECK_IF(opParamInfo_.sequsedQ.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "seqused_q", + QLIV2VaDataTypeToSerialString( + opParamInfo_.sequsedQ.desc->GetDataType()) + .c_str(), + "The dtype of seqused_q only supports int32"), + return ge::GRAPH_FAILED); + } + } + // metadata 必传 + OP_CHECK_IF(opParamInfo_.metadata.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "metadata", "Metadata must not be null"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::CheckShapeDim() { + OP_CHECK_IF( + (opParamInfo_.blockTable.tensor != nullptr) && + (opParamInfo_.blockTable.tensor->GetStorageShape().GetDimNum() != + DIM_NUM_TWO), + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + "block_table", + std::to_string( + opParamInfo_.blockTable.tensor->GetStorageShape().GetDimNum()) + .c_str(), + "2"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + ((kLayout_ == QliV2DataLayout::PA_BBND) || + (kLayout_ == QliV2DataLayout::BSND)) && + (opParamInfo_.key.shape->GetStorageShape().GetDimNum() != + DIM_NUM_FOUR), + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + "k", + std::to_string(opParamInfo_.key.shape->GetStorageShape().GetDimNum()) + .c_str(), + "4"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (kLayout_ == QliV2DataLayout::TND) && + (opParamInfo_.key.shape->GetStorageShape().GetDimNum() != + DIM_NUM_THREE), + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + "k", + std::to_string(opParamInfo_.key.shape->GetStorageShape().GetDimNum()) + .c_str(), + "3"), + return ge::GRAPH_FAILED); + + uint32_t qShapeDim = opParamInfo_.query.shape->GetStorageShape().GetDimNum(); + uint32_t weightsShapeDim = + opParamInfo_.weights.shape->GetStorageShape().GetDimNum(); + uint32_t outShapeDim = + opParamInfo_.attenOut.shape->GetStorageShape().GetDimNum(); + uint32_t expectShapeDim = DIM_NUM_FOUR; + if (qLayout_ == QliV2DataLayout::TND) { + expectShapeDim = DIM_NUM_THREE; + } + OP_CHECK_IF( + qShapeDim != expectShapeDim, + OP_LOGE_FOR_INVALID_SHAPEDIM(opName_, + "q", + std::to_string(qShapeDim).c_str(), + std::to_string(expectShapeDim).c_str()), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + outShapeDim != expectShapeDim, + OP_LOGE_FOR_INVALID_SHAPEDIM(opName_, + "sparse_indices", + std::to_string(outShapeDim).c_str(), + std::to_string(expectShapeDim).c_str()), + return ge::GRAPH_FAILED); + if (opParamInfo_.outputIdxOffset.tensor != nullptr) { + uint32_t outputIdxOffsetShapeDim = + opParamInfo_.outputIdxOffset.tensor->GetStorageShape().GetDimNum(); + OP_CHECK_IF((outputIdxOffsetShapeDim != expectShapeDim - 1), + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + "output_idx_offset", + std::to_string(outputIdxOffsetShapeDim).c_str(), + std::to_string(expectShapeDim - 1).c_str()), + return ge::GRAPH_FAILED); + } + OP_CHECK_IF( + !(weightsShapeDim == expectShapeDim - 1), + OP_LOGE_FOR_INVALID_SHAPEDIM(opName_, + "w", + std::to_string(weightsShapeDim).c_str(), + std::to_string(expectShapeDim - 1).c_str()), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetN1Size() { + if (qLayout_ == QliV2DataLayout::BSND) { + n1Size_ = static_cast( + opParamInfo_.query.shape->GetStorageShape().GetDim(DIM_IDX_TWO)); + } else { + // TND + n1Size_ = static_cast( + opParamInfo_.query.shape->GetStorageShape().GetDim(DIM_IDX_ONE)); + } + OP_LOGI(context_->GetNodeName(), "n1Size is %d", n1Size_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetActualSeqLenSize( + uint32_t& size, + const gert::Tensor* tensor, + const std::string& actualSeqLenName) const { + size = static_cast(tensor->GetShapeSize()); + if (size <= 0) { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + actualSeqLenName.c_str(), + std::to_string(size).c_str(), + "The shape size of " + actualSeqLenName + " should be greater than 0"); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetAndCheckN2Size() { + // PA_BBND + if (kLayout_ == QliV2DataLayout::TND) { + n2Size_ = static_cast( + opParamInfo_.key.shape->GetStorageShape().GetDim(DIM_IDX_ONE)); + } else { + n2Size_ = static_cast( + opParamInfo_.key.shape->GetStorageShape().GetDim(DIM_IDX_TWO)); + } + OP_LOGI(context_->GetNodeName(), "N2 is %d", n2Size_); + OP_CHECK_IF( + n2Size_ != 1, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "k", + ToStringRaw(opParamInfo_.key.shape->GetStorageShape()).c_str(), + "The head num of k only supports 1"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetGSize() { + if (n1Size_ % n2Size_ != 0) { + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and k", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog(opParamInfo_.key.shape->GetStorageShape()), + "The head num of q can not be a multiple of the head num of k"); + return ge::GRAPH_FAILED; + } + gSize_ = n1Size_ / n2Size_; + + // 910b/910_93: 支持 gSize=64/32 (32 参照 v1 quant_lightning_indexer, + // mBaseSize=4*gSize 推导) + OP_CHECK_IF( + (gSize_ != G_SIZE_LIMIT) && (gSize_ != G_SIZE_LIMIT_32), + OP_LOGE(opName_, + "N1 is %u, N2 is %u, N1 divided by N2 must equal 64 or 32.", + n1Size_, + n2Size_), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetBatchSize() { + // 获取B基准值 + // 1、非TND时, 以query的batch_size维度为基准; + // 2、TND时, 以cu_seqlens_q的shape[0]-1为B轴大小 + if (qLayout_ == QliV2DataLayout::BSND) { + bSize_ = opParamInfo_.query.shape->GetStorageShape().GetDim(DIM_IDX_ZERO); + OP_LOGI(context_->GetNodeName(), + "b: %d, s: %d, n: %d,d :%d", + opParamInfo_.query.shape->GetStorageShape().GetDim(DIM_IDX_ZERO), + opParamInfo_.query.shape->GetStorageShape().GetDim(DIM_IDX_ONE), + opParamInfo_.query.shape->GetStorageShape().GetDim(DIM_IDX_TWO), + opParamInfo_.query.shape->GetStorageShape().GetDim(DIM_IDX_THREE)); + return ge::GRAPH_SUCCESS; + } else { // TND + // cu_seqlens_q shape is [B+1], batch_size = shape[0] - 1 + uint32_t cuSeqLensQSize = 0; + if (GetActualSeqLenSize(cuSeqLensQSize, + opParamInfo_.cuSeqLensQ.tensor, + "input cu_seqlens_q") != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + cuSeqLensQSize <= 1, + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "cu_seqlens_q", + std::to_string(cuSeqLensQSize).c_str(), + "The shape size of cu_seqlens_q should be greater than 1 (B+1)"), + return ge::GRAPH_FAILED); + bSize_ = cuSeqLensQSize - 1; + + // Validate key side batch size consistency + if (kLayout_ == QliV2DataLayout::TND) { + uint32_t cuSeqLensKSize = 0; + if (GetActualSeqLenSize(cuSeqLensKSize, + opParamInfo_.cuSeqLensK.tensor, + "cu_seqlens_k") != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + (cuSeqLensKSize - 1) != bSize_, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "cu_seqlens_q and cu_seqlens_k", + ShapeToStringForLog( + opParamInfo_.cuSeqLensK.tensor->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.cuSeqLensK.tensor->GetStorageShape()), + "The batch sizes derived from cu_seqlens_q and cu_seqlens_k must " + "be same"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; + } +} + +ge::graphStatus QLIV2VaInfoParser::GetHeadDim() { + // 以query的D维度为基准 + uint32_t dIndex = DIM_IDX_TWO; + // 根据layout确定D维度在shape中的位置 + switch (qLayout_) { + case QliV2DataLayout::TND: + // TND格式: [Total, N, D] -> D是第2维(索引2) + dIndex = DIM_IDX_TWO; + break; + case QliV2DataLayout::BSND: + // BSND格式: [Batch, SeqLen, N, D] -> D是第3维(索引3) + dIndex = DIM_IDX_THREE; + break; + default: + OP_LOGE(opName_, "unsupported layout for getting head dim."); + return ge::GRAPH_FAILED; + } + headDim_ = opParamInfo_.query.shape->GetStorageShape().GetDim(dIndex); + OP_CHECK_IF(headDim_ != HEAD_DIM_LIMIT, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "q", + ToStringRaw(opParamInfo_.query.shape->GetStorageShape()), + "The head dim of q only supports 128"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetS1Size() { + if (qLayout_ == QliV2DataLayout::BSND) { + s1Size_ = opParamInfo_.query.shape->GetStorageShape().GetDim(1); + } else if (qLayout_ == QliV2DataLayout::TND) { + // A12: TND 的 q 为 [T, G, D] 拼接, s1Size = 总行数 T。 + // 注意: TND 主路径的批前缀/行数均由 kernel 从 cu_seqlens_q(GM) 逐批读取, + // 不消费 s1Size; tiling 阶段禁止读 tensor 数据 (gert::Tensor data 未就绪, + // 读取直接段错误); consumer shape 校验式已用 TND 专分支 (query.shape[0] x + // N2 x candBlocks), 与 s1Size 解耦 + s1Size_ = opParamInfo_.query.shape->GetStorageShape().GetDim(0); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetAndCheckBlockSize() { + blockSize_ = static_cast( + opParamInfo_.key.shape->GetStorageShape().GetDim(1)); + OP_LOGI(context_->GetNodeName(), "blockSize_ is %d", blockSize_); + + OP_CHECK_IF(((blockSize_ % BLOCK_SIZE_FACTOR != 0) || (blockSize_ == 0) || + (blockSize_ > BLOCK_SIZE_LIMIT)), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "k", + ToStringRaw(opParamInfo_.key.shape->GetStorageShape()), + "The block_size of k must be a multiple of 16 and belong to " + "(0, 1024]"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetS2SizeForPageAttention() { + if (GetAndCheckBlockSize() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + int32_t blockCount_ = static_cast( + opParamInfo_.key.shape->GetStorageShape().GetDim(0)); + OP_CHECK_IF((blockCount_ == 0), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "k", + ToStringRaw(opParamInfo_.key.shape->GetStorageShape()), + "The block_count of k cannot be 0"), + return ge::GRAPH_FAILED); + + maxBlockNumPerBatch_ = + opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(1); + s2Size_ = maxBlockNumPerBatch_ * blockSize_; + OP_LOGI(context_->GetNodeName(), + "maxBlockNumPerBatch_ is %d, blockSize_ is %d, s2Size_ is %d", + maxBlockNumPerBatch_, + blockSize_, + s2Size_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetS2SizeForBatchContinuous() { + std::string layout_key(opParamInfo_.layOutKey); + if (kLayout_ == QliV2DataLayout::BSND) { + s2Size_ = opParamInfo_.key.shape->GetStorageShape().GetDim(DIM_IDX_ONE); + } else if (kLayout_ == QliV2DataLayout::TND) { + s2Size_ = opParamInfo_.key.shape->GetStorageShape().GetDim(DIM_IDX_ZERO); + } + OP_CHECK_IF( + (kLayout_ != QliV2DataLayout::BSND) && (kLayout_ != QliV2DataLayout::TND), + OP_LOGE_FOR_INVALID_VALUE( + opName_, "layout_k", layout_key.c_str(), "BSND or TND"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::GetS2Size() { + // 获取S2基准值 + // 1、BATCH_CONTINUOUS时, 从key的S轴获取 + // 3、PAGE_ATTENTION时, S2 = block_table.dim1 * block_size + if (kLayout_ == QliV2DataLayout::PA_BBND) { + return GetS2SizeForPageAttention(); + } + return GetS2SizeForBatchContinuous(); +} + +ge::graphStatus QLIV2VaInfoParser::ValidateInputShapesMatch() { + /* + TND: + query [T,N1,D], + key [BlockNum,BlockSize,N2,D], + weight [T,N1], + block_table [BatchSize, BatchMaxBlockNum], + act_seq_k [BatchSize] + act_seq_q [BatchSize], + out [T,N2,topk] + ---------------------- + BSND: + query [BatchSize,S1,N1,D], + key [BlockNum,BlockSize,N2,D], + weight [BatchSize,S1,N1], + block_table [BatchSize, BatchMaxBlockNum], + act_seq_k [BatchSize] + act_seq_q [BatchSize] 可选 + out [BatchSize,S1,N2,topk] + */ + uint32_t queryWeightsN1Dim = 1; + uint32_t outN2Dim = 1; + + if (qLayout_ == QliV2DataLayout::TND) { + // -----------------------check BatchSize------------------- + // bSize_ 来源于cu_seqlens_q (shape=[B+1], bSize_=B) + OP_CHECK_IF((kLayout_ == QliV2DataLayout::PA_BBND) && + ((opParamInfo_.sequsedK.tensor->GetShapeSize() != bSize_) || + (opParamInfo_.blockTable.tensor != nullptr && + opParamInfo_.blockTable.tensor->GetStorageShape().GetDim( + 0) != bSize_)), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "cu_seqlens_q, seqused_k and block_table", + ShapeToStringForLog( + opParamInfo_.cuSeqLensQ.tensor->GetStorageShape()) + + ", " + + ShapeToStringForLog( + opParamInfo_.sequsedK.tensor->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.blockTable.tensor->GetStorageShape()), + "TND case, the dim 0 of cu_seqlens_q, seqused_k and " + "block_table must be same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (kLayout_ == QliV2DataLayout::TND) && + (opParamInfo_.cuSeqLensK.tensor->GetShapeSize() != bSize_ + 1), + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + opName_, + "cu_seqlens_q and cu_seqlens_k", + std::to_string(opParamInfo_.cuSeqLensQ.tensor->GetStorageShape() + .GetShapeSize()) + + " and " + + std::to_string(opParamInfo_.cuSeqLensK.tensor->GetStorageShape() + .GetShapeSize()), + "TND case, the shape size of cu_seqlens_q and cu_seqlens_k must be " + "same"), + return ge::GRAPH_FAILED); + // -----------------------check T------------------- + uint32_t qTsize = opParamInfo_.query.shape->GetStorageShape().GetDim(0); + OP_CHECK_IF( + (opParamInfo_.weights.shape->GetStorageShape().GetDim(0) != qTsize) || + (opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0) != + qTsize), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q, w and sparse_indices", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + ", " + + ShapeToStringForLog( + opParamInfo_.weights.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.attenOut.shape->GetStorageShape()), + "TND case q, w, sparse_values dim 0 are " + std::to_string(qTsize) + + ", " + + std::to_string( + opParamInfo_.weights.shape->GetStorageShape().GetDim(0)) + + ", " + + std::to_string( + opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + } else { + // -----------------------check BatchSize------------------- + // bSize_ 来源于query + OP_CHECK_IF( + (kLayout_ == QliV2DataLayout::PA_BBND) && + ((opParamInfo_.weights.shape->GetStorageShape().GetDim(0) != + bSize_) || + (opParamInfo_.blockTable.tensor != nullptr && + opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(0) != + bSize_) || + (opParamInfo_.sequsedK.tensor->GetShapeSize() != bSize_) || + (opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0) != + bSize_)), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q, w, seqused_k, block_table and sparse_indices", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + ", " + + ShapeToStringForLog( + opParamInfo_.weights.shape->GetStorageShape()) + + ", " + + ShapeToStringForLog( + opParamInfo_.sequsedK.tensor->GetStorageShape()) + + ", " + + ShapeToStringForLog( + opParamInfo_.blockTable.tensor->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.attenOut.shape->GetStorageShape()), + "BSND case q, w, seqused_k, block_table, sparse_indices dim 0 " + "are " + + std::to_string(bSize_) + ", " + + std::to_string( + opParamInfo_.weights.shape->GetStorageShape().GetDim(0)) + + ", " + + std::to_string( + opParamInfo_.sequsedK.tensor->GetStorageShape().GetDim(0)) + + ", " + + std::to_string(opParamInfo_.blockTable.tensor->GetStorageShape() + .GetDim(0)) + + ", " + + std::to_string( + opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (kLayout_ != QliV2DataLayout::PA_BBND) && + ((opParamInfo_.weights.shape->GetStorageShape().GetDim(0) != + bSize_) || + (opParamInfo_.sequsedK.tensor != nullptr && + opParamInfo_.sequsedK.tensor->GetShapeSize() != bSize_) || + (opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0) != + bSize_)), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q, w, seqused_k and sparse_indices", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + ", " + + ShapeToStringForLog( + opParamInfo_.weights.shape->GetStorageShape()) + + ", " + + ShapeToStringForLog( + opParamInfo_.sequsedK.tensor->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.attenOut.shape->GetStorageShape()), + "BSND case q, w, seqused_k, sparse_indices dim 0 are " + + std::to_string(bSize_) + ", " + + std::to_string( + opParamInfo_.weights.shape->GetStorageShape().GetDim(0)) + + ", " + + std::to_string( + opParamInfo_.sequsedK.tensor->GetStorageShape().GetDim(0)) + + ", " + + std::to_string( + opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (opParamInfo_.sequsedQ.tensor != nullptr) && + (opParamInfo_.sequsedQ.tensor->GetShapeSize() != bSize_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and seqused_q", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.sequsedQ.tensor->GetStorageShape()), + "BSND case q, seqused_q dim 0 are " + std::to_string(bSize_) + + ", " + + std::to_string( + opParamInfo_.sequsedQ.tensor->GetStorageShape().GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + // -----------------------check S1------------------- + OP_CHECK_IF( + (opParamInfo_.weights.shape->GetStorageShape().GetDim(1) != s1Size_) || + (opParamInfo_.attenOut.shape->GetStorageShape().GetDim(1) != + s1Size_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q, w and sparse_indices", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + ", " + + ShapeToStringForLog( + opParamInfo_.weights.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.attenOut.shape->GetStorageShape()), + "BSND case q, w and sparse_indices dim 1 are " + + std::to_string(s1Size_) + ", " + + std::to_string( + opParamInfo_.weights.shape->GetStorageShape().GetDim(1)) + + ", " + + std::to_string( + opParamInfo_.attenOut.shape->GetStorageShape().GetDim(1)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + queryWeightsN1Dim = DIM_IDX_TWO; + outN2Dim = DIM_IDX_TWO; + } + // -----------------------check N1------------------- + OP_CHECK_IF( + (opParamInfo_.weights.shape->GetStorageShape().GetDim( + queryWeightsN1Dim) != n1Size_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and w", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.weights.shape->GetStorageShape()), + "BSND case the head num of q, w are " + std::to_string(n1Size_) + + ", " + + std::to_string(opParamInfo_.weights.shape->GetStorageShape() + .GetDim(queryWeightsN1Dim)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + // -----------------------check D------------------- + OP_CHECK_IF( + ((kLayout_ != QliV2DataLayout::TND && + opParamInfo_.key.shape->GetStorageShape().GetDim(DIM_IDX_THREE) != + headDim_) || + (kLayout_ == QliV2DataLayout::TND && + opParamInfo_.key.shape->GetStorageShape().GetDim(DIM_IDX_TWO) != + headDim_)), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and k", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog(opParamInfo_.key.shape->GetStorageShape()), + "BSND case q, k last dim are " + std::to_string(headDim_) + ", " + + std::to_string(opParamInfo_.key.shape->GetStorageShape().GetDim( + (kLayout_ == QliV2DataLayout::TND) ? DIM_IDX_TWO + : DIM_IDX_THREE)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + // -----------------------check N2------------------- + OP_CHECK_IF( + (opParamInfo_.attenOut.shape->GetStorageShape().GetDim(outN2Dim) != + n2Size_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "k and sparse_indices", + ShapeToStringForLog(opParamInfo_.key.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.attenOut.shape->GetStorageShape()), + "BSND case the head num of k, sparse_indices are " + + std::to_string(n2Size_) + ", " + + std::to_string(opParamInfo_.attenOut.shape->GetStorageShape() + .GetDim(outN2Dim)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + // -----------------------check sparse_count------------------- + OP_CHECK_IF( + (opParamInfo_.attenOut.shape->GetStorageShape().GetDim(outN2Dim + 1) != + *opParamInfo_.sparseCount), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "sparse_count and sparse_indices", + ShapeToStringForLog(opParamInfo_.key.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.attenOut.shape->GetStorageShape()), + "BSND case sparse_count, sparse_indices last dim are " + + std::to_string(*opParamInfo_.sparseCount) + ", " + + std::to_string(opParamInfo_.attenOut.shape->GetStorageShape() + .GetDim(outN2Dim + 1)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + // -----------------------check cmp_residual_k------------------- + if (opParamInfo_.cmpResidualK.tensor != nullptr) { + OP_CHECK_IF( + (opParamInfo_.cmpResidualK.tensor->GetShapeSize() != bSize_), + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "cmp_residual_k", + std::to_string(opParamInfo_.cmpResidualK.tensor->GetShapeSize()), + "The shape size of cmp_residual_k must be equal to batch_size (" + + std::to_string(bSize_) + ")"), + return ge::GRAPH_FAILED); + } + // -----------------------check metadata------------------- + OP_CHECK_IF( + (opParamInfo_.metadata.tensor->GetShapeSize() != METADATA_LIMIT), + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "metadata", + std::to_string(opParamInfo_.metadata.tensor->GetShapeSize()).c_str(), + "The shape size of metadata must be " + + std::to_string(METADATA_LIMIT)), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QLIV2VaInfoParser::CheckScaleShape() { + uint32_t qShapeDim = opParamInfo_.query.shape->GetStorageShape().GetDimNum(); + uint32_t kShapeDim = opParamInfo_.key.shape->GetStorageShape().GetDimNum(); + uint32_t qDequantScaleShapeDim = + opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDimNum(); + uint32_t kDequantScaleShapeDim = + opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDimNum(); + + OP_CHECK_IF(qDequantScaleShapeDim != (qShapeDim - 1), + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + "q_descale", + std::to_string(qDequantScaleShapeDim).c_str(), + std::to_string(qShapeDim - 1).c_str()), + return ge::GRAPH_FAILED); + OP_CHECK_IF(kDequantScaleShapeDim != (kShapeDim - 1), + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + "k_descale", + std::to_string(kDequantScaleShapeDim).c_str(), + std::to_string(kShapeDim - 1).c_str()), + return ge::GRAPH_FAILED); + // check q scale + for (uint32_t i = 0; i < (qShapeDim - 1); i++) { + uint32_t dimValueQueryScale = + opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDim(i); + uint32_t dimValueQuery = + opParamInfo_.query.shape->GetStorageShape().GetDim(i); + OP_CHECK_IF( + dimValueQueryScale != dimValueQuery, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q_descale and q", + ShapeToStringForLog( + opParamInfo_.query_dequant_scale.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.query.shape->GetStorageShape()), + "q_descale's shape[" + std::to_string(i) + "] and q's shape[" + + std::to_string(i) + "] are not the same"), + return ge::GRAPH_FAILED); + } + // check k scale + for (uint32_t i = 0; i < (kShapeDim - 1); i++) { + uint32_t dimValueKeyScale = + opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDim(i); + uint32_t dimValueKey = opParamInfo_.key.shape->GetStorageShape().GetDim(i); + OP_CHECK_IF( + dimValueKeyScale != dimValueKey, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "k_descale and k", + ShapeToStringForLog( + opParamInfo_.key_dequant_scale.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog(opParamInfo_.key.shape->GetStorageShape()), + "k_descale's shape[" + std::to_string(i) + "] and k's shape[" + + std::to_string(i) + "] are not the same"), + return ge::GRAPH_FAILED); + } + + return ge::GRAPH_SUCCESS; +} + +// key非连续校验:通过shape计算expected stride进行校验 +// PA_BBND时,只允许0轴非连续,其余轴必须连续 +// 非PA_BBND时,所有轴都必须连续 +ge::graphStatus QLIV2VaInfoParser::CheckKeyContiguous() const { + bool keyNonContiguous = false; + bool scaleNonContiguous = false; + // A11 PA_BBND: 0轴允许非连续,从1轴开始检查;非PA_BBND: 从0轴开始检查 + // (arch22 kernel 已按 keyStride0/keyDequantScaleStride0 寻址, 紧凑值兜底) + // PA_BBND: axis 0 allows non-contiguous, check starts from axis 1 + // Non-PA_BBND: check starts from axis 0 + size_t checkStartIdx = (kLayout_ == QliV2DataLayout::PA_BBND) ? 1 : 0; + if (!keyStridesVec_.empty() && opParamInfo_.key.shape != nullptr) { + auto& shape = opParamInfo_.key.shape->GetStorageShape(); + std::vector expectedStrides; + if (kLayout_ == QliV2DataLayout::BSND || + kLayout_ == QliV2DataLayout::PA_BBND) { + expectedStrides = {shape.GetDim(1) * shape.GetDim(2) * shape.GetDim(3), + shape.GetDim(2) * shape.GetDim(3), + shape.GetDim(3), + 1}; + } else if (kLayout_ == QliV2DataLayout::TND) { + expectedStrides = {shape.GetDim(1) * shape.GetDim(2), shape.GetDim(2), 1}; + } + for (size_t i = checkStartIdx; i < expectedStrides.size(); ++i) { + if (i < keyStridesVec_.size() && + keyStridesVec_[i] != expectedStrides[i]) { + keyNonContiguous = true; + break; + } + } + } + if (!keyDequantScaleStridesVec_.empty() && + opParamInfo_.key_dequant_scale.shape != nullptr) { + auto& shape = opParamInfo_.key_dequant_scale.shape->GetStorageShape(); + std::vector expectedStrides; + if (kLayout_ == QliV2DataLayout::BSND || + kLayout_ == QliV2DataLayout::PA_BBND) { + expectedStrides = {shape.GetDim(1) * shape.GetDim(2), shape.GetDim(2), 1}; + } else if (kLayout_ == QliV2DataLayout::TND) { + expectedStrides = {shape.GetDim(1), 1}; + } + for (size_t i = checkStartIdx; i < expectedStrides.size(); ++i) { + if (i < keyDequantScaleStridesVec_.size() && + keyDequantScaleStridesVec_[i] != expectedStrides[i]) { + scaleNonContiguous = true; + break; + } + } + } + if (kLayout_ == QliV2DataLayout::PA_BBND) { + if (!keyStridesVec_.empty()) { + OP_CHECK_IF(keyStridesVec_[0] <= 0, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "k", + "When layout_k is PA_BBND, key stride0 must be positive, " + "but got " + + std::to_string(keyStridesVec_[0])), + return ge::GRAPH_FAILED); + } + // A11 校验: 显式属性 stride0 不得小于紧凑值 (0 轴只允许 padding 型非连续) + if (opParamInfo_.keyStride0Attr != nullptr && + *opParamInfo_.keyStride0Attr > 0) { + uint64_t compactKey0 = + static_cast(blockSize_) * n2Size_ * headDim_; + OP_CHECK_IF( + static_cast(*opParamInfo_.keyStride0Attr) < compactKey0, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "key_stride0", + "key_stride0 (" + std::to_string(*opParamInfo_.keyStride0Attr) + + ") is smaller than the compact value (" + + std::to_string(compactKey0) + + "); only 0-axis padding (stride >= compact) is supported"), + return ge::GRAPH_FAILED); + } + if (opParamInfo_.keyDequantScaleStride0Attr != nullptr && + *opParamInfo_.keyDequantScaleStride0Attr > 0) { + uint64_t compactScale0 = static_cast(blockSize_) * n2Size_; + OP_CHECK_IF( + static_cast(*opParamInfo_.keyDequantScaleStride0Attr) < + compactScale0, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "key_dequant_scale_stride0", + "key_dequant_scale_stride0 (" + + std::to_string(*opParamInfo_.keyDequantScaleStride0Attr) + + ") is smaller than the compact value (" + + std::to_string(compactScale0) + ")"), + return ge::GRAPH_FAILED); + } + } + OP_CHECK_IF( + keyNonContiguous || scaleNonContiguous, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "k and k_descale", + "k and k_descale only support non-continuous keying on the 0-axis"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +void QLIV2VaInfoParser::GenerateInfo(QLIV2VaTilingInfo& QLIV2VaInfo) { + QLIV2VaInfo.opName = opName_; + QLIV2VaInfo.platformInfo = platformInfo_; + QLIV2VaInfo.opParamInfo = opParamInfo_; + QLIV2VaInfo.socVersion = socVersion_; + QLIV2VaInfo.npuArch = npuArch_; + + QLIV2VaInfo.bSize = bSize_; + QLIV2VaInfo.n1Size = n1Size_; + QLIV2VaInfo.n2Size = n2Size_; + QLIV2VaInfo.s1Size = s1Size_; + QLIV2VaInfo.s2Size = s2Size_; + QLIV2VaInfo.gSize = gSize_; + + QLIV2VaInfo.inputQType = inputQType_; + QLIV2VaInfo.inputKType = inputKType_; + QLIV2VaInfo.outputType = outputType_; + + QLIV2VaInfo.blockSize = blockSize_; + QLIV2VaInfo.maxBlockNumPerBatch = maxBlockNumPerBatch_; + + QLIV2VaInfo.pageAttentionFlag = (kLayout_ == QliV2DataLayout::PA_BBND); + QLIV2VaInfo.sparseMode = *opParamInfo_.sparseMode; + QLIV2VaInfo.sparseCount = *opParamInfo_.sparseCount; + QLIV2VaInfo.cmpRatio = *opParamInfo_.cmpRatio; + QLIV2VaInfo.returnValue = *opParamInfo_.returnValue; + QLIV2VaInfo.maxSeqlenQ = + (opParamInfo_.maxSeqlenQ != nullptr) ? *opParamInfo_.maxSeqlenQ : -1; + QLIV2VaInfo.candidateMode = + (opParamInfo_.candidateMode != nullptr) + ? static_cast(*opParamInfo_.candidateMode) + : CANDIDATE_MODE_OFF; + QLIV2VaInfo.candidateTopkBlocks = + (opParamInfo_.candidateTopkBlocks != nullptr) + ? static_cast(*opParamInfo_.candidateTopkBlocks) + : CANDIDATE_TOPK_BLOCKS_FIX; + QLIV2VaInfo.candidateBlockSize = + (opParamInfo_.candidateBlockSize != nullptr) + ? static_cast(*opParamInfo_.candidateBlockSize) + : CANDIDATE_BLOCK_SIZE_DEFAULT; + + QLIV2VaInfo.keyStridesVec = keyStridesVec_; + QLIV2VaInfo.keyDequantScaleStridesVec = keyDequantScaleStridesVec_; + if (!keyStridesVec_.empty()) { + QLIV2VaInfo.keyStride0 = static_cast(keyStridesVec_[0]); + } else if (opParamInfo_.keyStride0Attr != nullptr && + *opParamInfo_.keyStride0Attr > 0) { + // A11: aclnn 动态调用下 GetDynamicInputStride 恒空, 由显式属性兜底 (csrc + // 自动取 tensor.stride(0) 传入) + QLIV2VaInfo.keyStride0 = + static_cast(*opParamInfo_.keyStride0Attr); + } else { + QLIV2VaInfo.keyStride0 = 0; // 紧凑存储 + } + if (!keyDequantScaleStridesVec_.empty()) { + QLIV2VaInfo.keyDequantScaleStride0 = + static_cast(keyDequantScaleStridesVec_[0]); + } else if (opParamInfo_.keyDequantScaleStride0Attr != nullptr && + *opParamInfo_.keyDequantScaleStride0Attr > 0) { + QLIV2VaInfo.keyDequantScaleStride0 = + static_cast(*opParamInfo_.keyDequantScaleStride0Attr); + } else { + QLIV2VaInfo.keyDequantScaleStride0 = 0; + } + // A11 校验: 显式/描述的 stride0 不得小于紧凑值 (1 轴起必须连续, 由 + // CheckKeyContiguous 保证; 0 轴 stride < 块紧凑值意味着块内跨块, 不支持) — 见 + // CheckKeyContiguous 内 PA_BBND 段 + + QLIV2VaInfo.inputQLayout = qLayout_; + QLIV2VaInfo.inputKLayout = kLayout_; +} + +ge::graphStatus QLIV2VaInfoParser::ParseAndCheck( + QLIV2VaTilingInfo& QLIV2VaInfo) { + if (ge::GRAPH_SUCCESS != GetOpName() || ge::GRAPH_SUCCESS != GetNpuInfo() || + ge::GRAPH_SUCCESS != GetOpParaInfo() || + ge::GRAPH_SUCCESS != CheckRequiredParaExistence()) { + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != GetAndCheckInOutDataType() || + ge::GRAPH_SUCCESS != GetQueryKeyAndOutLayout() || + ge::GRAPH_SUCCESS != GetAndCheckOptionalInput()) { + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != CheckShapeDim() || + ge::GRAPH_SUCCESS != GetN1Size() || + ge::GRAPH_SUCCESS != GetAndCheckN2Size() || + ge::GRAPH_SUCCESS != GetGSize()) { + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != GetBatchSize() || ge::GRAPH_SUCCESS != GetS1Size() || + ge::GRAPH_SUCCESS != GetHeadDim() || ge::GRAPH_SUCCESS != GetS2Size()) { + return ge::GRAPH_FAILED; + } + if (ge::GRAPH_SUCCESS != ValidateInputShapesMatch() || + ge::GRAPH_SUCCESS != CheckScaleShape() || + ge::GRAPH_SUCCESS != CheckKeyContiguous()) { + return ge::GRAPH_FAILED; + } + + GenerateInfo(QLIV2VaInfo); + + return ge::GRAPH_SUCCESS; +} + +// --------------------------TilingPrepare函数定义------------------------------------- +static ge::graphStatus TilingPrepareForXllmKernelQuantLightningIndexerV2Va( + gert::TilingParseContext* /* context */) { + return ge::GRAPH_SUCCESS; +} + +// --------------------------XllmKernelQuantLightningIndexerV2VaTiling类成员函数定义----------------------- +ge::graphStatus XllmKernelQuantLightningIndexerV2VaTiling::DoTiling( + QLIV2VaTilingInfo* tilingInfo) { + // -------------set blockdim----------------- + auto ascendcPlatform = + platform_ascendc::PlatformAscendC(tilingInfo->platformInfo); + uint32_t aivNum = ascendcPlatform.GetCoreNumAiv(); + uint32_t aicNum = ascendcPlatform.GetCoreNumAic(); + uint32_t blockDim = ascendcPlatform.CalcTschBlockDim(aivNum, aicNum, aivNum); + context_->SetBlockDim(blockDim); + + // -------------set workspacesize----------------- + constexpr uint32_t MM1_RES_ELEM_SIZE = 4; // 4: fp32 + constexpr uint32_t DOUBLE_BUFFER = 2; // 双Buffer + constexpr uint32_t M_BASE_SIZE = 256; // m轴基本块大小 + constexpr uint32_t S2_BASE_SIZE = 2048; // S2轴基本块大小 + constexpr uint32_t V1_RES_ELEM_SIZE = 4; // 4: int32 + constexpr uint32_t V1_RES_ELEM_TYPE = 2; // 保留Index和Value 2种数据 + constexpr uint32_t V1_DECODE_PARAM_ELEM_SIZE = 8; // 8: int64 + constexpr uint32_t V1_DECODE_PARAM_NUM = 16; // Decode参数个数 + constexpr uint32_t V1_DECODE_DATA_NUM = + 2; // Decode每个核需要存储头和尾部两块数据 + constexpr uint32_t S1_BASE_SIZE = 4; // S1轴基本块的大小 + constexpr uint32_t TOPK_MAX_SIZE = 2048; // TopK选取个数 + uint64_t workspaceSize = ascendcPlatform.GetLibApiWorkSpaceSize(); + // 主流程需Workspace大小 + uint32_t mm1ResSize = M_BASE_SIZE * S2_BASE_SIZE; + workspaceSize += mm1ResSize * MM1_RES_ELEM_SIZE * DOUBLE_BUFFER * aicNum; + // Decode流程(LD)需要Workspace大小 + // 临时存储Decode中间结果大小: + // 2(头/尾)*8(s1Base)*2(idx/value)*2048(K)*sizeof(int32)*24=6M + workspaceSize += V1_DECODE_DATA_NUM * S1_BASE_SIZE * V1_RES_ELEM_TYPE * + TOPK_MAX_SIZE * V1_RES_ELEM_SIZE * aicNum; + // 临时存储Decode中间参数信息大小: + // 2(头/尾)*8(s1Base)*16(paramNum)*sizeof(int64_t)*24=48k + workspaceSize += V1_DECODE_DATA_NUM * S1_BASE_SIZE * V1_DECODE_PARAM_NUM * + V1_DECODE_PARAM_ELEM_SIZE * aicNum; + size_t* workSpaces = context_->GetWorkspaceSizes(1); + workSpaces[0] = workspaceSize; + + // -------------set tilingdata----------------- + // candidate (two-level topk) 输入校验: mode=2 时 candidate_topk_index 必须为 + // [B, S1, N2, candBlocks] int32 + if (tilingInfo->candidateMode == CANDIDATE_MODE_CONSUMER) { + OP_CHECK_IF( + tilingInfo->opParamInfo.candidateTopkIndex.desc == nullptr || + tilingInfo->opParamInfo.candidateTopkIndex.desc->GetDataType() != + ge::DT_INT32, + OP_LOGE("XllmKernelQuantLightningIndexerV2Va", + "candidate_topk_index dtype only supports int32."), + return ge::GRAPH_FAILED); + int64_t expectSize = 0; + if (tilingInfo->inputQLayout == QliV2DataLayout::TND) { + // A12 修正: TND 输出布局为 [T, N2, K], T = query.shape[0], 非 B x s1Size + // (会双重计数) + expectSize = + tilingInfo->opParamInfo.query.shape->GetStorageShape().GetDim(0) * + tilingInfo->n2Size * tilingInfo->candidateTopkBlocks; + } else { + expectSize = static_cast(tilingInfo->bSize) * + tilingInfo->s1Size * tilingInfo->n2Size * + tilingInfo->candidateTopkBlocks; + } + int64_t actualSize = + tilingInfo->opParamInfo.candidateTopkIndex.tensor->GetShapeSize(); + OP_CHECK_IF( + actualSize != expectSize, + OP_LOGE("XllmKernelQuantLightningIndexerV2Va", + "candidate_topk_index shape size must be %ld, but got %ld.", + expectSize, + actualSize), + return ge::GRAPH_FAILED); + } + tilingData_.set_bSize(tilingInfo->bSize); + tilingData_.set_s2Size(tilingInfo->s2Size); + tilingData_.set_s1Size(tilingInfo->s1Size); + tilingData_.set_sparseCount(tilingInfo->sparseCount); + tilingData_.set_gSize(tilingInfo->gSize); + tilingData_.set_blockSize(tilingInfo->blockSize); + tilingData_.set_maxBlockNumPerBatch(tilingInfo->maxBlockNumPerBatch); + tilingData_.set_sparseMode(tilingInfo->sparseMode); + tilingData_.set_cmpRatio(tilingInfo->cmpRatio); + tilingData_.set_returnValue(tilingInfo->returnValue); + tilingData_.set_maxSeqlenQ(tilingInfo->maxSeqlenQ); + tilingData_.set_keyStride0(tilingInfo->keyStride0); + tilingData_.set_keyDequantScaleStride0(tilingInfo->keyDequantScaleStride0); + tilingData_.set_quantMode(*tilingInfo->opParamInfo.quantMode); + tilingData_.set_usedCoreNum(blockDim); + // ---- candidate (two-level topk) ---- + tilingData_.set_candidateMode(tilingInfo->candidateMode); + tilingData_.set_candidateTopkBlocks(tilingInfo->candidateTopkBlocks); + tilingData_.set_candidateBlockSize(tilingInfo->candidateBlockSize); + tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), + context_->GetRawTilingData()->GetCapacity()); + context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize()); + + // -------------set tilingkey----------------- + // DT_Q, DT_KV, DT_OUT, PAGE_ATTENTION, FLASH_DECODE, LAYOUT_T, KV_LAYOUT_T + uint32_t inputQType = static_cast(tilingInfo->inputQType); + uint32_t inputKType = static_cast(tilingInfo->inputKType); + uint32_t outputType = static_cast(tilingInfo->outputType); + uint32_t pageAttentionFlag = + static_cast(tilingInfo->pageAttentionFlag); + uint32_t inputQLayout = static_cast(tilingInfo->inputQLayout); + uint32_t inputKLayout = static_cast(tilingInfo->inputKLayout); + uint64_t tilingKey = GET_TPL_TILING_KEY(inputQType, + inputKType, + outputType, + pageAttentionFlag, + inputQLayout, + inputKLayout); + context_->SetTilingKey(tilingKey); + context_->SetScheduleMode(1); + + return ge::GRAPH_SUCCESS; +} + +// --------------------------Tiling函数定义--------------------------- +ge::graphStatus TilingForXllmKernelQuantLightningIndexerV2Va( + gert::TilingContext* context) { + OP_CHECK_IF( + context == nullptr, + OP_LOGE("XllmKernelQuantLightningIndexerV2Va", "Tiling context is null."), + return ge::GRAPH_FAILED); + QLIV2VaTilingInfo QLIV2VaInfo; + QLIV2VaInfoParser QLIV2VaInfoParser(context); + if (QLIV2VaInfoParser.ParseAndCheck(QLIV2VaInfo) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + XllmKernelQuantLightningIndexerV2VaTiling QLIV2VaTiling(context); + return QLIV2VaTiling.DoTiling(&QLIV2VaInfo); +} + +// --------------------------Tiling及函数TilingPrepare函数注册-------- +IMPL_OP_OPTILING(XllmKernelQuantLightningIndexerV2Va) + .Tiling(TilingForXllmKernelQuantLightningIndexerV2Va) + .TilingParse( + TilingPrepareForXllmKernelQuantLightningIndexerV2Va); + +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.h new file mode 100644 index 0000000000..cbd3a08542 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.h @@ -0,0 +1,312 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va_tiling.h + * \brief + */ + +#ifndef QUANT_LIGHTNING_INDEXER_V2_VA_TILING_H +#define QUANT_LIGHTNING_INDEXER_V2_VA_TILING_H + +#include "err/ops_err.h" +#include "exe_graph/runtime/tiling_context.h" +#include "platform/platform_info.h" +#include "register/op_def_registry.h" +#include "register/tilingdata_base.h" +#include "tiling/platform/platform_ascendc.h" +#include "tiling/tiling_api.h" + +namespace optiling { +// ------------------公共定义-------------------------- +struct QliV2TilingRequiredParaInfo { + const gert::CompileTimeTensorDesc* desc; + const gert::StorageShape* shape; +}; + +struct QliV2TilingOptionalParaInfo { + const gert::CompileTimeTensorDesc* desc; + const gert::Tensor* tensor; +}; + +enum class QliV2DataLayout : uint32_t { BSND = 0, TND = 1, PA_BBND = 2 }; + +// ------------------算子原型索引常量定义---------------- +// Inputs Index +constexpr uint32_t QUERY_INDEX = 0; +constexpr uint32_t KEY_INDEX = 1; +constexpr uint32_t WEIGTHS_INDEX = 2; +constexpr uint32_t QUERY_DEQUANT_SCALE_INDEX = 3; +constexpr uint32_t KEY_DEQUANT_SCALE_INDEX = 4; +constexpr uint32_t CU_SEQLENS_Q_INDEX = 5; +constexpr uint32_t CU_SEQLENS_K_INDEX = 6; +constexpr uint32_t SEQUSED_Q_INDEX = 7; +constexpr uint32_t SEQUSED_K_INDEX = 8; +constexpr uint32_t CMP_RESIDUAL_K_INDEX = 9; +constexpr uint32_t BLOCK_TABLE_INDEX = 10; +constexpr uint32_t OUTPUT_IDX_OFFSET_INDEX = 11; +constexpr uint32_t METADATA_INDEX = 12; +constexpr uint32_t CANDIDATE_TOPK_INDEX_INPUT_INDEX = 13; +constexpr uint32_t SPARSE_INDICES_INDEX = 0; +constexpr uint32_t SPARSE_VALUES_INDEX = 1; +constexpr uint32_t CANDIDATE_TOPK_INDEX_OUTPUT_INDEX = 2; +// Attributes Index +constexpr uint32_t ATTR_TOPK_INDEX = 0; +constexpr uint32_t ATTR_QUANT_MODE_INDEX = 1; +constexpr uint32_t ATTR_MAX_SEQLEN_Q_INDEX = 2; +constexpr uint32_t ATTR_QUERY_LAYOUT_INDEX = 3; +constexpr uint32_t ATTR_KEY_LAYOUT_INDEX = 4; +constexpr uint32_t ATTR_MASK_MODE_INDEX = 5; +constexpr uint32_t ATTR_CMP_RATIO_INDEX = 6; +constexpr uint32_t ATTR_RETURN_VALUE_INDEX = 7; +constexpr uint32_t ATTR_CANDIDATE_MODE_INDEX = 8; +constexpr uint32_t ATTR_CANDIDATE_TOPK_BLOCKS_INDEX = 9; +constexpr uint32_t ATTR_CANDIDATE_BLOCK_SIZE_INDEX = 10; +constexpr uint32_t ATTR_KEY_STRIDE0_INDEX = 11; // A11: key 第0维 stride +constexpr uint32_t ATTR_KEY_DEQUANT_SCALE_STRIDE0_INDEX = + 12; // A11: k_scale 第0维 stride + +// Dim Index +constexpr uint32_t DIM_IDX_ZERO = 0; +constexpr uint32_t DIM_IDX_ONE = 1; +constexpr uint32_t DIM_IDX_TWO = 2; +constexpr uint32_t DIM_IDX_THREE = 3; +// Dim Num +constexpr uint32_t DIM_NUM_TWO = 2; +constexpr uint32_t DIM_NUM_THREE = 3; +constexpr uint32_t DIM_NUM_FOUR = 4; +// 入参限制常量 +constexpr uint32_t HEAD_DIM_LIMIT = 128; +constexpr uint32_t SPARSE_LIMIT = 2048; +constexpr uint32_t G_SIZE_LIMIT = 64; +constexpr uint32_t G_SIZE_LIMIT_32 = 32; +constexpr uint32_t BLOCK_SIZE_LIMIT = 1024; +constexpr uint32_t BLOCK_SIZE_FACTOR = 16; +constexpr uint32_t SPARSE_MODE_LOWER = 3; +constexpr uint32_t METADATA_LIMIT = 1024; +constexpr int32_t QUANT_MODE_INT8 = 2; + +// ------------------candidate 两级TopK 常量------------------ +constexpr uint32_t CANDIDATE_MODE_SOURCE = + 1; // is_candidate_source: 输出候选块索引 +constexpr uint32_t CANDIDATE_MODE_CONSUMER = + 2; // use_candidate: 输入候选块索引, 候选内选topk +constexpr uint32_t CANDIDATE_MODE_OFF = 3; // 关闭candidate功能(默认) +constexpr uint32_t CANDIDATE_TOPK_BLOCKS_FIX = + 2048; // 上限2048, 支持(0, 2048]内64的倍数 +constexpr uint32_t CANDIDATE_BLOCK_SIZE_DEFAULT = 8; +constexpr uint32_t CANDIDATE_BLOCK_SIZE_MAX = 64; + +// -----------算子TilingData定义--------------- +BEGIN_TILING_DATA_DEF(QLIV2VaTilingData) +TILING_DATA_FIELD_DEF(uint32_t, bSize) +TILING_DATA_FIELD_DEF(uint32_t, n2Size) +TILING_DATA_FIELD_DEF(uint32_t, gSize) +TILING_DATA_FIELD_DEF(uint32_t, s1Size) +TILING_DATA_FIELD_DEF(uint32_t, s2Size) +TILING_DATA_FIELD_DEF(uint32_t, sparseCount) +TILING_DATA_FIELD_DEF(uint32_t, usedCoreNum) +TILING_DATA_FIELD_DEF(uint32_t, blockSize) +TILING_DATA_FIELD_DEF(uint32_t, maxBlockNumPerBatch) +TILING_DATA_FIELD_DEF(uint32_t, sparseMode) +TILING_DATA_FIELD_DEF(uint32_t, cmpRatio) +TILING_DATA_FIELD_DEF(uint32_t, returnValue) +TILING_DATA_FIELD_DEF(int32_t, maxSeqlenQ) +TILING_DATA_FIELD_DEF(uint32_t, keyStride0) +TILING_DATA_FIELD_DEF(uint32_t, keyDequantScaleStride0) +TILING_DATA_FIELD_DEF(uint32_t, quantMode) +// ---- candidate (two-level topk) ---- +TILING_DATA_FIELD_DEF(uint32_t, candidateMode) +TILING_DATA_FIELD_DEF(uint32_t, candidateTopkBlocks) +TILING_DATA_FIELD_DEF(uint32_t, candidateBlockSize) +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(XllmKernelQuantLightningIndexerV2Va, + QLIV2VaTilingData) + +// -----------算子CompileInfo定义------------------- +struct QLIV2VaCompileInfo {}; + +// -----------算子Tiling入参结构体定义--------------- +struct QLIV2VaParaInfo { + QliV2TilingRequiredParaInfo query = {nullptr, nullptr}; + QliV2TilingRequiredParaInfo key = {nullptr, nullptr}; + QliV2TilingRequiredParaInfo weights = {nullptr, nullptr}; + QliV2TilingRequiredParaInfo query_dequant_scale = {nullptr, nullptr}; + QliV2TilingRequiredParaInfo key_dequant_scale = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo cuSeqLensQ = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo cuSeqLensK = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo sequsedQ = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo sequsedK = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo cmpResidualK = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo blockTable = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo outputIdxOffset = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo metadata = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo candidateTopkIndex = {nullptr, nullptr}; + QliV2TilingRequiredParaInfo attenOut = {nullptr, nullptr}; + QliV2TilingRequiredParaInfo sparseValues = {nullptr, nullptr}; + + const int32_t* quantMode = nullptr; + const int32_t* maxSeqlenQ = nullptr; + const char* layOutQuery = nullptr; + const char* layOutKey = nullptr; + const int32_t* blockSize = nullptr; + const int32_t* sparseMode = nullptr; + const int32_t* sparseCount = nullptr; + const int32_t* cmpRatio = nullptr; + const int32_t* returnValue = nullptr; + const int32_t* candidateMode = nullptr; + const int32_t* candidateTopkBlocks = nullptr; + const int32_t* candidateBlockSize = nullptr; + const int32_t* keyStride0Attr = nullptr; // A11: key 第0维 stride 显式属性 + const int32_t* keyDequantScaleStride0Attr = + nullptr; // A11: k_scale 第0维 stride 显式属性 +}; + +// -----------算子Tiling入参信息类--------------- +class QLIV2VaTilingInfo { + public: + const char* opName = nullptr; + fe::PlatFormInfos* platformInfo = nullptr; + QLIV2VaParaInfo opParamInfo; + // Base Param + platform_ascendc::SocVersion socVersion = + platform_ascendc::SocVersion::ASCEND910B; + NpuArch npuArch = NpuArch::DAV_2201; + uint32_t bSize = 0; + uint32_t n1Size = 0; + uint32_t n2Size = 0; + uint32_t s1Size = 0; + int64_t s2Size = 0; + uint32_t qkHeadDim = 0; + uint32_t gSize = 0; + // PageAttention + bool pageAttentionFlag = false; + int32_t blockSize = 0; + uint32_t maxBlockNumPerBatch = 0; + // Mask + int32_t sparseMode = 0; + // Others Flag + uint32_t sparseCount = 0; + uint32_t cmpRatio = 1; + bool returnValue = false; + uint32_t keyStride0 = 0; + uint32_t keyDequantScaleStride0 = 0; + std::vector keyStridesVec; + std::vector keyDequantScaleStridesVec; + int32_t maxSeqlenQ = -1; + // candidate (two-level topk) + uint32_t candidateMode = CANDIDATE_MODE_OFF; + uint32_t candidateTopkBlocks = CANDIDATE_TOPK_BLOCKS_FIX; + uint32_t candidateBlockSize = CANDIDATE_BLOCK_SIZE_DEFAULT; + // DType + ge::DataType inputQType = ge::DT_FLOAT16; + ge::DataType inputKType = ge::DT_FLOAT16; + ge::DataType outputType = ge::DT_INT32; + // Layout + QliV2DataLayout inputQLayout = QliV2DataLayout::BSND; + QliV2DataLayout inputKLayout = QliV2DataLayout::PA_BBND; +}; + +// -----------算子Tiling入参信息解析及Check类--------------- +class QLIV2VaInfoParser { + public: + explicit QLIV2VaInfoParser(gert::TilingContext* context) + : context_(context) {} + ~QLIV2VaInfoParser() = default; + + ge::graphStatus CheckRequiredInOutExistence() const; + ge::graphStatus CheckRequiredAttrExistence() const; + ge::graphStatus CheckRequiredParaExistence() const; + ge::graphStatus GetActualSeqLenSize( + uint32_t& size, + const gert::Tensor* tensor, + const std::string& actualSeqLenName) const; + ge::graphStatus GetOpName(); + ge::graphStatus GetNpuInfo(); + void GetOptionalInputParaInfo(); + void GetInputParaInfo(); + void GetOutputParaInfo(); + ge::graphStatus GetAttrParaInfo(); + ge::graphStatus CheckAttrParaInfo(); + ge::graphStatus GetOpParaInfo(); + ge::graphStatus ValidateInputShapesMatch(); + ge::graphStatus CheckScaleShape(); + ge::graphStatus GetAndCheckInOutDataType(); + ge::graphStatus GetBatchSize(); + ge::graphStatus GetHeadDim(); + ge::graphStatus GetS1Size(); + ge::graphStatus GetAndCheckOptionalInput(); + ge::graphStatus CheckShapeDim(); + ge::graphStatus GetAndCheckBlockSize(); + ge::graphStatus GetS2SizeForPageAttention(); + ge::graphStatus GetS2SizeForBatchContinuous(); + ge::graphStatus GetS2Size(); + ge::graphStatus GetQueryKeyAndOutLayout(); + ge::graphStatus GetN1Size(); + ge::graphStatus GetAndCheckN2Size(); + ge::graphStatus GetGSize(); + ge::graphStatus GetAttenMaskInfo(); + ge::graphStatus GetActualSeqInfo(); + ge::graphStatus CheckKeyContiguous() const; + void GenerateInfo(QLIV2VaTilingInfo& QLIV2VaInfo); + ge::graphStatus ParseAndCheck(QLIV2VaTilingInfo& QLIV2VaInfo); + + public: + gert::TilingContext* context_ = nullptr; + const char* opName_; + fe::PlatFormInfos* platformInfo_; + QLIV2VaParaInfo opParamInfo_; + + // BaseParams + uint32_t bSize_ = 0; + uint32_t n1Size_ = 0; + uint32_t n2Size_ = 0; + uint32_t gSize_ = 0; + uint32_t s1Size_ = 0; + int64_t s2Size_ = 0; + uint32_t headDim_ = 0; + // Layout + QliV2DataLayout qLayout_ = QliV2DataLayout::BSND; + QliV2DataLayout kLayout_ = QliV2DataLayout::PA_BBND; + // PageAttention + uint32_t maxBlockNumPerBatch_ = 0; + int32_t blockSize_ = 0; + platform_ascendc::SocVersion socVersion_ = + platform_ascendc::SocVersion::ASCEND910B; + NpuArch npuArch_ = NpuArch::DAV_2201; + ge::DataType inputQType_ = ge::DT_FLOAT16; + ge::DataType inputKType_ = ge::DT_FLOAT16; + ge::DataType weightsType_ = ge::DT_FLOAT16; + ge::DataType inputQueryScaleType_ = ge::DT_FLOAT16; + ge::DataType inputKeyScaleType_ = ge::DT_FLOAT16; + ge::DataType blockTableType_ = ge::DT_FLOAT16; + ge::DataType inputKRopeType_ = ge::DT_FLOAT16; + ge::DataType outputType_ = ge::DT_FLOAT16; + ge::DataType valuesOutType_ = ge::DT_BF16; + std::vector keyStridesVec_; + std::vector keyDequantScaleStridesVec_; +}; + +// ---------------算子Tiling类--------------- +class XllmKernelQuantLightningIndexerV2VaTiling { + public: + explicit XllmKernelQuantLightningIndexerV2VaTiling( + gert::TilingContext* context) + : context_(context) {}; + ge::graphStatus DoTiling(QLIV2VaTilingInfo* tilingInfo); + + private: + gert::TilingContext* context_ = nullptr; + QLIV2VaTilingData tilingData_; +}; + +} // namespace optiling +#endif // QUANT_LIGHTNING_INDEXER_V2_VA_TILING_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_common_arch22.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_common_arch22.h new file mode 100644 index 0000000000..07747cae7c --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_common_arch22.h @@ -0,0 +1,180 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va_common_arch22.h + * \brief + */ +#ifndef QUANT_LIGHTNING_INDEXER_V2_VA_COMMON_H +#define QUANT_LIGHTNING_INDEXER_V2_VA_COMMON_H + +namespace QLIV2VaCommon { + +// candidate (two-level topk) 模式, 与 host 侧 tiling.h 定义保持一致 +inline constexpr uint32_t CANDIDATE_MODE_SOURCE = + 1; // is_candidate_source: 输出候选块索引 +inline constexpr uint32_t CANDIDATE_MODE_CONSUMER = + 2; // use_candidate: 输入候选块索引, 候选内选topk +inline constexpr uint32_t CANDIDATE_MODE_OFF = 3; // 关闭candidate功能(默认) + +// 与tiling的layout保持一致 +enum class LI_LAYOUT : uint32_t { BSND = 0, TND = 1, PA_BBND = 2 }; + +template +struct QLIV2VaType { + using queryType = Q_T; + using keyType = K_T; + using outputType = OUT_T; + static constexpr bool pageAttention = PAGE_ATTENTION; + static constexpr LI_LAYOUT layout = Q_LAYOUT_T; + static constexpr LI_LAYOUT keyLayout = K_LAYOUT_T; +}; + +struct RunInfo { + uint32_t loop; + uint32_t bN2Idx; + uint32_t bIdx; + uint32_t n2Idx = 0; + uint32_t gS1Idx; + uint32_t s2Idx; + + uint32_t actS1Size = 1; + uint32_t actS2Size = 1; + uint32_t actS2SizeOrig = 1; + uint32_t actMBaseSize; + uint32_t actualSingleProcessSInnerSize; + uint32_t actualSingleProcessSInnerSizeAlign; + + uint64_t tensorQueryOffset; + uint64_t tensorKeyOffset; + uint64_t tensorKeyScaleOffset; + uint64_t tensorWeightsOffset; + uint64_t indiceOutOffset; + uint64_t candidateOutOffset; + uint64_t outputIdxOffsetCoreOffset; // A15: output_idx_offset 的 batch 级前缀 + // (行 x kHeadNum 布局) + + bool isFirstS2InnerLoop; + bool isLastS2InnerLoop; + bool isValid = false; + bool isNeedLD = false; + uint32_t saveWorkSpaceIdx = 0; +}; + +struct ConstInfo { + // CUBE与VEC核间同步的模式 + static constexpr uint32_t FIA_SYNC_MODE2 = 2; + // BUFFER的字节数 + static constexpr uint32_t BUFFER_SIZE_BYTE_32B = 32; + static constexpr uint32_t BUFFER_SIZE_BYTE_64B = 64; + static constexpr uint32_t BUFFER_SIZE_BYTE_256B = 256; + static constexpr uint32_t BUFFER_SIZE_BYTE_512B = 512; + static constexpr uint32_t BUFFER_SIZE_BYTE_1K = 1024; + static constexpr uint32_t BUFFER_SIZE_BYTE_2K = 2048; + static constexpr uint32_t BUFFER_SIZE_BYTE_4K = 4096; + static constexpr uint32_t BUFFER_SIZE_BYTE_8K = 8192; + static constexpr uint32_t BUFFER_SIZE_BYTE_16K = 16384; + static constexpr uint32_t BUFFER_SIZE_BYTE_32K = 32768; + // 无效索引 + static constexpr int INVALID_IDX = -1; + + // CUBE和VEC的核间同步EventID + uint32_t syncC1V1 = 0U; + uint32_t syncC1V0 = 2U; + uint32_t syncV1C1 = 0U; + uint32_t syncV0C1 = 1U; + + // 基本块大小 + uint32_t mBaseSize = 1ULL; + uint32_t s1BaseSize = 1ULL; + uint32_t s2BaseSize = 1ULL; + + uint64_t batchSize = 0ULL; + uint64_t gSize = 0ULL; + uint64_t qHeadNum = 0ULL; + uint64_t kHeadNum; + uint64_t headDim; + uint64_t sparseCount; // topK选取大小 + uint64_t kSeqSize = 0ULL; // kv最大S长度 + uint64_t qSeqSize = 1ULL; // q最大S长度 + uint32_t kCacheBlockSize = 0; // PA场景的block size + uint32_t maxBlockNumPerBatch = 0; // PA场景的最大单batch block number + uint32_t keyStride0 = + 0; // key 第0维真实 stride (0=非PA/旧调用, 紧凑兜底; A11) + uint32_t keyDequantScaleStride0 = 0; // k_scale 第0维真实 stride (同上) + LI_LAYOUT outputLayout; // 输出的格式 + bool attenMaskFlag = false; + uint32_t cmpRatio = 1; // 压缩率 + + uint32_t actualLenQDims = 0U; // query的actualSeqLength 的维度 + uint32_t actualLenDims = 0U; // KV 的actualSeqLength 的维度 + uint32_t cmpResiduaKLenDims = 0U; // cmpResidualK的维度 + bool isAccumSeqS1 = false; // 是否累加模式 + bool isAccumSeqS2 = false; // 是否累加模式 + + // candidate (two-level topk) + uint32_t candidateMode = 3U; // 1=source 2=consumer 3=off + uint32_t candidateTopkBlocks = 2048U; + uint32_t candidateBlockSize = 8U; + + uint32_t s2Start = 0U; + uint32_t s2End = 0U; + uint32_t bN2Start = 0U; + uint32_t bN2End = 0U; + uint32_t gS1Start = 0U; + uint32_t gS1End = 0U; + uint32_t coreEnable = 0U; +}; + +struct LdSplitCoreInfo { + bool isLdCoreEnable = false; // 当前核是否参与规约任务 + uint32_t saveWorkSpaceIdx = 0U; // 存放LD参数的地址 + uint32_t bn2Idx = 0U; // 归约任务 + uint32_t bIdx = 0U; + uint32_t n2Idx = 0U; + uint32_t mIdx = 0U; + uint32_t workspaceIdx = 0U; // 当前AIV核上规约任务的索引 + uint32_t workspaceNum = 0U; // 当前AIV核上规约任务的S2切分数量 + uint32_t mStart = 0U; + uint32_t mNum = 0U; + uint64_t indiceOutCoreOffset = 0U; // 最终输出索引搬出Topk的初始偏移地址 +}; + +template +__aicore__ inline T1 Align(T1 num, T2 rnd) { + return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd) * (rnd))); +} + +template +__aicore__ inline T1 Min(T1 a, T2 b) { + return (a > b) ? (b) : (a); +} + +template +__aicore__ inline T1 Max(T1 a, T2 b) { + return (a > b) ? (a) : (b); +} + +template +__aicore__ inline T CeilDiv(T num, T rnd) { + return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd))); +} +} // namespace QLIV2VaCommon + +#endif // QUANT_LIGHTNING_INDEXER_V2_VA_COMMON_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_kernel_arch22.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_kernel_arch22.h new file mode 100644 index 0000000000..659a123060 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_kernel_arch22.h @@ -0,0 +1,1008 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va_kernel_arch22.h + * \brief + */ + +#ifndef QUANT_LIGHTNING_INDEXER_V2_VA_KERNEL_H +#define QUANT_LIGHTNING_INDEXER_V2_VA_KERNEL_H + +#include "../quant_lightning_indexer_v2_metadata_va.h" +#include "kernel_operator.h" +#include "kernel_operator_list_tensor_intf.h" +#include "kernel_tiling/kernel_tiling.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" +#include "quant_lightning_indexer_v2_va_common_arch22.h" +#include "quant_lightning_indexer_v2_va_service_cube_arch22.h" +#include "quant_lightning_indexer_v2_va_service_vector_arch22.h" + +namespace QLIV2VaKernel { +using namespace QLIV2VaCommon; +using namespace QLIV2VaServiceVec; +using namespace matmul; +using namespace optiling::detail; +using namespace optiling; +using AscendC::CacheMode; +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +// 由于S2循环前,RunInfo还没有赋值,使用TempLoopInfo临时存放B、N、S1轴相关的信息 +// 同时减少重复计算 +struct TempLoopInfo { + uint32_t bN2Idx = 0; + uint32_t bIdx = 0U; + uint32_t n2Idx = 0U; + uint32_t gS1Idx = 0U; + uint32_t gS1LoopEnd = 0U; // gS1方向循环的结束Idx + uint32_t s2LoopEnd = 0U; // S2方向循环的结束Idx + uint32_t actS1Size = 1ULL; // 当前Batch循环处理的S1轴的实际大小 + uint32_t actS2Size = 0ULL; + uint32_t actS2SizeOrig = 0ULL; + bool curActSeqLenIsZero = false; + bool needDealActS1LessThanS1 = + false; // S1的实际长度小于shape的S1长度时,是否需要清理输出 + bool isNeedLD = false; // 该基本块是否需要LD + uint32_t actMBaseSize = 0U; // m轴(gS1)方向实际大小 + uint32_t mBasicSizeTail = 0U; // gS1方向循环的尾基本块大小 + uint32_t s2BasicSizeTail = 0U; // S2方向循环的尾基本块大小 + uint32_t validS2Len = 0U; +}; + +template +class QLIV2VaPreload { + public: + __aicore__ inline QLIV2VaPreload(){}; + __aicore__ inline void Init(__gm__ uint8_t* query, + __gm__ uint8_t* key, + __gm__ uint8_t* weights, + __gm__ uint8_t* queryScale, + __gm__ uint8_t* keyScale, + __gm__ uint8_t* cuSeqlensQ, + __gm__ uint8_t* cuSeqlensK, + __gm__ uint8_t* sequsedQ, + __gm__ uint8_t* sequsedK, + __gm__ uint8_t* cmpResidualK, + __gm__ uint8_t* blockTable, + __gm__ uint8_t* outputIdxOffset, + __gm__ uint8_t* metadata, + __gm__ uint8_t* candidateTopkIndex, + __gm__ uint8_t* sparseIndices, + __gm__ uint8_t* sparseValues, + __gm__ uint8_t* candidateTopkIndexOut, + __gm__ uint8_t* workspace, + const QLIV2VaTilingData* __restrict tiling, + TPipe* tPipe); + __aicore__ inline void Process(); + + // =================================类型定义区================================= + using Q_T = typename QLIV2VaT::queryType; + using K_T = typename QLIV2VaT::keyType; + using OUT_T = typename QLIV2VaT::outputType; + static constexpr bool PAGE_ATTENTION = QLIV2VaT::pageAttention; + static constexpr LI_LAYOUT Q_LAYOUT_T = QLIV2VaT::layout; + static constexpr LI_LAYOUT K_LAYOUT_T = QLIV2VaT::keyLayout; + + using MM1_OUT_T = float; + + QLIV2VaMatmul matmulService; + QLIV2VaVector vectorService; + + // =================================常量区================================= + static constexpr uint32_t SYNC_C1_V1_FLAG = 4; + static constexpr uint32_t SYNC_V1_C1_FLAG = 5; + + // 参照 v1: s1BaseSize 固定, mBaseSize = s1BaseSize * gSize (支持 gSize=32/64) + static constexpr uint32_t S1_BASE_SIZE = 4; + static constexpr uint32_t S2_BASE_SIZE = 2048; + static constexpr uint32_t HEAD_DIM = 128; + static constexpr uint32_t K_HEAD_NUM = 1; + static constexpr uint32_t GM_ALIGN_BYTES = 512; + static constexpr uint32_t LI_QUANT_PRELOAD_TASK_CACHE_SIZE = 2; + + // for workspace double + static constexpr uint32_t WS_DOUBLE = 2; + static constexpr uint32_t ELE_NUM_PER_BLOCK = 16; + + static constexpr int64_t LD_PREFETCH_LEN = 2; + + protected: + TPipe* pipe = nullptr; + + // offset + uint64_t queryCoreOffset = 0ULL; + uint64_t keyCoreOffset = 0ULL; + uint64_t keyScaleCoreOffset = 0ULL; + uint64_t weightsCoreOffset = 0ULL; + uint64_t indiceOutCoreOffset = 0ULL; + uint64_t candidateOutCoreOffset = 0ULL; + uint64_t outputIdxOffsetCoreOffset = 0ULL; // A15 + uint32_t coreZeroEnable = 1U; + + // ================================Global + // Buffer区================================= + GlobalTensor queryGm; + GlobalTensor keyGm; + GlobalTensor weightsGm; + GlobalTensor metadataGm; + GlobalTensor indiceOutGm; + GlobalTensor candidateTopkIndexInGm; + GlobalTensor candidateTopkIndexOutGm; + GlobalTensor blockTableGm; + GlobalTensor outputIdxOffsetGm; // A15: 每行输出索引偏移 + + GlobalTensor actualSeqLengthsGmQ; + GlobalTensor actualSeqLengthsGm; + GlobalTensor cmpResidualKGm; + + // ================================类成员变量==================================== + // aic、aiv核信息 + uint32_t tmpBlockIdx = 0U; + uint32_t aiCoreIdx = 0U; + + QLIV2VaCommon::ConstInfo constInfo{}; + QLIV2VaCommon::LdSplitCoreInfo ldInfo{}; + TempLoopInfo tempLoopInfo{}; + + // ================================Init + // functions================================== + __aicore__ inline void InitTilingData( + const QLIV2VaTilingData* __restrict tilingData); + __aicore__ inline void InitBuffers(); + __aicore__ inline void InitActualSeqLen(__gm__ uint8_t* cuSeqlensQ, + __gm__ uint8_t* cuSeqlensK, + __gm__ uint8_t* sequsedQ, + __gm__ uint8_t* sequsedK, + __gm__ uint8_t* cmpResidualK); + // ================================Split Core================================ + __aicore__ inline void SplitCore(); + __aicore__ inline uint32_t GetS2BaseBlockNumOnMask(uint32_t s1gIdx, + uint32_t actS1Size, + uint32_t actS2SizeOrig, + uint32_t& validS2Len); + __aicore__ inline uint32_t GetTotalBaseBlockNum(); + // ================================Process + // functions================================ + __aicore__ inline void ProcessMain(); + __aicore__ inline void ProcessBaseBlock( + uint32_t loop, + uint64_t s2LoopIdx, + QLIV2VaCommon::RunInfo runInfo[LI_QUANT_PRELOAD_TASK_CACHE_SIZE]); + __aicore__ inline void ProcessInvalid(); + __aicore__ inline void ProcessDecode(); + // ================================Params + // Calc===================================== + __aicore__ inline void CalcGS1LoopParams(uint32_t bN2Idx); + __aicore__ inline void GetBN2Idx(uint32_t bN2Idx); + __aicore__ inline uint32_t GetActualSeqLen( + uint32_t bIdx, + uint32_t actualLenDims, + bool isAccumSeq, + GlobalTensor& actualSeqLengthsGm, + uint32_t defaultSeqLen); + __aicore__ inline uint32_t GetActualSeqLenKey( + uint32_t bIdx, + uint32_t actualLenDims, + uint32_t cmpResiduaKLenDims, + bool isAccumSeq, + GlobalTensor& actualSeqLengthsGm, + GlobalTensor& cmpResidualKGm, + uint32_t defaultSeqLen, + uint32_t cmpRatio); + __aicore__ inline void GetS1S2ActualSeqLen(uint32_t bIdx, + uint32_t& actS1Size, + uint32_t& actS2Size, + uint32_t& actS2SizeOrig); + __aicore__ inline void CalcS2LoopParams(uint32_t bN2LoopIdx, + uint32_t gS1LoopIdx); + __aicore__ inline void CalcRunInfo(uint32_t loop, + uint32_t s2LoopIdx, + QLIV2VaCommon::RunInfo& runInfo); + __aicore__ inline void DealActSeqLenIsZero(uint32_t bIdx, + uint32_t n2Idx, + uint32_t s1Start); +}; + +template +__aicore__ inline void QLIV2VaPreload::InitTilingData( + const QLIV2VaTilingData* __restrict tilingData) { + constInfo.batchSize = tilingData->bSize; + constInfo.qHeadNum = constInfo.gSize = tilingData->gSize; + constInfo.kSeqSize = tilingData->s2Size; + constInfo.qSeqSize = tilingData->s1Size; + constInfo.attenMaskFlag = (tilingData->sparseMode == 3); + constInfo.kCacheBlockSize = tilingData->blockSize; + constInfo.maxBlockNumPerBatch = tilingData->maxBlockNumPerBatch; + constInfo.keyStride0 = tilingData->keyStride0; // A11: key 0轴非连续 + constInfo.keyDequantScaleStride0 = tilingData->keyDequantScaleStride0; + constInfo.sparseCount = tilingData->sparseCount; + constInfo.cmpRatio = tilingData->cmpRatio; + constInfo.outputLayout = Q_LAYOUT_T; // 输出和输入形状一致 + if constexpr (Q_LAYOUT_T == LI_LAYOUT::TND) { + constInfo.isAccumSeqS1 = true; + } + if constexpr (K_LAYOUT_T == LI_LAYOUT::TND) { + constInfo.isAccumSeqS2 = true; + } + + constInfo.kHeadNum = K_HEAD_NUM; + constInfo.headDim = HEAD_DIM; + + constInfo.s1BaseSize = S1_BASE_SIZE; + constInfo.s2BaseSize = S2_BASE_SIZE; + constInfo.mBaseSize = constInfo.s1BaseSize * constInfo.gSize; + + // candidate (two-level topk) + constInfo.candidateMode = tilingData->candidateMode; + constInfo.candidateTopkBlocks = tilingData->candidateTopkBlocks; + constInfo.candidateBlockSize = tilingData->candidateBlockSize; +} + +template +__aicore__ inline void QLIV2VaPreload::InitBuffers() { + if ASCEND_IS_AIV { + vectorService.InitBuffers(pipe); + } else { + matmulService.InitBuffers(pipe); + } +} + +template +__aicore__ inline void QLIV2VaPreload::InitActualSeqLen( + __gm__ uint8_t* cuSeqlensQ, + __gm__ uint8_t* cuSeqlensK, + __gm__ uint8_t* sequsedQ, + __gm__ uint8_t* sequsedK, + __gm__ uint8_t* cmpResidualK) { + // Q side: cu_seqlens (TND) or seqused (non-TND) + if constexpr (Q_LAYOUT_T == LI_LAYOUT::TND) { + if (cuSeqlensQ != nullptr) { + constInfo.actualLenQDims = constInfo.batchSize + 1; + actualSeqLengthsGmQ.SetGlobalBuffer((__gm__ uint32_t*)cuSeqlensQ, + constInfo.actualLenQDims); + } else { + constInfo.actualLenQDims = 0; + } + } else { + if (sequsedQ != nullptr) { + constInfo.actualLenQDims = constInfo.batchSize; + actualSeqLengthsGmQ.SetGlobalBuffer((__gm__ uint32_t*)sequsedQ, + constInfo.actualLenQDims); + } else { + constInfo.actualLenQDims = 0; + } + } + // K side: cu_seqlens (TND) or seqused (non-TND) + if constexpr (K_LAYOUT_T == LI_LAYOUT::TND) { + if (cuSeqlensK != nullptr) { + constInfo.actualLenDims = constInfo.batchSize + 1; + actualSeqLengthsGm.SetGlobalBuffer((__gm__ uint32_t*)cuSeqlensK, + constInfo.actualLenDims); + } else { + constInfo.actualLenDims = 0; + } + } else { + if (sequsedK != nullptr) { + constInfo.actualLenDims = constInfo.batchSize; + actualSeqLengthsGm.SetGlobalBuffer((__gm__ uint32_t*)sequsedK, + constInfo.actualLenDims); + } else { + constInfo.actualLenDims = 0; + } + } + // cmpResidualK获取 + if (cmpResidualK != nullptr) { + constInfo.cmpResiduaKLenDims = constInfo.batchSize; + cmpResidualKGm.SetGlobalBuffer((__gm__ uint32_t*)cmpResidualK, + constInfo.batchSize); + } else { + constInfo.cmpResiduaKLenDims = 0; + } +} + +template +__aicore__ inline uint32_t QLIV2VaPreload::GetActualSeqLen( + uint32_t bIdx, + uint32_t actualLenDims, + bool isAccumSeq, + GlobalTensor& actualSeqLengthsGm, + uint32_t defaultSeqLen) { + if (actualLenDims == 0) { + return defaultSeqLen; + } else if (isAccumSeq) { + // TND with cu_seqlens: length[i] = cu_seqlens[i+1] - cu_seqlens[i] + return actualSeqLengthsGm.GetValue(bIdx + 1) - + actualSeqLengthsGm.GetValue(bIdx); + } else { + // non-TND with seqused: length[i] = seqused[i] + return actualSeqLengthsGm.GetValue(bIdx); + } +} + +template +__aicore__ inline uint32_t QLIV2VaPreload::GetActualSeqLenKey( + uint32_t bIdx, + uint32_t actualLenDims, + uint32_t cmpResiduaKLenDims, + bool isAccumSeq, + GlobalTensor& actualSeqLengthsGm, + GlobalTensor& cmpResidualKGm, + uint32_t defaultSeqLen, + uint32_t cmpRatio) { + uint32_t cmpResidualK; // 当前bidx对应的cmpResidualK + if (cmpResiduaKLenDims == 0) { + cmpResidualK = 0; + } else { + cmpResidualK = cmpResidualKGm.GetValue(bIdx); + } + if (actualLenDims == 0) { + return defaultSeqLen * cmpRatio + cmpResidualK; + } else if (isAccumSeq) { + // TND with cu_seqlens: length[i] = cu_seqlens[i+1] - cu_seqlens[i] + return (actualSeqLengthsGm.GetValue(bIdx + 1) - + actualSeqLengthsGm.GetValue(bIdx)) * + cmpRatio + + cmpResidualK; + } else { + return (actualSeqLengthsGm.GetValue(bIdx)) * cmpRatio + cmpResidualK; + } +} + +template +__aicore__ inline void QLIV2VaPreload::GetS1S2ActualSeqLen( + uint32_t bIdx, + uint32_t& actS1Size, + uint32_t& actS2Size, + uint32_t& actS2SizeOrig) { + actS1Size = GetActualSeqLen(bIdx, + constInfo.actualLenQDims, + constInfo.isAccumSeqS1, + actualSeqLengthsGmQ, + constInfo.qSeqSize); + actS2SizeOrig = GetActualSeqLenKey(bIdx, + constInfo.actualLenDims, + constInfo.cmpResiduaKLenDims, + constInfo.isAccumSeqS2, + actualSeqLengthsGm, + cmpResidualKGm, + constInfo.kSeqSize, + constInfo.cmpRatio); // 压缩前的actS2Size + actS2Size = actS2SizeOrig / constInfo.cmpRatio; // 真实使用的压缩后S2长度 +} + +template +__aicore__ inline uint32_t QLIV2VaPreload::GetS2BaseBlockNumOnMask( + uint32_t s1gIdx, + uint32_t actS1Size, + uint32_t actS2SizeOrig, + uint32_t& validS2Len) { + if (actS2SizeOrig / constInfo.cmpRatio == 0) { + validS2Len = 0; + return 0; + } + uint32_t s1Offset = constInfo.s1BaseSize * s1gIdx; + int32_t validS2LenBase = + static_cast(actS2SizeOrig) - + static_cast(actS1Size); // 压缩前的validS2LenBase + validS2Len = (static_cast(s1Offset) + validS2LenBase + + static_cast(constInfo.s1BaseSize)) / + static_cast(constInfo.cmpRatio); + validS2Len = + Min(validS2Len, static_cast(actS2SizeOrig) / constInfo.cmpRatio); + validS2Len = Max(validS2Len, 1); + return (validS2Len + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize; +} + +template +__aicore__ inline uint32_t QLIV2VaPreload::GetTotalBaseBlockNum() { + uint32_t totalBlockNum = 0; + uint32_t actS1Size, actS2Size, actS2SizeOrig; + uint32_t s1GBaseNum, s2BaseNum; + uint32_t validS2Len = 0; + for (uint32_t bIdx = 0; bIdx < constInfo.batchSize; bIdx++) { + GetS1S2ActualSeqLen(bIdx, actS1Size, actS2Size, actS2SizeOrig); + s1GBaseNum = CeilDiv(actS1Size, constInfo.s1BaseSize); + if (!constInfo.attenMaskFlag) { + s2BaseNum = CeilDiv(actS2Size, constInfo.s2BaseSize); + totalBlockNum += s1GBaseNum * s2BaseNum * constInfo.kHeadNum; + continue; + } + for (uint32_t s1gIdx = 0; s1gIdx < s1GBaseNum; s1gIdx++) { + s2BaseNum = + GetS2BaseBlockNumOnMask(s1gIdx, actS1Size, actS2SizeOrig, validS2Len); + totalBlockNum += s2BaseNum * constInfo.kHeadNum; + } + } + return totalBlockNum; +} + +// 多核版本,双闭区间。基本原则:计算每个核最少处理的块数, +// 剩余的部分前面的核每个核多处理一块 +template +__aicore__ void inline QLIV2VaPreload::SplitCore() { + constInfo.coreEnable = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, QLI_V2_CORE_ENABLE_INDEX, false)); + if (aiCoreIdx != 0) { + constInfo.bN2Start = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, QLI_V2_BN2_START_INDEX, false)); + constInfo.gS1Start = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, QLI_V2_M_START_INDEX, false)); + constInfo.s2Start = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, QLI_V2_S2_START_INDEX, false)); + } + constInfo.bN2End = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, QLI_V2_BN2_END_INDEX, false)); + constInfo.gS1End = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, QLI_V2_M_END_INDEX, false)); + constInfo.s2End = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, QLI_V2_S2_END_INDEX, false)); + + // 如果0核都没有启动,说明所有核都没启动 + coreZeroEnable = + metadataGm.GetValue(GetAttrAbsIndex(0, QLI_V2_CORE_ENABLE_INDEX, false)); + + // LD 第一个workspace的索引 + uint32_t ldFirstWorkSpaceIndex = GetAttrAbsIndex( + aiCoreIdx, QLI_V2_FIRST_QLD_V2_DATA_WORKSPACE_IDX_INDEX, false); + ldInfo.saveWorkSpaceIdx = metadataGm.GetValue(ldFirstWorkSpaceIndex); + if ASCEND_IS_AIV { + uint32_t vecCoreIdx = tmpBlockIdx; // 此时代表vectoe核数 + uint32_t ldCoreEnableIndex = + GetAttrAbsIndex(vecCoreIdx, QLD_V2_CORE_ENABLE_INDEX, true); + ldInfo.isLdCoreEnable = metadataGm.GetValue(ldCoreEnableIndex); + + if (!ldInfo.isLdCoreEnable) { + return; + } + + // LD 参数信息 + uint32_t ldBn2IdxIndex = + GetAttrAbsIndex(vecCoreIdx, QLD_V2_BN2_IDX_INDEX, true); + uint32_t ldMIdxIndex = + GetAttrAbsIndex(vecCoreIdx, QLD_V2_M_IDX_INDEX, true); + uint32_t ldWorkspaceIdxIndex = + GetAttrAbsIndex(vecCoreIdx, QLD_V2_WORKSPACE_IDX_INDEX, true); + uint32_t ldWorkspaceNumINDEX = + GetAttrAbsIndex(vecCoreIdx, QLD_V2_WORKSPACE_NUM_INDEX, true); + uint32_t ldMstartIndex = + GetAttrAbsIndex(vecCoreIdx, QLD_V2_M_START_INDEX, true); + uint32_t ldMNumIndex = + GetAttrAbsIndex(vecCoreIdx, QLD_V2_M_NUM_INDEX, true); + + ldInfo.bn2Idx = metadataGm.GetValue(ldBn2IdxIndex); + ldInfo.bIdx = ldInfo.bn2Idx / constInfo.kHeadNum; + ldInfo.n2Idx = ldInfo.bn2Idx % constInfo.kHeadNum; + ldInfo.mIdx = metadataGm.GetValue(ldMIdxIndex); + ldInfo.workspaceIdx = metadataGm.GetValue(ldWorkspaceIdxIndex); + ldInfo.workspaceNum = metadataGm.GetValue(ldWorkspaceNumINDEX); + ldInfo.mStart = metadataGm.GetValue(ldMstartIndex); + ldInfo.mNum = metadataGm.GetValue(ldMNumIndex); + uint64_t actualSeqQPrefixSum = 0; + if constexpr (Q_LAYOUT_T == LI_LAYOUT::TND) { + actualSeqQPrefixSum = + (ldInfo.bIdx <= 0) ? 0 : actualSeqLengthsGmQ.GetValue(ldInfo.bIdx); + } else { // BSND + actualSeqQPrefixSum = + (ldInfo.bIdx <= 0) ? 0 : ldInfo.bIdx * constInfo.qSeqSize; + } + // 搬出Topk的初始偏移地址 + ldInfo.indiceOutCoreOffset = + actualSeqQPrefixSum * constInfo.kHeadNum * constInfo.sparseCount + + static_cast(ldInfo.n2Idx) * constInfo.sparseCount + + static_cast(ldInfo.mIdx) * constInfo.s1BaseSize * + constInfo.kHeadNum * constInfo.sparseCount; + } +} + +template +__aicore__ inline void QLIV2VaPreload::DealActSeqLenIsZero( + uint32_t bIdx, + uint32_t n2Idx, + uint32_t s1Start) { + if ASCEND_IS_AIV { + if (constInfo.outputLayout == LI_LAYOUT::TND) { + uint32_t tSize = actualSeqLengthsGmQ.GetValue(constInfo.batchSize); + uint32_t tBase = bIdx == 0 ? 0 : actualSeqLengthsGmQ.GetValue(bIdx); + uint32_t s1Count = tempLoopInfo.actS1Size; + + for (uint32_t s1Idx = s1Start; s1Idx < s1Count; s1Idx++) { + uint64_t indiceOutOffset = (tBase + s1Idx) * constInfo.kHeadNum * + constInfo.sparseCount + // T轴、s1轴偏移 + n2Idx * constInfo.sparseCount; // N2轴偏移 + vectorService.CleanInvalidOutput(indiceOutOffset); + } + } else if (constInfo.outputLayout == LI_LAYOUT::BSND) { + for (uint32_t s1Idx = s1Start; s1Idx < constInfo.qSeqSize; s1Idx++) { + // B,S1,N2,K + uint64_t indiceOutOffset = + static_cast(bIdx) * constInfo.qSeqSize * + constInfo.kHeadNum * constInfo.sparseCount + + static_cast(s1Idx) * constInfo.kHeadNum * + constInfo.sparseCount + // B轴、S1轴偏移 + static_cast(n2Idx) * constInfo.sparseCount; // N2轴偏移 + vectorService.CleanInvalidOutput(indiceOutOffset); + } + } + } +} + +template +__aicore__ inline void QLIV2VaPreload::Init( + __gm__ uint8_t* query, + __gm__ uint8_t* key, + __gm__ uint8_t* weights, + __gm__ uint8_t* queryScale, + __gm__ uint8_t* keyScale, + __gm__ uint8_t* cuSeqlensQ, + __gm__ uint8_t* cuSeqlensK, + __gm__ uint8_t* sequsedQ, + __gm__ uint8_t* sequsedK, + __gm__ uint8_t* cmpResidualK, + __gm__ uint8_t* blockTable, + __gm__ uint8_t* outputIdxOffset, + __gm__ uint8_t* metadata, + __gm__ uint8_t* candidateTopkIndex, + __gm__ uint8_t* sparseIndices, + __gm__ uint8_t* sparseValues, + __gm__ uint8_t* candidateTopkIndexOut, + __gm__ uint8_t* workspace, + const QLIV2VaTilingData* __restrict tiling, + TPipe* tPipe) { + if ASCEND_IS_AIV { + tmpBlockIdx = GetBlockIdx(); // vec:0-47 + aiCoreIdx = tmpBlockIdx / 2; + } else { + tmpBlockIdx = GetBlockIdx(); // cube:0-23 + aiCoreIdx = tmpBlockIdx; + } + + InitTilingData(tiling); + InitActualSeqLen(cuSeqlensQ, cuSeqlensK, sequsedQ, sequsedK, cmpResidualK); + + if (metadata != nullptr) { + metadataGm.SetGlobalBuffer((__gm__ uint32_t*)metadata); + // 计算分核 + SplitCore(); + } + + pipe = tPipe; + // workspace 内存排布 + // |mm1ResGm(存S) + uint64_t offset = 0; + + // mm1开DoubleBuffer + GlobalTensor mm1ResGm; // 存放S + uint64_t singleCoreMm1ResSize = WS_DOUBLE * constInfo.s1BaseSize * + constInfo.s2BaseSize * sizeof(MM1_OUT_T); + mm1ResGm.SetGlobalBuffer( + (__gm__ MM1_OUT_T*)(workspace + aiCoreIdx * singleCoreMm1ResSize)); + offset += GetBlockNum() * singleCoreMm1ResSize; + + GlobalTensor weightWorkspaceGm; // v1阶段处理w*scale后的结果 + uint64_t weightMemSize = + BLOCK_CUBE * constInfo.mBaseSize * WS_DOUBLE * sizeof(half); + weightWorkspaceGm.SetGlobalBuffer( + (__gm__ half*)(workspace + offset + aiCoreIdx * weightMemSize)); + offset += GetBlockNum() * weightMemSize; + + // ld流程需要ws大小: [aicnum, 2, s1BaseSize, topkOut_*2] + // (aic, 8, 2, 2, 2048) + // (aic, s1_cube, 头尾, idx/value, K) + GlobalTensor vec1ResGm; // 存放TopK计算中间结果 + vec1ResGm.SetGlobalBuffer((__gm__ float*)(workspace + offset)); + offset += GetBlockNum() * constInfo.s1BaseSize * WS_DOUBLE * WS_DOUBLE * + BASE_TOPK * sizeof(float); + + GlobalTensor qScaleGm; + GlobalTensor kScaleGm; + if ASCEND_IS_AIV { + vectorService.InitParams(constInfo, ldInfo, tiling); + indiceOutGm.SetGlobalBuffer((__gm__ int32_t*)sparseIndices); + weightsGm.SetGlobalBuffer((__gm__ half*)weights); + qScaleGm.SetGlobalBuffer((__gm__ half*)queryScale); + kScaleGm.SetGlobalBuffer((__gm__ half*)keyScale); + blockTableGm.SetGlobalBuffer((__gm__ int32_t*)blockTable); + if (constInfo.candidateMode == CANDIDATE_MODE_CONSUMER && + candidateTopkIndex != nullptr) { + candidateTopkIndexInGm.SetGlobalBuffer( + (__gm__ int32_t*)candidateTopkIndex); + } + if (constInfo.candidateMode == CANDIDATE_MODE_SOURCE && + candidateTopkIndexOut != nullptr) { + candidateTopkIndexOutGm.SetGlobalBuffer( + (__gm__ int32_t*)candidateTopkIndexOut); + } + if (outputIdxOffset != nullptr) { // A15: 使能 output_idx_offset + outputIdxOffsetGm.SetGlobalBuffer((__gm__ int32_t*)outputIdxOffset); + } + // A15: 有效标志须与 tensor 一并传给 vector (InitParams 已先值拷贝 + // constInfo, 此处再改标志不生效) + bool outputIdxOffsetValid = (outputIdxOffset != nullptr); + vectorService.InitVecInputTensor( + weightsGm, qScaleGm, kScaleGm, indiceOutGm, blockTableGm); + vectorService.InitVecCandidateTensor(candidateTopkIndexInGm, + candidateTopkIndexOutGm, + outputIdxOffsetGm, + outputIdxOffsetValid); + vectorService.InitVecWorkspaceTensor( + weightWorkspaceGm, mm1ResGm, vec1ResGm); + } else { + matmulService.InitParams(constInfo); + queryGm.SetGlobalBuffer((__gm__ Q_T*)query); + if constexpr (PAGE_ATTENTION) { + blockTableGm.SetGlobalBuffer((__gm__ int32_t*)blockTable); + } + keyGm.SetGlobalBuffer((__gm__ K_T*)key); + matmulService.InitMm1GlobalTensor( + blockTableGm, keyGm, queryGm, mm1ResGm, weightWorkspaceGm); + } + InitBuffers(); +} + +template +__aicore__ inline void QLIV2VaPreload::GetBN2Idx(uint32_t bN2Idx) { + tempLoopInfo.bN2Idx = bN2Idx; + tempLoopInfo.bIdx = bN2Idx / constInfo.kHeadNum; + tempLoopInfo.n2Idx = bN2Idx % constInfo.kHeadNum; +} + +template +__aicore__ inline void QLIV2VaPreload::CalcS2LoopParams( + uint32_t bN2LoopIdx, + uint32_t gS1LoopIdx) { + tempLoopInfo.gS1Idx = gS1LoopIdx; + tempLoopInfo.actMBaseSize = constInfo.mBaseSize; + uint32_t remainedGS1Size = tempLoopInfo.actS1Size * constInfo.gSize - + tempLoopInfo.gS1Idx * constInfo.mBaseSize; + if (remainedGS1Size <= constInfo.mBaseSize && remainedGS1Size > 0) { + tempLoopInfo.actMBaseSize = tempLoopInfo.mBasicSizeTail; + } + + bool isEnd = (bN2LoopIdx + 1 == constInfo.bN2End) && + (gS1LoopIdx + 1 == tempLoopInfo.gS1LoopEnd); + uint32_t s2BlockNum; + uint32_t validS2Len = 0; + if (constInfo.attenMaskFlag) { + s2BlockNum = GetS2BaseBlockNumOnMask(gS1LoopIdx, + tempLoopInfo.actS1Size, + tempLoopInfo.actS2SizeOrig, + tempLoopInfo.validS2Len); + } else { + s2BlockNum = (tempLoopInfo.actS2Size + constInfo.s2BaseSize - 1) / + constInfo.s2BaseSize; + tempLoopInfo.validS2Len = tempLoopInfo.actS2Size; + } + tempLoopInfo.s2LoopEnd = + (isEnd && constInfo.s2End != 0) ? constInfo.s2End : s2BlockNum; + if (constInfo.s2Start > 0 || tempLoopInfo.s2LoopEnd < s2BlockNum) { + tempLoopInfo.isNeedLD = true; + } else { + tempLoopInfo.isNeedLD = false; + } + tempLoopInfo.s2BasicSizeTail = tempLoopInfo.validS2Len % constInfo.s2BaseSize; + tempLoopInfo.s2BasicSizeTail = (tempLoopInfo.s2BasicSizeTail == 0) + ? constInfo.s2BaseSize + : tempLoopInfo.s2BasicSizeTail; +} + +template +__aicore__ inline void QLIV2VaPreload::CalcGS1LoopParams( + uint32_t bN2LoopIdx) { + GetBN2Idx(bN2LoopIdx); + GetS1S2ActualSeqLen(tempLoopInfo.bIdx, + tempLoopInfo.actS1Size, + tempLoopInfo.actS2Size, + tempLoopInfo.actS2SizeOrig); + if ((tempLoopInfo.actS2Size == 0) || (tempLoopInfo.actS1Size == 0)) { + tempLoopInfo.curActSeqLenIsZero = true; + return; + } + tempLoopInfo.curActSeqLenIsZero = false; + tempLoopInfo.mBasicSizeTail = + (tempLoopInfo.actS1Size * constInfo.gSize) % constInfo.mBaseSize; + tempLoopInfo.mBasicSizeTail = (tempLoopInfo.mBasicSizeTail == 0) + ? constInfo.mBaseSize + : tempLoopInfo.mBasicSizeTail; + + uint32_t gS1SplitNum = + (tempLoopInfo.actS1Size * constInfo.gSize + constInfo.mBaseSize - 1) / + constInfo.mBaseSize; + tempLoopInfo.gS1LoopEnd = + (bN2LoopIdx + 1 == constInfo.bN2End && constInfo.gS1End != 0) + ? constInfo.gS1End + : gS1SplitNum; + if constexpr (Q_LAYOUT_T == LI_LAYOUT::BSND) { + if (tempLoopInfo.gS1LoopEnd == gS1SplitNum && + constInfo.qSeqSize > tempLoopInfo.actS1Size) { + tempLoopInfo.needDealActS1LessThanS1 = true; + } + } +} + +template +__aicore__ inline void QLIV2VaPreload::CalcRunInfo( + uint32_t loop, + uint32_t s2LoopIdx, + QLIV2VaCommon::RunInfo& runInfo) { + runInfo.loop = loop; + runInfo.bIdx = tempLoopInfo.bIdx; + runInfo.gS1Idx = tempLoopInfo.gS1Idx; + runInfo.s2Idx = s2LoopIdx; + runInfo.bN2Idx = tempLoopInfo.bN2Idx; + runInfo.isValid = s2LoopIdx < tempLoopInfo.s2LoopEnd; + runInfo.isNeedLD = tempLoopInfo.isNeedLD; + if (runInfo.isNeedLD && s2LoopIdx + 1 == tempLoopInfo.s2LoopEnd) { + runInfo.saveWorkSpaceIdx = ldInfo.saveWorkSpaceIdx; + ldInfo.saveWorkSpaceIdx++; + } + + if (!runInfo.isValid) { + return; + } + + runInfo.actS1Size = tempLoopInfo.actS1Size; + runInfo.actS2Size = tempLoopInfo.actS2Size; + runInfo.actS2SizeOrig = tempLoopInfo.actS2SizeOrig; + // 计算实际基本块size + runInfo.actMBaseSize = tempLoopInfo.actMBaseSize; + runInfo.actualSingleProcessSInnerSize = constInfo.s2BaseSize; + uint32_t s2SplitNum = (tempLoopInfo.validS2Len + constInfo.s2BaseSize - 1) / + constInfo.s2BaseSize; + if (runInfo.s2Idx == s2SplitNum - 1) { + runInfo.actualSingleProcessSInnerSize = tempLoopInfo.s2BasicSizeTail; + } + runInfo.actualSingleProcessSInnerSizeAlign = + QLIV2VaCommon::Align((uint32_t)runInfo.actualSingleProcessSInnerSize, + QLIV2VaCommon::ConstInfo::BUFFER_SIZE_BYTE_32B); + + runInfo.isFirstS2InnerLoop = s2LoopIdx == constInfo.s2Start; + runInfo.isLastS2InnerLoop = (s2LoopIdx + 1 == tempLoopInfo.s2LoopEnd); + + if (runInfo.isFirstS2InnerLoop) { + uint64_t actualSeqQPrefixSum; + if constexpr (Q_LAYOUT_T == LI_LAYOUT::TND) { + actualSeqQPrefixSum = + (runInfo.bIdx <= 0) ? 0 : actualSeqLengthsGmQ.GetValue(runInfo.bIdx); + } else { // BSND + actualSeqQPrefixSum = + (runInfo.bIdx <= 0) ? 0 : runInfo.bIdx * constInfo.qSeqSize; + } + uint64_t tndBIdxOffset = + actualSeqQPrefixSum * constInfo.qHeadNum * constInfo.headDim; + // B,S1,N1(N2,G),D + queryCoreOffset = tndBIdxOffset + + runInfo.gS1Idx * constInfo.mBaseSize * constInfo.headDim; + // B,S1,N1(N2,G)/T,N1(N2,G) + weightsCoreOffset = actualSeqQPrefixSum * constInfo.qHeadNum + + runInfo.n2Idx * constInfo.gSize; + // B,S1,N2,k/T,N2,k + indiceOutCoreOffset = + actualSeqQPrefixSum * constInfo.kHeadNum * constInfo.sparseCount + + runInfo.n2Idx * constInfo.sparseCount; + candidateOutCoreOffset = actualSeqQPrefixSum * constInfo.kHeadNum * + constInfo.candidateTopkBlocks + + runInfo.n2Idx * constInfo.candidateTopkBlocks; + // A15: output_idx_offset 布局 [行, N2] (每行每 key 头一个 int32), batch + // 级前缀 + outputIdxOffsetCoreOffset = + actualSeqQPrefixSum * constInfo.kHeadNum + runInfo.n2Idx; + } + uint64_t actualSeqKPrefixSum; + if constexpr (K_LAYOUT_T == LI_LAYOUT::TND) { // T N2 D, cu_seqlens_k + actualSeqKPrefixSum = + (runInfo.bIdx <= 0) ? 0 : actualSeqLengthsGm.GetValue(runInfo.bIdx); + } else { + actualSeqKPrefixSum = + (runInfo.bIdx <= 0) ? 0 : runInfo.bIdx * constInfo.kSeqSize; + } + uint64_t tndBIdxOffsetForK = + actualSeqKPrefixSum * constInfo.kHeadNum * constInfo.headDim; + keyCoreOffset = tndBIdxOffsetForK + runInfo.s2Idx * constInfo.s2BaseSize * + constInfo.kHeadNum * + constInfo.headDim; + keyScaleCoreOffset = + (actualSeqKPrefixSum + runInfo.s2Idx * constInfo.s2BaseSize) * + constInfo.kHeadNum; + runInfo.tensorQueryOffset = queryCoreOffset; + runInfo.tensorKeyOffset = keyCoreOffset; + runInfo.tensorKeyScaleOffset = keyScaleCoreOffset; + runInfo.tensorWeightsOffset = weightsCoreOffset; + runInfo.indiceOutOffset = indiceOutCoreOffset; + runInfo.candidateOutOffset = candidateOutCoreOffset; + runInfo.outputIdxOffsetCoreOffset = outputIdxOffsetCoreOffset; +} + +template +__aicore__ inline void QLIV2VaPreload::Process() { + // 没有计算任务,直接清理输出 + if (coreZeroEnable == 0) { + ProcessInvalid(); + return; + } + ProcessMain(); + + ProcessDecode(); +} + +template +__aicore__ inline void QLIV2VaPreload::ProcessInvalid() { + if ASCEND_IS_AIV { + uint32_t aivCoreNum = GetBlockNum() * 2; // 2 means c:v = 1:2 + uint64_t totalOutputSize = constInfo.batchSize * constInfo.qSeqSize * + constInfo.kHeadNum * constInfo.sparseCount; + uint64_t singleCoreSize = + QLIV2VaCommon::Align((totalOutputSize + aivCoreNum - 1) / aivCoreNum, + GM_ALIGN_BYTES / sizeof(OUT_T)); + uint64_t baseSize = tmpBlockIdx * singleCoreSize; + if (baseSize < totalOutputSize) { + uint64_t dealSize = (baseSize + singleCoreSize <= totalOutputSize) + ? singleCoreSize + : totalOutputSize - baseSize; + GlobalTensor output = indiceOutGm[baseSize]; + AscendC::InitGlobalMemory(output, dealSize, constInfo.INVALID_IDX); + } + } +} + +template +__aicore__ inline void QLIV2VaPreload::ProcessMain() { + // 无任务核直接返回 + if (constInfo.coreEnable == 0) { + return; + } + + if ASCEND_IS_AIV { + vectorService.AllocEventID(); + CrossCoreSetFlag( + constInfo.syncV1C1); + CrossCoreSetFlag( + constInfo.syncV1C1); + } else { + matmulService.AllocEventID(); + CrossCoreSetFlag( + constInfo.syncC1V0); + CrossCoreSetFlag( + constInfo.syncC1V0); + } + + QLIV2VaCommon::RunInfo runInfo[LI_QUANT_PRELOAD_TASK_CACHE_SIZE]; + + // 适配左闭右开 + if (constInfo.bN2Start == constInfo.bN2End) { + if (constInfo.gS1Start != constInfo.gS1End || + constInfo.s2Start != constInfo.s2End) { + constInfo.bN2End += 1; + if (constInfo.s2End != 0) { + constInfo.gS1End += 1; + } + } + } else if ((constInfo.gS1End != 0) || (constInfo.s2End != 0)) { + constInfo.bN2End += 1; + if (constInfo.s2End != 0) { + constInfo.gS1End += 1; + } + } + + uint32_t gloop = 0; + for (uint32_t bN2LoopIdx = constInfo.bN2Start; bN2LoopIdx < constInfo.bN2End; + bN2LoopIdx++) { + CalcGS1LoopParams(bN2LoopIdx); + if (tempLoopInfo.curActSeqLenIsZero) { + DealActSeqLenIsZero(tempLoopInfo.bIdx, tempLoopInfo.n2Idx, 0U); + + if ASCEND_IS_AIV { + if (bN2LoopIdx + 1 == constInfo.bN2End && gloop > 0) { + CrossCoreWaitFlag(constInfo.syncC1V1); + vectorService.ProcessVec1( + runInfo[1 - gloop % LI_QUANT_PRELOAD_TASK_CACHE_SIZE]); + CrossCoreSetFlag( + constInfo.syncV1C1); // 反向同步 1 + } + } + continue; + } + for (uint32_t gS1LoopIdx = constInfo.gS1Start; + gS1LoopIdx < tempLoopInfo.gS1LoopEnd; + gS1LoopIdx++) { + CalcS2LoopParams(bN2LoopIdx, gS1LoopIdx); + bool isEnd = (bN2LoopIdx + 1 == constInfo.bN2End) && + (gS1LoopIdx + 1 == tempLoopInfo.gS1LoopEnd); + uint32_t extraLoop = + isEnd ? LI_QUANT_PRELOAD_TASK_CACHE_SIZE - 1 : 0; // 只preload一轮 + + for (uint32_t s2LoopIdx = constInfo.s2Start; + s2LoopIdx < (tempLoopInfo.s2LoopEnd + extraLoop); + s2LoopIdx++) { + ProcessBaseBlock(gloop, s2LoopIdx, runInfo); + ++gloop; + } + constInfo.s2Start = 0; + } + if (tempLoopInfo.needDealActS1LessThanS1) { + DealActSeqLenIsZero( + tempLoopInfo.bIdx, tempLoopInfo.n2Idx, tempLoopInfo.actS1Size); + } + constInfo.gS1Start = 0; + } + + if ASCEND_IS_AIV { + vectorService.FreeEventID(); + CrossCoreWaitFlag(constInfo.syncC1V0); + CrossCoreWaitFlag(constInfo.syncC1V0); + } else { + matmulService.FreeEventID(); + CrossCoreWaitFlag(constInfo.syncV1C1); + CrossCoreWaitFlag(constInfo.syncV1C1); + } +} + +template +__aicore__ inline void QLIV2VaPreload::ProcessBaseBlock( + uint32_t loop, + uint64_t s2LoopIdx, + QLIV2VaCommon::RunInfo runInfo[LI_QUANT_PRELOAD_TASK_CACHE_SIZE]) { + int32_t curTaskId = loop % LI_QUANT_PRELOAD_TASK_CACHE_SIZE; + QLIV2VaCommon::RunInfo& curRunInfo = runInfo[curTaskId]; + QLIV2VaCommon::RunInfo& lastRunInfo = runInfo[1 - curTaskId]; + + CalcRunInfo(loop, s2LoopIdx, curRunInfo); + + if (curRunInfo.isValid) { + if ASCEND_IS_AIC { + if (curRunInfo.isFirstS2InnerLoop) { + CrossCoreWaitFlag(constInfo.syncV0C1); + } + CrossCoreWaitFlag(constInfo.syncV1C1); // 反向同步 1 + matmulService.ComputeMm1(curRunInfo); + CrossCoreSetFlag( + constInfo.syncC1V1); + if (curRunInfo.isLastS2InnerLoop) { + // 反向同步 0 + CrossCoreSetFlag( + constInfo.syncC1V0); + } + } else { + if (curRunInfo.isFirstS2InnerLoop) { + CrossCoreWaitFlag(constInfo.syncC1V0); // 反向同步 0 + vectorService.ProcessVec0(curRunInfo); + CrossCoreSetFlag( + constInfo.syncV0C1); + } + } + } + + if (lastRunInfo.isValid) { + if ASCEND_IS_AIV { + CrossCoreWaitFlag(constInfo.syncC1V1); + vectorService.ProcessVec1(lastRunInfo); + CrossCoreSetFlag( + constInfo.syncV1C1); // 反向同步 1 + } + lastRunInfo.isValid = false; + } +} + +template +__aicore__ inline void QLIV2VaPreload::ProcessDecode() { + if ASCEND_IS_AIV { + vectorService.InitLDBuffers(pipe); + ICachePreLoad(LD_PREFETCH_LEN); + SyncAll(); + if (ldInfo.isLdCoreEnable) { + vectorService.ProcessLD(); + } + } +} + +} // namespace QLIV2VaKernel +#endif // QUANT_LIGHTNING_INDEXER_V2_VA_KERNEL_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_cube_arch22.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_cube_arch22.h new file mode 100644 index 0000000000..6022c93eb1 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_cube_arch22.h @@ -0,0 +1,753 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va_service_cube_arch22.h + * \brief use 5 buffer for matmul l1, better pipeline + */ +#ifndef QUANT_LIGHTNING_INDEXER_V2_VA_SERVICE_CUBE_H +#define QUANT_LIGHTNING_INDEXER_V2_VA_SERVICE_CUBE_H + +#include "kernel_operator.h" +#include "kernel_operator_list_tensor_intf.h" +#include "kernel_tiling/kernel_tiling.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" +#include "quant_lightning_indexer_v2_va_common_arch22.h" + +namespace QLIV2VaKernel { +using namespace AscendC; +using namespace QLIV2VaCommon; +struct MmInfo { + int64_t s2L0LoopId; + int64_t s1gL0LoopId; + int64_t s2L0RealSize; + int64_t s2GmOffset; +}; + +template +class QLIV2VaMatmul { + public: + using Q_T = typename QLIV2VaT::queryType; + using K_T = typename QLIV2VaT::keyType; + + __aicore__ inline QLIV2VaMatmul(){}; + __aicore__ inline void InitBuffers(TPipe* pipe); + __aicore__ inline void InitMm1GlobalTensor( + const GlobalTensor& blkTableGm, + const GlobalTensor& keyGm, + const GlobalTensor& queryGm, + const GlobalTensor& mm1ResGm, + const GlobalTensor& weightWorkspaceGm); + __aicore__ inline void InitParams(const ConstInfo& constInfo); + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + __aicore__ inline void ComputeMm1(const QLIV2VaCommon::RunInfo& runInfo); + + static constexpr IsResetLoad3dConfig LOAD3DV2_CONFIG = { + true, + true}; // isSetFMatrix isSetPadding; + static constexpr uint64_t DOUBLE_BUF_NUM = 2; + static constexpr uint64_t L0AB_BUF_NUM = 4; + + static constexpr uint32_t KEY_MTE1_MTE2_EVENT = EVENT_ID2; + static constexpr uint32_t QW_MTE1_MTE2_EVENT = + EVENT_ID5; // KEY_MTE1_MTE2_EVENT + DOUBLE_BUF_NUM; + static constexpr uint32_t M_MTE1_EVENT = EVENT_ID3; + static constexpr uint32_t M_FIX_EVENT = EVENT_ID0; + static constexpr uint32_t FIX_M_EVENT = EVENT_ID2; + static constexpr uint32_t FIX_MTE1_EVENT = EVENT_ID4; + + static constexpr uint64_t S8_BLOCK_CUBE = 32; + + static constexpr uint32_t MTE2_MTE1_EVENT = EVENT_ID2; + static constexpr uint32_t MTE1_M_EVENT = EVENT_ID2; + + static constexpr uint64_t D_BASIC_BLOCK = 128; + static constexpr uint64_t S1G_BASIC_BLOCK_L1 = 256; + + static constexpr uint64_t S1G_BASIC_BLOCK_L0 = 128; + static constexpr uint64_t S2_BASIC_BLOCK_L0 = 128; + + static constexpr uint64_t QUERY_BUFFER_OFFSET = + S1G_BASIC_BLOCK_L1 * D_BASIC_BLOCK; + static constexpr uint64_t SL1_BUFFER_OFFSET = + S1G_BASIC_BLOCK_L0 * S2_BASIC_BLOCK_L0; + static constexpr uint64_t KEY_BUFFER_OFFSET = + S2_BASIC_BLOCK_L0 * D_BASIC_BLOCK; + static constexpr uint64_t WEIGHT_BUFFER_OFFSET = + S1G_BASIC_BLOCK_L1 * BLOCK_CUBE; + static constexpr uint64_t L0AB_BUFFER_OFFSET_S8_16K = 16 * 1024; + static constexpr uint64_t L0AB_BUFFER_OFFSET_FP16_16K = 16 * 512; + static constexpr uint64_t L0C_BUFFER_OFFSET = 64 * 256; + + private: + __aicore__ inline void WeightDmaCopy(uint64_t s1gL1RealSize, + const QLIV2VaCommon::RunInfo& runInfo); + __aicore__ inline void LoadKeyToL0b(uint64_t s2L0RealSize); + __aicore__ inline void LoadQueryToL0a(uint64_t s1gL1Offset, + uint64_t s1gL1RealSize, + uint64_t s1gL0RealSize); + __aicore__ inline void QueryNd2Nz(uint64_t s1gL1RealSize, + const QLIV2VaCommon::RunInfo& runInfo); + __aicore__ inline void KeyNd2NzForPA(uint64_t s2L1RealSize, + uint64_t s2GmOffset, + const QLIV2VaCommon::RunInfo& runInfo); + __aicore__ inline void KeyNd2Nz(uint64_t s2L1RealSize, + const MmInfo& mmInfo, + const QLIV2VaCommon::RunInfo& runInfo); + __aicore__ inline void FixpSToL1(uint64_t s1gL0RealSize, + uint64_t s2L0RealSize); + __aicore__ inline void LoadSToL0b(uint64_t s1gL1RealSize, + uint64_t s2L0RealSize, + uint64_t sL1BufIdx, + int64_t mStartPt); + __aicore__ inline void LoadWeightToL0a(uint64_t s1gL1Offset); + __aicore__ inline void ComputeWs(uint64_t s1gL0RealSize, + uint64_t s2L0RealSize, + int64_t s1gOffset); + __aicore__ inline void FixpResToGm(uint64_t s1L0RealCount, + uint64_t s2L0RealSize, + uint64_t s1GmOffset, + uint64_t s2GmOffset, + const QLIV2VaCommon::RunInfo& runInfo); + __aicore__ inline void ComputeQk(uint64_t s1gL0RealSize, + uint64_t s2L0RealSize); + __aicore__ inline void ProcessWs(uint64_t s1gL0RealSize, + uint64_t s1gL1Offset, + uint64_t sL1BufIdx, + const MmInfo& mmInfo, + const QLIV2VaCommon::RunInfo& runInfo); + __aicore__ inline void ProcessQk(uint64_t s1gL0RealSize, + uint64_t s1gL1Offset, + uint64_t s1L0LoopCnt, + const MmInfo& mmInfo, + const QLIV2VaCommon::RunInfo& runInfo); + __aicore__ inline void CalcMmInfo(MmInfo& mmInfo, + uint64_t loopIdx, + uint64_t s1L0LoopCnt, + const MmInfo& lastMmInfo, + const QLIV2VaCommon::RunInfo& runInfo); + static constexpr LI_LAYOUT Q_LAYOUT_T = QLIV2VaT::layout; + static constexpr LI_LAYOUT K_LAYOUT_T = QLIV2VaT::keyLayout; + GlobalTensor blkTableGm_; + GlobalTensor keyGm_; + GlobalTensor queryGm_; + GlobalTensor weightGm_; + GlobalTensor mm1ResGm_; + + TBuf bufQL1_; + LocalTensor queryL1_; + TBuf bufKeyL1_; + LocalTensor keyL1_; + TBuf bufWeightL1_; + LocalTensor weightL1_; + TBuf bufSL1_; + LocalTensor sL1_; + + TBuf bufL0A_; + LocalTensor l0a_; + TBuf bufL0B_; + LocalTensor l0b_; + + TBuf bufL0C_; + LocalTensor cL0_; + + uint64_t keyL1BufIdx_ = 0; + uint64_t qwL1Mte2BufIdx_ = 0; + uint64_t sL1BufIdx_ = 0; + uint64_t l0BufIdx_ = 0; + uint64_t l0cBufIdx_ = 0; + + ConstInfo constInfo_; +}; + +template +__aicore__ inline void QLIV2VaMatmul::InitParams( + const ConstInfo& constInfo) { + constInfo_ = constInfo; +} + +template +__aicore__ inline void QLIV2VaMatmul::InitBuffers(TPipe* pipe) { + pipe->InitBuffer( + bufQL1_, + DOUBLE_BUF_NUM * S1G_BASIC_BLOCK_L1 * D_BASIC_BLOCK * sizeof(Q_T)); + queryL1_ = bufQL1_.Get(); + pipe->InitBuffer( + bufKeyL1_, + DOUBLE_BUF_NUM * S2_BASIC_BLOCK_L0 * D_BASIC_BLOCK * sizeof(K_T)); + keyL1_ = bufKeyL1_.Get(); + + pipe->InitBuffer( + bufWeightL1_, + DOUBLE_BUF_NUM * S1G_BASIC_BLOCK_L1 * BLOCK_CUBE * sizeof(half)); + weightL1_ = bufWeightL1_.Get(); + pipe->InitBuffer( + bufSL1_, + DOUBLE_BUF_NUM * S2_BASIC_BLOCK_L0 * S1G_BASIC_BLOCK_L0 * sizeof(half)); + sL1_ = bufSL1_.Get(); + + pipe->InitBuffer(bufL0A_, 64 * 1024); + l0a_ = bufL0A_.Get(); + pipe->InitBuffer(bufL0B_, 64 * 1024); + l0b_ = bufL0B_.Get(); + + pipe->InitBuffer(bufL0C_, 128 * 1024); + cL0_ = bufL0C_.Get(); +} + +template +__aicore__ inline void QLIV2VaMatmul::InitMm1GlobalTensor( + const GlobalTensor& blkTableGm, + const GlobalTensor& keyGm, + const GlobalTensor& queryGm, + const GlobalTensor& mm1ResGm, + const GlobalTensor& weightWorkspaceGm) { + blkTableGm_ = blkTableGm; + keyGm_ = keyGm; + queryGm_ = queryGm; + mm1ResGm_ = mm1ResGm; + weightGm_ = weightWorkspaceGm; +} + +template +__aicore__ inline void QLIV2VaMatmul::ProcessWs( + uint64_t s1gL0RealSize, + uint64_t s1gL1Offset, + uint64_t sL1BufIdx, + const MmInfo& mmInfo, + const QLIV2VaCommon::RunInfo& runInfo) { + WaitFlag(FIX_M_EVENT + l0cBufIdx_ % DOUBLE_BUF_NUM); + for (int64_t s1gOffset = 0; s1gOffset < s1gL0RealSize; + s1gOffset += constInfo_.gSize) { + WaitFlag(M_MTE1_EVENT + l0BufIdx_ % L0AB_BUF_NUM); + LoadSToL0b(s1gL0RealSize, mmInfo.s2L0RealSize, sL1BufIdx, s1gOffset); + LoadWeightToL0a(s1gOffset + s1gL1Offset); + + ComputeWs(s1gL0RealSize, mmInfo.s2L0RealSize, s1gOffset); + + SetFlag(M_MTE1_EVENT + l0BufIdx_ % L0AB_BUF_NUM); + l0BufIdx_++; + } + + FixpResToGm(s1gL0RealSize / constInfo_.gSize, + mmInfo.s2L0RealSize, + s1gL1Offset / constInfo_.gSize, + mmInfo.s2L0LoopId * S2_BASIC_BLOCK_L0, + runInfo); + SetFlag(FIX_M_EVENT + l0cBufIdx_ % DOUBLE_BUF_NUM); + l0cBufIdx_++; +} + +template +__aicore__ inline void QLIV2VaMatmul::ProcessQk( + uint64_t s1gL0RealSize, + uint64_t s1gL1Offset, + uint64_t s1L0LoopCnt, + const MmInfo& mmInfo, + const QLIV2VaCommon::RunInfo& runInfo) { + if (mmInfo.s1gL0LoopId == 0) { + WaitFlag(KEY_MTE1_MTE2_EVENT + + keyL1BufIdx_ % DOUBLE_BUF_NUM); + if constexpr (K_LAYOUT_T == LI_LAYOUT::PA_BBND) { + KeyNd2NzForPA(mmInfo.s2L0RealSize, + runInfo.s2Idx * constInfo_.s2BaseSize + mmInfo.s2GmOffset, + runInfo); + } else { + KeyNd2Nz(mmInfo.s2L0RealSize, mmInfo, runInfo); + } + + SetFlag(MTE2_MTE1_EVENT); + WaitFlag(MTE2_MTE1_EVENT); + } + + WaitFlag(M_MTE1_EVENT + l0BufIdx_ % L0AB_BUF_NUM); + LoadQueryToL0a(s1gL1Offset, runInfo.actMBaseSize, s1gL0RealSize); + LoadKeyToL0b(mmInfo.s2L0RealSize); + + if (mmInfo.s1gL0LoopId + 1 >= s1L0LoopCnt) { + SetFlag(KEY_MTE1_MTE2_EVENT + + keyL1BufIdx_ % DOUBLE_BUF_NUM); + keyL1BufIdx_++; + } + + WaitFlag(FIX_M_EVENT + l0cBufIdx_ % DOUBLE_BUF_NUM); + ComputeQk(s1gL0RealSize, mmInfo.s2L0RealSize); + SetFlag(M_MTE1_EVENT + l0BufIdx_ % L0AB_BUF_NUM); + + FixpSToL1(s1gL0RealSize, mmInfo.s2L0RealSize); + SetFlag(FIX_M_EVENT + l0cBufIdx_ % DOUBLE_BUF_NUM); + l0BufIdx_++; + l0cBufIdx_++; +} + +template +__aicore__ inline void QLIV2VaMatmul::CalcMmInfo( + MmInfo& mmInfo, + uint64_t loopIdx, + uint64_t s1L0LoopCnt, + const MmInfo& lastMmInfo, + const QLIV2VaCommon::RunInfo& runInfo) { + mmInfo.s2L0LoopId = loopIdx / s1L0LoopCnt; + mmInfo.s1gL0LoopId = loopIdx % s1L0LoopCnt; + + if (mmInfo.s1gL0LoopId == 0) { + mmInfo.s2GmOffset = mmInfo.s2L0LoopId * S2_BASIC_BLOCK_L0; + mmInfo.s2L0RealSize = + mmInfo.s2GmOffset + S2_BASIC_BLOCK_L0 > + runInfo.actualSingleProcessSInnerSize + ? runInfo.actualSingleProcessSInnerSize - mmInfo.s2GmOffset + : S2_BASIC_BLOCK_L0; + } else { + mmInfo.s2L0RealSize = lastMmInfo.s2L0RealSize; + } +} + +template +__aicore__ inline void QLIV2VaMatmul::ComputeMm1( + const QLIV2VaCommon::RunInfo& runInfo) { + if (runInfo.isFirstS2InnerLoop) { + WaitFlag(QW_MTE1_MTE2_EVENT + + qwL1Mte2BufIdx_ % DOUBLE_BUF_NUM); + QueryNd2Nz(runInfo.actMBaseSize, runInfo); // 256 * 128 // L1BasicBlock + WeightDmaCopy(runInfo.actMBaseSize, runInfo); + } + int64_t loopIdx = 0; + int64_t s2L0LoopCnt = CeilDiv(runInfo.actualSingleProcessSInnerSize, + S2_BASIC_BLOCK_L0); // 2048取128 + int64_t s1L0LoopCnt = + CeilDiv(runInfo.actMBaseSize, S1G_BASIC_BLOCK_L0); // 256取128 + int64_t s1gL1Offset[2] = {0, static_cast(S1G_BASIC_BLOCK_L0)}; + int64_t s1gL0RealSize[2] = {s1L0LoopCnt > 1 + ? static_cast(S1G_BASIC_BLOCK_L0) + : runInfo.actMBaseSize, + runInfo.actMBaseSize - s1gL1Offset[1]}; + MmInfo mmInfo[2]; + CalcMmInfo(mmInfo[loopIdx & 1], + loopIdx, + s1L0LoopCnt, + mmInfo[(loopIdx + 1) & 1], + runInfo); + + ProcessQk(s1gL0RealSize[mmInfo[loopIdx & 1].s1gL0LoopId % s1L0LoopCnt], + s1gL1Offset[mmInfo[loopIdx & 1].s1gL0LoopId % s1L0LoopCnt], + s1L0LoopCnt, + mmInfo[loopIdx & 1], + runInfo); + + SetFlag(FIX_MTE1_EVENT + sL1BufIdx_ % DOUBLE_BUF_NUM); + sL1BufIdx_++; + loopIdx++; + + while (loopIdx < s2L0LoopCnt * s1L0LoopCnt) { + CalcMmInfo(mmInfo[loopIdx & 1], + loopIdx, + s1L0LoopCnt, + mmInfo[(loopIdx + 1) & 1], + runInfo); + + ProcessQk(s1gL0RealSize[mmInfo[loopIdx & 1].s1gL0LoopId % s1L0LoopCnt], + s1gL1Offset[mmInfo[loopIdx & 1].s1gL0LoopId % s1L0LoopCnt], + s1L0LoopCnt, + mmInfo[loopIdx & 1], + runInfo); + + SetFlag(FIX_MTE1_EVENT + sL1BufIdx_ % DOUBLE_BUF_NUM); + sL1BufIdx_++; + + WaitFlag(FIX_MTE1_EVENT + sL1BufIdx_ % DOUBLE_BUF_NUM); + + ProcessWs( + s1gL0RealSize[mmInfo[(loopIdx + 1) & 1].s1gL0LoopId % s1L0LoopCnt], + s1gL1Offset[mmInfo[(loopIdx + 1) & 1].s1gL0LoopId % s1L0LoopCnt], + sL1BufIdx_, + mmInfo[(loopIdx + 1) & 1], + runInfo); + loopIdx++; + } + + WaitFlag(FIX_MTE1_EVENT + + (sL1BufIdx_ + 1) % DOUBLE_BUF_NUM); + + ProcessWs(s1gL0RealSize[mmInfo[(loopIdx + 1) & 1].s1gL0LoopId % s1L0LoopCnt], + s1gL1Offset[mmInfo[(loopIdx + 1) & 1].s1gL0LoopId % s1L0LoopCnt], + sL1BufIdx_ - 1, + mmInfo[(loopIdx + 1) & 1], + runInfo); + + if (runInfo.isLastS2InnerLoop) { + SetFlag(QW_MTE1_MTE2_EVENT + + qwL1Mte2BufIdx_ % DOUBLE_BUF_NUM); + qwL1Mte2BufIdx_++; + } +} + +// blkNum, blkSize, N2, D +template +__aicore__ inline void QLIV2VaMatmul::KeyNd2NzForPA( + uint64_t s2L1RealSize, + uint64_t s2GmOffset, + const QLIV2VaCommon::RunInfo& runInfo) { + uint64_t s2L1Offset = 0; + // A11: key 0 轴非连续寻址 — 块基址 = 表值 x keyStride0 (host 下发的真实 + // stride)。 keyStride0 == 0 (旧调用/非 PA 紧凑) 时兜底原紧凑公式, 现网行为 + // bit 级不变 (R8) + uint64_t blkStride = constInfo_.keyStride0 != 0 + ? static_cast(constInfo_.keyStride0) + : static_cast(constInfo_.kCacheBlockSize) * + constInfo_.kHeadNum * constInfo_.headDim; + while (s2L1Offset < s2L1RealSize) { + uint64_t s2BlkId = (s2L1Offset + s2GmOffset) / constInfo_.kCacheBlockSize; + uint64_t s2BlkOffset = + (s2L1Offset + s2GmOffset) % constInfo_.kCacheBlockSize; + uint64_t keyGmOffset = + blkTableGm_.GetValue(runInfo.bIdx * constInfo_.maxBlockNumPerBatch + + s2BlkId) * + blkStride + + s2BlkOffset * constInfo_.headDim; + uint64_t s2Mte2Size = s2L1RealSize - s2L1Offset; + s2Mte2Size = s2BlkOffset + s2Mte2Size >= constInfo_.kCacheBlockSize + ? constInfo_.kCacheBlockSize - s2BlkOffset + : s2Mte2Size; + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = s2Mte2Size; // 行数 + nd2nzPara.dValue = constInfo_.headDim; + nd2nzPara.srcDValue = constInfo_.headDim; + nd2nzPara.dstNzC0Stride = + CeilAlign(s2L1RealSize, (uint64_t)BLOCK_CUBE); // 对齐到16 单位block + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(keyL1_[(keyL1BufIdx_ % DOUBLE_BUF_NUM) * KEY_BUFFER_OFFSET + + s2L1Offset * S8_BLOCK_CUBE], + keyGm_[keyGmOffset], + nd2nzPara); + + s2L1Offset += s2Mte2Size; + } +} + +template +__aicore__ inline void QLIV2VaMatmul::KeyNd2Nz( + uint64_t s2L1RealSize, + const MmInfo& mmInfo, + const QLIV2VaCommon::RunInfo& runInfo) { + uint64_t dStride = constInfo_.headDim; + if constexpr (K_LAYOUT_T == LI_LAYOUT::BSND || K_LAYOUT_T == LI_LAYOUT::TND) { + dStride = constInfo_.headDim * constInfo_.kHeadNum; // constInfo_.kHeadNum + } + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = s2L1RealSize; // 行数 + nd2nzPara.dValue = constInfo_.headDim; + nd2nzPara.srcDValue = dStride; + nd2nzPara.dstNzC0Stride = + CeilAlign(s2L1RealSize, (uint64_t)BLOCK_CUBE); // 对齐到16 单位block + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + // 默认一块buf最多放两份 + DataCopy( + keyL1_[(keyL1BufIdx_ % DOUBLE_BUF_NUM) * KEY_BUFFER_OFFSET], + keyGm_[runInfo.tensorKeyOffset + mmInfo.s2GmOffset * constInfo_.headDim], + nd2nzPara); +} + +// batch, s1, g, 1 +template +__aicore__ inline void QLIV2VaMatmul::WeightDmaCopy( + uint64_t s1gL1RealSize, + const QLIV2VaCommon::RunInfo& runInfo) { + DataCopyParams copyInParams; + copyInParams.blockCount = 1; + copyInParams.blockLen = s1gL1RealSize; + copyInParams.srcStride = 0; + copyInParams.dstStride = 0; + DataCopy(weightL1_[(qwL1Mte2BufIdx_ % DOUBLE_BUF_NUM) * WEIGHT_BUFFER_OFFSET], + weightGm_[runInfo.loop % DOUBLE_BUF_NUM * BLOCK_CUBE * + constInfo_.mBaseSize], + copyInParams); +} + +// batch, s1, n2, g, d +template +__aicore__ inline void QLIV2VaMatmul::QueryNd2Nz( + uint64_t s1gL1RealSize, + const QLIV2VaCommon::RunInfo& runInfo) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = s1gL1RealSize; // 行数 + nd2nzPara.dValue = constInfo_.headDim; + nd2nzPara.srcDValue = constInfo_.headDim; + nd2nzPara.dstNzC0Stride = + CeilAlign(s1gL1RealSize, (uint64_t)BLOCK_CUBE); // 对齐到16 单位block + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + // 默认一块buf最多放两份 + DataCopy(queryL1_[(qwL1Mte2BufIdx_ % DOUBLE_BUF_NUM) * QUERY_BUFFER_OFFSET], + queryGm_[runInfo.tensorQueryOffset], + nd2nzPara); +} + +// s1g, d +template +__aicore__ inline void QLIV2VaMatmul::LoadQueryToL0a( + uint64_t s1gL1Offset, + uint64_t s1gL1RealSize, + uint64_t s1gL0RealSize) { + LoadData3DParamsV2 loadData3DParams; + // SetFmatrixParams + loadData3DParams.l1H = CeilDiv(s1gL1RealSize, BLOCK_CUBE); // Hin=M1=8 + loadData3DParams.l1W = BLOCK_CUBE; // Win=M0 + loadData3DParams.channelSize = constInfo_.headDim; // Cin=K + + loadData3DParams.padList[0] = 0; + loadData3DParams.padList[1] = 0; + loadData3DParams.padList[2] = 0; + loadData3DParams.padList[3] = 255; // 尾部数据不影响滑窗的结果 + + // SetLoadToA0Params + loadData3DParams.mExtension = + CeilAlign(s1gL0RealSize, BLOCK_CUBE); // M height维度目的 + loadData3DParams.kExtension = constInfo_.headDim; // K width维度目的 + loadData3DParams.mStartPt = s1gL1Offset; + loadData3DParams.kStartPt = 0; + loadData3DParams.strideW = 1; + loadData3DParams.strideH = 1; + loadData3DParams.filterW = 1; + loadData3DParams.filterSizeW = (1 >> 8) & 255; + loadData3DParams.filterH = 1; + loadData3DParams.filterSizeH = (1 >> 8) & 255; + loadData3DParams.dilationFilterW = 1; + loadData3DParams.dilationFilterH = 1; + loadData3DParams.enTranspose = 0; + loadData3DParams.fMatrixCtrl = 0; + + LoadData( + l0a_[(l0BufIdx_ % L0AB_BUF_NUM) * L0AB_BUFFER_OFFSET_S8_16K], + queryL1_[(qwL1Mte2BufIdx_ % DOUBLE_BUF_NUM) * QUERY_BUFFER_OFFSET], + loadData3DParams); +} + +// s1, g, s2 --> 2 * 64* 128 +template +__aicore__ inline void QLIV2VaMatmul::LoadSToL0b( + uint64_t s1gL1RealSize, + uint64_t s2L0RealSize, + uint64_t sL1BufIdx, + int64_t mStartPt) { + LoadData3DParamsV2 loadData3DParams; + // SetFmatrixParams + loadData3DParams.l1H = S1G_BASIC_BLOCK_L0 / BLOCK_CUBE; // Hin=M1=8 + loadData3DParams.l1W = BLOCK_CUBE; // Win=M0 + loadData3DParams.channelSize = CeilAlign(s2L0RealSize, BLOCK_CUBE); // Cin=K + + loadData3DParams.padList[0] = 0; + loadData3DParams.padList[1] = 0; + loadData3DParams.padList[2] = 0; + loadData3DParams.padList[3] = 255; // 尾部数据不影响滑窗的结果 + + // SetLoadToA0Params + loadData3DParams.mExtension = constInfo_.gSize; // M height维度目的 + loadData3DParams.kExtension = + CeilAlign(s2L0RealSize, BLOCK_CUBE); // K width维度目的 + loadData3DParams.kStartPt = 0; + loadData3DParams.strideW = 1; + loadData3DParams.strideH = 1; + loadData3DParams.filterW = 1; + loadData3DParams.filterSizeW = (1 >> 8) & 255; + loadData3DParams.filterH = 1; + loadData3DParams.filterSizeH = (1 >> 8) & 255; + loadData3DParams.dilationFilterW = 1; + loadData3DParams.dilationFilterH = 1; + loadData3DParams.enTranspose = 1; + loadData3DParams.fMatrixCtrl = 0; + + loadData3DParams.mStartPt = mStartPt; + LoadData( + l0b_.template ReinterpretCast()[(l0BufIdx_ % L0AB_BUF_NUM) * + L0AB_BUFFER_OFFSET_FP16_16K], + sL1_[(sL1BufIdx % DOUBLE_BUF_NUM) * SL1_BUFFER_OFFSET], + loadData3DParams); +} + +// s1,g,1(16), 2,64,16 +template +__aicore__ inline void QLIV2VaMatmul::LoadWeightToL0a( + uint64_t s1gL1Offset) { + LoadData2DParams loadData2DParams; + loadData2DParams.startIndex = 0; + loadData2DParams.repeatTimes = CeilDiv(constInfo_.gSize, BLOCK_CUBE); + loadData2DParams.srcStride = 1; + loadData2DParams.dstGap = 0; + loadData2DParams.ifTranspose = true; + LoadData(l0a_.template ReinterpretCast()[(l0BufIdx_ % L0AB_BUF_NUM) * + L0AB_BUFFER_OFFSET_FP16_16K], + weightL1_[(qwL1Mte2BufIdx_ % DOUBLE_BUF_NUM) * WEIGHT_BUFFER_OFFSET + + s1gL1Offset * BLOCK_CUBE], + loadData2DParams); +} + +// s2, d -> 128,128 +template +__aicore__ inline void QLIV2VaMatmul::LoadKeyToL0b( + uint64_t s2L0RealSize) { + LoadData2DParams loadData2DParams; + loadData2DParams.startIndex = 0; + loadData2DParams.repeatTimes = CeilDiv(s2L0RealSize, BLOCK_CUBE) * + CeilDiv(constInfo_.headDim, S8_BLOCK_CUBE); + loadData2DParams.srcStride = 1; + loadData2DParams.dstGap = 0; + loadData2DParams.ifTranspose = false; + LoadData(l0b_[(l0BufIdx_ % L0AB_BUF_NUM) * L0AB_BUFFER_OFFSET_S8_16K], + keyL1_[(keyL1BufIdx_ % DOUBLE_BUF_NUM) * KEY_BUFFER_OFFSET], + loadData2DParams); +} + +// A: s1,g,1(16) B: s1,g,s2 C: s1, 1(16), s2 +template +__aicore__ inline void QLIV2VaMatmul::ComputeWs( + uint64_t s1gL0RealSize, + uint64_t s2L0RealSize, + int64_t s1gOffset) { + SetFlag(MTE1_M_EVENT); + WaitFlag(MTE1_M_EVENT); + MmadParams mmadParams; + mmadParams.m = BLOCK_CUBE; + mmadParams.n = s2L0RealSize; + mmadParams.k = constInfo_.gSize; + mmadParams.cmatrixInitVal = true; + mmadParams.cmatrixSource = false; + Mmad(cL0_.template ReinterpretCast()[(l0cBufIdx_ % DOUBLE_BUF_NUM) * + L0C_BUFFER_OFFSET + + s1gOffset * S2_BASIC_BLOCK_L0], + l0a_.template ReinterpretCast()[(l0BufIdx_ % L0AB_BUF_NUM) * + L0AB_BUFFER_OFFSET_FP16_16K], + l0b_.template ReinterpretCast()[(l0BufIdx_ % L0AB_BUF_NUM) * + L0AB_BUFFER_OFFSET_FP16_16K], + mmadParams); +} + +template +__aicore__ inline void QLIV2VaMatmul::ComputeQk( + uint64_t s1gL0RealSize, + uint64_t s2L0RealSize) { + SetFlag(MTE1_M_EVENT); + WaitFlag(MTE1_M_EVENT); + + MmadParams mmadParams; + mmadParams.m = CeilAlign(s1gL0RealSize, BLOCK_CUBE); + mmadParams.n = s2L0RealSize; + mmadParams.k = constInfo_.headDim; + mmadParams.cmatrixInitVal = true; + mmadParams.cmatrixSource = false; + Mmad(cL0_[(l0cBufIdx_ % DOUBLE_BUF_NUM) * L0C_BUFFER_OFFSET], + l0a_[(l0BufIdx_ % L0AB_BUF_NUM) * L0AB_BUFFER_OFFSET_S8_16K], + l0b_[(l0BufIdx_ % L0AB_BUF_NUM) * L0AB_BUFFER_OFFSET_S8_16K], + mmadParams); + if ((mmadParams.m / 16) * (mmadParams.n / 16) < 10) { + PipeBarrier(); + } +} + +template +__aicore__ inline void QLIV2VaMatmul::FixpSToL1( + uint64_t s1gL0RealSize, + uint64_t s2L0RealSize) { + SetFlag(M_FIX_EVENT); + WaitFlag(M_FIX_EVENT); + DataCopyCO12DstParams params; + params.mSize = CeilAlign(s1gL0RealSize, BLOCK_CUBE); + params.nSize = CeilAlign(s2L0RealSize, BLOCK_CUBE); + params.dstStride = S1G_BASIC_BLOCK_L0; + params.srcStride = params.mSize; + params.quantPre = QuantMode_t::DEQF16; + params.reluPre = 1; + params.channelSplit = 0; + params.nz2ndEn = 0; + SetFixpipePreQuantFlag(0x3a800000); + DataCopy(sL1_[(sL1BufIdx_ % DOUBLE_BUF_NUM) * SL1_BUFFER_OFFSET], + cL0_[(l0cBufIdx_ % DOUBLE_BUF_NUM) * L0C_BUFFER_OFFSET], + params); +} + +template +__aicore__ inline void QLIV2VaMatmul::FixpResToGm( + uint64_t s1L0RealCount, + uint64_t s2L0RealSize, + uint64_t s1GmOffset, + uint64_t s2GmOffset, + const QLIV2VaCommon::RunInfo& runInfo) { + SetFlag(M_FIX_EVENT); + WaitFlag(M_FIX_EVENT); + + AscendC::DataCopyCO12DstParams intriParams; + intriParams.mSize = 1; + intriParams.nSize = s2L0RealSize; + intriParams.dstStride = constInfo_.s2BaseSize; + intriParams.srcStride = 16; + // set mode according to dtype + intriParams.quantPre = QuantMode_t::NoQuant; + intriParams.nz2ndEn = true; + intriParams.reluPre = 0; + AscendC::SetFixpipeNz2ndFlag( + s1L0RealCount, + CeilDiv(constInfo_.gSize, BLOCK_CUBE) * S2_BASIC_BLOCK_L0 / BLOCK_CUBE, + 2048); + AscendC::DataCopy( + mm1ResGm_[(runInfo.loop % 2) * constInfo_.mBaseSize / constInfo_.gSize * + constInfo_.s2BaseSize + + s1GmOffset * intriParams.dstStride + s2GmOffset], + cL0_.template ReinterpretCast()[(l0cBufIdx_ % DOUBLE_BUF_NUM) * + L0C_BUFFER_OFFSET], + intriParams); +} + +template +__aicore__ inline void QLIV2VaMatmul::AllocEventID() { + SetFlag(KEY_MTE1_MTE2_EVENT + 0); + SetFlag(KEY_MTE1_MTE2_EVENT + 1); + SetFlag(KEY_MTE1_MTE2_EVENT + 2); + + SetFlag(QW_MTE1_MTE2_EVENT + 0); + SetFlag(QW_MTE1_MTE2_EVENT + 1); + + SetFlag(M_MTE1_EVENT + 0); + SetFlag(M_MTE1_EVENT + 1); + SetFlag(M_MTE1_EVENT + 2); + SetFlag(M_MTE1_EVENT + 3); + + SetFlag(FIX_M_EVENT + 0); + SetFlag(FIX_M_EVENT + 1); +} + +template +__aicore__ inline void QLIV2VaMatmul::FreeEventID() { + WaitFlag(KEY_MTE1_MTE2_EVENT + 0); + WaitFlag(KEY_MTE1_MTE2_EVENT + 1); + WaitFlag(KEY_MTE1_MTE2_EVENT + 2); + + WaitFlag(QW_MTE1_MTE2_EVENT + 0); + WaitFlag(QW_MTE1_MTE2_EVENT + 1); + + WaitFlag(M_MTE1_EVENT + 0); + WaitFlag(M_MTE1_EVENT + 1); + WaitFlag(M_MTE1_EVENT + 2); + WaitFlag(M_MTE1_EVENT + 3); + + WaitFlag(FIX_M_EVENT + 0); + WaitFlag(FIX_M_EVENT + 1); +} +} // namespace QLIV2VaKernel +#endif // QUANT_LIGHTNING_INDEXER_V2_VA_SERVICE_CUBE_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_vector_arch22.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_vector_arch22.h new file mode 100644 index 0000000000..7db88dc204 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_vector_arch22.h @@ -0,0 +1,1370 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va_service_vector_arch22.h + * \brief + */ +#ifndef QUANT_LIGHTNING_INDEXER_V2_VA_SERVICE_VECTOR_H +#define QUANT_LIGHTNING_INDEXER_V2_VA_SERVICE_VECTOR_H + +#include "kernel_operator.h" +#include "kernel_operator_list_tensor_intf.h" +#include "kernel_tiling/kernel_tiling.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" +#include "quant_lightning_indexer_v2_va_common_arch22.h" +#include "quant_lightning_indexer_v2_va_vector.h" + +namespace QLIV2VaKernel { +using namespace QLIV2VaCommon; +using namespace QLIV2VaServiceVec; +constexpr uint32_t BASE_TOPK = 2048; +constexpr uint32_t BASE_TOPK_VALUE_IDX_SIZE = 4096; +constexpr uint32_t ELE_NUM_32 = 32; +constexpr uint32_t ELE_NUM_128 = 128; +constexpr uint32_t ELE_NUM_512 = 512; + +template +class QLIV2VaVector { + public: + // =================================类型定义区================================= + static constexpr LI_LAYOUT Q_LAYOUT_T = QLIV2VaT::layout; + static constexpr LI_LAYOUT K_LAYOUT_T = QLIV2VaT::keyLayout; + static constexpr bool PAGE_ATTENTION = QLIV2VaT::pageAttention; + // MM输出数据类型, 当前只支持float + using MM1_OUT_T = float; + + __aicore__ inline QLIV2VaVector(){}; + __aicore__ inline void ProcessVec0(const QLIV2VaCommon::RunInfo& info); + __aicore__ inline void ProcessVec1(const QLIV2VaCommon::RunInfo& info); + __aicore__ inline void InitBuffers(TPipe* pipe); + __aicore__ inline void InitParams( + const struct QLIV2VaCommon::ConstInfo& constInfo, + const struct QLIV2VaCommon::LdSplitCoreInfo& ldInfo, + const QLIV2VaTilingData* __restrict tilingData); + __aicore__ inline void ProcessLD(); + __aicore__ inline void InitVecWorkspaceTensor( + GlobalTensor vec0OutGm, + GlobalTensor mm1ResGm, + GlobalTensor vec1ResGm); + __aicore__ inline void InitVecCandidateTensor( + GlobalTensor candidateTopkIndexInGm, + GlobalTensor candidateTopkIndexOutGm, + GlobalTensor outputIdxOffsetGm, + bool outputIdxOffsetValid); + __aicore__ inline void InitVecInputTensor(GlobalTensor weightsGm, + GlobalTensor qScaleGm, + GlobalTensor kScaleGm, + GlobalTensor indiceOutGm, + GlobalTensor blockTableGm); + __aicore__ inline void CleanInvalidOutput(int64_t invalidS1offset); + __aicore__ inline int32_t AlignS2(int32_t cuS2Len); + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + __aicore__ inline void InitLDBuffers(TPipe* pipe); + + protected: + GlobalTensor mm1ResGm; + GlobalTensor vec1ResGm; + GlobalTensor weightsGm; + GlobalTensor qScaleGm; + GlobalTensor kScaleGm; + GlobalTensor vec0OutGm; + GlobalTensor indiceOutGm; + GlobalTensor candidateTopkIndexInGm; + GlobalTensor candidateTopkIndexOutGm; + GlobalTensor blockTableGm; + // =================================常量区================================= + + private: + __aicore__ inline void GetKeyScale(const QLIV2VaCommon::RunInfo& runInfo, + const LocalTensor& resUb, + int64_t batchId, + int64_t startS2, + int64_t getLen); + // candidate (two-level topk) + __aicore__ inline int32_t CountGE(const LocalTensor& sortedDesc, + int32_t n, + float x); + __aicore__ inline void BuildCandidateMask(const QLIV2VaCommon::RunInfo& info, + int32_t cuS1Idx, + int32_t cuBaseS2Idx, + int32_t innerS1Idx); + __aicore__ inline void ProcessCandBlockTopk( + const QLIV2VaCommon::RunInfo& info, + int32_t cuS1Idx, + int32_t cuS2Len, + int32_t cuS2LenVecAlign, + int32_t cuRealAcSeq, + int32_t innerS1Idx); + __aicore__ inline void CopyOutCandTopkIndex( + const QLIV2VaCommon::RunInfo& info, + int32_t cuS1Idx, + int32_t innerS1Idx); + // candidate 新增向量 op 的 64 元素分块封装 (本版本 Level-2 count > 64 的 vmax + // 等指令会触发 aicore 异常) + __aicore__ inline void VecMaxPair(const LocalTensor& dst, + const LocalTensor& src0, + const LocalTensor& src1, + int32_t n); + __aicore__ inline void VecMinPair(const LocalTensor& dst, + const LocalTensor& src0, + const LocalTensor& src1, + int32_t n); + __aicore__ inline void VecAbs(const LocalTensor& dst, + const LocalTensor& src, + int32_t n); + __aicore__ inline void VecMinsScalar(const LocalTensor& dst, + const LocalTensor& src, + float v, + int32_t n); + __aicore__ inline void VecMaxsScalar(const LocalTensor& dst, + const LocalTensor& src, + float v, + int32_t n); + __aicore__ inline void VecSubPair(const LocalTensor& dst, + const LocalTensor& src0, + const LocalTensor& src1, + int32_t n); + __aicore__ inline void VecAddsScalar(const LocalTensor& dst, + const LocalTensor& src, + float v, + int32_t n); + __aicore__ inline void VecMulPair(const LocalTensor& dst, + const LocalTensor& src0, + const LocalTensor& src1, + int32_t n); + // ================================Local + // Buffer区==================================== queue + TQue inQueue_; + TQue outQueue_; + + // tmp buff for vector + TBuf sortOutBuf_; + TBuf indexBuf_; + TBuf tmpBuf_; + + // tmp buff for LD + TBuf<> ldToBeMrgBuf_; + TBuf<> ldTmpBuf_; + TBuf<> ldOutValueBuf_; + TBuf<> ldOutIdxBuf_; + + // tmp buff for candidate (two-level topk) + TBuf + blockSortOutBuf_; // mode=1: 块级 topk 累加器 [CeilDiv(s1BaseSize,2), + // 2048, 2] + TBuf + candBuf_; // mode=2: 排序后的候选块索引 [2048, 2] (value+idx) + TBuf candConstBuf_; // mode=1/2: negHuge 常量 [2048] + + LocalTensor globalTopkIndice_; + LocalTensor globalTopkUb_; + LocalTensor globalBlockTopkUb_; + LocalTensor candIsOut_; // mode=2: position 级 0/1 (1=候选外), + // 仅用于分数降级 (R11 leak) + LocalTensor candNegHuge_; // -1e30 常量 + GlobalTensor + outputIdxOffsetGm_; // A15: 每行输出索引偏移 (仅 sparse_indices) + bool isOutputIdxOffsetValid_ = + false; // A15: offset 是否传入 (经 InitVecCandidateTensor 传递) + + int32_t blockId_ = -1; + // para for vector + int32_t groupInner_ = 0; + int32_t globalTopkNum_ = 0; + int64_t blockS2StartIdx_ = 0; + int32_t gSize_ = 0; + int32_t kSeqSize_ = 0; + int32_t kHeadNum_ = 0; + int32_t qHeadNum_ = 0; + int32_t s1BaseSize_ = 0; + int32_t s2BaseSize_ = 0; + int32_t kCacheBlockSize_ = 0; + int32_t maxBlockNumPerBatch_ = 0; + + // para for LD + uint32_t mrgListNum_ = 4; + + struct QLIV2VaCommon::ConstInfo constInfo_; + struct QLIV2VaCommon::LdSplitCoreInfo ldInfo_; +}; + +template +__aicore__ inline void QLIV2VaVector::GetKeyScale( + const QLIV2VaCommon::RunInfo& runInfo, + const LocalTensor& resUb, + int64_t batchId, + int64_t startS2, + int64_t getLen) { + // startS2一定能整除kCacheBlockSize_ + AscendC::DataCopyPadExtParams padParams{false, 0, 0, 0}; + AscendC::DataCopyExtParams copyInParams; + if constexpr (PAGE_ATTENTION) { + // A11: k_scale 0 轴非连续 — 块基址 = 表值 x keyDequantScaleStride0 (真实 + // stride); 0 时兜底原紧凑公式 (kCacheBlockSize_), 现网行为不变 (R8) Paged + // hybrid caches can span more than 2^31 scale elements. Promote before + // multiplication so high physical block IDs do not wrap. + int64_t kScaleBlkStride = + constInfo_.keyDequantScaleStride0 != 0 + ? static_cast(constInfo_.keyDequantScaleStride0) + : kCacheBlockSize_; + int32_t startBlockTableIdx = startS2 / kCacheBlockSize_; + int32_t startBlockTableOffset = startS2 % kCacheBlockSize_; + int32_t blockTableBatchOffset = batchId * maxBlockNumPerBatch_; + copyInParams.blockCount = 1; + copyInParams.srcStride = 0; + copyInParams.dstStride = 0; + copyInParams.rsv = 0; + int32_t resUbBaseOffset = 0; + if (startBlockTableOffset > 0) { + int32_t firstPartLen = kCacheBlockSize_ - startBlockTableOffset > getLen + ? getLen + : kCacheBlockSize_ - startBlockTableOffset; + copyInParams.blockLen = firstPartLen * sizeof(half); + int32_t blockId = + blockTableGm.GetValue(blockTableBatchOffset + startBlockTableIdx); + SetWaitFlag(HardEvent::S_MTE2); + AscendC::DataCopyPad( + resUb, + kScaleGm[blockId * kScaleBlkStride + startBlockTableOffset], + copyInParams, + padParams); + startBlockTableIdx++; + getLen = getLen - firstPartLen; + resUbBaseOffset = firstPartLen; + } + int32_t getLoopNum = CeilDiv(getLen, kCacheBlockSize_); + copyInParams.blockLen = kCacheBlockSize_ * sizeof(half); + for (int32_t i = 0; i < getLoopNum; i++) { + if (i == getLoopNum - 1) { + copyInParams.blockLen = (getLen - i * kCacheBlockSize_) * sizeof(half); + } + int32_t blockId = + blockTableGm.GetValue(blockTableBatchOffset + startBlockTableIdx + i); + SetWaitFlag(HardEvent::S_MTE2); + AscendC::DataCopyPad(resUb[resUbBaseOffset + i * kCacheBlockSize_], + kScaleGm[blockId * kScaleBlkStride], + copyInParams, + padParams); + } + } else { + copyInParams.blockCount = 1; + copyInParams.blockLen = getLen * sizeof(half); + copyInParams.srcStride = 0; + copyInParams.dstStride = 0; + copyInParams.rsv = 0; + AscendC::DataCopyPad( + resUb, kScaleGm[runInfo.tensorKeyScaleOffset], copyInParams, padParams); + } +} + +template +__aicore__ inline void QLIV2VaVector::InitBuffers(TPipe* pipe) { + pipe->InitBuffer(inQueue_, 2, s2BaseSize_ * sizeof(float) * 2); // 32KB + pipe->InitBuffer(outQueue_, 1, BASE_TOPK * sizeof(float)); // 8 KB + pipe->InitBuffer(indexBuf_, s2BaseSize_ * sizeof(int32_t)); // 8 KB + pipe->InitBuffer(tmpBuf_, 64 * 1024); // 64KB + pipe->InitBuffer(sortOutBuf_, + CeilDiv(s1BaseSize_, 2) * BASE_TOPK_VALUE_IDX_SIZE * + sizeof(float)); // 32KB + + globalTopkIndice_ = indexBuf_.Get(); + globalTopkUb_ = sortOutBuf_.Get(); + globalTopkNum_ = 0; + + // candidate (two-level topk) 按模式分配, mode=3 不占用额外 UB + // UB 预算 (192KB): 基础 144KB + mode=1 blockSortOutBuf 32KB = 176KB / mode=2 + // candBuf 16KB + candConstBuf 8KB = 168KB + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + pipe->InitBuffer(blockSortOutBuf_, + CeilDiv(s1BaseSize_, 2) * BASE_TOPK_VALUE_IDX_SIZE * + sizeof(float)); // 32KB + globalBlockTopkUb_ = blockSortOutBuf_.Get(); + InitSortOutBuf(globalBlockTopkUb_, + CeilDiv(s1BaseSize_, 2) * BASE_TOPK_VALUE_IDX_SIZE); + } else if (constInfo_.candidateMode == CANDIDATE_MODE_CONSUMER) { + // R6 修复: candBuf 按行分区 (每 AIV 处理 CeilDiv(s1BaseSize,2)=2 行, 行间 + // tile0 重排序 会互相覆盖) — 2 行 x 2048 对 x 8B = 32KB; mode=2 UB 预算 + // 144+32+8=184KB <= 192KB + pipe->InitBuffer(candBuf_, + CeilDiv(s1BaseSize_, 2) * BASE_TOPK * 2 * sizeof(float)); + pipe->InitBuffer(candConstBuf_, BASE_TOPK * sizeof(float)); // 8KB: negHuge + candNegHuge_ = candConstBuf_.Get(); + Duplicate(candNegHuge_.template ReinterpretCast(), + QLIV2VaServiceVec::NEG_HUGE_F32, + BASE_TOPK); + PipeBarrier(); + } + + // 基本块执行前初始化UB和GM + // step1. 初始化一个有序索引 0 - s2BaseSize_ + ArithProgression(globalTopkIndice_, 0, 1, s2BaseSize_); + // step2. globalTopkUb_ [CeilDiv(s1BaseSize_, 2), BASE_TOPK, 2] -inf,-1 + InitSortOutBuf(globalTopkUb_, + CeilDiv(s1BaseSize_, 2) * BASE_TOPK_VALUE_IDX_SIZE); +} + +template +__aicore__ inline void QLIV2VaVector::InitLDBuffers(TPipe* pipe) { + pipe->Reset(); + pipe->InitBuffer(ldToBeMrgBuf_, + BASE_TOPK_VALUE_IDX_SIZE * mrgListNum_ * sizeof(float)); + pipe->InitBuffer(ldTmpBuf_, + BASE_TOPK_VALUE_IDX_SIZE * mrgListNum_ * sizeof(float)); + pipe->InitBuffer(ldOutValueBuf_, BASE_TOPK * sizeof(float)); + pipe->InitBuffer(ldOutIdxBuf_, BASE_TOPK * sizeof(int32_t)); +} + +template +__aicore__ inline void QLIV2VaVector::InitParams( + const struct QLIV2VaCommon::ConstInfo& constInfo, + const struct QLIV2VaCommon::LdSplitCoreInfo& ldInfo, + const QLIV2VaTilingData* __restrict tilingData) { + this->constInfo_ = constInfo; + this->ldInfo_ = ldInfo; + blockS2StartIdx_ = 0; + gSize_ = constInfo.gSize; + kSeqSize_ = constInfo.kSeqSize; + // define N2 para + kHeadNum_ = constInfo.kHeadNum; + qHeadNum_ = constInfo.qHeadNum; + // define MMBase para + s1BaseSize_ = constInfo.s1BaseSize; // 4 + s2BaseSize_ = constInfo.s2BaseSize; // 2048 + kCacheBlockSize_ = constInfo.kCacheBlockSize; + maxBlockNumPerBatch_ = constInfo.maxBlockNumPerBatch; + blockId_ = GetBlockIdx(); +} + +template +__aicore__ inline void QLIV2VaVector::InitVecInputTensor( + GlobalTensor weightsGm, + GlobalTensor qScaleGm, + GlobalTensor kScaleGm, + GlobalTensor indiceOutGm, + GlobalTensor blockTableGm) { + this->weightsGm = weightsGm; + this->qScaleGm = qScaleGm; + this->kScaleGm = kScaleGm; + this->indiceOutGm = indiceOutGm; + this->blockTableGm = blockTableGm; +} + +template +__aicore__ inline void QLIV2VaVector::InitVecWorkspaceTensor( + GlobalTensor vec0OutGm, + GlobalTensor mm1ResGm, + GlobalTensor vec1ResGm) { + this->mm1ResGm = mm1ResGm; + this->vec1ResGm = vec1ResGm; + this->vec0OutGm = vec0OutGm; +} + +template +__aicore__ inline void QLIV2VaVector::InitVecCandidateTensor( + GlobalTensor candidateTopkIndexInGm, + GlobalTensor candidateTopkIndexOutGm, + GlobalTensor outputIdxOffsetGm, + bool outputIdxOffsetValid) { + this->candidateTopkIndexInGm = candidateTopkIndexInGm; + this->candidateTopkIndexOutGm = candidateTopkIndexOutGm; + this->outputIdxOffsetGm_ = outputIdxOffsetGm; // A15 + this->isOutputIdxOffsetValid_ = outputIdxOffsetValid; +} + +template +__aicore__ inline void QLIV2VaVector::AllocEventID() {} + +template +__aicore__ inline void QLIV2VaVector::FreeEventID() {} + +template +__aicore__ inline void QLIV2VaVector::CleanInvalidOutput( + int64_t invalidS1offset) { + // init -1 and copy to output + LocalTensor valueULocal = outQueue_.AllocTensor(); + LocalTensor idxULocal1 = + valueULocal.template ReinterpretCast(); + Duplicate(idxULocal1, constInfo_.INVALID_IDX, constInfo_.sparseCount); + outQueue_.EnQue(valueULocal); + valueULocal = outQueue_.DeQue(); + QLIV2VaServiceVec::CopyOut( + indiceOutGm[invalidS1offset], idxULocal1, constInfo_.sparseCount); + outQueue_.FreeTensor(valueULocal); + // mode=1: candidate_topk_index 同步填 -1 (行偏移 = sparse 偏移 / sparseCount + // * candidateTopkBlocks) + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + uint64_t candOffset = static_cast(invalidS1offset) / + constInfo_.sparseCount * + constInfo_.candidateTopkBlocks; + LocalTensor candULocal = outQueue_.AllocTensor(); + LocalTensor candIdxLocal = + candULocal.template ReinterpretCast(); + Duplicate( + candIdxLocal, constInfo_.INVALID_IDX, constInfo_.candidateTopkBlocks); + outQueue_.EnQue(candULocal); + candULocal = outQueue_.DeQue(); + QLIV2VaServiceVec::CopyOut(candidateTopkIndexOutGm[candOffset], + candIdxLocal, + constInfo_.candidateTopkBlocks); + outQueue_.FreeTensor(candULocal); + } +} + +// 64 元素分块封装: 规避 Level-2 大 count 的 vmax/vmin/vabs 等指令异常 +template +__aicore__ inline void QLIV2VaVector::VecMaxPair( + const LocalTensor& dst, + const LocalTensor& src0, + const LocalTensor& src1, + int32_t n) { + for (int32_t off = 0; off < n; off += 64) { + Max(dst[off], src0[off], src1[off], 64); + } + PipeBarrier(); +} + +template +__aicore__ inline void QLIV2VaVector::VecMinPair( + const LocalTensor& dst, + const LocalTensor& src0, + const LocalTensor& src1, + int32_t n) { + for (int32_t off = 0; off < n; off += 64) { + Min(dst[off], src0[off], src1[off], 64); + } + PipeBarrier(); +} + +template +__aicore__ inline void QLIV2VaVector::VecAbs( + const LocalTensor& dst, + const LocalTensor& src, + int32_t n) { + for (int32_t off = 0; off < n; off += 64) { + Abs(dst[off], src[off], 64); + } + PipeBarrier(); +} + +template +__aicore__ inline void QLIV2VaVector::VecMinsScalar( + const LocalTensor& dst, + const LocalTensor& src, + float v, + int32_t n) { + for (int32_t off = 0; off < n; off += 64) { + Mins(dst[off], src[off], v, 64); + } + PipeBarrier(); +} + +template +__aicore__ inline void QLIV2VaVector::VecMaxsScalar( + const LocalTensor& dst, + const LocalTensor& src, + float v, + int32_t n) { + for (int32_t off = 0; off < n; off += 64) { + Maxs(dst[off], src[off], v, 64); + } + PipeBarrier(); +} + +template +__aicore__ inline void QLIV2VaVector::VecSubPair( + const LocalTensor& dst, + const LocalTensor& src0, + const LocalTensor& src1, + int32_t n) { + for (int32_t off = 0; off < n; off += 64) { + Sub(dst[off], src0[off], src1[off], 64); + } + PipeBarrier(); +} + +template +__aicore__ inline void QLIV2VaVector::VecAddsScalar( + const LocalTensor& dst, + const LocalTensor& src, + float v, + int32_t n) { + for (int32_t off = 0; off < n; off += 64) { + Adds(dst[off], src[off], v, 64); + } + PipeBarrier(); +} + +template +__aicore__ inline void QLIV2VaVector::VecMulPair( + const LocalTensor& dst, + const LocalTensor& src0, + const LocalTensor& src1, + int32_t n) { + for (int32_t off = 0; off < n; off += 64) { + Mul(dst[off], src0[off], src1[off], 64); + } + PipeBarrier(); +} + +// 统计降序序列 (偶数 lane 为 value) 中 >= x 的元素个数, 二分实现 +template +__aicore__ inline int32_t QLIV2VaVector::CountGE( + const LocalTensor& sortedDesc, + int32_t n, + float x) { + int32_t lo = 0; + int32_t hi = n; + while (lo < hi) { + int32_t mid = (lo + hi) / 2; + if (sortedDesc.GetValue(2 * mid) >= x) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; +} + +// mode=2 (use_candidate): 加载/排序候选行 (每行首个S2分片), 判定 tile 内块归属, +// 产出 position 级 isOut (fp32 0/1, 1=候选外) 与其 int32 形式 +template +__aicore__ inline void QLIV2VaVector::BuildCandidateMask( + const QLIV2VaCommon::RunInfo& info, + int32_t cuS1Idx, + int32_t cuBaseS2Idx, + int32_t innerS1Idx) { + int32_t candBlocks = static_cast(constInfo_.candidateTopkBlocks); + int32_t blockSize = static_cast(constInfo_.candidateBlockSize); + int32_t tileBlkNum = s2BaseSize_ / blockSize; + int32_t tileBlockBase = cuBaseS2Idx / blockSize; + // R6 修复: 同核多行 (每 AIV 处理 CeilDiv(s1BaseSize,2)=2 行) 共享 candBuf 时, + // 后一行的 tile0 重排序会覆盖前行候选 (s2 内层循环按 gS1 块整体推进) — + // candBuf 按行分区 + LocalTensor tmp = tmpBuf_.Get(); + LocalTensor candPairs = + candBuf_.Get()[innerS1Idx * candBlocks * 2]; + if (info.isFirstS2InnerLoop) { + // 加载候选行到 tmp 尾部, 转 fp32 后与有序索引组成 [values | idx] + // 对并降序排序 + LocalTensor candInt = + tmp[12288].template ReinterpretCast(); + AscendC::DataCopyExtParams copyInParams; + copyInParams.blockCount = 1; + copyInParams.blockLen = candBlocks * sizeof(int32_t); + copyInParams.srcStride = 0; + copyInParams.dstStride = 0; + copyInParams.rsv = 0; + AscendC::DataCopyPadExtParams padParams{true, 0, 0, 0}; + SetWaitFlag(HardEvent::V_MTE2); + AscendC::DataCopyPad( + candInt, + candidateTopkIndexInGm[info.candidateOutOffset + + cuS1Idx * constInfo_.candidateTopkBlocks], + copyInParams, + padParams); + SetWaitFlag(HardEvent::MTE2_V); + PipeBarrier(); + Cast(candPairs, candInt, RoundMode::CAST_NONE, candBlocks); + PipeBarrier(); + DataCopy(candPairs[candBlocks].template ReinterpretCast(), + globalTopkIndice_, + candBlocks); + PipeBarrier(); + LocalTensor candSortTmp = tmp[4096]; + QLIV2VaServiceVec::SortAll(candPairs, candSortTmp, candBlocks); + PipeBarrier(); + // V->S 围栏: 排序结果对后续标量 GetValue (CountGE 二分) 可见 + // (PipeBarrier 不足以保证标量读到 V 写数据; 参照 CANN topk_v200 的 + // SetFlag/WaitFlag 模式) + SetWaitFlag(HardEvent::V_S); + } + // 候选与 tile 块号 [tileBlockBase, tileBlockBase+tileBlkNum) 的最小距离, 0 + // 即命中 (candBuf 按行分区, R6: 同核行间覆盖已修复) + LocalTensor candPairs2 = + candBuf_.Get()[innerS1Idx * candBlocks * 2]; + int32_t lo = + CountGE(candPairs2, candBlocks, static_cast(tileBlockBase)); + int32_t hi = CountGE( + candPairs2, candBlocks, static_cast(tileBlockBase + tileBlkNum)); + LocalTensor blkIdxF = tmp[4096]; // [tileBlkNum] + LocalTensor acc = tmp[4352]; // [tileBlkNum] + LocalTensor diff = tmp[4608]; // [tileBlkNum] + Cast(blkIdxF, globalTopkIndice_, RoundMode::CAST_NONE, tileBlkNum); + PipeBarrier(); + Adds(blkIdxF, blkIdxF, static_cast(tileBlockBase), tileBlkNum); + PipeBarrier(); + Duplicate(acc.ReinterpretCast(), + QLIV2VaServiceVec::POS_INF_F32, + tileBlkNum); + PipeBarrier(); + // 降序排序下: 值 >= base+tileBlkNum 占 [0, hi), 落在 tile 内的候选占 [hi, + // lo), < base (含 -1 pad) 占 [lo, ...) + for (int32_t j = hi; j < lo; j++) { + float v = candPairs2.GetValue(2 * j); + Adds(diff, blkIdxF, -v, tileBlkNum); + PipeBarrier(); + VecAbs(diff, diff, tileBlkNum); + VecMinPair(acc, acc, diff, tileBlkNum); + } + // 距离 0 → 候选块; Brcb 展开到位置级; 距离 clamp 到 1 得 isOut (0/1) + LocalTensor posDist = tmp[12288]; // candInt 已释放, 可复用 + Brcb(posDist, acc, tileBlkNum / 8, {1, 8}); + PipeBarrier(); + VecMinsScalar(posDist, posDist, 1.0f, s2BaseSize_); + PipeBarrier(); + candIsOut_ = posDist; + // R11 (leak 语义, §1.6): isOut 仅用于分数降级 (pen 链), 索引保留真实位置号 — + // 候选外可达位置作为 topk 填充泄漏成有效索引 (对齐模型 where(idxs < + // compress_lens) 语义), 不再把候选外索引改 -1 (原 isOutI32/CAST_RINT + // 链已删)。 +} + +// mode=1 (is_candidate_source): 块内 amax (log2(blockSize) 轮 Max 树) + pin +// 尾块 + 块级排序/归并 +template +__aicore__ inline void QLIV2VaVector::ProcessCandBlockTopk( + const QLIV2VaCommon::RunInfo& info, + int32_t cuS1Idx, + int32_t cuS2Len, + int32_t cuS2LenVecAlign, + int32_t cuRealAcSeq, + int32_t innerS1Idx) { + int32_t blkLen = cuS2LenVecAlign; + int32_t blockSize = static_cast(constInfo_.candidateBlockSize); + int32_t blockNum = blkLen / blockSize; // 含尾块 (pad -inf 后按对齐长度计) + int32_t realBlockNum = + (cuS2Len + blockSize - 1) / blockSize; // 含有效位置的块数 + // 所有向量 count 按 64 对齐 (非对齐 count 的向量指令在本架构触发 aicore + // 异常); 且块数必须过 AlignS2 (32*(4^n)*m, m<=3): SortAll 的 MrgSort 循环按 + // mrgGroups/4 缩减, 非 4 幂组数 (如 192 块=6 组) 会整组丢失 (实测 s2=1536 + // 丢块 128..191 段) + int32_t blockNumPad = (blockNum < 64) ? 64 : AlignS2(blockNum); + int32_t tileBlockBase = info.s2Idx * s2BaseSize_ / blockSize; + LocalTensor tmp = tmpBuf_.Get(); + // 块内归约: vcgmax 每 32B 块 (8 fp32) 出 1 个 max, 紧凑输出 [blockNum] + LocalTensor blkScore = tmp[6144]; + // R10: blkLen=96 是 AlignS2 输出中唯一非 64 倍数的值 (≤128 段对齐到 32 + // 的倍数), 96/64 整除截断为 1 只归约 [0,64) — 块 8..11 残留上一 tile/行的 + // stale 分数 (实测 big128k_b2_varlen b1 行 73 tile 56: 块 14344 拿到 tile 55 + // 块 14088 的 3.5568, 虚高挤掉 2048 名边界块 2760; 小 shape 总块数≤2048 + // 集合不变故未暴露)。 改 CeilDiv 覆盖全部块; 多归约的 [96,128) stale 只落在 + // pad 块槽位, 被 -inf 位型链位精确覆盖, 无害。 + int32_t brmRepeat = CeilDiv(blkLen, 64); + BlockReduceMax(blkScore, tmp[0], brmRepeat, 64, 1, 1, 8); + PipeBarrier(); + int32_t lastBlk = (cuRealAcSeq - 1) / blockSize; + int32_t pinLocal = lastBlk - tileBlockBase; + // 块级 [scores | idx] 对: idx = tileBlockBase + j; j >= realBlockNum 的 pad + // 块置 -1 (禁止标量 SetValue: 标量写不受 PipeBarrier 围栏, 与后续 V + // 管道读存在确定性竞态 + // (实测 innerS1Idx=1 行的填充被 SortAll 抢跑覆盖); 禁止 s32->f32 Cast (v220 + // 无此组合)。 改为纯 int32 向量算术: idx' = idx - (idx+1)*isPad, isPad = + // clamp(idx - thr, 0, 1), thr = base + realBlockNum - 1; 所有指令 + // count=blockNumPad (64 对齐), 按 64 分块避免 mask 寄存器限制。 scratch 用 + // mode=1 独占区 [14336,15360) (mode=2 的 isOutI32 已随 R11 leak 改造删除), + // 避开主路径 tmpSortBuf [4096,12288), 消除跨迭代残留读的隐患) + LocalTensor idxScr = + tmp[14336].template ReinterpretCast(); // 等差源 + LocalTensor thrI = + tmp[14592].template ReinterpretCast(); // 阈值 + LocalTensor offI = + tmp[14848].template ReinterpretCast(); // idx-thr -> isPad + LocalTensor tI = + tmp[15104].template ReinterpretCast(); // (idx+1)*isPad + LocalTensor blkIdx = + tmp[6144 + blockNumPad].template ReinterpretCast(); // 最终 idx + ArithProgression( + idxScr, static_cast(tileBlockBase), 1, blockNumPad); + Duplicate(thrI, tileBlockBase + realBlockNum - 1, blockNumPad); + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Sub(offI[off], idxScr[off], thrI[off], 64); + } + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Maxs(offI[off], offI[off], 0, 64); + } + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Mins(offI[off], offI[off], 1, 64); + } + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Adds(tI[off], idxScr[off], 1, 64); + } + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Mul(tI[off], tI[off], offI[off], 64); + } + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Sub(blkIdx[off], idxScr[off], tI[off], 64); + } + PipeBarrier(); + // pad 块 score 归一为 -inf 位型: 覆盖 [realBlockNum, blockNumPad), 含 stale + // 区 [blockNum, blockNumPad) (尾 tile cuS2Len 非整块时 BlockReduceMax 只写 + // [0, blockNum), 其后是脏数据 — + // 脏 score 的 (-inf,-1) 不同构对会挤进 topk 挤掉真实块, 实测 128K 场景 -1 + // 槽超标) + // score' = score + (score - NINF_bits)*(-isPad), isPad 于 pad 位为 1; 全 + // int32 向量 + if (blockNumPad > realBlockNum) { + LocalTensor pRaw = + tmp[15360].template ReinterpretCast(); // -isPad + LocalTensor pNeg = + tmp[15616] + .template ReinterpretCast(); // (score-NINF)*(-isPad) + LocalTensor scoreI = blkScore.template ReinterpretCast(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Duplicate(pRaw[off], -1, 64); + } + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Mul(pRaw[off], pRaw[off], offI[off], 64); // -isPad + } + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Adds(pNeg[off], + scoreI[off], + 8388608, + 64); // score - NINF_bits (NINF=0xFF800000=-8388608) + } + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Mul(pNeg[off], pNeg[off], pRaw[off], 64); + } + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Add(scoreI[off], scoreI[off], pNeg[off], 64); // pad 块 -> -inf 位型 + } + PipeBarrier(); + } + // pin 最新 token 所在块 (+inf 位型注入该块 score): 纯 int32 向量实现, 在 + // isPad 链之后 (复用其 scratch; 标量 SetValue 写不受 PipeBarrier + // fence, 与 SortAll 多轮读存在竞态, 已弃用)。 flag = -1 于 pin 位, 0 于其余: + // score' = score + (score - PINF_bits) * flag, pin 位得 PINF_bits (0x7F800000 + // = +inf), 其余不变 (flag=0 使 pad 位 -inf 的中间溢出无害)。 + if (pinLocal >= 0 && pinLocal < realBlockNum) { + LocalTensor pRaw = + tmp[15360].template ReinterpretCast(); // [15360,15616) + LocalTensor pNeg = + tmp[15616].template ReinterpretCast(); // [15616,15872) + LocalTensor pA = thrI; // 复用 isPad 链已释放 scratch + LocalTensor pB = offI; + LocalTensor pFlag = tI; + LocalTensor scoreI = blkScore.template ReinterpretCast(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + // idxScr 为全局块号, pin 也必须用全局 id (tileBlockBase + pinLocal) 比较 + Adds(pRaw[off], + idxScr[off], + -(tileBlockBase + pinLocal), + 64); // 0 于 pin 块 + } + PipeBarrier(); + Duplicate(pNeg, 0, blockNumPad); + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Sub(pNeg[off], pNeg[off], pRaw[off], 64); // -(idx-pinLocal) + } + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Maxs(pA[off], pRaw[off], 0, 64); + } + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Mins(pA[off], pA[off], 1, 64); // 1 若 idx > pin + } + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Maxs(pB[off], pNeg[off], 0, 64); + } + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Mins(pB[off], pB[off], 1, 64); // 1 若 idx < pin + } + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Add(pFlag[off], pA[off], pB[off], 64); // isNotPin (0/1, 互斥) + } + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Adds(pFlag[off], pFlag[off], -1, 64); // -1 于 pin, 0 其余 + } + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Adds(pRaw[off], + scoreI[off], + -2139095040, + 64); // score - 0x7F800000 (复用 pRaw) + } + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Mul(pRaw[off], pRaw[off], pFlag[off], 64); // (score-PINF)*flag + } + PipeBarrier(); + for (int32_t off = 0; off < blockNumPad; off += 64) { + Add(scoreI[off], scoreI[off], pRaw[off], 64); // pin -> +inf 位型 + } + PipeBarrier(); + } + // 块级排序 + 归并到块级累加器 + LocalTensor blkPairs = + tmp[6144]; // [scores blockNumPad | idx blockNumPad] + // MrgSort tmp 需容纳 mrgDst+mrgSrc = 2048*2 + blockNumPad*2 <= 4608 floats; + // 11776 + 4608 = 16384 恰为 tmpBuf_(64KB) 末尾, 12288 起会越界 2KB (aicore + // 异常) + LocalTensor blkSortTmp = + tmp[11776]; // 与 blkPairs 不重叠 (MrgSort src/tmp 禁止重叠) + QLIV2VaServiceVec::SortAll(blkPairs, blkSortTmp, blockNumPad); + PipeBarrier(); + // 候选专用合并: 纯 V 回拷 (MergeSort 尾部 UB->UB DataCopy 不受 + // PipeBarrier fence, 多 tile 下一次 MrgSort 读 acc 存在调度敏感竞态, + // 实测 tile1 读到 stale 数据) + QLIV2VaServiceVec::MergeSortVecCopy( + globalBlockTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], + constInfo_.candidateTopkBlocks, + blkPairs, + blockNumPad, + blkSortTmp); + PipeBarrier(); +} + +// mode=1: 行末直出 candidate_topk_index 并复位块级累加器 +template +__aicore__ inline void QLIV2VaVector::CopyOutCandTopkIndex( + const QLIV2VaCommon::RunInfo& info, + int32_t cuS1Idx, + int32_t innerS1Idx) { + LocalTensor candIdxULocal = outQueue_.AllocTensor(); + ExtractIndex(candIdxULocal, + globalBlockTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE] + .template ReinterpretCast(), + constInfo_.candidateTopkBlocks); + PipeBarrier(); + InitSortOutBuf(globalBlockTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], + BASE_TOPK_VALUE_IDX_SIZE); + outQueue_.EnQue(candIdxULocal); + candIdxULocal = outQueue_.DeQue(); + QLIV2VaServiceVec::CopyOut( + candidateTopkIndexOutGm[info.candidateOutOffset + + cuS1Idx * constInfo_.candidateTopkBlocks], + candIdxULocal.template ReinterpretCast(), + constInfo_.candidateTopkBlocks); + outQueue_.FreeTensor(candIdxULocal); +} + +template +__aicore__ inline void QLIV2VaVector::ProcessVec0( + const QLIV2VaCommon::RunInfo& info) { + // 只需要一个v核做 + if (blockId_ % 2 != 0) { + return; + } + int32_t cuBaseS1Idx = info.gS1Idx * s1BaseSize_; + // 计算输出w基地址偏移 偶数循环 -> 0 + aic_offset 奇数循环 -> 4*64 + + // aic_offset + int64_t vec0OutGmOffset = + (info.loop % 2) * ((s1BaseSize_ * gSize_ * BLOCK_CUBE)); + // 计算输入weight的地址偏移,qScale的地址偏移与weight相同 + int64_t weightGmOffset = info.tensorWeightsOffset + cuBaseS1Idx * qHeadNum_; + // 当前需要计算的S1行数,处理尾块场景 + int32_t cuS1ProcNum = cuBaseS1Idx + s1BaseSize_ > info.actS1Size + ? info.actS1Size % s1BaseSize_ + : s1BaseSize_; + int32_t cuProcRealNum = cuS1ProcNum * gSize_; + int32_t cuProcEleNum = + QLIV2VaCommon::Align(cuProcRealNum, 32); // 32: UB对齐, 参照v1 + + LocalTensor inWeightsUb = inQueue_.AllocTensor(); + LocalTensor inQScaleUb = inWeightsUb[cuProcEleNum]; + AscendC::DataCopyPadExtParams padParams{false, 0, 0, 0}; + AscendC::DataCopyExtParams copyInParams; + copyInParams.blockCount = 1; + copyInParams.blockLen = cuProcRealNum * sizeof(half); + copyInParams.srcStride = 0; + copyInParams.dstStride = 0; + copyInParams.rsv = 0; + AscendC::DataCopyPad( + inWeightsUb, weightsGm[weightGmOffset], copyInParams, padParams); + AscendC::DataCopyPad( + inQScaleUb, qScaleGm[weightGmOffset], copyInParams, padParams); + + inQueue_.EnQue(inWeightsUb); + inWeightsUb = inQueue_.DeQue(); + AscendC::Mul(inWeightsUb, inWeightsUb, inQScaleUb, cuProcEleNum); + PipeBarrier(); + LocalTensor resUb = outQueue_.AllocTensor(); + AscendC::Brcb( + resUb, inWeightsUb, static_cast(cuProcEleNum / 8), {1, 8}); + inQueue_.FreeTensor(inWeightsUb); + + outQueue_.EnQue(resUb); + resUb = outQueue_.DeQue(); + AscendC::DataCopyParams copyOutParams; + copyOutParams.blockCount = 1; + copyOutParams.blockLen = cuProcRealNum * BLOCK_CUBE * sizeof(half); + copyOutParams.srcStride = 0; + copyOutParams.dstStride = 0; + AscendC::DataCopyPad(vec0OutGm[vec0OutGmOffset], resUb, copyOutParams); + outQueue_.FreeTensor(resUb); +} + +template +__aicore__ inline int32_t QLIV2VaVector::AlignS2(int32_t cuS2Len) { + // 限制:当前cuS2Len最大为2048,暂不考虑更长 + // 该函数目的是将cuS2Len对齐到形如 32*(4^n)*m 的形式 (m ∈ [1, + // 3]),方便后续sort/merge + if (cuS2Len <= ELE_NUM_128) { + return Align(cuS2Len, ELE_NUM_32); + } else if (cuS2Len <= ELE_NUM_512) { + return Align(cuS2Len, ELE_NUM_128); + } else { + return Align(cuS2Len, ELE_NUM_512); + } +} + +template +__aicore__ inline void QLIV2VaVector::ProcessVec1( + const QLIV2VaCommon::RunInfo& info) { + int32_t cuBaseS1Idx = info.gS1Idx * s1BaseSize_; + int32_t cuBaseS2Idx = info.s2Idx * s2BaseSize_; + + // 计算基本块基地址偏移 偶数循环 -> 0 + aic_offset 奇数循环 -> 4*2048 + + // aic_offset + int64_t mmGmOffset = (info.loop % 2) * (s1BaseSize_ * s2BaseSize_); + + // cuS1BeginIdxPerAiv: 每个AIV的S1起始偏移 + int32_t cuS1BeginIdxPerAiv = cuBaseS1Idx; + int32_t cuS1ProcNum = cuS1BeginIdxPerAiv + s1BaseSize_ > info.actS1Size + ? info.actS1Size % s1BaseSize_ + : s1BaseSize_; + // cuS1ProcNumPerAiv: 每个AIv的S1计算量 + int32_t cuS1ProcNumPerAiv = + blockId_ % 2 == 0 ? CeilDiv(cuS1ProcNum, 2) : (cuS1ProcNum / 2); + cuS1BeginIdxPerAiv += (blockId_ % 2) * CeilDiv(cuS1ProcNum, 2); + // 基本块基地址偏移奇数核加一个S1地址偏移 + mmGmOffset += (blockId_ % 2) * CeilDiv(cuS1ProcNum, 2) * s2BaseSize_; + // 非首个基本块, M(S1)轴发生切换需要初始化 + if (info.loop != 0 && info.s2Idx == 0) { + // globalTopkUb_ value,index=-inf,-1 + InitSortOutBuf(globalTopkUb_, + CeilDiv(s1BaseSize_, 2) * BASE_TOPK_VALUE_IDX_SIZE); + blockS2StartIdx_ = 0; + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + InitSortOutBuf(globalBlockTopkUb_, + CeilDiv(s1BaseSize_, 2) * BASE_TOPK_VALUE_IDX_SIZE); + } + } else if (info.loop == 0) { + blockS2StartIdx_ = info.s2Idx; + } + // cuRealAcSeq: 当前基本块S1对应的AcSeq + int32_t cuRealAcSeq = info.actS2Size; + int32_t cuRealAcSeqCount = 0; + if (constInfo_.attenMaskFlag) { + // attenMask true场景 + cuRealAcSeq = info.actS2SizeOrig - info.actS1Size + cuS1BeginIdxPerAiv; + } + int32_t cuRealAcSeqIni = cuRealAcSeq; + + // LD输出S1方向偏移,保证2个Vector输出的内容连续 + uint32_t ldS1Offset = + (blockId_ % 2 == 0) ? s1BaseSize_ / 2 - cuS1ProcNumPerAiv : 0; + for (int innerS1Idx = 0; innerS1Idx < cuS1ProcNumPerAiv; innerS1Idx++) { + if (constInfo_.attenMaskFlag) { + cuRealAcSeqCount += 1; + cuRealAcSeq = (cuRealAcSeqCount + cuRealAcSeqIni) / + static_cast(constInfo_.cmpRatio); + } + int32_t cuS2Len = cuBaseS2Idx + s2BaseSize_ >= cuRealAcSeq + ? cuRealAcSeq - cuBaseS2Idx + : s2BaseSize_; + int32_t cuS1Idx = cuS1BeginIdxPerAiv + innerS1Idx; + // 当前vec1ResGm对应S1的位置 + uint64_t wsOffset = + static_cast(info.saveWorkSpaceIdx) * s1BaseSize_ * + BASE_TOPK_VALUE_IDX_SIZE + + static_cast(cuS1Idx - cuBaseS1Idx) * BASE_TOPK_VALUE_IDX_SIZE; + if (cuRealAcSeq > 0 && cuS2Len > 0) { + int32_t cuS2LenVecAlign = AlignS2(cuS2Len); + LocalTensor mmInUb = inQueue_.AllocTensor(); + LocalTensor kScaleUb = mmInUb[cuS2LenVecAlign]; + LocalTensor kScaleTUb = + kScaleUb.template ReinterpretCast()[cuS2LenVecAlign]; + AscendC::DataCopyPadExtParams padParams{false, 0, 0, 0}; + AscendC::DataCopyPadExtParams padTParams{false, 0, 0, 0}; + AscendC::DataCopyExtParams copyInParams; + copyInParams.blockCount = 1; + copyInParams.blockLen = cuS2Len * sizeof(float); + copyInParams.srcStride = 0; + copyInParams.dstStride = 0; + copyInParams.rsv = 0; + AscendC::DataCopyPad(mmInUb, + mm1ResGm[mmGmOffset + innerS1Idx * s2BaseSize_], + copyInParams, + padParams); + GetKeyScale(info, kScaleTUb, info.bIdx, cuBaseS2Idx, cuS2Len); + inQueue_.EnQue(mmInUb); + mmInUb = inQueue_.DeQue(); + AscendC::Cast(kScaleUb, kScaleTUb, RoundMode::CAST_NONE, cuS2Len); + PipeBarrier(); + AscendC::Mul(mmInUb, mmInUb, kScaleUb, cuS2Len); + PipeBarrier(); + // mode=2 (use_candidate, R11 leak): 候选块外 score 降级 NEG_HUGE (S4a, + // 纯算术无 NaN); 仅降级排序资格、不取消入选资格 — 不足 topk + // 时候选外可达位置作为填充泄漏 (§1.6) + if (constInfo_.candidateMode == CANDIDATE_MODE_CONSUMER) { + BuildCandidateMask(info, cuS1Idx, cuBaseS2Idx, innerS1Idx); + PipeBarrier(); + LocalTensor pen = + tmpBuf_.Get()[4096]; // blkIdxF/acc/d 已释放, 复用 + Sub(pen, candNegHuge_, mmInUb, cuS2Len); + PipeBarrier(); + Mul(pen, pen, candIsOut_, cuS2Len); + PipeBarrier(); + Add(mmInUb, mmInUb, pen, cuS2Len); + PipeBarrier(); + } + LocalTensor sortBuff = tmpBuf_.Get(); + LocalTensor sortScoreUb = sortBuff; + LocalTensor sortIndiceUb = sortBuff[cuS2LenVecAlign]; + PipeBarrier(); + Duplicate(sortScoreUb.template ReinterpretCast(), + QLIV2VaServiceVec::NEG_INF, + cuS2LenVecAlign); + PipeBarrier(); + Adds(sortScoreUb, mmInUb, 0.0f, cuS2Len); + PipeBarrier(); + inQueue_.FreeTensor(mmInUb); + LocalTensor sortIndiceUbInt = + sortIndiceUb.template ReinterpretCast(); + // 无效数据索引填充为-1 + if (cuS2LenVecAlign != cuS2Len) { + Duplicate(sortIndiceUbInt, -1, cuS2LenVecAlign); + PipeBarrier(); + } + Adds(sortIndiceUbInt, + globalTopkIndice_, + static_cast(cuBaseS2Idx), + cuS2Len); + PipeBarrier(); + // R11 (leak 语义, §1.6): 候选块外索引不再置 -1 — + // 分数已在 S4a 降级 NEG_HUGE (仍高于 -inf: 不足 topk 时作为填充入选, + // 排候选内之后), 索引保留真实位置号, 与模型 where(idxs < compress_lens, + // idxs + offset, -1) 等价: 仅不可达位置 (score -inf 沉底 + 尾部 -1 填充) + // 输出 -1。 mode=1 (is_candidate_source): 块化 amax + pin + 块级排序归并 + // (S5a/S6a) + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + ProcessCandBlockTopk( + info, cuS1Idx, cuS2Len, cuS2LenVecAlign, cuRealAcSeq, innerS1Idx); + } + LocalTensor tmpSortBuf = sortBuff[2 * cuS2LenVecAlign]; + QLIV2VaServiceVec::SortAll(sortBuff, tmpSortBuf, cuS2LenVecAlign); + PipeBarrier(); + // 主路径累加器归并: 与候选路径 (:689) 一致, 改用纯 V 回拷的 + // MergeSortVecCopy。 旧 MergeSort 尾部 UB->UB DataCopy 若落 MTE 管道, + // 其后的 PipeBarrier 不构成 fence, 跨 tile/跨行对 globalTopkUb_ + // 的下一次 MrgSort 读存在调度敏感竞态 (tile1 读到 tile0 stale 数据, + // 累加器出现 -inf 位型+垃圾)。MergeSortVecCopy 回拷全程 V 管道, 受 + // PipeBarrier 约束。 + QLIV2VaServiceVec::MergeSortVecCopy( + globalTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], + BASE_TOPK, + sortBuff, + cuS2LenVecAlign, + tmpSortBuf); + PipeBarrier(); + bool isS2End = cuBaseS2Idx + s2BaseSize_ >= cuRealAcSeq; + bool needCopyOutGm = blockS2StartIdx_ == 0 && isS2End; + // 中间结果保存 + if (needCopyOutGm && !info.isNeedLD) { + LocalTensor idxULocal = outQueue_.AllocTensor(); + ExtractIndex(idxULocal, + globalTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE] + .template ReinterpretCast(), + BASE_TOPK); + PipeBarrier(); + // A15: output_idx_offset — 输出拷 GM 前逐元素加行偏移 + // (IndicesAddOffset; 零偏移零开销; GM 标量读无 V_S 竞态; int32 整数域 + // Adds 位精确, -1 槽 +0 不变。 candidate_topk_index 不加 (相对块号契约, + // §11.6)) + if (isOutputIdxOffsetValid_) { + int32_t rowOff = outputIdxOffsetGm_.GetValue( + info.outputIdxOffsetCoreOffset + cuS1Idx * kHeadNum_); + if (rowOff != 0) { + LocalTensor idxI32 = + idxULocal.template ReinterpretCast(); + for (int32_t off = 0; off < constInfo_.sparseCount; off += 64) { + Adds(idxI32[off], idxI32[off], rowOff, 64); + } + PipeBarrier(); + } + } + InitSortOutBuf(globalTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], + BASE_TOPK_VALUE_IDX_SIZE); + outQueue_.EnQue(idxULocal); + idxULocal = outQueue_.DeQue(); + QLIV2VaServiceVec::CopyOut( + indiceOutGm[info.indiceOutOffset + + cuS1Idx * constInfo_.sparseCount], + idxULocal.template ReinterpretCast(), + constInfo_.sparseCount); + outQueue_.FreeTensor(idxULocal); + // mode=1: 块级 topk 直出 candidate_topk_index + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + CopyOutCandTopkIndex(info, cuS1Idx, innerS1Idx); + } + } + // LD拷贝到当前vector对应S1的位置 + if (info.isNeedLD && + info.isLastS2InnerLoop) { // 当前核存在归约任务 且是最后处理的一段 + AscendC::DataCopyExtParams copyWsParams; + copyWsParams.blockLen = BASE_TOPK_VALUE_IDX_SIZE * sizeof(float); + copyWsParams.srcStride = 0; + copyWsParams.dstStride = 0; + copyWsParams.blockCount = 1; + SetWaitFlag(HardEvent::V_MTE3); + AscendC::DataCopyPad( + vec1ResGm[wsOffset], + globalTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], + copyWsParams); + SetWaitFlag(HardEvent::MTE3_V); + InitSortOutBuf(globalTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], + BASE_TOPK_VALUE_IDX_SIZE); + PipeBarrier(); + } + } else if (cuRealAcSeq <= 0) { + // 无效长度处理 + if (info.isNeedLD && info.isLastS2InnerLoop) { + PipeBarrier(); + InitSortOutBuf(globalTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], + BASE_TOPK_VALUE_IDX_SIZE); + SetWaitFlag(HardEvent::V_MTE3); + QLIV2VaServiceVec::CopyOut( + vec1ResGm[wsOffset], + globalTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], + BASE_TOPK_VALUE_IDX_SIZE); + SetWaitFlag(HardEvent::MTE3_V); + } else { + CleanInvalidOutput(info.indiceOutOffset + + cuS1Idx * constInfo_.sparseCount); + } + } else if (cuS2Len <= 0) { + // LD拷贝到当前vector对应S1的位置 + if (info.isNeedLD && + info.isLastS2InnerLoop) { // 当前核存在归约任务 且是最后处理的一段 + SetWaitFlag(HardEvent::V_MTE3); + QLIV2VaServiceVec::CopyOut( + vec1ResGm[wsOffset], + globalTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], + BASE_TOPK_VALUE_IDX_SIZE); + SetWaitFlag(HardEvent::MTE3_V); + InitSortOutBuf(globalTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], + BASE_TOPK_VALUE_IDX_SIZE); + PipeBarrier(); + } + } + } + + // BNSD场景无效S1 输出-1 + if (Q_LAYOUT_T == LI_LAYOUT::BSND) { + // 最后一个S1的基本块, 需要 >= info.actS1Size + bool isS1LoopEnd = (cuBaseS1Idx + s1BaseSize_) >= info.actS1Size; + int32_t invalidS1Num = constInfo_.qSeqSize - info.actS1Size; + // blockS2StartIdx_ == 0 控制S2从开始的核去做冗余清理 + if (invalidS1Num > 0 && isS1LoopEnd && blockS2StartIdx_ == 0) { + int32_t s1NumPerAiv = + blockId_ % 2 == 0 ? CeilDiv(invalidS1Num, 2) : (invalidS1Num / 2); + int32_t s1OffsetPerAiv = + info.actS1Size + (blockId_ % 2) * CeilDiv(invalidS1Num, 2); + for (int innerS1Idx = 0; innerS1Idx < s1NumPerAiv; innerS1Idx++) { + CleanInvalidOutput(info.indiceOutOffset + + (s1OffsetPerAiv + innerS1Idx) * + constInfo_.sparseCount); + } + } + + int32_t invalidS1Num2 = info.actS1Size - info.actS2SizeOrig; + if (invalidS1Num2 > 0 && isS1LoopEnd && blockS2StartIdx_ == 0 && + constInfo_.attenMaskFlag) { + int32_t s1NumPerAiv = + blockId_ % 2 == 0 ? CeilDiv(invalidS1Num2, 2) : (invalidS1Num2 / 2); + int32_t s1OffsetPerAiv = (blockId_ % 2) * CeilDiv(invalidS1Num2, 2); + for (int innerS1Idx = 0; innerS1Idx < s1NumPerAiv; innerS1Idx++) { + CleanInvalidOutput( + (info.bN2Idx * constInfo_.qSeqSize + s1OffsetPerAiv + innerS1Idx) * + constInfo_.sparseCount); + } + } + } + + if (info.isLastS2InnerLoop) { + // S2最后一个Loop后, 下一个基本块初始从0开始 + blockS2StartIdx_ = 0; + } +} + +template +__aicore__ inline void QLIV2VaVector::ProcessLD() { + LocalTensor curValueIdxUb = ldToBeMrgBuf_.Get(); + LocalTensor tmpUb = ldTmpBuf_.Get(); + + LocalTensor outValueUb = ldOutValueBuf_.Get(); + LocalTensor outIdxUb = ldOutIdxBuf_.Get(); + + AscendC::DataCopyParams copyOutParams; + copyOutParams.blockCount = 1; + copyOutParams.blockLen = constInfo_.sparseCount * sizeof(int32_t); // bytes + copyOutParams.srcStride = 0; + copyOutParams.dstStride = 0; + + AscendC::DataCopyPadExtParams indexValuePadParams{true, 0, 0, 0}; + AscendC::DataCopyExtParams indexValueParams; + indexValueParams.blockLen = + BASE_TOPK_VALUE_IDX_SIZE * sizeof(int32_t); // bytes + indexValueParams.srcStride = 3 * BASE_TOPK_VALUE_IDX_SIZE * sizeof(int32_t); + indexValueParams.dstStride = 0; + + uint32_t ldProWorkspaceNum = ldInfo_.workspaceNum; + uint32_t ldProcessLen = 4; // 4: 4块归约任务做一次Merge + uint32_t ldProcessNum = (ldProWorkspaceNum - 1) / (ldProcessLen - 1); + uint32_t ldTailLen = + ldProWorkspaceNum - (ldProcessNum * (ldProcessLen - 1) + 1); // 尾块长度 + + for (uint32_t j = 0; j < ldInfo_.mNum; j++) { + SetWaitFlag(HardEvent::V_MTE2); + // 拷贝第一块归约任务 + indexValueParams.blockCount = 1; + uint64_t wsOffsetIni = + static_cast(ldInfo_.workspaceIdx) * s1BaseSize_ * + BASE_TOPK_VALUE_IDX_SIZE + + static_cast(ldInfo_.mStart + j) * BASE_TOPK_VALUE_IDX_SIZE; + AscendC::DataCopyPad(curValueIdxUb, + vec1ResGm[wsOffsetIni], + indexValueParams, + indexValuePadParams); + uint64_t valueOffset = BASE_TOPK_VALUE_IDX_SIZE; + SetWaitFlag(HardEvent::MTE2_V); + + // 处理等于4的部分 + for (uint32_t i = 0; i < ldProcessNum; i++) { + // LD处理偏移 + uint64_t wsOffset = + static_cast(ldInfo_.workspaceIdx) * s1BaseSize_ * + BASE_TOPK_VALUE_IDX_SIZE + + static_cast(ldInfo_.mStart + j) * BASE_TOPK_VALUE_IDX_SIZE + + static_cast(i * (ldProcessLen - 1) + 1) * s1BaseSize_ * + BASE_TOPK_VALUE_IDX_SIZE; + indexValueParams.blockCount = ldProcessLen - 1; // 拷贝4块进行merge + + SetWaitFlag(HardEvent::V_MTE2); + AscendC::DataCopyPad(curValueIdxUb[valueOffset], + vec1ResGm[wsOffset], + indexValueParams, + indexValuePadParams); + // merge参数 + AscendC::MrgSort4Info params; + params.elementLengths[0] = BASE_TOPK; + params.elementLengths[1] = BASE_TOPK; + params.elementLengths[2] = BASE_TOPK; + params.elementLengths[3] = BASE_TOPK; + params.ifExhaustedSuspension = true; + params.validBit = 0b1111; + params.repeatTimes = 1; + + SetWaitFlag(HardEvent::MTE2_V); + AscendC::MrgSortSrcList srcList; + srcList.src1 = curValueIdxUb[0]; + srcList.src2 = curValueIdxUb[BASE_TOPK_VALUE_IDX_SIZE]; + srcList.src3 = curValueIdxUb[2 * BASE_TOPK_VALUE_IDX_SIZE]; + srcList.src4 = curValueIdxUb[3 * BASE_TOPK_VALUE_IDX_SIZE]; + MrgSort(tmpUb, srcList, params); + PipeBarrier(); + DataCopy(curValueIdxUb, tmpUb, BASE_TOPK_VALUE_IDX_SIZE); + PipeBarrier(); + } + + // 处理不等于4的部分 + if (ldTailLen != 0) { + // 搬运尾块 + uint64_t wsOffsetTail = + static_cast(ldInfo_.workspaceIdx) * s1BaseSize_ * + BASE_TOPK_VALUE_IDX_SIZE + + static_cast(ldInfo_.mStart + j) * BASE_TOPK_VALUE_IDX_SIZE + + static_cast(ldProcessNum * (ldProcessLen - 1) + 1) * + s1BaseSize_ * BASE_TOPK_VALUE_IDX_SIZE; + indexValueParams.blockCount = ldTailLen; + SetWaitFlag(HardEvent::V_MTE2); + AscendC::DataCopyPad(curValueIdxUb[valueOffset], + vec1ResGm[wsOffsetTail], + indexValueParams, + indexValuePadParams); + SetWaitFlag(HardEvent::MTE2_V); + AscendC::MrgSort4Info params; + params.elementLengths[0] = BASE_TOPK; + params.elementLengths[1] = BASE_TOPK; + params.elementLengths[2] = BASE_TOPK; + params.elementLengths[3] = BASE_TOPK; + params.ifExhaustedSuspension = true; + if (ldTailLen == 1) { + params.validBit = 0b0011; + } else if (ldTailLen == 2) { + params.validBit = 0b0111; + } + params.repeatTimes = 1; + + AscendC::MrgSortSrcList srcList; + srcList.src1 = curValueIdxUb[0]; + srcList.src2 = curValueIdxUb[BASE_TOPK_VALUE_IDX_SIZE]; + srcList.src3 = curValueIdxUb[2 * BASE_TOPK_VALUE_IDX_SIZE]; + srcList.src4 = curValueIdxUb[3 * BASE_TOPK_VALUE_IDX_SIZE]; + PipeBarrier(); + MrgSort(tmpUb, srcList, params); + PipeBarrier(); + DataCopy(curValueIdxUb, tmpUb, BASE_TOPK_VALUE_IDX_SIZE); + PipeBarrier(); + } + + // 搬出 + Extract(outValueUb, outIdxUb, curValueIdxUb, (BASE_TOPK / 32)); + PipeBarrier(); + InitSortOutBuf(curValueIdxUb, BASE_TOPK_VALUE_IDX_SIZE); + LocalTensor idxULocal1 = + outIdxUb.template ReinterpretCast(); + // A15: LD(decode) 路径同样加 output_idx_offset (行前缀 = + // indiceOutCoreOffset/sparseCount, 即 batch 前缀 x kHeadNum + n2; 与 + // ProcessVec1 消费点同语义) + if (isOutputIdxOffsetValid_) { + uint32_t rowGlobal = ldInfo_.mStart + j; + int32_t rowOff = outputIdxOffsetGm_.GetValue( + ldInfo_.indiceOutCoreOffset / constInfo_.sparseCount + + rowGlobal * constInfo_.kHeadNum); + if (rowOff != 0) { + for (int32_t off = 0; off < constInfo_.sparseCount; off += 64) { + Adds(idxULocal1[off], idxULocal1[off], rowOff, 64); + } + PipeBarrier(); + } + } + SetWaitFlag(HardEvent::V_MTE3); + uint64_t outOffset = + ldInfo_.indiceOutCoreOffset + + (ldInfo_.mStart + j) * constInfo_.kHeadNum * constInfo_.sparseCount; + AscendC::DataCopyPad(indiceOutGm[outOffset], idxULocal1, copyOutParams); + SetWaitFlag(HardEvent::MTE3_V); + } + SetWaitFlag(HardEvent::MTE3_V); +} + +} // namespace QLIV2VaKernel +#endif // QUANT_LIGHTNING_INDEXER_V2_VA_SERVICE_VECTOR_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_vector.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_vector.h new file mode 100644 index 0000000000..5b6f971cd7 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_vector.h @@ -0,0 +1,278 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_lightning_indexer_v2_va_vector.h + * \brief + */ +#ifndef QUANT_LIGHTNING_INDEXER_V2_VA_VECTOR_H +#define QUANT_LIGHTNING_INDEXER_V2_VA_VECTOR_H + +#include "kernel_operator.h" + +namespace QLIV2VaServiceVec { +using namespace AscendC; + +constexpr int32_t NEG_INF = 0xFF800000; +constexpr int32_t POS_INF_F32 = 0x7F800000; // +inf (fp32 bits) +constexpr int32_t NEG_HUGE_F32 = 0xF14A3E31; // -1e30 (fp32 bits) +constexpr int32_t INVALID_INDEX = -1; +constexpr uint8_t VEC_REPEAT_MAX = 255; +constexpr uint8_t B32_VEC_ELM_NUM = 64; +constexpr uint8_t B32_BLOCK_ALIGN_NUM = 8; +constexpr uint8_t B32_VEC_REPEAT_STRIDE = 8; +constexpr uint64_t VEC_REPEAT_BYTES = 256; +constexpr int32_t CONST_TWO = 2; +constexpr int64_t VALUE_AND_INDEX_NUM = 2; +constexpr int64_t BLOCK_BYTES = 32; +constexpr int64_t MRG_QUE_0 = 0; +constexpr int64_t MRG_QUE_1 = 1; +constexpr int64_t MRG_QUE_2 = 2; +constexpr int64_t MRG_QUE_3 = 3; +constexpr int64_t MRG_BLOCK_2 = 2; +constexpr int64_t MRG_BLOCK_3 = 3; +constexpr int64_t MRG_BLOCK_4 = 4; + +template +__aicore__ inline void CopyOut(const GlobalTensor& dstGm, + const LocalTensor& srcUb, + int64_t copyCount) { + AscendC::DataCopyParams dataCopyOutyParams; + dataCopyOutyParams.blockCount = 1; + dataCopyOutyParams.blockLen = copyCount * sizeof(T); + dataCopyOutyParams.srcStride = 0; + dataCopyOutyParams.dstStride = 0; + AscendC::DataCopyPad(dstGm, srcUb, dataCopyOutyParams); +} + +/** + src: 传入的初始化空间 + eleNum: 需要初始化的元素个数需为64整数倍,元素将被初始化为交错排布的-inf,-1 + */ +__aicore__ inline void InitSortOutBuf(const LocalTensor& src, + int64_t eleNum) { + uint64_t mask1[2] = {0x5555555555555555, 0}; + uint64_t mask0[2] = {0xaaaaaaaaaaaaaaaa, 0}; + int64_t repeatNum = eleNum / B32_VEC_ELM_NUM; + int64_t forLoop = repeatNum / VEC_REPEAT_MAX; + int64_t forRemain = repeatNum % VEC_REPEAT_MAX; + for (int i = 0; i < forLoop; i++) { + AscendC::Duplicate(src.template ReinterpretCast(), + NEG_INF, + mask1, + VEC_REPEAT_MAX, + 1, + B32_VEC_REPEAT_STRIDE); + AscendC::Duplicate(src.template ReinterpretCast(), + INVALID_INDEX, + mask0, + VEC_REPEAT_MAX, + 1, + B32_VEC_REPEAT_STRIDE); + } + if (forRemain > 0) { + AscendC::Duplicate( + src.template ReinterpretCast()[forLoop * VEC_REPEAT_MAX * + B32_VEC_ELM_NUM], + NEG_INF, + mask1, + forRemain, + 1, + B32_VEC_REPEAT_STRIDE); + AscendC::Duplicate( + src.template ReinterpretCast()[forLoop * VEC_REPEAT_MAX * + B32_VEC_ELM_NUM], + INVALID_INDEX, + mask0, + forRemain, + 1, + B32_VEC_REPEAT_STRIDE); + } + AscendC::PipeBarrier(); +} + +/** + src: logits和索引,前logitsNum为logits,后logitsNum为索引 + tmp: 计算使用到的临时空间,大小与src一致 + logitsNum: 排序的元素个数, 暂只支持[128,256,384,512,1024,2048] + */ +__aicore__ inline void SortAll(LocalTensor& src, + LocalTensor& tmp, + int64_t logitsNum) { + int64_t sort32Repeats = logitsNum / BLOCK_BYTES; + AscendC::Sort32( + tmp, src, src[logitsNum].ReinterpretCast(), sort32Repeats); + AscendC::PipeBarrier(); + + int64_t mrgGroups = sort32Repeats; + int64_t mrgElements = BLOCK_BYTES; + int64_t i = 0; + AscendC::LocalTensor srcTensor; + AscendC::LocalTensor dstTensor; + while (true) { + if (i % CONST_TWO == 0) { + srcTensor = tmp; + dstTensor = src; + } else { + srcTensor = src; + dstTensor = tmp; + } + AscendC::MrgSort4Info params; + params.elementLengths[0] = mrgElements; + params.elementLengths[MRG_QUE_1] = mrgElements; + params.elementLengths[MRG_QUE_2] = mrgElements; + params.elementLengths[MRG_QUE_3] = mrgElements; + params.ifExhaustedSuspension = false; + params.validBit = 0b1111; + + AscendC::MrgSortSrcList srcList; + srcList.src1 = srcTensor[0]; + srcList.src2 = srcTensor[MRG_QUE_1 * VALUE_AND_INDEX_NUM * mrgElements]; + srcList.src3 = srcTensor[MRG_QUE_2 * VALUE_AND_INDEX_NUM * mrgElements]; + srcList.src4 = srcTensor[MRG_QUE_3 * VALUE_AND_INDEX_NUM * mrgElements]; + if (mrgGroups <= MRG_BLOCK_4) { + params.repeatTimes = 1; + if (mrgGroups == 1) { + break; + } else if (mrgGroups == MRG_BLOCK_2) { + params.validBit = 0b0011; + } else if (mrgGroups == MRG_BLOCK_3) { + params.validBit = 0b0111; + } else if (mrgGroups == MRG_BLOCK_4) { + params.validBit = 0b1111; + } + AscendC::MrgSort(dstTensor, srcList, params); + AscendC::PipeBarrier(); + i += 1; + break; + } else { + params.repeatTimes = mrgGroups / MRG_BLOCK_4; + AscendC::MrgSort(dstTensor, srcList, params); + i += 1; + mrgElements = mrgElements * MRG_BLOCK_4; + mrgGroups = mrgGroups / MRG_BLOCK_4; + } + AscendC::PipeBarrier(); + } + if (i % CONST_TWO == 0) { + // 尾部回拷与 MergeSort 同类问题: 若该 UB->UB DataCopy 落 MTE 管道, 其后的 + // PipeBarrier 不构成 fence, 调用方随后对 src 的 V 管道 MrgSort 读 + // (合并到 globalTopkUb_/globalBlockTopkUb_) 存在调度敏感竞态。改为 int32 + // 视图 Adds(+0) 位精确回拷, 全程 V 管道受 PipeBarrier 约束; 顺带避免 float + // vadd 把 -1 (0xFFFFFFFF, 负符号 NaN) 规范化成 0x7FFFFFFF 而破坏 + // (value,index) 对的位型。 + int32_t copyNum = static_cast(logitsNum * VALUE_AND_INDEX_NUM); + AscendC::LocalTensor dstI = + src.template ReinterpretCast(); + AscendC::LocalTensor srcI = + tmp.template ReinterpretCast(); + for (int32_t off = 0; off < copyNum; off += B32_VEC_ELM_NUM) { + AscendC::Adds(dstI[off], srcI[off], 0, B32_VEC_ELM_NUM); + } + AscendC::PipeBarrier(); + } +} + +/** + mrgDst: 合并进的Tensor + mrgSrc: 待合并的Tensor + tmpTensor:空间为mrgDst+mrgSrc + */ +__aicore__ inline void MergeSort(const LocalTensor& mrgDst, + int32_t mrgDstNum, + LocalTensor& mrgSrc, + int32_t mrgSrcNum, + LocalTensor& tmpTensor) { + AscendC::MrgSort4Info params; + params.elementLengths[0] = mrgSrcNum; + params.elementLengths[1] = mrgDstNum; + params.ifExhaustedSuspension = false; + params.validBit = 0b0011; + params.repeatTimes = 1; + + AscendC::MrgSortSrcList srcList; + srcList.src1 = mrgSrc; + srcList.src2 = mrgDst; + + AscendC::MrgSort(tmpTensor, srcList, params); + AscendC::PipeBarrier(); + AscendC::DataCopy(mrgDst, tmpTensor, mrgDstNum * VALUE_AND_INDEX_NUM); + AscendC::PipeBarrier(); +} + +__aicore__ inline void ExtractIndex(const LocalTensor& idxULocal, + const LocalTensor& sortLocal, + int64_t extractNum) { + AscendC::GatherMaskParams gatherMaskParams; + gatherMaskParams.repeatTimes = + Ceil(extractNum * sizeof(float) * VALUE_AND_INDEX_NUM, VEC_REPEAT_BYTES); + gatherMaskParams.src0BlockStride = 1; + gatherMaskParams.src0RepeatStride = B32_VEC_REPEAT_STRIDE; + gatherMaskParams.src1RepeatStride = 0; + uint64_t rsvdCnt = 0; // 用于保存筛选后保留下来的元素个数 + uint8_t src1Pattern = 2; // 固定模式2,表示筛选出奇数索引的数 + AscendC::GatherMask(idxULocal, + sortLocal, + src1Pattern, + false, + static_cast(0), + gatherMaskParams, + rsvdCnt); + AscendC::PipeBarrier(); +} + +/** + 候选路径专用合并: 与 MergeSort 语义相同, 但回拷 mrgDst 用纯向量 Adds (64 + 分块)。 MergeSort 尾部的 UB->UB DataCopy 若走 MTE 管道, 其后的 + PipeBarrier 不构成 fence, 跨 tile/跨行对累加器的下一次 MrgSort + 读存在调度敏感竞态 (实测多 tile 场景 tile1 读到 tile0 stale 数据, 累加器出现 + -inf 位型+8k 垃圾且 tile1 块整段缺失)。纯 V 回拷全程受 PipeBarrier 约束。 + */ +__aicore__ inline void MergeSortVecCopy(const LocalTensor& mrgDst, + int32_t mrgDstNum, + LocalTensor& mrgSrc, + int32_t mrgSrcNum, + LocalTensor& tmpTensor) { + AscendC::MrgSort4Info params; + params.elementLengths[0] = mrgSrcNum; + params.elementLengths[1] = mrgDstNum; + params.ifExhaustedSuspension = false; + params.validBit = 0b0011; + params.repeatTimes = 1; + + AscendC::MrgSortSrcList srcList; + srcList.src1 = mrgSrc; + srcList.src2 = mrgDst; + + AscendC::MrgSort(tmpTensor, srcList, params); + AscendC::PipeBarrier(); + // 回拷必须位精确: -1 (0xFFFFFFFF) 作为 float 是负符号 NaN, vadd 会规范化为 + // 0x7FFFFFFF; 用 int32 视图 Adds(+0) 保证 bit-exact 且全程 V 管道 (受 + // PipeBarrier fence) + int32_t copyNum = mrgDstNum * VALUE_AND_INDEX_NUM; + LocalTensor dstI = mrgDst.template ReinterpretCast(); + LocalTensor srcI = tmpTensor.template ReinterpretCast(); + for (int32_t off = 0; off < copyNum; off += 64) { + AscendC::Adds(dstI[off], srcI[off], 0, 64); + } + AscendC::PipeBarrier(); +} + +template +__aicore__ inline void SetWaitFlag(HardEvent evt) { + event_t eventId = static_cast(GetTPipePtr()->FetchEventID(evt)); + AscendC::SetFlag(eventId); + AscendC::WaitFlag(eventId); +} + +} // namespace QLIV2VaServiceVec +#endif // QUANT_LIGHTNING_INDEXER_V2_VA_VECTOR_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h new file mode 100644 index 0000000000..47d2c04f77 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h @@ -0,0 +1,84 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_lightning_indexer_v2_metadata_va.h + * \brief + */ + +#ifndef QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_H +#define QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_H + +#include + +namespace optiling { + +// Constants +inline constexpr uint32_t AIC_CORE_MAX_NUM = 36; +inline constexpr uint32_t AIV_CORE_MAX_NUM = 72; +constexpr uint32_t QLI_V2_METADATA_TOTAL_SIZE = 1024; +using QLI_V2_METADATA_T = int32_t; + +inline constexpr uint32_t QLI_V2_METADATA_SIZE = 8; +inline constexpr uint32_t QLD_V2_METADATA_SIZE = 8; + +// LI Metadata Index Definitions +inline constexpr uint32_t QLI_V2_CORE_ENABLE_INDEX = 0; +inline constexpr uint32_t QLI_V2_BN2_START_INDEX = 1; +inline constexpr uint32_t QLI_V2_M_START_INDEX = 2; +inline constexpr uint32_t QLI_V2_S2_START_INDEX = 3; +inline constexpr uint32_t QLI_V2_BN2_END_INDEX = 4; +inline constexpr uint32_t QLI_V2_M_END_INDEX = 5; +inline constexpr uint32_t QLI_V2_S2_END_INDEX = 6; +inline constexpr uint32_t QLI_V2_FIRST_QLD_V2_DATA_WORKSPACE_IDX_INDEX = 7; + +// LD Metadata Index Definitions +inline constexpr uint32_t QLD_V2_CORE_ENABLE_INDEX = 0; +inline constexpr uint32_t QLD_V2_BN2_IDX_INDEX = 1; +inline constexpr uint32_t QLD_V2_M_IDX_INDEX = 2; +inline constexpr uint32_t QLD_V2_WORKSPACE_IDX_INDEX = 3; +inline constexpr uint32_t QLD_V2_WORKSPACE_NUM_INDEX = 4; +inline constexpr uint32_t QLD_V2_M_START_INDEX = 5; +inline constexpr uint32_t QLD_V2_M_NUM_INDEX = 6; + +/** + * @brief 获取属性的绝对索引 + * @param coreIdx 核索引 + * @param metaIdx 元数据索引 + * @param isAIV 是否为AIV数据,默认为false + * @return 返回属性的绝对索引 + */ +#ifdef __CCE_AICORE__ +__aicore__ inline uint32_t GetAttrAbsIndex(uint32_t coreIdx, + uint32_t metaIdx, + bool isAIV = false) { + if (isAIV) { + return QLI_V2_METADATA_SIZE * AIC_CORE_MAX_NUM + + QLD_V2_METADATA_SIZE * coreIdx + metaIdx; + } else { + return QLI_V2_METADATA_SIZE * coreIdx + metaIdx; + } +} +#endif + +namespace detail { +struct QliV2Metadata { + uint32_t qliV2Metadata[AIC_CORE_MAX_NUM][QLI_V2_METADATA_SIZE]; + uint32_t qldV2Metadata[AIV_CORE_MAX_NUM][QLD_V2_METADATA_SIZE]; +}; +}; // namespace detail + +static_assert(QLI_V2_METADATA_TOTAL_SIZE * sizeof(QLI_V2_METADATA_T) >= + sizeof(detail::QliV2Metadata)); +}; // namespace optiling + +#endif // QUANT_LIGHTNING_INDEXER_V2_METADATA_VA_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_va_template_tiling_key.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_va_template_tiling_key.h new file mode 100644 index 0000000000..68150d77f8 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_va_template_tiling_key.h @@ -0,0 +1,241 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va_template_tiling_key.h + * \brief + */ + +#ifndef QUANT_LIGHTNING_INDEXER_V2_VA_TEMPLATE_TILING_KEY_H +#define QUANT_LIGHTNING_INDEXER_V2_VA_TEMPLATE_TILING_KEY_H + +#include "ascendc/host_api/tiling/template_argument.h" + +#define QLIV2Va_TPL_INT8 2 +#define QLIV2Va_TPL_INT32 3 +#define QLIV2Va_TPL_FLOAT8_E4M3FN 36 +#define QLIV2Va_TPL_HIFLOAT8 34 +#define QLIV2Va_TPL_FLOAT4_E2M1 40 +#define QLIV2Va_LAYOUT_BSND 0 +#define QLIV2Va_LAYOUT_TND 1 +#define QLIV2Va_LAYOUT_PA_BBND 2 + +#define ASCENDC_TPL_4_BW 4 + +// 模板参数支持的范围定义 +#if (__CCE_AICORE__ == 310) +ASCENDC_TPL_ARGS_DECL(XllmKernelQuantLightningIndexerV2Va, // 算子OpType + ASCENDC_TPL_DTYPE_DECL(DT_Q, + QLIV2Va_TPL_FLOAT8_E4M3FN, + QLIV2Va_TPL_HIFLOAT8, + QLIV2Va_TPL_FLOAT4_E2M1, + QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_DECL(DT_K, + QLIV2Va_TPL_FLOAT8_E4M3FN, + QLIV2Va_TPL_HIFLOAT8, + QLIV2Va_TPL_FLOAT4_E2M1, + QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_DECL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_DECL(PAGE_ATTENTION, 1, 0), + ASCENDC_TPL_UINT_DECL(Q_LAYOUT_T, + ASCENDC_TPL_4_BW, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND, + QLIV2Va_LAYOUT_TND), + ASCENDC_TPL_UINT_DECL(K_LAYOUT_T, + ASCENDC_TPL_4_BW, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND, + QLIV2Va_LAYOUT_TND, + QLIV2Va_LAYOUT_PA_BBND), ); +// 支持的模板参数组合 +// 用于调用GET_TPL_TILING_KEY获取TilingKey时,接口内部校验TilingKey是否合法 +ASCENDC_TPL_SEL( + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_FLOAT8_E4M3FN), + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_FLOAT8_E4M3FN), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND, + QLIV2Va_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_PA_BBND), ), + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_FLOAT8_E4M3FN), + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_FLOAT8_E4M3FN), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND), ), + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_FLOAT8_E4M3FN), + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_FLOAT8_E4M3FN), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_TND), ), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_HIFLOAT8), + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_HIFLOAT8), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND, + QLIV2Va_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_PA_BBND), ), + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_HIFLOAT8), + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_HIFLOAT8), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND), ), + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_HIFLOAT8), + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_HIFLOAT8), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_TND), ), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_FLOAT4_E2M1), + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_FLOAT4_E2M1), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND, + QLIV2Va_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_PA_BBND), ), + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_FLOAT4_E2M1), + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_FLOAT4_E2M1), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND), ), + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_FLOAT4_E2M1), + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_FLOAT4_E2M1), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_TND), ), + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND, + QLIV2Va_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_PA_BBND), ), + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND), ), + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_TND), )); +#else +ASCENDC_TPL_ARGS_DECL(XllmKernelQuantLightningIndexerV2Va, // 算子OpType + ASCENDC_TPL_DTYPE_DECL(DT_Q, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_DECL(DT_K, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_DECL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_DECL(PAGE_ATTENTION, 1, 0), + ASCENDC_TPL_UINT_DECL(Q_LAYOUT_T, + ASCENDC_TPL_4_BW, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND, + QLIV2Va_LAYOUT_TND), + ASCENDC_TPL_UINT_DECL(K_LAYOUT_T, + ASCENDC_TPL_4_BW, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND, + QLIV2Va_LAYOUT_TND, + QLIV2Va_LAYOUT_PA_BBND), ); +// 支持的模板参数组合 +// 用于调用GET_TPL_TILING_KEY获取TilingKey时,接口内部校验TilingKey是否合法 +ASCENDC_TPL_SEL( + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND, + QLIV2Va_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_PA_BBND), ), + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_BSND), ), + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_INT8), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + QLIV2Va_LAYOUT_TND), ), ); +#endif + +#endif // QUANT_LIGHTNING_INDEXER_V2_VA_TEMPLATE_TILING_KEY_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/xllm_kernel_quant_lightning_indexer_v2_va.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/xllm_kernel_quant_lightning_indexer_v2_va.cpp new file mode 100644 index 0000000000..31c135d8de --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/xllm_kernel_quant_lightning_indexer_v2_va.cpp @@ -0,0 +1,92 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file quant_lightning_indexer_v2_va.cpp + * \brief + */ + +#include "arch22/quant_lightning_indexer_v2_va_kernel_arch22.h" +#include "kernel_operator.h" +#include "lib/matmul_intf.h" +#include "quant_lightning_indexer_v2_va_template_tiling_key.h" +using namespace QLIV2VaKernel; +using namespace optiling::detail; + +// 含 candidate_topk_index 输入/输出 (两级TopK) +#define INVOKE_LI_CANDIDATE_OP_IMPL(templateClass, ...) \ + do { \ + templateClass> op; \ + op.Init(query, \ + key, \ + weights, \ + queryScale, \ + keyScale, \ + cuSeqlensQ, \ + cuSeqlensK, \ + sequsedQ, \ + sequsedK, \ + cmpResidualK, \ + blockTable, \ + outputIdxOffset, \ + metadata, \ + candidateTopkIndex, \ + sparseIndices, \ + sparseValues, \ + candidateTopkIndexOut, \ + user, \ + tiling_data, \ + &tPipe); \ + op.Process(); \ + } while (0) + +template +__global__ __aicore__ void xllm_kernel_quant_lightning_indexer_v2_va( + __gm__ uint8_t* query, + __gm__ uint8_t* key, + __gm__ uint8_t* weights, + __gm__ uint8_t* queryScale, + __gm__ uint8_t* keyScale, + __gm__ uint8_t* cuSeqlensQ, + __gm__ uint8_t* cuSeqlensK, + __gm__ uint8_t* sequsedQ, + __gm__ uint8_t* sequsedK, + __gm__ uint8_t* cmpResidualK, + __gm__ uint8_t* blockTable, + __gm__ uint8_t* outputIdxOffset, + __gm__ uint8_t* metadata, + __gm__ uint8_t* candidateTopkIndex, + __gm__ uint8_t* sparseIndices, + __gm__ uint8_t* sparseValues, + __gm__ uint8_t* candidateTopkIndexOut, + __gm__ uint8_t* workspace, + __gm__ uint8_t* tiling) { + TPipe tPipe; + __gm__ uint8_t* user = GetUserWorkspace(workspace); + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); + GET_TILING_DATA_WITH_STRUCT(QLIV2VaTilingData, tiling_data_in, tiling); + const QLIV2VaTilingData* __restrict tiling_data = &tiling_data_in; + + INVOKE_LI_CANDIDATE_OP_IMPL(QLIV2VaPreload, + int8_t, + int8_t, + float, + uint16_t, + int32_t, + PAGE_ATTENTION, + LI_LAYOUT(Q_LAYOUT_T), + LI_LAYOUT(K_LAYOUT_T)); +} diff --git a/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_def.cpp b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_def.cpp new file mode 100644 index 0000000000..7f0835c34f --- /dev/null +++ b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_def.cpp @@ -0,0 +1,39 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * Licensed under CANN Open Software License Agreement Version 2.0. + */ +#include "register/op_def_registry.h" + +namespace ops { +class XllmKernelRmsNormCastVa : public OpDef { + public: + explicit XllmKernelRmsNormCastVa(const char* name) : OpDef(name) { + this->Input("x") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("gamma") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Output("y") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("y_fp32") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Attr("epsilon").AttrType(OPTIONAL).Float(1e-6f); + this->AICore().AddConfig("ascend910b"); + this->AICore().AddConfig("ascend910_93"); + } +}; +OP_ADD(XllmKernelRmsNormCastVa); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_infershape.cpp b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_infershape.cpp new file mode 100644 index 0000000000..be91303e67 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_infershape.cpp @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * Licensed under CANN Open Software License Agreement Version 2.0. + */ +#include "log/log.h" +#include "register/op_impl_registry.h" + +namespace ops { +static ge::graphStatus InferShape4RmsNormCast( + gert::InferShapeContext* context) { + const gert::Shape* x_shape = context->GetInputShape(0); + gert::Shape* y_shape = context->GetOutputShape(0); + gert::Shape* y_fp32_shape = context->GetOutputShape(1); + OP_CHECK_NULL_WITH_CONTEXT(context, x_shape); + OP_CHECK_NULL_WITH_CONTEXT(context, y_shape); + OP_CHECK_NULL_WITH_CONTEXT(context, y_fp32_shape); + *y_shape = *x_shape; + *y_fp32_shape = *x_shape; + return ge::GRAPH_SUCCESS; +} + +static ge::graphStatus InferDataType4RmsNormCast( + gert::InferDataTypeContext* context) { + context->SetOutputDataType(0, context->GetInputDataType(0)); + context->SetOutputDataType(1, ge::DT_FLOAT); + return ge::GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(XllmKernelRmsNormCastVa) + .InferShape(InferShape4RmsNormCast) + .InferDataType(InferDataType4RmsNormCast); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_tiling.cpp b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_tiling.cpp new file mode 100644 index 0000000000..9bb9c0a9c2 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_tiling.cpp @@ -0,0 +1,86 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * Licensed under CANN Open Software License Agreement Version 2.0. + */ +#include "rms_norm_cast_va_tiling.h" + +#include + +namespace optiling { +namespace { +constexpr uint32_t FP16_KEY = 1; +constexpr uint32_t BF16_KEY = 3; +constexpr uint32_t B16_PER_BLOCK = 16; +constexpr uint64_t RESERVED_UB_BYTES = 1024; +constexpr uint64_t BYTES_PER_COLUMN = 12; // two b16 and two fp32 buffers + +ge::graphStatus Tiling4RmsNormCast(gert::TilingContext* context) { + const auto* x_shape_ptr = context->GetInputShape(0); + const auto* gamma_shape_ptr = context->GetInputShape(1); + OP_CHECK_NULL_WITH_CONTEXT(context, x_shape_ptr); + OP_CHECK_NULL_WITH_CONTEXT(context, gamma_shape_ptr); + const gert::Shape& x_shape = x_shape_ptr->GetStorageShape(); + const gert::Shape& gamma_shape = gamma_shape_ptr->GetStorageShape(); + OP_CHECK_IF( + x_shape.GetDimNum() < 1 || gamma_shape.GetDimNum() != 1, + OP_LOGE(context, "x must have rank >= 1 and gamma must have rank 1"), + return ge::GRAPH_FAILED); + + const uint32_t num_col = gamma_shape.GetShapeSize(); + OP_CHECK_IF( + num_col == 0 || x_shape.GetDim(x_shape.GetDimNum() - 1) != num_col, + OP_LOGE(context, "gamma must match the last dimension of x"), + return ge::GRAPH_FAILED); + const uint64_t total = x_shape.GetShapeSize(); + OP_CHECK_IF(total == 0 || total % num_col != 0, + OP_LOGE(context, "x must be non-empty"), + return ge::GRAPH_FAILED); + const uint32_t num_row = total / num_col; + + auto platform = platform_ascendc::PlatformAscendC(context->GetPlatformInfo()); + uint64_t ub_size = 0; + platform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ub_size); + const uint32_t num_col_aligned = + (num_col + B16_PER_BLOCK - 1) / B16_PER_BLOCK * B16_PER_BLOCK; + OP_CHECK_IF( + static_cast(num_col_aligned) * BYTES_PER_COLUMN > + ub_size - RESERVED_UB_BYTES, + OP_LOGE(context, + "last dimension is too large for the fused RMSNorm kernel"), + return ge::GRAPH_FAILED); + + const uint32_t core_num = platform.GetCoreNumAiv(); + const uint32_t used_core_num = std::min(num_row, core_num); + const uint32_t rows_per_core = (num_row + used_core_num - 1) / used_core_num; + const auto* attrs = context->GetAttrs(); + OP_CHECK_NULL_WITH_CONTEXT(context, attrs); + const float* epsilon = attrs->GetFloat(0); + OP_CHECK_NULL_WITH_CONTEXT(context, epsilon); + OP_CHECK_IF(*epsilon < 0.0f, + OP_LOGE(context, "epsilon must be non-negative"), + return ge::GRAPH_FAILED); + + const auto dtype = context->GetInputDesc(0)->GetDataType(); + OP_CHECK_IF(dtype != ge::DT_FLOAT16 && dtype != ge::DT_BF16, + OP_LOGE(context, "x only supports float16 and bfloat16"), + return ge::GRAPH_FAILED); + context->SetTilingKey(dtype == ge::DT_FLOAT16 ? FP16_KEY : BF16_KEY); + context->SetBlockDim(used_core_num); + + XllmKernelRmsNormCastTilingData tiling; + tiling.set_num_row(num_row); + tiling.set_num_col(num_col); + tiling.set_num_col_aligned(num_col_aligned); + tiling.set_rows_per_core(rows_per_core); + tiling.set_inv_num_col(1.0f / static_cast(num_col)); + tiling.set_epsilon(*epsilon); + tiling.SaveToBuffer(context->GetRawTilingData()->GetData(), + context->GetRawTilingData()->GetCapacity()); + context->GetRawTilingData()->SetDataSize(tiling.GetDataSize()); + context->GetWorkspaceSizes(1)[0] = 0; + return ge::GRAPH_SUCCESS; +} +} // namespace + +IMPL_OP_OPTILING(XllmKernelRmsNormCastVa).Tiling(Tiling4RmsNormCast); +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_tiling.h b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_tiling.h new file mode 100644 index 0000000000..deca1af39d --- /dev/null +++ b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_host/rms_norm_cast_va_tiling.h @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * Licensed under CANN Open Software License Agreement Version 2.0. + */ +#ifndef XLLM_OPS_RMS_NORM_CAST_TILING_H +#define XLLM_OPS_RMS_NORM_CAST_TILING_H + +#include "log/log.h" +#include "register/op_impl_registry.h" +#include "register/tilingdata_base.h" +#include "tiling/platform/platform_ascendc.h" + +namespace optiling { +BEGIN_TILING_DATA_DEF(XllmKernelRmsNormCastTilingData) +TILING_DATA_FIELD_DEF(uint32_t, num_row); +TILING_DATA_FIELD_DEF(uint32_t, num_col); +TILING_DATA_FIELD_DEF(uint32_t, num_col_aligned); +TILING_DATA_FIELD_DEF(uint32_t, rows_per_core); +TILING_DATA_FIELD_DEF(float, inv_num_col); +TILING_DATA_FIELD_DEF(float, epsilon); +END_TILING_DATA_DEF; + +struct RmsNormCastCompileInfo { + uint32_t total_core_num = 0; + uint64_t total_ub_size = 0; +}; + +REGISTER_TILING_DATA_CLASS(XllmKernelRmsNormCastVa, + XllmKernelRmsNormCastTilingData) +} // namespace optiling +#endif diff --git a/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/rms_norm_cast_va.h b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/rms_norm_cast_va.h new file mode 100644 index 0000000000..db0c87736f --- /dev/null +++ b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/rms_norm_cast_va.h @@ -0,0 +1,153 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * Licensed under CANN Open Software License Agreement Version 2.0. + */ +#ifndef XLLM_OPS_RMS_NORM_CAST_KERNEL_H +#define XLLM_OPS_RMS_NORM_CAST_KERNEL_H + +#include "rms_norm_cast_va_base.h" + +using namespace AscendC; +using namespace RmsNormCast; + +template +class KernelRmsNormCastVa { + public: + __aicore__ inline explicit KernelRmsNormCastVa(TPipe* pipe) : pipe_(pipe) {} + + __aicore__ inline void Init(GM_ADDR x, + GM_ADDR gamma, + GM_ADDR y, + GM_ADDR y_fp32, + const XllmKernelRmsNormCastTilingData* tiling) { + num_row_ = tiling->num_row; + num_col_ = tiling->num_col; + num_col_aligned_ = tiling->num_col_aligned; + rows_per_core_ = tiling->rows_per_core; + inv_num_col_ = tiling->inv_num_col; + epsilon_ = tiling->epsilon; + block_idx_ = GetBlockIdx(); + const uint32_t row_begin = block_idx_ * rows_per_core_; + row_end_ = Min(num_row_, row_begin + rows_per_core_); + row_begin_ = row_begin; + + x_gm_.SetGlobalBuffer((__gm__ T*)x, num_row_ * num_col_); + gamma_gm_.SetGlobalBuffer((__gm__ T*)gamma, num_col_); + y_gm_.SetGlobalBuffer((__gm__ T*)y, num_row_ * num_col_); + y_fp32_gm_.SetGlobalBuffer((__gm__ float*)y_fp32, num_row_ * num_col_); + + pipe_->InitBuffer(x_buf_, num_col_aligned_ * sizeof(T)); + pipe_->InitBuffer(gamma_buf_, num_col_aligned_ * sizeof(T)); + pipe_->InitBuffer(fp32_buf_, num_col_aligned_ * sizeof(float)); + pipe_->InitBuffer(work_buf_, num_col_aligned_ * sizeof(float)); + pipe_->InitBuffer(reduce_buf_, NUM_PER_REP_FP32 * sizeof(float)); + } + + __aicore__ inline void Process() { + if (row_begin_ >= num_row_) { + return; + } + LocalTensor gamma_local = gamma_buf_.Get(); + DataCopyCustom(gamma_local, gamma_gm_, num_col_); + event_t gamma_ready = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(gamma_ready); + WaitFlag(gamma_ready); + + for (uint32_t row = row_begin_; row < row_end_; ++row) { + ProcessRow(row, gamma_local); + } + } + + private: + __aicore__ inline void ProcessRow(uint32_t row, LocalTensor& gamma_local) { + LocalTensor x_local = x_buf_.Get(); + LocalTensor x_fp32 = fp32_buf_.Get(); + LocalTensor work = work_buf_.Get(); + LocalTensor reduce = reduce_buf_.Get(); + const uint32_t offset = row * num_col_; + + DataCopyCustom(x_local, x_gm_[offset], num_col_); + event_t x_ready = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(x_ready); + WaitFlag(x_ready); + Cast(x_fp32, x_local, RoundMode::CAST_NONE, num_col_); + PipeBarrier(); + Mul(work, x_fp32, x_fp32, num_col_); + PipeBarrier(); + Muls(work, work, inv_num_col_, num_col_); + PipeBarrier(); + ReduceSumCustom(work, work, reduce, num_col_); + PipeBarrier(); + Adds(work, work, epsilon_, 1); + PipeBarrier(); + Sqrt(work, work, 1); + Duplicate(reduce, 1.0f, 1); + PipeBarrier(); + Div(work, reduce, work, 1); + PipeBarrier(); + + event_t vector_to_scalar = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_S)); + SetFlag(vector_to_scalar); + WaitFlag(vector_to_scalar); + const float rstd = work.GetValue(0); + event_t scalar_to_vector = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); + SetFlag(scalar_to_vector); + WaitFlag(scalar_to_vector); + + Muls(x_fp32, x_fp32, rstd, num_col_); + PipeBarrier(); + if constexpr (IsSame::value) { + Cast(x_local, x_fp32, RoundMode::CAST_NONE, num_col_); + PipeBarrier(); + Mul(x_local, x_local, gamma_local, num_col_); + } else { + Cast(work, gamma_local, RoundMode::CAST_NONE, num_col_); + PipeBarrier(); + Mul(x_fp32, x_fp32, work, num_col_); + PipeBarrier(); + Cast(x_local, x_fp32, RoundMode::CAST_RINT, num_col_); + } + PipeBarrier(); + + // The FP32 result deliberately widens the rounded low-precision + // result. HashTopK therefore sees exactly the same values as the + // original RMSNorm followed by Tensor.float(). + Cast(x_fp32, x_local, RoundMode::CAST_NONE, num_col_); + PipeBarrier(); + event_t output_ready = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_MTE3)); + SetFlag(output_ready); + WaitFlag(output_ready); + DataCopyCustom(y_gm_[offset], x_local, num_col_); + DataCopyCustom(y_fp32_gm_[offset], x_fp32, num_col_); + event_t output_done = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE3_MTE2)); + SetFlag(output_done); + WaitFlag(output_done); + } + + TPipe* pipe_; + TBuf x_buf_; + TBuf gamma_buf_; + TBuf fp32_buf_; + TBuf work_buf_; + TBuf reduce_buf_; + GlobalTensor x_gm_; + GlobalTensor gamma_gm_; + GlobalTensor y_gm_; + GlobalTensor y_fp32_gm_; + uint32_t num_row_; + uint32_t num_col_; + uint32_t num_col_aligned_; + uint32_t rows_per_core_; + uint32_t row_begin_; + uint32_t row_end_; + uint32_t block_idx_; + float inv_num_col_; + float epsilon_; +}; +#endif diff --git a/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/rms_norm_cast_va_base.h b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/rms_norm_cast_va_base.h new file mode 100644 index 0000000000..b8e991f131 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/rms_norm_cast_va_base.h @@ -0,0 +1,113 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * Licensed under CANN Open Software License Agreement Version 2.0. + */ +#ifndef XLLM_OPS_RMS_NORM_CAST_BASE_H +#define XLLM_OPS_RMS_NORM_CAST_BASE_H + +#include "kernel_operator.h" + +namespace RmsNormCast { +using namespace AscendC; + +#if defined(__CCE_AICORE__) && __CCE_AICORE__ != 220 && __CCE_AICORE__ != 310 +#define bfloat16_t int16_t +#endif + +constexpr int32_t NUM_PER_REP_FP32 = 64; + +template +__aicore__ inline T Min(T left, T right) { + return left < right ? left : right; +} + +template +struct IntegralConstant { + static constexpr Tp value = value_; +}; +using TrueType = IntegralConstant; +using FalseType = IntegralConstant; +template +struct IsSame : public FalseType {}; +template +struct IsSame : public TrueType {}; + +__aicore__ inline void ReduceSumCustom(const LocalTensor& dst, + const LocalTensor& src, + const LocalTensor& work, + int32_t count) { + constexpr uint64_t mask = NUM_PER_REP_FP32; + const int32_t repeat_times = count / NUM_PER_REP_FP32; + const int32_t tail_count = count % NUM_PER_REP_FP32; + const int32_t body_count = repeat_times * NUM_PER_REP_FP32; + BinaryRepeatParams params; + params.src0RepStride = ONE_REPEAT_BYTE_SIZE / ONE_BLK_SIZE; + params.src0BlkStride = 1; + params.src1RepStride = 0; + params.src1BlkStride = 1; + params.dstRepStride = 0; + params.dstBlkStride = 1; + Duplicate(work, 0.0f, NUM_PER_REP_FP32); + PipeBarrier(); + if (repeat_times > 0) { + Add(work, src, work, mask, repeat_times, params); + PipeBarrier(); + } + if (tail_count != 0) { + Add(work, src[body_count], work, tail_count, 1, params); + PipeBarrier(); + } + AscendCUtils::SetMask(NUM_PER_REP_FP32); +#if defined(__CCE_AICORE__) && __CCE_AICORE__ == 220 + if (g_coreType == AIV) { + WholeReduceSum(dst, work, MASK_PLACEHOLDER, 1, 0, 1, 0); + } +#elif !(defined(__NPU_ARCH__) && __NPU_ARCH__ == 3003) + WholeReduceSum( + dst, work, MASK_PLACEHOLDER, 1, 1, 1, DEFAULT_REPEAT_STRIDE); +#endif + PipeBarrier(); +} + +template +__aicore__ inline void DataCopyCustom(const U& dst, + const R& src, + uint32_t count) { +#if (defined(__CCE_AICORE__) && __CCE_AICORE__ == 220) || \ + (defined(__NPU_ARCH__) && __NPU_ARCH__ == 3003) + DataCopyParams params; + params.blockLen = count * sizeof(T); + params.blockCount = 1; + if constexpr (IsSame>::value) { + DataCopyPadParams pad_params; + DataCopyPad(dst, src, params, pad_params); + } else { + DataCopyPad(dst, src, params); + } +#else + const int32_t values_per_block = ONE_BLK_SIZE / sizeof(T); + if (count % values_per_block == 0) { + DataCopy(dst, src, count); + } else if constexpr (IsSame>::value) { + DataCopy(dst, src, AlignUp(count, values_per_block)); + } else { + if (count < values_per_block) { + DataCopy(dst, src, values_per_block); + } else { + const int32_t aligned_count = count / values_per_block * values_per_block; + DataCopy(dst, src, aligned_count); + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + for (int32_t i = 0; i < values_per_block; ++i) { + const T value = src.GetValue(count - values_per_block + i); + src.SetValue(i, value); + } + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + DataCopy(dst[count - values_per_block], src, values_per_block); + } + } +#endif +} +} // namespace RmsNormCast +#endif diff --git a/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/xllm_kernel_rms_norm_cast_va.cpp b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/xllm_kernel_rms_norm_cast_va.cpp new file mode 100644 index 0000000000..f1d94388c2 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/rms_norm_cast_va/op_kernel/xllm_kernel_rms_norm_cast_va.cpp @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * Licensed under CANN Open Software License Agreement Version 2.0. + */ +#include "rms_norm_cast_va.h" + +using namespace AscendC; + +#define RUN_RMS_NORM_CAST(TYPE) \ + do { \ + KernelRmsNormCastVa op(&pipe); \ + op.Init(x, gamma, y, y_fp32, &tiling_data); \ + op.Process(); \ + } while (0) + +extern "C" __global__ __aicore__ void xllm_kernel_rms_norm_cast_va( + GM_ADDR x, + GM_ADDR gamma, + GM_ADDR y, + GM_ADDR y_fp32, + GM_ADDR workspace, + GM_ADDR tiling) { + TPipe pipe; + GET_TILING_DATA(tiling_data, tiling); + if (TILING_KEY_IS(1)) { + RUN_RMS_NORM_CAST(half); + } else if (TILING_KEY_IS(3)) { +#if !(defined(__NPU_ARCH__) && __NPU_ARCH__ == 3003) + RUN_RMS_NORM_CAST(bfloat16_t); +#endif + } +} diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_kernel_aicpu/sparse_attn_sharedkv_metadata_aicpu.json b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_kernel_aicpu/sparse_attn_sharedkv_metadata_aicpu.json index 2e94516021..b3b1174a2f 100644 --- a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_kernel_aicpu/sparse_attn_sharedkv_metadata_aicpu.json +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_kernel_aicpu/sparse_attn_sharedkv_metadata_aicpu.json @@ -6,7 +6,7 @@ "flagAsync":"False", "flagPartial":"False", "functionName":"RunCpuKernel", - "kernelSo":"libxllm_kernel_aicpu.so", + "kernelSo":"libmath_aicpu_kernels.so", "opKernelLib":"CUSTAICPUKernel", "userDefined":"True", "workspaceSize":"100" diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/SOURCE.txt b/xllm-kernel/csrc/ascendc/sparse_flash_mla/SOURCE.txt new file mode 100644 index 0000000000..08d92a2435 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/SOURCE.txt @@ -0,0 +1,7 @@ +Source: https://gitcode.com/cann/ops-transformer, commit 814116886e54f04053f8870a400dfd31c46bf53c +Directory: attention/sparse_flash_mla +License: CANN Open Software License Agreement Version 2.0 (see CANN_LICENSE.txt). +The xllm-kernel package builds the Ascend A3 implementation with a distinct +operator name. The metadata protocol and kernel inputs follow the upstream ABI. +The CANN 9.0 logging compatibility header is adapted from +mc2/common/utils/mc2_log_compat.h at the same revision. diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/base_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/base_checker.cpp new file mode 100644 index 0000000000..bf86fe6b41 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/base_checker.cpp @@ -0,0 +1,240 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#include +#include + +#include "base_checker_sparse_flash_mla.h" +#include "sparse_flash_mla/op_host/common/log.h" + +namespace optiling { +namespace sparse_mla_checker { +namespace { +const char* GetOpName(const CheckContext& context) { + return context.opName == nullptr ? "SparseMla" : context.opName; +} + +std::string ShapeToString(const gert::Shape* shape) { + if (shape == nullptr) { + return "nullptr"; + } + std::ostringstream oss; + oss << "("; + for (size_t i = 0; i < shape->GetDimNum(); ++i) { + if (i > 0) { + oss << ", "; + } + oss << shape->GetDim(i); + } + oss << ")"; + return oss.str(); +} + +template +std::string ValuesToString(std::initializer_list values) { + std::ostringstream oss; + bool first = true; + for (const auto value : values) { + if (!first) { + oss << ", "; + } + oss << static_cast(value); + first = false; + } + return oss.str(); +} +} // namespace + +ge::graphStatus BaseChecker::CheckSinglePara( + const CheckContext& context) const { + (void)context; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus BaseChecker::CheckParaExistence( + const CheckContext& context) const { + (void)context; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus BaseChecker::CheckFeature(const CheckContext& context) const { + (void)context; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus BaseChecker::CheckMultiPara(const CheckContext& context) const { + (void)context; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus BaseChecker::CheckTensorDesc( + const CheckContext& context, + const TensorParam& param, + const char* name, + std::initializer_list dtypes) const { + if (!param.present) { + return ge::GRAPH_SUCCESS; + } + OP_CHECK_IF(param.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + GetOpName(context), name, "Tensor desc cannot be null"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + param.desc->GetOriginFormat() != ge::FORMAT_ND, + OP_LOGE_FOR_INVALID_FORMAT( + GetOpName(context), + name, + std::to_string(static_cast(param.desc->GetOriginFormat())) + .c_str(), + "ND"), + return ge::GRAPH_FAILED); + const ge::DataType actual = param.desc->GetDataType(); + const std::string expectedDtypes = ValuesToString(dtypes); + OP_CHECK_IF(std::find(dtypes.begin(), dtypes.end(), actual) == dtypes.end(), + OP_LOGE_FOR_INVALID_DTYPE( + GetOpName(context), + name, + std::to_string(static_cast(actual)).c_str(), + expectedDtypes.c_str()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus BaseChecker::CheckDimNum( + const CheckContext& context, + const TensorParam& param, + const char* name, + std::initializer_list dimNums) const { + if (!param.present) { + return ge::GRAPH_SUCCESS; + } + OP_CHECK_IF(param.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + GetOpName(context), name, "Tensor shape cannot be null"), + return ge::GRAPH_FAILED); + const size_t actual = param.shape->GetDimNum(); + const std::string expectedDimNums = ValuesToString(dimNums); + OP_CHECK_IF( + std::find(dimNums.begin(), dimNums.end(), actual) == dimNums.end(), + OP_LOGE_FOR_INVALID_SHAPEDIM(GetOpName(context), + name, + std::to_string(actual).c_str(), + expectedDimNums.c_str()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus BaseChecker::CheckNoEmptyDim(const CheckContext& context, + const TensorParam& param, + const char* name) const { + if (!param.present) { + return ge::GRAPH_SUCCESS; + } + OP_CHECK_IF(param.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + GetOpName(context), name, "Tensor shape cannot be null"), + return ge::GRAPH_FAILED); + for (size_t i = 0; i < param.shape->GetDimNum(); ++i) { + OP_CHECK_IF(param.shape->GetDim(i) <= 0, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + GetOpName(context), + name, + ShapeToString(param.shape).c_str(), + "Each dimension must be greater than 0"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus BaseChecker::CheckShape( + const CheckContext& context, + const TensorParam& param, + const char* name, + std::initializer_list expected) const { + if (!param.present) { + return ge::GRAPH_SUCCESS; + } + OP_CHECK_IF( + param.shape == nullptr || param.shape->GetDimNum() != expected.size(), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + GetOpName(context), + name, + ShapeToString(param.shape).c_str(), + "Shape dim number does not match the documented shape"), + return ge::GRAPH_FAILED); + size_t index = 0; + for (const int64_t value : expected) { + OP_CHECK_IF(param.shape->GetDim(index) != value, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + GetOpName(context), + name, + ShapeToString(param.shape).c_str(), + ("Dimension " + std::to_string(index) + " must be " + + std::to_string(value)) + .c_str()), + return ge::GRAPH_FAILED); + ++index; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus BaseChecker::CheckSameShape(const CheckContext& context, + const TensorParam& left, + const char* leftName, + const TensorParam& right, + const char* rightName) const { + OP_CHECK_IF(left.shape == nullptr || right.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + GetOpName(context), + (std::string(leftName) + " and " + rightName).c_str(), + "Tensor shape cannot be null"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + left.shape->GetDimNum() != right.shape->GetDimNum(), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + GetOpName(context), + (std::string(leftName) + " and " + rightName).c_str(), + (ShapeToString(left.shape) + " and " + ShapeToString(right.shape)) + .c_str(), + "Tensor dim numbers must be the same"), + return ge::GRAPH_FAILED); + for (size_t i = 0; i < left.shape->GetDimNum(); ++i) { + OP_CHECK_IF( + left.shape->GetDim(i) != right.shape->GetDim(i), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + GetOpName(context), + (std::string(leftName) + " and " + rightName).c_str(), + (ShapeToString(left.shape) + " and " + ShapeToString(right.shape)) + .c_str(), + ("Dimension " + std::to_string(i) + " must be the same").c_str()), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +int64_t BaseChecker::GetDim(const TensorParam& param, size_t index) const { + if (param.shape == nullptr || index >= param.shape->GetDimNum()) { + return -1; + } + return param.shape->GetDim(index); +} + +bool BaseChecker::CanOmitSequsedOriKv(const CheckContext& context) const { + return context.oriTopkLength.present; +} + +bool BaseChecker::CanOmitSequsedCmpKv(const CheckContext& context) const { + return context.cmpTopkLength.present; +} + +} // namespace sparse_mla_checker +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/base_checker_sparse_flash_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/base_checker_sparse_flash_mla.h new file mode 100644 index 0000000000..ed99879d71 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/base_checker_sparse_flash_mla.h @@ -0,0 +1,64 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef SPARSE_MLA_BASE_CHECKER_SPARSE_FLASH_MLA_H +#define SPARSE_MLA_BASE_CHECKER_SPARSE_FLASH_MLA_H + +#include +#include + +#include "checker_context.h" + +namespace optiling { +namespace sparse_mla_checker { + +class BaseChecker { + public: + BaseChecker() = default; + virtual ~BaseChecker() = default; + + virtual ge::graphStatus CheckSinglePara(const CheckContext& context) const; + virtual ge::graphStatus CheckParaExistence(const CheckContext& context) const; + virtual ge::graphStatus CheckFeature(const CheckContext& context) const; + virtual ge::graphStatus CheckMultiPara(const CheckContext& context) const; + + protected: + ge::graphStatus CheckTensorDesc( + const CheckContext& context, + const TensorParam& param, + const char* name, + std::initializer_list dtypes) const; + ge::graphStatus CheckDimNum(const CheckContext& context, + const TensorParam& param, + const char* name, + std::initializer_list dimNums) const; + ge::graphStatus CheckNoEmptyDim(const CheckContext& context, + const TensorParam& param, + const char* name) const; + ge::graphStatus CheckShape(const CheckContext& context, + const TensorParam& param, + const char* name, + std::initializer_list expected) const; + ge::graphStatus CheckSameShape(const CheckContext& context, + const TensorParam& left, + const char* leftName, + const TensorParam& right, + const char* rightName) const; + int64_t GetDim(const TensorParam& param, size_t index) const; + bool CanOmitSequsedOriKv(const CheckContext& context) const; + bool CanOmitSequsedCmpKv(const CheckContext& context) const; +}; + +} // namespace sparse_mla_checker +} // namespace optiling + +#endif // SPARSE_MLA_BASE_CHECKER_SPARSE_FLASH_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_adapter.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_adapter.h new file mode 100644 index 0000000000..b23d7c58ad --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_adapter.h @@ -0,0 +1,103 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef SPARSE_MLA_CHECKER_ADAPTER_H +#define SPARSE_MLA_CHECKER_ADAPTER_H + +#include "checker_context.h" + +namespace optiling { +namespace sparse_mla_checker { + +template +void PopulateOptionalTensorParam(gert::TilingContext* context, + uint32_t index, + OptionalParam& param) { + param.desc = context->GetOptionalInputDesc(index); + param.shape = context->GetOptionalInputShape(index); + param.tensor = context->GetOptionalInputTensor(index); +} + +template +TensorParam MakeRequiredTensor(const RequiredParam& param) { + return {param.desc, + param.shape == nullptr ? nullptr : ¶m.shape->GetStorageShape(), + param.desc != nullptr || param.shape != nullptr}; +} + +template +TensorParam MakeOptionalTensor(const OptionalParam& param) { + const gert::Shape* shape = + param.shape == nullptr ? nullptr : ¶m.shape->GetStorageShape(); + if (shape == nullptr && param.tensor != nullptr) { + shape = ¶m.tensor->GetStorageShape(); + } + return {param.desc, shape, shape != nullptr}; +} + +inline int64_t GetLastDim(const TensorParam& param) { + return param.shape == nullptr || param.shape->GetDimNum() == 0 + ? 0 + : param.shape->GetDim(param.shape->GetDimNum() - 1); +} + +template +void PopulateCommonContext(CheckContext& context, const TilingInfo& info) { + const auto& param = info.opParamInfo; + context.opName = info.opName; + context.q = MakeRequiredTensor(param.q); + context.oriKv = MakeOptionalTensor(param.oriKv); + context.cmpKv = MakeOptionalTensor(param.cmpKv); + context.oriSparseIndices = MakeOptionalTensor(param.oriSparseIndices); + context.cmpSparseIndices = MakeOptionalTensor(param.cmpSparseIndices); + context.oriBlockTable = MakeOptionalTensor(param.oriBlockTable); + context.cmpBlockTable = MakeOptionalTensor(param.cmpBlockTable); + context.cuSeqlensQ = MakeOptionalTensor(param.cuSeqLensQ); + context.cuSeqlensOriKv = MakeOptionalTensor(param.cuSeqLensOriKv); + context.cuSeqlensCmpKv = MakeOptionalTensor(param.cuSeqLensCmpKv); + context.sequsedQ = MakeOptionalTensor(param.seqUsedQ); + context.sequsedOriKv = MakeOptionalTensor(param.sequsedOriKv); + context.sequsedCmpKv = MakeOptionalTensor(param.sequsedCmpKv); + context.cmpResidualKv = MakeOptionalTensor(param.cmpResidualKv); + context.oriTopkLength = MakeOptionalTensor(param.oriTopkLength); + context.cmpTopkLength = MakeOptionalTensor(param.cmpTopkLength); + context.sinks = MakeOptionalTensor(param.sinks); + context.metadata = MakeOptionalTensor(param.metadata); + context.attentionOut = MakeRequiredTensor(param.attnOut); + context.softmaxLse = MakeRequiredTensor(param.softmaxLse); + + context.qLayout = static_cast(static_cast(info.qLayout)); + context.kvLayout = static_cast(static_cast(info.kvLayout)); + context.npuArch = info.npuArch; + context.bSize = info.bSize; + context.qNumHeads = info.n1Size; + context.kvNumHeads = info.n2Size; + context.qSeqSize = info.s1Size; + context.qTotalSize = info.qTSize; + context.oriBlockSize = info.oriBlockSize; + context.cmpBlockSize = info.cmpBlockSize; + context.oriTopk = GetLastDim(context.oriSparseIndices); + context.cmpTopk = GetLastDim(context.cmpSparseIndices); + context.softmaxScale = info.softmaxScale; + context.cmpRatio = info.cmpRatio; + context.oriMaskMode = static_cast(info.oriMaskMode); + context.cmpMaskMode = static_cast(info.cmpMaskMode); + context.oriWinLeft = info.oriWinLeft; + context.oriWinRight = info.oriWinRight; + context.topkValueMode = info.topkValueMode; + context.returnSoftmaxLse = info.returnSoftmaxLse; +} + +} // namespace sparse_mla_checker +} // namespace optiling + +#endif // SPARSE_MLA_CHECKER_ADAPTER_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_context.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_context.h new file mode 100644 index 0000000000..195f45d934 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_context.h @@ -0,0 +1,108 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef SPARSE_MLA_CHECKER_CONTEXT_H +#define SPARSE_MLA_CHECKER_CONTEXT_H + +#include +#include + +#include "exe_graph/runtime/tiling_context.h" +#include "platform/platform_info.h" +#include "platform/soc_spec.h" +#include "sparse_flash_mla/op_host/common/log.h" +#include "tiling/tiling_api.h" + +namespace optiling { +namespace sparse_mla_checker { + +enum class OperatorVariant : uint32_t { + SPARSE = 0, + MIXED_QUANT = 1, + QUANT = 2, +}; + +enum class Layout : uint32_t { + BSND = 0, + TND = 1, + PA_BBND = 2, +}; + +struct TensorParam { + const gert::CompileTimeTensorDesc* desc = nullptr; + const gert::Shape* shape = nullptr; + bool present = false; +}; + +struct CheckContext { + const char* opName = nullptr; + OperatorVariant variant = OperatorVariant::SPARSE; + NpuArch npuArch = NpuArch::DAV_2201; + + TensorParam q; + TensorParam oriKv; + TensorParam cmpKv; + TensorParam qDescale; + TensorParam oriKvDescale; + TensorParam cmpKvDescale; + TensorParam oriSparseIndices; + TensorParam cmpSparseIndices; + TensorParam oriBlockTable; + TensorParam cmpBlockTable; + TensorParam cuSeqlensQ; + TensorParam cuSeqlensOriKv; + TensorParam cuSeqlensCmpKv; + TensorParam sequsedQ; + TensorParam sequsedOriKv; + TensorParam sequsedCmpKv; + TensorParam cmpResidualKv; + TensorParam oriTopkLength; + TensorParam cmpTopkLength; + TensorParam sinks; + TensorParam metadata; + TensorParam attentionOut; + TensorParam softmaxLse; + + Layout qLayout = Layout::BSND; + Layout kvLayout = Layout::BSND; + int64_t bSize = 0; + int64_t qNumHeads = 0; + int64_t kvNumHeads = 0; + int64_t qSeqSize = 0; + int64_t qTotalSize = 0; + int64_t qHeadDim = 0; + int64_t oriKvHeadDim = 0; + int64_t cmpKvHeadDim = 0; + int64_t oriBlockSize = 0; + int64_t cmpBlockSize = 0; + int64_t oriTopk = 0; + int64_t cmpTopk = 0; + + int64_t quantMode = 0; + int64_t ropeHeadDim = 0; + float softmaxScale = 1.0F; + int64_t cmpRatio = 1; + int64_t oriMaskMode = 0; + int64_t cmpMaskMode = 0; + int64_t oriWinLeft = -1; + int64_t oriWinRight = -1; + int64_t topkValueMode = 1; + bool returnSoftmaxLse = false; + + std::vector oriKvStrides; + std::vector cmpKvStrides; +}; + +} // namespace sparse_mla_checker +} // namespace optiling + +#endif // SPARSE_MLA_CHECKER_CONTEXT_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_runner.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_runner.cpp new file mode 100644 index 0000000000..e44cd29b6f --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_runner.cpp @@ -0,0 +1,63 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#include "checker_runner.h" + +#include "common_checker_sparse_flash_mla.h" +#include "mask_checker_sparse_flash_mla.h" +#include "metadata_checker_sparse_flash_mla.h" +#include "paged_attention_checker_sparse_flash_mla.h" +#include "seq_len_checker_sparse_flash_mla.h" +#include "sinks_checker_sparse_flash_mla.h" +#include "softmax_lse_checker_sparse_flash_mla.h" +#include "sparse_compression_checker.h" + +namespace optiling { +namespace sparse_mla_checker { + +void CheckerRunner::Add(std::unique_ptr checker) { + checkers_.push_back(std::move(checker)); +} + +ge::graphStatus CheckerRunner::Run(CheckMethod method, + const CheckContext& context) const { + for (const auto& checker : checkers_) { + if ((checker.get()->*method)(context) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CheckerRunner::Process(const CheckContext& context) const { + if (Run(&BaseChecker::CheckSinglePara, context) != ge::GRAPH_SUCCESS || + Run(&BaseChecker::CheckParaExistence, context) != ge::GRAPH_SUCCESS || + Run(&BaseChecker::CheckFeature, context) != ge::GRAPH_SUCCESS || + Run(&BaseChecker::CheckMultiPara, context) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +void RegisterCommonCheckers(CheckerRunner& runner) { + runner.Add(std::make_unique()); + runner.Add(std::make_unique()); + runner.Add(std::make_unique()); + runner.Add(std::make_unique()); + runner.Add(std::make_unique()); + runner.Add(std::make_unique()); + runner.Add(std::make_unique()); + runner.Add(std::make_unique()); +} + +} // namespace sparse_mla_checker +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_runner.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_runner.h new file mode 100644 index 0000000000..0677279f43 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_runner.h @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef SPARSE_MLA_CHECKER_RUNNER_H +#define SPARSE_MLA_CHECKER_RUNNER_H + +#include +#include + +#include "base_checker_sparse_flash_mla.h" + +namespace optiling { +namespace sparse_mla_checker { + +class CheckerRunner { + public: + CheckerRunner() = default; + ~CheckerRunner() = default; + + void Add(std::unique_ptr checker); + ge::graphStatus Process(const CheckContext& context) const; + + private: + using CheckMethod = + ge::graphStatus (BaseChecker::*)(const CheckContext&) const; + ge::graphStatus Run(CheckMethod method, const CheckContext& context) const; + std::vector> checkers_; +}; + +void RegisterCommonCheckers(CheckerRunner& runner); + +} // namespace sparse_mla_checker +} // namespace optiling + +#endif // SPARSE_MLA_CHECKER_RUNNER_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/common_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/common_checker.cpp new file mode 100644 index 0000000000..853aadfea5 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/common_checker.cpp @@ -0,0 +1,366 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#include +#include + +#include "common_checker_sparse_flash_mla.h" +#include "sparse_flash_mla/op_host/common/log.h" + +namespace optiling { +namespace sparse_mla_checker { +constexpr int64_t TURBO_QUANT_MODE = 3; +constexpr uint32_t DIM_IDX_TWO = 2; +constexpr uint32_t DIM_IDX_THREE = 3; + +namespace { +const char* Op(const CheckContext& context) { + return context.opName == nullptr ? "SparseMla" : context.opName; +} + +bool IsTurboQuantEmptyTndTensor(const CheckContext& context, + const TensorParam& param) { + return context.variant == OperatorVariant::MIXED_QUANT && + context.quantMode == TURBO_QUANT_MODE && + context.qLayout == Layout::TND && param.shape != nullptr && + param.shape->GetDimNum() > 0 && param.shape->GetDim(0) == 0; +} +} // namespace + +ge::graphStatus CommonChecker::CheckQuery(const CheckContext& context) const { + if (!context.q.present) { + return ge::GRAPH_SUCCESS; + } + ge::graphStatus status = ge::GRAPH_FAILED; + if (context.variant == OperatorVariant::SPARSE) { + status = + CheckTensorDesc(context, context.q, "q", {ge::DT_FLOAT16, ge::DT_BF16}); + } else if (context.variant == OperatorVariant::MIXED_QUANT) { + status = context.quantMode == TURBO_QUANT_MODE + ? CheckTensorDesc( + context, context.q, "q", {ge::DT_FLOAT16, ge::DT_BF16}) + : CheckTensorDesc(context, context.q, "q", {ge::DT_BF16}); + } else { + status = CheckTensorDesc(context, context.q, "q", {ge::DT_HIFLOAT8}); + } + if (status != ge::GRAPH_SUCCESS || + (!IsTurboQuantEmptyTndTensor(context, context.q) && + CheckNoEmptyDim(context, context.q, "q") != ge::GRAPH_SUCCESS)) { + return ge::GRAPH_FAILED; + } + const size_t expectedDimNum = context.qLayout == Layout::BSND ? 4U : 3U; + return CheckDimNum(context, context.q, "q", {expectedDimNum}); +} + +ge::graphStatus CommonChecker::CheckKv(const CheckContext& context, + const TensorParam& kv, + const char* name) const { + if (!kv.present) { + return ge::GRAPH_SUCCESS; + } + ge::graphStatus status = ge::GRAPH_FAILED; + if (context.variant == OperatorVariant::SPARSE) { + status = CheckTensorDesc(context, kv, name, {ge::DT_FLOAT16, ge::DT_BF16}); + } else if (context.variant == OperatorVariant::MIXED_QUANT) { + if (context.quantMode == TURBO_QUANT_MODE) { + status = std::string(name) == "cmp_kv" + ? CheckTensorDesc(context, kv, name, {ge::DT_UINT8}) + : CheckTensorDesc( + context, kv, name, {ge::DT_FLOAT16, ge::DT_BF16}); + } else { + status = CheckTensorDesc(context, kv, name, {ge::DT_FLOAT8_E4M3FN}); + } + } else { + status = CheckTensorDesc(context, kv, name, {ge::DT_HIFLOAT8}); + } + if (status != ge::GRAPH_SUCCESS || + CheckNoEmptyDim(context, kv, name) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + const size_t expectedDimNum = context.kvLayout == Layout::TND ? 3U : 4U; + return CheckDimNum(context, kv, name, {expectedDimNum}); +} + +ge::graphStatus CommonChecker::CheckOutput(const CheckContext& context) const { + if (!context.attentionOut.present) { + return ge::GRAPH_SUCCESS; + } + ge::graphStatus status = ge::GRAPH_FAILED; + if (context.variant == OperatorVariant::SPARSE || + (context.variant == OperatorVariant::MIXED_QUANT && + context.quantMode == TURBO_QUANT_MODE)) { + status = CheckTensorDesc(context, + context.attentionOut, + "attention_out", + {ge::DT_FLOAT16, ge::DT_BF16}); + } else { + status = CheckTensorDesc( + context, context.attentionOut, "attention_out", {ge::DT_BF16}); + } + if (status != ge::GRAPH_SUCCESS || + (!IsTurboQuantEmptyTndTensor(context, context.attentionOut) && + CheckNoEmptyDim(context, context.attentionOut, "attention_out") != + ge::GRAPH_SUCCESS)) { + return ge::GRAPH_FAILED; + } + const size_t expectedDimNum = context.qLayout == Layout::BSND ? 4U : 3U; + return CheckDimNum( + context, context.attentionOut, "attention_out", {expectedDimNum}); +} + +ge::graphStatus CommonChecker::CheckSinglePara( + const CheckContext& context) const { + OP_CHECK_IF( + context.qLayout != Layout::BSND && context.qLayout != Layout::TND, + OP_LOGE_FOR_INVALID_VALUE( + Op(context), + "layout_q", + std::to_string(static_cast(context.qLayout)).c_str(), + "BSND or TND"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context.kvLayout != Layout::BSND && context.kvLayout != Layout::TND && + context.kvLayout != Layout::PA_BBND, + OP_LOGE_FOR_INVALID_VALUE( + Op(context), + "layout_kv", + std::to_string(static_cast(context.kvLayout)).c_str(), + "BSND, TND or PA_BBND"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(!std::isfinite(context.softmaxScale), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + Op(context), + "softmax_scale", + std::to_string(context.softmaxScale).c_str(), + "Softmax_scale must be finite"), + return ge::GRAPH_FAILED); + if (CheckQuery(context) != ge::GRAPH_SUCCESS || + CheckKv(context, context.oriKv, "ori_kv") != ge::GRAPH_SUCCESS || + CheckKv(context, context.cmpKv, "cmp_kv") != ge::GRAPH_SUCCESS || + CheckOutput(context) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CommonChecker::CheckParaExistence( + const CheckContext& context) const { + OP_CHECK_IF(!context.q.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), "q", "Q is required"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + !context.oriKv.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), "ori_kv", "Ori_kv is required in all supported modes"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(!context.attentionOut.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), "attention_out", "Attention_out is required"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CommonChecker::CheckFeature(const CheckContext& context) const { + OP_CHECK_IF( + context.kvLayout != Layout::PA_BBND && + context.qLayout != context.kvLayout, + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + Op(context), + "layout_q and layout_kv", + (std::to_string(static_cast(context.qLayout)) + " and " + + std::to_string(static_cast(context.kvLayout))) + .c_str(), + "Non-PA layout_q and layout_kv must be the same"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CommonChecker::CheckQueryAxes( + const CheckContext& context) const { + const int64_t qSeq = GetDim(context.q, 0); + int64_t qHeads = -1; + int64_t qDim = -1; + if (context.qLayout == Layout::BSND) { + OP_CHECK_IF(GetDim(context.q, 0) <= 0 || GetDim(context.q, 1) <= 0, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + Op(context), + "q", + ("Batch=" + std::to_string(GetDim(context.q, 0)) + + ", sequence=" + std::to_string(GetDim(context.q, 1))) + .c_str(), + "Batch and sequence dimensions must be greater than 0"), + return ge::GRAPH_FAILED); + qHeads = GetDim(context.q, DIM_IDX_TWO); + qDim = GetDim(context.q, DIM_IDX_THREE); + } else { + const bool turboQuant = context.variant == OperatorVariant::MIXED_QUANT && + context.quantMode == TURBO_QUANT_MODE; + OP_CHECK_IF(qSeq < 0 || (!turboQuant && qSeq == 0), + OP_LOGE_FOR_INVALID_SHAPESIZE(Op(context), + "q_t", + std::to_string(qSeq).c_str(), + turboQuant ? ">= 0" : "> 0"), + return ge::GRAPH_FAILED); + qHeads = GetDim(context.q, 1); + qDim = GetDim(context.q, DIM_IDX_TWO); + } + OP_CHECK_IF( + qHeads <= 0 || qHeads > 128, // 128:最大支持的注意力头数 + OP_LOGE_FOR_INVALID_VALUE( + Op(context), "q_n", std::to_string(qHeads).c_str(), "[1, 128]"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + qDim != 512, // 512:每个注意力头的固定维度大小 + OP_LOGE_FOR_INVALID_VALUE( + Op(context), "q head dimension", std::to_string(qDim).c_str(), "512"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CommonChecker::CheckKvAxes(const CheckContext& context, + const TensorParam& kv, + const char* name) const { + if (!kv.present) { + return ge::GRAPH_SUCCESS; + } + int64_t numHeads = -1; + int64_t headDim = -1; + if (context.kvLayout == Layout::TND) { + numHeads = GetDim(kv, 1); + headDim = GetDim(kv, DIM_IDX_TWO); + } else { + numHeads = GetDim(kv, DIM_IDX_TWO); + headDim = GetDim(kv, DIM_IDX_THREE); + } + OP_CHECK_IF(numHeads != 1, + OP_LOGE_FOR_INVALID_VALUE(Op(context), + (std::string(name) + " kv_n").c_str(), + std::to_string(numHeads).c_str(), + "1"), + return ge::GRAPH_FAILED); + int64_t expectedDim = 512; // 512:预期维度大小 + if (context.variant == OperatorVariant::MIXED_QUANT) { + if (context.quantMode == TURBO_QUANT_MODE) { + // TurboQuant uses 512 dimensions for ori_kv and 258 bytes for packed + // cmp_kv. + expectedDim = std::string(name) == "cmp_kv" ? 258 : 512; + } else { + expectedDim = + context.quantMode == 1 + ? 608 + : 584; // 608,584:混合量化模式下根据量化模式选择不同维度 + } + } + OP_CHECK_IF( + headDim != expectedDim, + OP_LOGE_FOR_INVALID_VALUE(Op(context), + (std::string(name) + " head dimension").c_str(), + std::to_string(headDim).c_str(), + std::to_string(expectedDim).c_str()), + return ge::GRAPH_FAILED); + if (context.kvLayout == Layout::PA_BBND) { + const int64_t blockSize = GetDim(kv, 1); + OP_CHECK_IF( + blockSize <= 0 || blockSize > 1024, + OP_LOGE_FOR_INVALID_VALUE(Op(context), + (std::string(name) + " block size").c_str(), + std::to_string(blockSize).c_str(), + "[1, 1024]"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CommonChecker::CheckMultiPara( + const CheckContext& context) const { + if (CheckSameShape( + context, context.q, "q", context.attentionOut, "attention_out") != + ge::GRAPH_SUCCESS || + CheckQueryAxes(context) != ge::GRAPH_SUCCESS || + CheckKvAxes(context, context.oriKv, "ori_kv") != ge::GRAPH_SUCCESS || + CheckKvAxes(context, context.cmpKv, "cmp_kv") != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + (context.variant == OperatorVariant::SPARSE || + (context.variant == OperatorVariant::MIXED_QUANT && + context.quantMode == TURBO_QUANT_MODE)) && + context.q.desc->GetDataType() != + context.attentionOut.desc->GetDataType(), + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( + Op(context), + "q and attention_out", + (std::to_string(static_cast(context.q.desc->GetDataType())) + + " and " + + std::to_string( + static_cast(context.attentionOut.desc->GetDataType()))) + .c_str(), + "Q and attention_out dtype must be the same"), + return ge::GRAPH_FAILED); + if (context.variant == OperatorVariant::SPARSE || + (context.variant == OperatorVariant::MIXED_QUANT && + context.quantMode == TURBO_QUANT_MODE)) { + OP_CHECK_IF( + context.q.desc->GetDataType() != context.oriKv.desc->GetDataType(), + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( + Op(context), + "q and ori_kv", + (std::to_string( + static_cast(context.q.desc->GetDataType())) + + " and " + + std::to_string( + static_cast(context.oriKv.desc->GetDataType()))) + .c_str(), + "Q and ori_kv dtype must be the same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context.variant == OperatorVariant::SPARSE && context.cmpKv.present && + context.q.desc->GetDataType() != context.cmpKv.desc->GetDataType(), + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( + Op(context), + "q and cmp_kv", + (std::to_string( + static_cast(context.q.desc->GetDataType())) + + " and " + + std::to_string( + static_cast(context.cmpKv.desc->GetDataType()))) + .c_str(), + "Q and cmp_kv dtype must be the same"), + return ge::GRAPH_FAILED); + } + if (context.kvLayout == Layout::BSND) { + const int64_t qBatch = GetDim(context.q, 0); + OP_CHECK_IF(GetDim(context.oriKv, 0) != qBatch, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + Op(context), + "q and ori_kv batch", + (std::to_string(qBatch) + " and " + + std::to_string(GetDim(context.oriKv, 0))) + .c_str(), + "Ori_kv batch must equal q batch"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context.cmpKv.present && GetDim(context.cmpKv, 0) != qBatch, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + Op(context), + "q and cmp_kv batch", + (std::to_string(qBatch) + " and " + + std::to_string(GetDim(context.cmpKv, 0))) + .c_str(), + "Cmp_kv batch must equal q batch"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +} // namespace sparse_mla_checker +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/common_checker_sparse_flash_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/common_checker_sparse_flash_mla.h new file mode 100644 index 0000000000..ab5a7746ad --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/common_checker_sparse_flash_mla.h @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef SPARSE_MLA_COMMON_CHECKER_SPARSE_FLASH_MLA_H +#define SPARSE_MLA_COMMON_CHECKER_SPARSE_FLASH_MLA_H + +#include "base_checker_sparse_flash_mla.h" + +namespace optiling { +namespace sparse_mla_checker { + +class CommonChecker : public BaseChecker { + public: + ge::graphStatus CheckSinglePara(const CheckContext& context) const override; + ge::graphStatus CheckParaExistence( + const CheckContext& context) const override; + ge::graphStatus CheckFeature(const CheckContext& context) const override; + ge::graphStatus CheckMultiPara(const CheckContext& context) const override; + + private: + ge::graphStatus CheckQuery(const CheckContext& context) const; + ge::graphStatus CheckKv(const CheckContext& context, + const TensorParam& kv, + const char* name) const; + ge::graphStatus CheckOutput(const CheckContext& context) const; + ge::graphStatus CheckQueryAxes(const CheckContext& context) const; + ge::graphStatus CheckKvAxes(const CheckContext& context, + const TensorParam& kv, + const char* name) const; +}; + +} // namespace sparse_mla_checker +} // namespace optiling + +#endif // SPARSE_MLA_COMMON_CHECKER_SPARSE_FLASH_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/mask_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/mask_checker.cpp new file mode 100644 index 0000000000..ccb9283fe9 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/mask_checker.cpp @@ -0,0 +1,81 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#include "mask_checker_sparse_flash_mla.h" +#include "sparse_flash_mla/op_host/common/log.h" + +namespace optiling { +namespace sparse_mla_checker { +namespace { +const char* Op(const CheckContext& context) { + return context.opName == nullptr ? "SparseMla" : context.opName; +} +} // namespace + +ge::graphStatus MaskChecker::CheckSinglePara( + const CheckContext& context) const { + OP_CHECK_IF( + context.oriMaskMode != 0 && context.oriMaskMode != 3 && + context.oriMaskMode != 4, // 3: RightDownCausal模式 4: Band模式 + OP_LOGE_FOR_INVALID_VALUE(Op(context), + "ori_mask_mode", + std::to_string(context.oriMaskMode).c_str(), + "0, 3 or 4"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context.cmpMaskMode != 0 && + context.cmpMaskMode != 3, // 3: RightDownCausal模式 + OP_LOGE_FOR_INVALID_VALUE(Op(context), + "cmp_mask_mode", + std::to_string(context.cmpMaskMode).c_str(), + "0 or 3"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context.oriWinLeft < -1 || context.oriWinRight < -1, + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + Op(context), + "ori_win_left and ori_win_right", + (std::to_string(context.oriWinLeft) + ", " + + std::to_string(context.oriWinRight)) + .c_str(), + "Both values must be -1 or non-negative"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MaskChecker::CheckFeature(const CheckContext& context) const { + if (context.oriMaskMode != 4) { // 4: Band模式 + OP_CHECK_IF(context.oriWinLeft != -1 || context.oriWinRight != -1, + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + Op(context), + "ori_win_left and ori_win_right", + (std::to_string(context.oriWinLeft) + ", " + + std::to_string(context.oriWinRight)) + .c_str(), + "Ori_win_left and ori_win_right must be -1 when " + "ori_mask_mode is not 4"), + return ge::GRAPH_FAILED); + } + + if (!context.cmpKv.present) { + OP_CHECK_IF(context.cmpMaskMode != 0, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + Op(context), + "cmp_mask_mode", + std::to_string(context.cmpMaskMode).c_str(), + "Cmp_mask_mode must be 0 when cmp_kv is absent"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +} // namespace sparse_mla_checker +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/mask_checker_sparse_flash_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/mask_checker_sparse_flash_mla.h new file mode 100644 index 0000000000..fa594c4fe4 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/mask_checker_sparse_flash_mla.h @@ -0,0 +1,30 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef SPARSE_MLA_MASK_CHECKER_SPARSE_FLASH_MLA_H +#define SPARSE_MLA_MASK_CHECKER_SPARSE_FLASH_MLA_H + +#include "base_checker_sparse_flash_mla.h" + +namespace optiling { +namespace sparse_mla_checker { + +class MaskChecker : public BaseChecker { + public: + ge::graphStatus CheckSinglePara(const CheckContext& context) const override; + ge::graphStatus CheckFeature(const CheckContext& context) const override; +}; + +} // namespace sparse_mla_checker +} // namespace optiling + +#endif // SPARSE_MLA_MASK_CHECKER_SPARSE_FLASH_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/metadata_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/metadata_checker.cpp new file mode 100644 index 0000000000..78da616ff4 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/metadata_checker.cpp @@ -0,0 +1,53 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#include "metadata_checker_sparse_flash_mla.h" +#include "sparse_flash_mla/op_host/common/log.h" + +namespace optiling { +namespace sparse_mla_checker { +namespace { +constexpr int64_t METADATA_SIZE_DEFAULT = 2048; + +const char* Op(const CheckContext& context) { + return context.opName == nullptr ? "SparseMla" : context.opName; +} +} // namespace + +ge::graphStatus MetadataChecker::CheckSinglePara( + const CheckContext& context) const { + if (!context.metadata.present) { + return ge::GRAPH_SUCCESS; + } + if (CheckTensorDesc(context, context.metadata, "metadata", {ge::DT_INT32}) != + ge::GRAPH_SUCCESS || + CheckShape( + context, context.metadata, "metadata", {METADATA_SIZE_DEFAULT}) != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MetadataChecker::CheckParaExistence( + const CheckContext& context) const { + OP_CHECK_IF(!context.metadata.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "metadata", + "Metadata is required in the current version"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +} // namespace sparse_mla_checker +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/metadata_checker_sparse_flash_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/metadata_checker_sparse_flash_mla.h new file mode 100644 index 0000000000..f879706a9e --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/metadata_checker_sparse_flash_mla.h @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef SPARSE_MLA_METADATA_CHECKER_SPARSE_FLASH_MLA_H +#define SPARSE_MLA_METADATA_CHECKER_SPARSE_FLASH_MLA_H + +#include "base_checker_sparse_flash_mla.h" + +namespace optiling { +namespace sparse_mla_checker { + +class MetadataChecker : public BaseChecker { + public: + ge::graphStatus CheckSinglePara(const CheckContext& context) const override; + ge::graphStatus CheckParaExistence( + const CheckContext& context) const override; +}; + +} // namespace sparse_mla_checker +} // namespace optiling + +#endif // SPARSE_MLA_METADATA_CHECKER_SPARSE_FLASH_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/paged_attention_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/paged_attention_checker.cpp new file mode 100644 index 0000000000..3b57f98e1d --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/paged_attention_checker.cpp @@ -0,0 +1,138 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#include "paged_attention_checker_sparse_flash_mla.h" +#include "sparse_flash_mla/op_host/common/log.h" + +namespace optiling { +namespace sparse_mla_checker { +constexpr int64_t TURBO_QUANT_MODE = 3; +namespace { +const char* Op(const CheckContext& context) { + return context.opName == nullptr ? "SparseMla" : context.opName; +} +} // namespace + +ge::graphStatus PagedAttentionChecker::CheckBlockTable( + const CheckContext& context, + const TensorParam& param, + const char* name) const { + if (!param.present) { + return ge::GRAPH_SUCCESS; + } + if (CheckTensorDesc(context, param, name, {ge::DT_INT32}) != + ge::GRAPH_SUCCESS || + CheckDimNum(context, param, name, {2U}) != ge::GRAPH_SUCCESS || + CheckNoEmptyDim(context, param, name) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus PagedAttentionChecker::CheckSinglePara( + const CheckContext& context) const { + if (CheckBlockTable(context, context.oriBlockTable, "ori_block_table") != + ge::GRAPH_SUCCESS || + CheckBlockTable(context, context.cmpBlockTable, "cmp_block_table") != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus PagedAttentionChecker::CheckParaExistence( + const CheckContext& context) const { + if (context.variant == OperatorVariant::MIXED_QUANT && + context.quantMode == TURBO_QUANT_MODE) { + OP_CHECK_IF( + !context.oriBlockTable.present || !context.cmpBlockTable.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "ori_block_table/cmp_block_table", + "TurboQuant requires both block tables"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; + } + if (context.kvLayout != Layout::PA_BBND) { + OP_CHECK_IF( + context.oriBlockTable.present || context.cmpBlockTable.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "ori_block_table and cmp_block_table", + "Block tables are only supported when layout_kv is PA_BBND"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; + } + + OP_CHECK_IF(!context.oriBlockTable.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "ori_block_table", + "Ori_block_table is required when layout_kv is PA_BBND"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context.cmpKv.present != context.cmpBlockTable.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "cmp_block_table", + "Cmp_block_table must be present exactly when PA cmp_kv is present"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context.oriBlockTable.present && !context.sequsedOriKv.present && + !CanOmitSequsedOriKv(context), + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "seqused_ori_kv and ori_topk_length", + "Seqused_ori_kv is required with ori_block_table unless " + "ORI_SPARSE or ORI_CMP_SPARSE uses " + "mask_mode=0 with ori_topk_length"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context.cmpBlockTable.present && !context.sequsedCmpKv.present && + !CanOmitSequsedCmpKv(context), + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "seqused_cmp_kv and cmp_topk_length", + "Seqused_cmp_kv is required with cmp_block_table unless " + "ORI_CMP_SPARSE uses mask_mode=0 " + "with cmp_topk_length"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus PagedAttentionChecker::CheckMultiPara( + const CheckContext& context) const { + if (context.oriBlockTable.present) { + OP_CHECK_IF(GetDim(context.oriBlockTable, 0) != context.bSize, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + Op(context), + "ori_block_table", + std::to_string(GetDim(context.oriBlockTable, 0)).c_str(), + ("The first dimension must equal batch size " + + std::to_string(context.bSize)) + .c_str()), + return ge::GRAPH_FAILED); + } + if (context.cmpBlockTable.present) { + OP_CHECK_IF(GetDim(context.cmpBlockTable, 0) != context.bSize, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + Op(context), + "cmp_block_table", + std::to_string(GetDim(context.cmpBlockTable, 0)).c_str(), + ("The first dimension must equal batch size " + + std::to_string(context.bSize)) + .c_str()), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +} // namespace sparse_mla_checker +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/paged_attention_checker_sparse_flash_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/paged_attention_checker_sparse_flash_mla.h new file mode 100644 index 0000000000..07f1c0cb42 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/paged_attention_checker_sparse_flash_mla.h @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef SPARSE_MLA_PAGED_ATTENTION_CHECKER_SPARSE_FLASH_MLA_H +#define SPARSE_MLA_PAGED_ATTENTION_CHECKER_SPARSE_FLASH_MLA_H + +#include "base_checker_sparse_flash_mla.h" + +namespace optiling { +namespace sparse_mla_checker { + +class PagedAttentionChecker : public BaseChecker { + public: + ge::graphStatus CheckSinglePara(const CheckContext& context) const override; + ge::graphStatus CheckParaExistence( + const CheckContext& context) const override; + ge::graphStatus CheckMultiPara(const CheckContext& context) const override; + + private: + ge::graphStatus CheckBlockTable(const CheckContext& context, + const TensorParam& param, + const char* name) const; +}; + +} // namespace sparse_mla_checker +} // namespace optiling + +#endif // SPARSE_MLA_PAGED_ATTENTION_CHECKER_SPARSE_FLASH_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/seq_len_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/seq_len_checker.cpp new file mode 100644 index 0000000000..44df821d24 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/seq_len_checker.cpp @@ -0,0 +1,192 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#include "seq_len_checker_sparse_flash_mla.h" +#include "sparse_flash_mla/op_host/common/log.h" + +namespace optiling { +namespace sparse_mla_checker { +constexpr int64_t TURBO_QUANT_MODE = 3; +namespace { +const char* Op(const CheckContext& context) { + return context.opName == nullptr ? "SparseMla" : context.opName; +} +} // namespace + +ge::graphStatus SeqLenChecker::CheckLengthTensor(const CheckContext& context, + const TensorParam& param, + const char* name) const { + if (!param.present) { + return ge::GRAPH_SUCCESS; + } + if (CheckTensorDesc(context, param, name, {ge::DT_INT32}) != + ge::GRAPH_SUCCESS || + CheckDimNum(context, param, name, {1U}) != ge::GRAPH_SUCCESS || + CheckNoEmptyDim(context, param, name) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SeqLenChecker::CheckSinglePara( + const CheckContext& context) const { + if (CheckLengthTensor(context, context.cuSeqlensQ, "cu_seqlens_q") != + ge::GRAPH_SUCCESS || + CheckLengthTensor(context, context.cuSeqlensOriKv, "cu_seqlens_ori_kv") != + ge::GRAPH_SUCCESS || + CheckLengthTensor(context, context.cuSeqlensCmpKv, "cu_seqlens_cmp_kv") != + ge::GRAPH_SUCCESS || + CheckLengthTensor(context, context.sequsedQ, "seqused_q") != + ge::GRAPH_SUCCESS || + CheckLengthTensor(context, context.sequsedOriKv, "seqused_ori_kv") != + ge::GRAPH_SUCCESS || + CheckLengthTensor(context, context.sequsedCmpKv, "seqused_cmp_kv") != + ge::GRAPH_SUCCESS || + CheckLengthTensor(context, context.cmpResidualKv, "cmp_residual_kv") != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SeqLenChecker::CheckParaExistence( + const CheckContext& context) const { + if (context.variant == OperatorVariant::MIXED_QUANT && + context.quantMode == TURBO_QUANT_MODE) { + OP_CHECK_IF(!context.cuSeqlensQ.present || !context.sequsedOriKv.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "cu_seqlens_q/seqused_ori_kv", + "TurboQuant requires both inputs"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context.cuSeqlensOriKv.present || + context.cuSeqlensCmpKv.present || + context.sequsedQ.present || context.sequsedCmpKv.present || + context.cmpResidualKv.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "sequence inputs", + "Unsupported sequence inputs were supplied for TurboQuant"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; + } + if (context.qLayout == Layout::TND) { + OP_CHECK_IF(!context.cuSeqlensQ.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "cu_seqlens_q", + "Cu_seqlens_q is required when layout_q is TND"), + return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF(context.cuSeqlensQ.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "cu_seqlens_q", + "Cu_seqlens_q is only supported when layout_q is TND"), + return ge::GRAPH_FAILED); + } + + if (context.kvLayout == Layout::TND) { + OP_CHECK_IF(!context.cuSeqlensOriKv.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "cu_seqlens_ori_kv", + "Cu_seqlens_ori_kv is required when layout_kv is TND"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context.cmpKv.present && !context.cuSeqlensCmpKv.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "cu_seqlens_cmp_kv", + "Cu_seqlens_cmp_kv is required when TND cmp_kv is present"), + return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF( + context.cuSeqlensOriKv.present || context.cuSeqlensCmpKv.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "cu_seqlens_ori_kv and cu_seqlens_cmp_kv", + "KV cu_seqlens inputs are only supported when layout_kv is TND"), + return ge::GRAPH_FAILED); + } + + if (context.kvLayout == Layout::PA_BBND) { + OP_CHECK_IF(!context.sequsedOriKv.present && !CanOmitSequsedOriKv(context), + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "seqused_ori_kv and ori_topk_length", + "Seqused_ori_kv is required for Paged Attention unless " + "ORI_SPARSE or ORI_CMP_SPARSE " + "uses mask_mode=0 with ori_topk_length"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context.cmpKv.present && !context.sequsedCmpKv.present && + !CanOmitSequsedCmpKv(context), + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "seqused_cmp_kv and cmp_topk_length", + "Seqused_cmp_kv is required for Paged Attention cmp_kv " + "unless ORI_CMP_SPARSE uses " + "mask_mode=0 with cmp_topk_length"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SeqLenChecker::CheckLength(const CheckContext& context, + const TensorParam& param, + const char* name, + int64_t expected) const { + if (!param.present) { + return ge::GRAPH_SUCCESS; + } + OP_CHECK_IF(GetDim(param, 0) != expected, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + Op(context), + name, + std::to_string(GetDim(param, 0)).c_str(), + ("The length must be " + std::to_string(expected)).c_str()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SeqLenChecker::CheckMultiPara( + const CheckContext& context) const { + const int64_t batch = context.bSize; + OP_CHECK_IF(batch <= 0, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + Op(context), + "batch size", + std::to_string(batch).c_str(), + "Batch size must be greater than 0"), + return ge::GRAPH_FAILED); + if (CheckLength(context, context.cuSeqlensQ, "cu_seqlens_q", batch + 1) != + ge::GRAPH_SUCCESS || + CheckLength( + context, context.cuSeqlensOriKv, "cu_seqlens_ori_kv", batch + 1) != + ge::GRAPH_SUCCESS || + CheckLength( + context, context.cuSeqlensCmpKv, "cu_seqlens_cmp_kv", batch + 1) != + ge::GRAPH_SUCCESS || + CheckLength(context, context.sequsedQ, "seqused_q", batch) != + ge::GRAPH_SUCCESS || + CheckLength(context, context.sequsedOriKv, "seqused_ori_kv", batch) != + ge::GRAPH_SUCCESS || + CheckLength(context, context.sequsedCmpKv, "seqused_cmp_kv", batch) != + ge::GRAPH_SUCCESS || + CheckLength(context, context.cmpResidualKv, "cmp_residual_kv", batch) != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +} // namespace sparse_mla_checker +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/seq_len_checker_sparse_flash_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/seq_len_checker_sparse_flash_mla.h new file mode 100644 index 0000000000..131b1d7fb9 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/seq_len_checker_sparse_flash_mla.h @@ -0,0 +1,41 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef SPARSE_MLA_SEQ_LEN_CHECKER_SPARSE_FLASH_MLA_H +#define SPARSE_MLA_SEQ_LEN_CHECKER_SPARSE_FLASH_MLA_H + +#include "base_checker_sparse_flash_mla.h" + +namespace optiling { +namespace sparse_mla_checker { + +class SeqLenChecker : public BaseChecker { + public: + ge::graphStatus CheckSinglePara(const CheckContext& context) const override; + ge::graphStatus CheckParaExistence( + const CheckContext& context) const override; + ge::graphStatus CheckMultiPara(const CheckContext& context) const override; + + private: + ge::graphStatus CheckLengthTensor(const CheckContext& context, + const TensorParam& param, + const char* name) const; + ge::graphStatus CheckLength(const CheckContext& context, + const TensorParam& param, + const char* name, + int64_t expected) const; +}; + +} // namespace sparse_mla_checker +} // namespace optiling + +#endif // SPARSE_MLA_SEQ_LEN_CHECKER_SPARSE_FLASH_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sinks_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sinks_checker.cpp new file mode 100644 index 0000000000..110d90fe1c --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sinks_checker.cpp @@ -0,0 +1,63 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#include "sinks_checker_sparse_flash_mla.h" +#include "sparse_flash_mla/op_host/common/log.h" + +namespace optiling { +namespace sparse_mla_checker { +namespace { +const char* Op(const CheckContext& context) { + return context.opName == nullptr ? "SparseMla" : context.opName; +} +} // namespace + +ge::graphStatus SinksChecker::CheckSinglePara( + const CheckContext& context) const { + if (!context.sinks.present) { + return ge::GRAPH_SUCCESS; + } + if (CheckTensorDesc(context, context.sinks, "sinks", {ge::DT_FLOAT}) != + ge::GRAPH_SUCCESS || + CheckDimNum(context, context.sinks, "sinks", {1U}) != ge::GRAPH_SUCCESS || + CheckNoEmptyDim(context, context.sinks, "sinks") != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SinksChecker::CheckParaExistence( + const CheckContext& context) const { + OP_CHECK_IF( + !context.sinks.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), "sinks", "Sinks is required in the current version"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SinksChecker::CheckMultiPara( + const CheckContext& context) const { + OP_CHECK_IF( + GetDim(context.sinks, 0) != context.qNumHeads, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + Op(context), + "sinks", + std::to_string(GetDim(context.sinks, 0)).c_str(), + ("The length must equal q_n " + std::to_string(context.qNumHeads)) + .c_str()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +} // namespace sparse_mla_checker +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sinks_checker_sparse_flash_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sinks_checker_sparse_flash_mla.h new file mode 100644 index 0000000000..f5dbee4785 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sinks_checker_sparse_flash_mla.h @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef SPARSE_MLA_SINKS_CHECKER_SPARSE_FLASH_MLA_H +#define SPARSE_MLA_SINKS_CHECKER_SPARSE_FLASH_MLA_H + +#include "base_checker_sparse_flash_mla.h" + +namespace optiling { +namespace sparse_mla_checker { + +class SinksChecker : public BaseChecker { + public: + ge::graphStatus CheckSinglePara(const CheckContext& context) const override; + ge::graphStatus CheckParaExistence( + const CheckContext& context) const override; + ge::graphStatus CheckMultiPara(const CheckContext& context) const override; +}; + +} // namespace sparse_mla_checker +} // namespace optiling + +#endif // SPARSE_MLA_SINKS_CHECKER_SPARSE_FLASH_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/softmax_lse_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/softmax_lse_checker.cpp new file mode 100644 index 0000000000..633aba8331 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/softmax_lse_checker.cpp @@ -0,0 +1,63 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#include "softmax_lse_checker_sparse_flash_mla.h" +#include "sparse_flash_mla/op_host/common/log.h" + +namespace optiling { +namespace sparse_mla_checker { +namespace { +const char* Op(const CheckContext& context) { + return context.opName == nullptr ? "SparseMla" : context.opName; +} +} // namespace + +ge::graphStatus SoftmaxLseChecker::CheckSinglePara( + const CheckContext& context) const { + if (!context.returnSoftmaxLse || !context.softmaxLse.present) { + return ge::GRAPH_SUCCESS; + } + return CheckTensorDesc( + context, context.softmaxLse, "softmax_lse", {ge::DT_FLOAT}); +} + +ge::graphStatus SoftmaxLseChecker::CheckMultiPara( + const CheckContext& context) const { + if (!context.returnSoftmaxLse || !context.softmaxLse.present) { + return ge::GRAPH_SUCCESS; + } + + OP_CHECK_IF(context.qNumHeads % context.kvNumHeads != 0, + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + Op(context), + "qNumHeads and kvNumHeads", + (std::to_string(context.qNumHeads) + ", " + + std::to_string(context.kvNumHeads)) + .c_str(), + "QNumHeads must be divisible by kvNumHeads for softmax_lse"), + return ge::GRAPH_FAILED); + const int64_t group = context.qNumHeads / context.kvNumHeads; + if (context.qLayout == Layout::BSND) { + return CheckShape( + context, + context.softmaxLse, + "softmax_lse", + {context.bSize, context.kvNumHeads, context.qSeqSize, group}); + } + return CheckShape(context, + context.softmaxLse, + "softmax_lse", + {context.kvNumHeads, context.qTotalSize, group}); +} + +} // namespace sparse_mla_checker +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/softmax_lse_checker_sparse_flash_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/softmax_lse_checker_sparse_flash_mla.h new file mode 100644 index 0000000000..59aeb3dd64 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/softmax_lse_checker_sparse_flash_mla.h @@ -0,0 +1,30 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef SPARSE_MLA_SOFTMAX_LSE_CHECKER_SPARSE_FLASH_MLA_H +#define SPARSE_MLA_SOFTMAX_LSE_CHECKER_SPARSE_FLASH_MLA_H + +#include "base_checker_sparse_flash_mla.h" + +namespace optiling { +namespace sparse_mla_checker { + +class SoftmaxLseChecker : public BaseChecker { + public: + ge::graphStatus CheckSinglePara(const CheckContext& context) const override; + ge::graphStatus CheckMultiPara(const CheckContext& context) const override; +}; + +} // namespace sparse_mla_checker +} // namespace optiling + +#endif // SPARSE_MLA_SOFTMAX_LSE_CHECKER_SPARSE_FLASH_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_compression_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_compression_checker.cpp new file mode 100644 index 0000000000..dce2d151a2 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_compression_checker.cpp @@ -0,0 +1,323 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#include "sparse_compression_checker.h" + +#include "sparse_flash_mla/op_host/common/log.h" + +namespace optiling { +namespace sparse_mla_checker { +constexpr int64_t TURBO_QUANT_MODE = 3; +namespace { +const char* Op(const CheckContext& context) { + return context.opName == nullptr ? "SparseMla" : context.opName; +} + +bool IsTurboQuantEmptyTndIndex(const CheckContext& context, + const TensorParam& param, + const char* name) { + return context.variant == OperatorVariant::MIXED_QUANT && + context.quantMode == TURBO_QUANT_MODE && + context.qLayout == Layout::TND && + std::string(name) == "cmp_sparse_indices" && param.shape != nullptr && + param.shape->GetDimNum() > 0 && param.shape->GetDim(0) == 0; +} +} // namespace + +ge::graphStatus SparseCompressionChecker::CheckIndex( + const CheckContext& context, + const TensorParam& param, + const char* name) const { + if (!param.present) { + return ge::GRAPH_SUCCESS; + } + const size_t dimNum = context.qLayout == Layout::BSND ? 4U : 3U; + if (CheckTensorDesc(context, param, name, {ge::DT_INT32}) != + ge::GRAPH_SUCCESS || + CheckDimNum(context, param, name, {dimNum}) != ge::GRAPH_SUCCESS || + (!IsTurboQuantEmptyTndIndex(context, param, name) && + CheckNoEmptyDim(context, param, name) != ge::GRAPH_SUCCESS)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SparseCompressionChecker::CheckTopkLength( + const CheckContext& context, + const TensorParam& param, + const char* name) const { + if (!param.present) { + return ge::GRAPH_SUCCESS; + } + const size_t dimNum = context.qLayout == Layout::BSND ? 3U : 2U; + if (CheckTensorDesc(context, param, name, {ge::DT_INT32}) != + ge::GRAPH_SUCCESS || + CheckDimNum(context, param, name, {dimNum}) != ge::GRAPH_SUCCESS || + CheckNoEmptyDim(context, param, name) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SparseCompressionChecker::CheckSinglePara( + const CheckContext& context) const { + OP_CHECK_IF(context.cmpRatio < 1 || context.cmpRatio > 128, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + Op(context), + "cmp_ratio", + std::to_string(context.cmpRatio).c_str(), + "Cmp_ratio must be in range [1, 128]"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context.topkValueMode != 1 && context.topkValueMode != 2, + OP_LOGE_FOR_INVALID_VALUE(Op(context), + "topk_value_mode", + std::to_string(context.topkValueMode).c_str(), + "1 or 2"), + return ge::GRAPH_FAILED); + if (CheckIndex(context, context.oriSparseIndices, "ori_sparse_indices") != + ge::GRAPH_SUCCESS || + CheckIndex(context, context.cmpSparseIndices, "cmp_sparse_indices") != + ge::GRAPH_SUCCESS || + CheckTopkLength(context, context.oriTopkLength, "ori_topk_length") != + ge::GRAPH_SUCCESS || + CheckTopkLength(context, context.cmpTopkLength, "cmp_topk_length") != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SparseCompressionChecker::CheckParaExistence( + const CheckContext& context) const { + if (context.variant == OperatorVariant::MIXED_QUANT && + context.quantMode == TURBO_QUANT_MODE) { + OP_CHECK_IF(!context.cmpKv.present || !context.cmpSparseIndices.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "cmp_kv/cmp_sparse_indices", + "TurboQuant requires both inputs"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context.oriSparseIndices.present || context.cmpResidualKv.present || + context.oriTopkLength.present || context.cmpTopkLength.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "unsupported TurboQuant inputs", + "ori_sparse_indices, cmp_residual_kv and topk length inputs must " + "be absent"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; + } + if (!context.cmpKv.present) { + OP_CHECK_IF(context.cmpSparseIndices.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "cmp_sparse_indices", + "Cmp_sparse_indices requires cmp_kv"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context.cmpTopkLength.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), "cmp_topk_length", "Cmp_topk_length requires cmp_kv"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context.cmpResidualKv.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), "cmp_residual_kv", "Cmp_residual_kv requires cmp_kv"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context.cmpBlockTable.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), "cmp_block_table", "Cmp_block_table requires cmp_kv"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context.cuSeqlensCmpKv.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "cu_seqlens_cmp_kv", + "Cu_seqlens_cmp_kv requires cmp_kv"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context.sequsedCmpKv.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), "seqused_cmp_kv", "Seqused_cmp_kv requires cmp_kv"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context.cmpRatio != 1, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + Op(context), + "cmp_ratio", + std::to_string(context.cmpRatio).c_str(), + "Cmp_ratio must be 1 when cmp_kv is absent"), + return ge::GRAPH_FAILED); + } + + const bool needResidual = context.cmpKv.present && context.cmpMaskMode == 3 && + context.cmpRatio != 1; + OP_CHECK_IF(needResidual && !context.cmpResidualKv.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "cmp_residual_kv", + "Cmp_residual_kv is required when cmp_mask_mode is 3 and " + "cmp_ratio is not 1"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context.cmpResidualKv.present && + (context.cmpMaskMode == 0 || context.cmpRatio == 1), + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "cmp_residual_kv", + std::string("Cmp_residual_kv is not supported when " + "cmp_mask_mode is 0 or cmp_ratio is 1, " + "but got cmp_mask_mode=") + + std::to_string(context.cmpMaskMode) + + ", cmp_ratio=" + std::to_string(context.cmpRatio)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context.oriSparseIndices.present && context.oriMaskMode == 0 && + !context.oriTopkLength.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "ori_topk_length", + "Ori_topk_length is required when ori_sparse_indices is " + "present and ori_mask_mode is 0"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context.cmpSparseIndices.present && context.cmpMaskMode == 0 && + !context.cmpTopkLength.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "cmp_topk_length", + "Cmp_topk_length is required when cmp_sparse_indices is " + "present and cmp_mask_mode is 0"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SparseCompressionChecker::CheckFeature( + const CheckContext& context) const { + if (context.topkValueMode == 2) { // 2:top-k + OP_CHECK_IF( + context.kvLayout != Layout::PA_BBND, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + Op(context), + "topk_value_mode", + std::to_string(static_cast(context.kvLayout)).c_str(), + "Topk_value_mode 2 is only supported when layout_kv is PA_BBND"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + !context.oriSparseIndices.present && !context.cmpSparseIndices.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "ori_sparse_indices/cmp_sparse_indices", + "At least one sparse_indices input is required when " + "topk_value_mode is 2"), + return ge::GRAPH_FAILED); + } + OP_CHECK_IF(context.cmpSparseIndices.present && !context.cmpKv.present, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Op(context), + "cmp_sparse_indices", + "Cmp_sparse_indices requires cmp_kv"), + return ge::GRAPH_FAILED); + if (context.cmpSparseIndices.present) { + OP_CHECK_IF(context.cmpTopk <= 0, + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + Op(context), + "cmp_sparse_indices", + std::to_string(context.cmpTopk).c_str(), + "The last dimension must be greater than 0 when " + "cmp_sparse_indices is present"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SparseCompressionChecker::CheckIndexShape( + const CheckContext& context, + const TensorParam& param, + const char* name) const { + if (!param.present) { + return ge::GRAPH_SUCCESS; + } + if (context.qLayout == Layout::BSND) { + const std::string actualShape = "(" + std::to_string(GetDim(param, 0)) + + ", " + std::to_string(GetDim(param, 1)) + + ", " + std::to_string(GetDim(param, 2)) + + ", " + std::to_string(GetDim(param, 3)) + + ")"; + OP_CHECK_IF( + GetDim(param, 0) != GetDim(context.q, 0) || + GetDim(param, 1) != GetDim(context.q, 1) || GetDim(param, 2) != 1, + OP_LOGE_FOR_INVALID_SHAPE( + Op(context), name, actualShape.c_str(), "(b, q_s, kv_n, topk)"), + return ge::GRAPH_FAILED); + } else { + const std::string actualShape = "(" + std::to_string(GetDim(param, 0)) + + ", " + std::to_string(GetDim(param, 1)) + + ", " + std::to_string(GetDim(param, 2)) + + ")"; + OP_CHECK_IF( + GetDim(param, 0) != GetDim(context.q, 0) || GetDim(param, 1) != 1, + OP_LOGE_FOR_INVALID_SHAPE( + Op(context), name, actualShape.c_str(), "(q_t, kv_n, topk)"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SparseCompressionChecker::CheckTopkLengthShape( + const CheckContext& context, + const TensorParam& param, + const char* name) const { + if (!param.present) { + return ge::GRAPH_SUCCESS; + } + if (context.qLayout == Layout::BSND) { + const std::string actualShape = "(" + std::to_string(GetDim(param, 0)) + + ", " + std::to_string(GetDim(param, 1)) + + ", " + std::to_string(GetDim(param, 2)) + + ")"; + OP_CHECK_IF(GetDim(param, 0) != GetDim(context.q, 0) || + GetDim(param, 1) != GetDim(context.q, 1) || + GetDim(param, 2) != 1, + OP_LOGE_FOR_INVALID_SHAPE( + Op(context), name, actualShape.c_str(), "(b, q_s, kv_n)"), + return ge::GRAPH_FAILED); + } else { + const std::string actualShape = "(" + std::to_string(GetDim(param, 0)) + + ", " + std::to_string(GetDim(param, 1)) + + ")"; + OP_CHECK_IF( + GetDim(param, 0) != GetDim(context.q, 0) || GetDim(param, 1) != 1, + OP_LOGE_FOR_INVALID_SHAPE( + Op(context), name, actualShape.c_str(), "(q_t, kv_n)"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SparseCompressionChecker::CheckMultiPara( + const CheckContext& context) const { + if (CheckIndexShape(context, + context.oriSparseIndices, + "ori_sparse_indices") != ge::GRAPH_SUCCESS || + CheckIndexShape(context, + context.cmpSparseIndices, + "cmp_sparse_indices") != ge::GRAPH_SUCCESS || + CheckTopkLengthShape(context, context.oriTopkLength, "ori_topk_length") != + ge::GRAPH_SUCCESS || + CheckTopkLengthShape(context, context.cmpTopkLength, "cmp_topk_length") != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +} // namespace sparse_mla_checker +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_compression_checker.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_compression_checker.h new file mode 100644 index 0000000000..20a6c96c12 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_compression_checker.h @@ -0,0 +1,47 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef SPARSE_MLA_SPARSE_COMPRESSION_CHECKER_H +#define SPARSE_MLA_SPARSE_COMPRESSION_CHECKER_H + +#include "base_checker_sparse_flash_mla.h" + +namespace optiling { +namespace sparse_mla_checker { + +class SparseCompressionChecker : public BaseChecker { + public: + ge::graphStatus CheckSinglePara(const CheckContext& context) const override; + ge::graphStatus CheckParaExistence( + const CheckContext& context) const override; + ge::graphStatus CheckFeature(const CheckContext& context) const override; + ge::graphStatus CheckMultiPara(const CheckContext& context) const override; + + private: + ge::graphStatus CheckIndex(const CheckContext& context, + const TensorParam& param, + const char* name) const; + ge::graphStatus CheckTopkLength(const CheckContext& context, + const TensorParam& param, + const char* name) const; + ge::graphStatus CheckIndexShape(const CheckContext& context, + const TensorParam& param, + const char* name) const; + ge::graphStatus CheckTopkLengthShape(const CheckContext& context, + const TensorParam& param, + const char* name) const; +}; + +} // namespace sparse_mla_checker +} // namespace optiling + +#endif // SPARSE_MLA_SPARSE_COMPRESSION_CHECKER_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_flash_mla_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_flash_mla_checker.cpp new file mode 100644 index 0000000000..cdb25ca88c --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_flash_mla_checker.cpp @@ -0,0 +1,38 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#include "sparse_flash_mla_checker.h" + +#include "checker_adapter.h" +#include "checker_runner.h" + +namespace optiling { +namespace { +using sparse_mla_checker::CheckContext; +CheckContext BuildContext(const SMLATilingInfo& info) { + CheckContext context; + sparse_mla_checker::PopulateCommonContext(context, info); + context.variant = sparse_mla_checker::OperatorVariant::SPARSE; + context.qHeadDim = info.qHeadDim; + context.oriKvHeadDim = info.oriKvHeadDim; + context.cmpKvHeadDim = info.cmpKvHeadDim; + return context; +} +} // namespace + +ge::graphStatus SparseFlashMlaChecker::Process() const { + sparse_mla_checker::CheckerRunner runner; + sparse_mla_checker::RegisterCommonCheckers(runner); + return runner.Process(BuildContext(info_)); +} + +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_flash_mla_checker.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_flash_mla_checker.h new file mode 100644 index 0000000000..02bdabf41d --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_flash_mla_checker.h @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef SPARSE_FLASH_MLA_CHECKER_H +#define SPARSE_FLASH_MLA_CHECKER_H + +#include "graph/ge_error_codes.h" +#include "sparse_flash_mla/op_host/sparse_flash_mla_tiling.h" + +namespace optiling { + +class SparseFlashMlaChecker { + public: + explicit SparseFlashMlaChecker(const SMLATilingInfo& info) : info_(info) {} + ge::graphStatus Process() const; + + private: + const SMLATilingInfo& info_; +}; + +} // namespace optiling + +#endif // SPARSE_FLASH_MLA_CHECKER_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/log.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/log.h new file mode 100644 index 0000000000..2b6a6c370f --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/log.h @@ -0,0 +1,776 @@ +/** + * Copyright (c) 2025 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file mc2_log_compat.h + * \brief Forward compatibility: provides OP_LOGE_LIBOPAPI_REPORT and + * OP_LOGE_FOR_* macros (EZ0008-EZ0034) when using an older log.h that only + * defines EZ0001-EZ0007. Includes log/log.h internally; include this file as + * the sole log header. + */ + +#ifndef SMLA_LOG_COMPAT_H +#define SMLA_LOG_COMPAT_H + +#include +#include +#include + +#include "log/log.h" + +// ============================================================================ +// OP_LOGE_LIBOPAPI_REPORT fallback +// New log.h defines this macro; old log.h does not. +// For opapi build (OP_LOG_LIBOPAPI_ONLY): use opdev's DOplogSub +// to avoid type conflicts with old log.h's GetOpInfo template. +// For host build: use old log.h's D_OP_LOGE via Ops::Base::GetOpInfo. +// ============================================================================ +#ifndef OP_LOGE_LIBOPAPI_REPORT +#ifdef OP_LOG_LIBOPAPI_ONLY +#define OP_LOGE_LIBOPAPI_REPORT(opName, fmt, ...) \ + DOplogSub(static_cast(OP_ID), \ + OPAPI_SUBMOD_NAME, \ + OP_LOG_ERROR, \ + "[%s][%lu] OpName:[%s] " fmt, \ + __FUNCTION__, \ + op::OpLog::GetTid(), \ + opName, \ + ##__VA_ARGS__) +#else +#define OP_LOGE_LIBOPAPI_REPORT(opName, fmt, ...) \ + D_OP_LOGE(Ops::Base::GetOpInfo(opName), fmt, ##__VA_ARGS__) +#endif /* OP_LOG_LIBOPAPI_ONLY */ +#endif /* OP_LOGE_LIBOPAPI_REPORT */ + +// ============================================================================ +// For opapi build (OP_LOG_LIBOPAPI_ONLY): old log.h unconditionally defines +// OP_LOGE, D_OP_LOGE, OpLogErrSub, etc. with signatures that differ from +// opdev/op_log.h's versions. The opapi source code expects opdev's signatures +// (e.g. OP_LOGE(errno, ...) where first arg is an error code, not opName). +// Undefine old log.h's versions and provide opdev-compatible replacements. +// ============================================================================ +#ifdef OP_LOG_LIBOPAPI_ONLY +#undef OpLogSub +#undef OpLogErrSub +#undef D_OP_LOGI +#undef D_OP_LOGW +#undef D_OP_LOGE +#undef D_OP_LOGD +#undef OP_LOGI +#undef OP_LOGW +#undef OP_LOGE_WITHOUT_REPORT +#undef OP_LOGE +#undef OP_LOGD +#undef OP_CHECK_IF +#undef OP_CHECK_NULL_WITH_CONTEXT + +// Restore opdev/op_log.h signatures after old log.h shadowed them. +// DOplogSub, GetOpName, GetFileName, +// and op::OpLog::GetTid() are from opdev/op_log.h and NOT redefined by old +// log.h (different names), so they remain available. +#define OpLogSub(moduleId, level, op_info, fmt, ...) \ + DOplogSub(static_cast(moduleId), \ + OPAPI_SUBMOD_NAME, \ + level, \ + "[%s][%lu] %s" fmt, \ + __FUNCTION__, \ + op::OpLog::GetTid(), \ + op_info, \ + ##__VA_ARGS__) + +#define OpLogErrSub(moduleId, level, op_info, errno, fmt, ...) \ + DOplogSub(static_cast(moduleId), \ + OPAPI_SUBMOD_NAME, \ + level, \ + "[%s][%lu] errno[%d] %s" fmt, \ + __FUNCTION__, \ + op::OpLog::GetTid(), \ + errno, \ + op_info, \ + ##__VA_ARGS__) + +#define OpDfxLogSub(moduleId, level, file, line, func, op_info, fmt, ...) \ + DDfxlogSub(static_cast(moduleId), \ + OPAPI_SUBMOD_NAME, \ + level, \ + GetFileName(file), \ + line, \ + "[%s][%lu] %s" fmt, \ + func, \ + op::OpLog::GetTid(), \ + op_info, \ + ##__VA_ARGS__) + +#define D_OP_LOGI(opname, fmt, ...) \ + OpLogSub(OP_ID, OP_LOG_INFO, opname, fmt, ##__VA_ARGS__) +#define D_OP_LOGW(opname, fmt, ...) \ + OpLogSub(OP_ID, OP_LOG_WARN, opname, fmt, ##__VA_ARGS__) +#define D_OP_LOGE(opname, errno, fmt, ...) \ + OpLogErrSub(OP_ID, OP_LOG_ERROR, opname, errno, fmt, ##__VA_ARGS__) +#define D_OP_LOGD(opname, fmt, ...) \ + OpLogSub(OP_ID, OP_LOG_DEBUG, opname, fmt, ##__VA_ARGS__) +#define D_OP_EVENT(opname, fmt, ...) \ + OpLogSub(OP_ID, OP_LOG_EVENT, opname, fmt, ##__VA_ARGS__) + +#define OP_LOGI(...) D_OP_LOGI(GetOpName().c_str(), __VA_ARGS__) +#define OP_LOGW(...) D_OP_LOGW(GetOpName().c_str(), __VA_ARGS__) +#define OP_LOGE_WITHOUT_REPORT(errno, ...) \ + D_OP_LOGE(GetOpName().c_str(), errno, __VA_ARGS__) +#define OP_LOGE(errno, ...) \ + do { \ + OP_LOGE_WITHOUT_REPORT(errno, __VA_ARGS__); \ + REPORT_ERROR_MESSAGE(errno, __VA_ARGS__); \ + } while (false) +#define OP_LOGD(...) D_OP_LOGD(GetOpName().c_str(), __VA_ARGS__) +#define OP_EVENT(...) D_OP_EVENT(GetOpName().c_str(), __VA_ARGS__) +#endif /* OP_LOG_LIBOPAPI_ONLY */ + +// ============================================================================ +// OP_LOGE_FOR_* macros (EZ0008-EZ0034) +// New log.h defines these; old log.h does not. +// ============================================================================ +#ifndef OP_LOGE_FOR_INVALID_SHAPE + +// EZ0008: Parameter shape error (single parameter, with correct shape) +#define OP_LOGE_FOR_INVALID_SHAPE( \ + opName, paramName, incorrectShape, correctShape) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramName_(paramName); \ + std::string _safe_incorrectShape_(incorrectShape); \ + std::string _safe_correctShape_(correctShape); \ + OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ + "Parameter %s of operator %s has incorrect shape " \ + "%s. It should be %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectShape_.c_str(), \ + _safe_correctShape_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0008", \ + "Parameter %s of operator %s has incorrect shape " \ + "%s. It should be %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectShape_.c_str(), \ + _safe_correctShape_.c_str()); \ + } while (0) + +// EZ0009: Parameter shape error (single parameter, with reason) +#define OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( \ + opName, paramName, incorrectShape, reason) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramName_(paramName); \ + std::string _safe_incorrectShape_(incorrectShape); \ + std::string _safe_reason_(reason); \ + OP_LOGE_LIBOPAPI_REPORT( \ + _safe_opName_.c_str(), \ + "Parameter %s of operator %s has incorrect shape %s. Reason: %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectShape_.c_str(), \ + _safe_reason_.c_str()); \ + REPORT_INNER_ERR_MSG( \ + "EZ0009", \ + "Parameter %s of operator %s has incorrect shape %s. Reason: %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectShape_.c_str(), \ + _safe_reason_.c_str()); \ + } while (0) + +// EZ0010: Parameters shape error (multiple parameters, with reason) +#define OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( \ + opName, paramNames, incorrectShapes, reason) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramNames_(paramNames); \ + std::string _safe_incorrectShapes_(incorrectShapes); \ + std::string _safe_reason_(reason); \ + OP_LOGE_LIBOPAPI_REPORT( \ + _safe_opName_.c_str(), \ + "Parameters %s of operator %s have incorrect shapes %s. Reason: %s.", \ + _safe_paramNames_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectShapes_.c_str(), \ + _safe_reason_.c_str()); \ + REPORT_INNER_ERR_MSG( \ + "EZ0010", \ + "Parameters %s of operator %s have incorrect shapes %s. Reason: %s.", \ + _safe_paramNames_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectShapes_.c_str(), \ + _safe_reason_.c_str()); \ + } while (0) + +// EZ0011: Parameter shape dim error (single parameter, with correct dim) +#define OP_LOGE_FOR_INVALID_SHAPEDIM( \ + opName, paramName, incorrectDim, correctDim) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramName_(paramName); \ + std::string _safe_incorrectDim_(incorrectDim); \ + std::string _safe_correctDim_(correctDim); \ + OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ + "Parameter %s of operator %s has incorrect shape " \ + "dim %s. It should be %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectDim_.c_str(), \ + _safe_correctDim_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0011", \ + "Parameter %s of operator %s has incorrect shape " \ + "dim %s. It should be %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectDim_.c_str(), \ + _safe_correctDim_.c_str()); \ + } while (0) + +// EZ0012: Parameter shape dim error (single parameter, with reason) +#define OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( \ + opName, paramName, incorrectDim, reason) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramName_(paramName); \ + std::string _safe_incorrectDim_(incorrectDim); \ + std::string _safe_reason_(reason); \ + OP_LOGE_LIBOPAPI_REPORT( \ + _safe_opName_.c_str(), \ + "Parameter %s of operator %s has incorrect shape dim %s. Reason: %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectDim_.c_str(), \ + _safe_reason_.c_str()); \ + REPORT_INNER_ERR_MSG( \ + "EZ0012", \ + "Parameter %s of operator %s has incorrect shape dim %s. Reason: %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectDim_.c_str(), \ + _safe_reason_.c_str()); \ + } while (0) + +// EZ0013: Parameters shape dim error (multiple parameters, with reason) +#define OP_LOGE_FOR_INVALID_SHAPEDIMS_WITH_REASON( \ + opName, paramNames, incorrectDims, reason) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramNames_(paramNames); \ + std::string _safe_incorrectDims_(incorrectDims); \ + std::string _safe_reason_(reason); \ + OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ + "Parameters %s of operator %s have incorrect " \ + "shape dims %s. Reason: %s.", \ + _safe_paramNames_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectDims_.c_str(), \ + _safe_reason_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0013", \ + "Parameters %s of operator %s have incorrect shape " \ + "dims %s. Reason: %s.", \ + _safe_paramNames_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectDims_.c_str(), \ + _safe_reason_.c_str()); \ + } while (0) + +// EZ0014: Parameter shape size error (single parameter, with correct size) +#define OP_LOGE_FOR_INVALID_SHAPESIZE( \ + opName, paramName, incorrectSize, correctSize) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramName_(paramName); \ + std::string _safe_incorrectSize_(incorrectSize); \ + std::string _safe_correctSize_(correctSize); \ + OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ + "Parameter %s of operator %s has incorrect shape " \ + "size %s. It should be %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectSize_.c_str(), \ + _safe_correctSize_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0014", \ + "Parameter %s of operator %s has incorrect shape " \ + "size %s. It should be %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectSize_.c_str(), \ + _safe_correctSize_.c_str()); \ + } while (0) + +// EZ0015: Parameter shape size error (single parameter, with reason) +#define OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( \ + opName, paramName, incorrectSize, reason) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramName_(paramName); \ + std::string _safe_incorrectSize_(incorrectSize); \ + std::string _safe_reason_(reason); \ + OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ + "Parameter %s of operator %s has incorrect shape " \ + "size %s. Reason: %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectSize_.c_str(), \ + _safe_reason_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0015", \ + "Parameter %s of operator %s has incorrect shape " \ + "size %s. Reason: %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectSize_.c_str(), \ + _safe_reason_.c_str()); \ + } while (0) + +// EZ0016: Parameters shape size error (multiple parameters, with reason) +#define OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( \ + opName, paramNames, incorrectSizes, reason) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramNames_(paramNames); \ + std::string _safe_incorrectSizes_(incorrectSizes); \ + std::string _safe_reason_(reason); \ + OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ + "Parameters %s of operator %s have incorrect " \ + "shape sizes %s. Reason: %s.", \ + _safe_paramNames_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectSizes_.c_str(), \ + _safe_reason_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0016", \ + "Parameters %s of operator %s have incorrect shape " \ + "sizes %s. Reason: %s.", \ + _safe_paramNames_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectSizes_.c_str(), \ + _safe_reason_.c_str()); \ + } while (0) + +// EZ0017: Parameter format error (single parameter, with correct format) +#define OP_LOGE_FOR_INVALID_FORMAT( \ + opName, paramName, incorrectFormat, correctFormat) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramName_(paramName); \ + std::string _safe_incorrectFormat_(incorrectFormat); \ + std::string _safe_correctFormat_(correctFormat); \ + OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ + "Parameter %s of operator %s has incorrect " \ + "format %s. It should be %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectFormat_.c_str(), \ + _safe_correctFormat_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0017", \ + "Parameter %s of operator %s has incorrect format " \ + "%s. It should be %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectFormat_.c_str(), \ + _safe_correctFormat_.c_str()); \ + } while (0) + +// EZ0018: Parameters format error (multiple parameters, with reason) +#define OP_LOGE_FOR_INVALID_FORMATS_WITH_REASON( \ + opName, paramNames, incorrectFormats, reason) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramNames_(paramNames); \ + std::string _safe_incorrectFormats_(incorrectFormats); \ + std::string _safe_reason_(reason); \ + OP_LOGE_LIBOPAPI_REPORT( \ + _safe_opName_.c_str(), \ + "Parameters %s of operator %s have incorrect formats %s. Reason: %s.", \ + _safe_paramNames_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectFormats_.c_str(), \ + _safe_reason_.c_str()); \ + REPORT_INNER_ERR_MSG( \ + "EZ0018", \ + "Parameters %s of operator %s have incorrect formats %s. Reason: %s.", \ + _safe_paramNames_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectFormats_.c_str(), \ + _safe_reason_.c_str()); \ + } while (0) + +// EZ0019: Parameter dtype error (single parameter, with correct dtype) +#define OP_LOGE_FOR_INVALID_DTYPE( \ + opName, paramName, incorrectDtype, correctDtype) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramName_(paramName); \ + std::string _safe_incorrectDtype_(incorrectDtype); \ + std::string _safe_correctDtype_(correctDtype); \ + OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ + "Parameter %s of operator %s has incorrect dtype " \ + "%s. It should be %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectDtype_.c_str(), \ + _safe_correctDtype_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0019", \ + "Parameter %s of operator %s has incorrect dtype " \ + "%s. It should be %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectDtype_.c_str(), \ + _safe_correctDtype_.c_str()); \ + } while (0) + +// EZ0020: Parameter dtype error (single parameter, with reason) +#define OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( \ + opName, paramName, incorrectDtype, reason) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramName_(paramName); \ + std::string _safe_incorrectDtype_(incorrectDtype); \ + std::string _safe_reason_(reason); \ + OP_LOGE_LIBOPAPI_REPORT( \ + _safe_opName_.c_str(), \ + "Parameter %s of operator %s has incorrect dtype %s. Reason: %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectDtype_.c_str(), \ + _safe_reason_.c_str()); \ + REPORT_INNER_ERR_MSG( \ + "EZ0020", \ + "Parameter %s of operator %s has incorrect dtype %s. Reason: %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectDtype_.c_str(), \ + _safe_reason_.c_str()); \ + } while (0) + +// EZ0021: Parameters dtype error (multiple parameters, with reason) +#define OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( \ + opName, paramNames, incorrectDtypes, reason) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramNames_(paramNames); \ + std::string _safe_incorrectDtypes_(incorrectDtypes); \ + std::string _safe_reason_(reason); \ + OP_LOGE_LIBOPAPI_REPORT( \ + _safe_opName_.c_str(), \ + "Parameters %s of operator %s have incorrect dtypes %s. Reason: %s.", \ + _safe_paramNames_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectDtypes_.c_str(), \ + _safe_reason_.c_str()); \ + REPORT_INNER_ERR_MSG( \ + "EZ0021", \ + "Parameters %s of operator %s have incorrect dtypes %s. Reason: %s.", \ + _safe_paramNames_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectDtypes_.c_str(), \ + _safe_reason_.c_str()); \ + } while (0) + +// EZ0022: Parameter tensor num error (single parameter, with correct num) +#define OP_LOGE_FOR_INVALID_TENSORNUM( \ + opName, paramName, incorrectNum, correctNum) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramName_(paramName); \ + std::string _safe_correctNum_(correctNum); \ + OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ + "Parameter %s of operator %s has invalid tensor " \ + "num %ld. It should be %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + static_cast(incorrectNum), \ + _safe_correctNum_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0022", \ + "Parameter %s of operator %s has invalid tensor num " \ + "%ld. It should be %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + static_cast(incorrectNum), \ + _safe_correctNum_.c_str()); \ + } while (0) + +// EZ0023: Parameters tensor num error (multiple parameters, with reason) +#define OP_LOGE_FOR_INVALID_TENSORNUMS_WITH_REASON( \ + opName, paramNames, incorrectNums, reason) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramNames_(paramNames); \ + std::string _safe_incorrectNums_(incorrectNums); \ + std::string _safe_reason_(reason); \ + OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ + "Parameters %s of operator %s have invalid " \ + "tensor nums %s. Reason: %s.", \ + _safe_paramNames_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectNums_.c_str(), \ + _safe_reason_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0023", \ + "Parameters %s of operator %s have invalid tensor " \ + "nums %s. Reason: %s.", \ + _safe_paramNames_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectNums_.c_str(), \ + _safe_reason_.c_str()); \ + } while (0) + +// EZ0024: Parameter value error (single parameter, with correct value) +#define OP_LOGE_FOR_INVALID_VALUE( \ + opName, paramName, incorrectValue, correctValue) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramName_(paramName); \ + std::string _safe_incorrectValue_(incorrectValue); \ + std::string _safe_correctValue_(correctValue); \ + OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ + "Parameter %s of operator %s has incorrect value " \ + "%s. It should be %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectValue_.c_str(), \ + _safe_correctValue_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0024", \ + "Parameter %s of operator %s has incorrect value " \ + "%s. It should be %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectValue_.c_str(), \ + _safe_correctValue_.c_str()); \ + } while (0) + +// EZ0025: Parameter list size error (single parameter, with correct size) +#define OP_LOGE_FOR_INVALID_LISTSIZE( \ + opName, paramName, incorrectSize, correctSize) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramName_(paramName); \ + std::string _safe_incorrectSize_(incorrectSize); \ + std::string _safe_correctSize_(correctSize); \ + OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ + "Parameter %s of operator %s has incorrect " \ + "element nums %s. It should be %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectSize_.c_str(), \ + _safe_correctSize_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0025", \ + "Parameter %s of operator %s has incorrect element " \ + "nums %s. It should be %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectSize_.c_str(), \ + _safe_correctSize_.c_str()); \ + } while (0) + +// EZ0026: Parameter value error (single parameter, with reason) +#define OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( \ + opName, paramName, incorrectValue, reason) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramName_(paramName); \ + std::string _safe_incorrectValue_(incorrectValue); \ + std::string _safe_reason_(reason); \ + OP_LOGE_LIBOPAPI_REPORT( \ + _safe_opName_.c_str(), \ + "Parameter %s of operator %s has incorrect value %s. Reason: %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectValue_.c_str(), \ + _safe_reason_.c_str()); \ + REPORT_INNER_ERR_MSG( \ + "EZ0026", \ + "Parameter %s of operator %s has incorrect value %s. Reason: %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectValue_.c_str(), \ + _safe_reason_.c_str()); \ + } while (0) + +// EZ0027: Parameters value error (multiple parameters, with reason) +#define OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( \ + opName, paramNames, incorrectValues, reason) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramNames_(paramNames); \ + std::string _safe_incorrectValues_(incorrectValues); \ + std::string _safe_reason_(reason); \ + OP_LOGE_LIBOPAPI_REPORT( \ + _safe_opName_.c_str(), \ + "Parameters %s of operator %s have incorrect values %s. Reason: %s.", \ + _safe_paramNames_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectValues_.c_str(), \ + _safe_reason_.c_str()); \ + REPORT_INNER_ERR_MSG( \ + "EZ0027", \ + "Parameters %s of operator %s have incorrect values %s. Reason: %s.", \ + _safe_paramNames_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectValues_.c_str(), \ + _safe_reason_.c_str()); \ + } while (0) + +// EZ0028: Parameter stride error (single parameter, with correct stride) +#define OP_LOGE_FOR_INVALID_STRIDE( \ + opName, paramName, incorrectStride, correctStride) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_paramName_(paramName); \ + std::string _safe_incorrectStride_(incorrectStride); \ + std::string _safe_correctStride_(correctStride); \ + OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ + "Parameter %s of operator %s has incorrect " \ + "stride %s, it should be %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectStride_.c_str(), \ + _safe_correctStride_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0028", \ + "Parameter %s of operator %s has incorrect stride " \ + "%s, it should be %s.", \ + _safe_paramName_.c_str(), \ + _safe_opName_.c_str(), \ + _safe_incorrectStride_.c_str(), \ + _safe_correctStride_.c_str()); \ + } while (0) + +// EZ0029: File operation path error +#define OP_LOGE_FOR_FILE_PATH(opName, filePath, reason) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_filePath_(filePath); \ + std::string _safe_reason_(reason); \ + OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ + "Input path %s is invalid. Reason: %s.", \ + _safe_filePath_.c_str(), \ + _safe_reason_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0029", \ + "Input path %s is invalid. Reason: %s.", \ + _safe_filePath_.c_str(), \ + _safe_reason_.c_str()); \ + } while (0) + +// EZ0030: File operation open error +#define OP_LOGE_FOR_FILE_OPEN(opName, filePath, reason) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_filePath_(filePath); \ + std::string _safe_reason_(reason); \ + OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ + "Failed to open file %s. Reason: %s.", \ + _safe_filePath_.c_str(), \ + _safe_reason_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0030", \ + "Failed to open file %s. Reason: %s.", \ + _safe_filePath_.c_str(), \ + _safe_reason_.c_str()); \ + } while (0) + +// EZ0031: File operation parse error +#define OP_LOGE_FOR_FILE_PARSE(opName, fileName, reason) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_fileName_(fileName); \ + std::string _safe_reason_(reason); \ + OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ + "Failed to parse file %s. Reason: %s.", \ + _safe_fileName_.c_str(), \ + _safe_reason_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0031", \ + "Failed to parse file %s. Reason: %s.", \ + _safe_fileName_.c_str(), \ + _safe_reason_.c_str()); \ + } while (0) + +// EZ0032: Config error (single item, with expect) +#define OP_LOGE_FOR_INVALID_CONFIG(opName, configFile, item, value, expect) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_configFile_(configFile); \ + std::string _safe_item_(item); \ + std::string _safe_value_(value); \ + std::string _safe_expect_(expect); \ + OP_LOGE_LIBOPAPI_REPORT( \ + _safe_opName_.c_str(), \ + "Value %s of configuration item %s in configuration file %s is " \ + "invalid, it should be %s.", \ + _safe_value_.c_str(), \ + _safe_item_.c_str(), \ + _safe_configFile_.c_str(), \ + _safe_expect_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0032", \ + "Value %s of configuration item %s in configuration " \ + "file %s is invalid, it should be %s.", \ + _safe_value_.c_str(), \ + _safe_item_.c_str(), \ + _safe_configFile_.c_str(), \ + _safe_expect_.c_str()); \ + } while (0) + +// EZ0033: Config error (single item, with reason) +#define OP_LOGE_FOR_INVALID_CONFIG_WITH_REASON( \ + opName, configFile, item, value, reason) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_configFile_(configFile); \ + std::string _safe_item_(item); \ + std::string _safe_value_(value); \ + std::string _safe_reason_(reason); \ + OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ + "Value %s of configuration item %s in " \ + "configuration file %s is invalid. Reason: %s.", \ + _safe_value_.c_str(), \ + _safe_item_.c_str(), \ + _safe_configFile_.c_str(), \ + _safe_reason_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0033", \ + "Value %s of configuration item %s in configuration " \ + "file %s is invalid. Reason: %s.", \ + _safe_value_.c_str(), \ + _safe_item_.c_str(), \ + _safe_configFile_.c_str(), \ + _safe_reason_.c_str()); \ + } while (0) + +// EZ0034: Config error (multiple items, with reason) +#define OP_LOGE_FOR_INVALID_CONFIGS_WITH_REASON( \ + opName, configFile, items, values, reason) \ + do { \ + std::string _safe_opName_(opName); \ + std::string _safe_configFile_(configFile); \ + std::string _safe_items_(items); \ + std::string _safe_values_(values); \ + std::string _safe_reason_(reason); \ + OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ + "Values %s of configuration items %s in " \ + "configuration file %s are invalid. Reason: %s.", \ + _safe_values_.c_str(), \ + _safe_items_.c_str(), \ + _safe_configFile_.c_str(), \ + _safe_reason_.c_str()); \ + REPORT_INNER_ERR_MSG("EZ0034", \ + "Values %s of configuration items %s in " \ + "configuration file %s are invalid. Reason: %s.", \ + _safe_values_.c_str(), \ + _safe_items_.c_str(), \ + _safe_configFile_.c_str(), \ + _safe_reason_.c_str()); \ + } while (0) + +#endif /* OP_LOGE_FOR_INVALID_SHAPE */ + +#ifndef OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON +#define OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(op, name, reason) \ + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(op, name, "", reason) +#endif + +#endif /* SMLA_LOG_COMPAT_H */ diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/ops_err.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/ops_err.h new file mode 100644 index 0000000000..45425615e0 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/ops_err.h @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2025 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file ops_err.h + * \brief + */ + +#ifndef Transformer_COMMON_OPS_ERR_H +#define Transformer_COMMON_OPS_ERR_H + +#include "sparse_flash_mla/op_host/common/log.h" + +constexpr int32_t OP_TRANSFORMER_MODULE_ID = 63; + +#define OPS_INNER_ERR_STUB(ERR_CODE_STR, OPS_DESC, FMT, ...) \ + do { \ + OpLogSub( \ + OP_TRANSFORMER_MODULE_ID, DLOG_ERROR, OPS_DESC, FMT, ##__VA_ARGS__); \ + REPORT_INNER_ERR_MSG(ERR_CODE_STR, FMT, ##__VA_ARGS__); \ + } while (0) + +/* 基础报错 */ +#define OPS_REPORT_VECTOR_INNER_ERR(OPS_DESC, ...) \ + OPS_INNER_ERR_STUB("E89999", OPS_DESC, __VA_ARGS__) +#define OPS_REPORT_CUBE_INNER_ERR(OPS_DESC, ...) \ + OPS_INNER_ERR_STUB("E69999", OPS_DESC, __VA_ARGS__) + +#endif // Transformer_COMMON_OPS_ERR_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/smla_host_common_defs.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/smla_host_common_defs.h new file mode 100644 index 0000000000..8f1c3f4e12 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/smla_host_common_defs.h @@ -0,0 +1,83 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file smla_host_common_defs.h + * \brief sparse_flash_mla / mixed_quant_sparse_flash_mla / + * quant_sparse_flash_mla 三个算子 op_host 侧共用的 枚举、Tiling 入参信息 POD + * 与索引常量定义。 + */ + +#ifndef SMLA_HOST_COMMON_DEFS_H +#define SMLA_HOST_COMMON_DEFS_H + +#include + +#include + +#include "register/tilingdata_base.h" + +namespace optiling { + +// ------------------公共定义-------------------------- +struct SMLATilingRequiredParaInfo { + const gert::CompileTimeTensorDesc* desc; + const gert::StorageShape* shape; +}; + +struct SMLATilingOptionalParaInfo { + const gert::CompileTimeTensorDesc* desc; + const gert::Tensor* tensor; + const gert::StorageShape* shape; +}; + +enum class SMLALayout : uint32_t { BSND = 0, TND = 1, PA_BBND = 2 }; + +enum class SMLAAxis : uint32_t { + B = 0, + S = 1, + N = 2, + D = 3, + K = 3, // sparse_indices的K和key的D枚举值相同,表达相同位置, 最后一维 + T = 5, + Bn = 6, // block number + Bs = 7 // block size +}; + +enum class SMLATemplateMode : uint32_t { + SWA_TEMPLATE_MODE = 0, + HCA_TEMPLATE_MODE = 1, + CSA_TEMPLATE_MODE = 2, + ORI_SPARSE_TEMPLATE_MODE = 3, + ORI_CMP_SPARSE_TEMPLATE_MODE = 4 +}; + +// Dim Index +constexpr uint32_t DIM_IDX_ZERO = 0; +constexpr uint32_t DIM_IDX_ONE = 1; +constexpr uint32_t DIM_IDX_TWO = 2; +constexpr uint32_t DIM_IDX_THREE = 3; +constexpr uint32_t DIM_IDX_FOUR = 4; + +// Dim Num +constexpr uint32_t DIM_NUM_ONE = 1; +constexpr uint32_t DIM_NUM_TWO = 2; +constexpr uint32_t DIM_NUM_THREE = 3; +constexpr uint32_t DIM_NUM_FOUR = 4; + +// Outputs Index +constexpr uint32_t ATTN_OUT_INDEX = 0; +constexpr uint32_t SOFTMAX_LSE_INDEX = 1; + +} // namespace optiling + +#endif // SMLA_HOST_COMMON_DEFS_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/smla_infershape_common.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/smla_infershape_common.h new file mode 100644 index 0000000000..9007a34e47 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/smla_infershape_common.h @@ -0,0 +1,228 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file smla_infershape_common.h + * \brief sparse_flash_mla / mixed_quant_sparse_flash_mla / + * quant_sparse_flash_mla 三个算子 InferShape / InferDataType 公共子函数。 + */ + +#ifndef SMLA_INFERSHAPE_COMMON_H +#define SMLA_INFERSHAPE_COMMON_H + +#include +#include +#include +#include + +#include +#include +#include + +#include "smla_host_common_defs.h" +#include "sparse_flash_mla/op_host/common/log.h" +#include "sparse_flash_mla/op_host/common/ops_err.h" + +namespace optiling { + +// 算子原型输入索引(三个算子 Q / ori_kv / cmp_kv 位置一致) +constexpr uint32_t SMLA_QUERY_INPUT_INDEX = 0; +constexpr uint32_t SMLA_ORI_KV_INPUT_INDEX = 1; +constexpr uint32_t SMLA_CMP_KV_INPUT_INDEX = 2; + +inline std::vector SMLAToVector(const gert::Shape* shape) { + size_t shapeSize = shape->GetDimNum(); + std::vector shapeVec(shapeSize, 0); + for (size_t i = 0; i < shapeSize; i++) { + shapeVec[i] = shape->GetDim(i); + } + return shapeVec; +} + +inline std::string SMLAToString(const gert::Shape* shape) { + std::ostringstream oss; + auto v = SMLAToVector(shape); + if (v.size() > 0) { + for (size_t i = 0; i < v.size() - 1; ++i) { + oss << v[i] << ", "; + } + oss << v[v.size() - 1]; + } + return oss.str(); +} + +inline int64_t SMLAGetKvHeadNum(const gert::Shape* kvShape, + const std::string& layoutKv) { + if (layoutKv == "TND") { + return kvShape->GetDim(DIM_IDX_ONE); + } + return kvShape->GetDim(DIM_IDX_TWO); +} + +inline ge::graphStatus SMLACheckKvHeadNum(const char* opName, + const gert::Shape* kvShape, + int64_t kvHeadNum) { + OP_CHECK_IF( + kvHeadNum <= 0, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName, + "ori_kv or cmp_kv", + SMLAToString(kvShape).c_str(), + "The head num of ori_kv or cmp_kv should be greater than 0 but got " + + std::to_string(kvHeadNum)), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +inline void SMLASetSoftmaxLseShape(gert::Shape* softmaxLseShape, + const gert::Shape* queryShape, + int64_t kvHeadNum, + bool isTnd, + bool returnSoftmaxLse) { + if (!returnSoftmaxLse) { + softmaxLseShape->SetDimNum(DIM_NUM_ONE); + softmaxLseShape->SetDim(DIM_IDX_ZERO, 0); + return; + } + if (isTnd) { + softmaxLseShape->SetDimNum(DIM_NUM_THREE); + softmaxLseShape->SetDim(DIM_IDX_ZERO, kvHeadNum); + softmaxLseShape->SetDim(DIM_IDX_ONE, queryShape->GetDim(DIM_IDX_ZERO)); + softmaxLseShape->SetDim(DIM_IDX_TWO, + queryShape->GetDim(DIM_IDX_ONE) / kvHeadNum); + } else { + softmaxLseShape->SetDimNum(DIM_NUM_FOUR); + softmaxLseShape->SetDim(DIM_IDX_ZERO, queryShape->GetDim(DIM_IDX_ZERO)); + softmaxLseShape->SetDim(DIM_IDX_ONE, kvHeadNum); + softmaxLseShape->SetDim(DIM_IDX_TWO, queryShape->GetDim(DIM_IDX_ONE)); + softmaxLseShape->SetDim(DIM_IDX_THREE, + queryShape->GetDim(DIM_IDX_TWO) / kvHeadNum); + } +} + +struct SMLAInferShapeBase { + const gert::Shape* queryShape = nullptr; + gert::Shape* attentionOutShape = nullptr; + gert::Shape* softmaxLseShape = nullptr; + const gert::RuntimeAttrs* attrs = nullptr; + const bool* returnSoftmaxLsePtr = nullptr; + const gert::Shape* kvShape = nullptr; +}; + +// 解析 query 输入、两个输出、attr 及 return_softmax_lse 指针 +inline ge::graphStatus SMLAGetInferShapeBase(gert::InferShapeContext* context, + uint32_t returnSoftmaxLseAttrIdx, + SMLAInferShapeBase& base) { + base.queryShape = context->GetInputShape(SMLA_QUERY_INPUT_INDEX); + OP_CHECK_IF((base.queryShape) == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + context->GetNodeName(), "q", "Null input"), + return ge::GRAPH_FAILED); + base.attentionOutShape = context->GetOutputShape(ATTN_OUT_INDEX); + OP_CHECK_IF((base.attentionOutShape) == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + context->GetNodeName(), + "base.attentionOutShape", + "Required base.attentionOutShape metadata is null; " + "context->GetOutputShape(ATTN_OUT_INDEX) must provide a " + "valid object."), + return ge::GRAPH_FAILED); + *base.attentionOutShape = *base.queryShape; + + base.softmaxLseShape = context->GetOutputShape(SOFTMAX_LSE_INDEX); + OP_CHECK_IF((base.softmaxLseShape) == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + context->GetNodeName(), + "base.softmaxLseShape", + "Required base.softmaxLseShape metadata is null; " + "context->GetOutputShape(SOFTMAX_LSE_INDEX) must provide a " + "valid object."), + return ge::GRAPH_FAILED); + base.attrs = context->GetAttrs(); + OP_CHECK_IF((base.attrs) == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + context->GetNodeName(), + "base.attrs", + "Required base.attrs metadata is null; context->GetAttrs() " + "must provide a valid object."), + return ge::GRAPH_FAILED); + base.returnSoftmaxLsePtr = + base.attrs->GetAttrPointer(returnSoftmaxLseAttrIdx); + return ge::GRAPH_SUCCESS; +} + +// 三个算子统一的 InferShape 主体:ori_kv / cmp_kv 均为可选输入,layout_q / +// layout_kv 为 String attr +inline ge::graphStatus SMLAInferShape(gert::InferShapeContext* context, + const char* opName, + uint32_t returnSoftmaxLseAttrIdx, + uint32_t layoutQAttrIdx, + uint32_t layoutKvAttrIdx) { + SMLAInferShapeBase base; + if (SMLAGetInferShapeBase(context, returnSoftmaxLseAttrIdx, base) != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + const gert::Shape* oriKvShape = + context->GetOptionalInputShape(SMLA_ORI_KV_INPUT_INDEX); + const gert::Shape* cmpKvShape = + context->GetOptionalInputShape(SMLA_CMP_KV_INPUT_INDEX); + base.kvShape = (oriKvShape != nullptr) ? oriKvShape : cmpKvShape; + OP_CHECK_IF((base.kvShape) == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + context->GetNodeName(), + "base.kvShape", + "Required base.kvShape metadata is null; (oriKvShape != " + "nullptr) ? oriKvShape : " + "cmpKvShape must provide a valid object."), + return ge::GRAPH_FAILED); + + const char* layoutQ = base.attrs->GetStr(layoutQAttrIdx); + const char* layoutKv = base.attrs->GetStr(layoutKvAttrIdx); + std::string layoutQStr = (layoutQ != nullptr) ? std::string(layoutQ) : "BSND"; + std::string layoutKvStr = + (layoutKv != nullptr) ? std::string(layoutKv) : "BSND"; + bool returnSoftmaxLse = + (base.returnSoftmaxLsePtr != nullptr) ? *base.returnSoftmaxLsePtr : false; + int64_t kvHeadNum = SMLAGetKvHeadNum(base.kvShape, layoutKvStr); + if (SMLACheckKvHeadNum(opName, base.kvShape, kvHeadNum) != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + SMLASetSoftmaxLseShape(base.softmaxLseShape, + base.queryShape, + kvHeadNum, + layoutQStr == "TND", + returnSoftmaxLse); + return ge::GRAPH_SUCCESS; +} + +// sparse_flash_mla / mixed_quant_sparse_flash_mla 的 InferDataType(输出 dtype +// 跟随 query 输入) +inline ge::graphStatus SMLAInferDataTypeByInput( + gert::InferDataTypeContext* context, + const char* opName) { + OP_CHECK_IF( + context == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(Ops::Base::GetOpInfo(opName), + "context", + "InferShapeContext is nullptr"), + return ge::GRAPH_FAILED); + const auto inputDataType = context->GetInputDataType(SMLA_QUERY_INPUT_INDEX); + context->SetOutputDataType(ATTN_OUT_INDEX, inputDataType); + context->SetOutputDataType(SOFTMAX_LSE_INDEX, ge::DT_FLOAT); + return ge::GRAPH_SUCCESS; +} + +} // namespace optiling + +#endif // SMLA_INFERSHAPE_COMMON_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_def.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_def.cpp new file mode 100644 index 0000000000..84d6e7d2ca --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_def.cpp @@ -0,0 +1,152 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file sparse_flash_mla_def.cpp + * \brief + */ + +#include "register/op_def_registry.h" + +namespace ops { +class XllmKernelSparseFlashMla : public OpDef { + public: + explicit XllmKernelSparseFlashMla(const char* name) : OpDef(name) { + this->Input("q") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("ori_kv") + .ParamType(OPTIONAL) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}) + .IgnoreContiguous(); + this->Input("cmp_kv") + .ParamType(OPTIONAL) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}) + .IgnoreContiguous(); + this->Input("ori_sparse_indices") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cmp_sparse_indices") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("ori_block_table") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cmp_block_table") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cu_seqlens_q") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cu_seqlens_ori_kv") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cu_seqlens_cmp_kv") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("seqused_q") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("seqused_ori_kv") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("seqused_cmp_kv") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cmp_residual_kv") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("ori_topk_length") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cmp_topk_length") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("sinks") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("metadata") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Output("attn_out") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}); + this->Output("softmax_lse") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}); + this->Attr("softmax_scale").AttrType(OPTIONAL).Float(1.0); + this->Attr("cmp_ratio").AttrType(OPTIONAL).Int(1); + this->Attr("ori_mask_mode") + .AttrType(OPTIONAL) + .Int(0); // ori_mask_mode默认值0 + this->Attr("cmp_mask_mode") + .AttrType(OPTIONAL) + .Int(0); // cmp_mask_mode默认值0 + this->Attr("ori_win_left") + .AttrType(OPTIONAL) + .Int(-1); // ori_win_left默认值-1 + this->Attr("ori_win_right") + .AttrType(OPTIONAL) + .Int(-1); // ori_win_right默认值-1 + this->Attr("layout_q").AttrType(OPTIONAL).String("BSND"); + this->Attr("layout_kv").AttrType(OPTIONAL).String("BSND"); + this->Attr("topk_value_mode").AttrType(OPTIONAL).Int(1); + this->Attr("return_softmax_lse").AttrType(OPTIONAL).Bool(false); + + OpAICoreConfig aicore_config; + aicore_config.DynamicCompileStaticFlag(true) + .DynamicFormatFlag(true) + .DynamicRankSupportFlag(true) + .DynamicShapeSupportFlag(true) + .NeedCheckSupportFlag(false) + .PrecisionReduceFlag(true) + .ExtendCfgInfo("aclnnSupport.value", "support_aclnn"); + this->AICore().AddConfig("ascend910_93", aicore_config); + } +}; +OP_ADD(XllmKernelSparseFlashMla); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_infershape.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_infershape.cpp new file mode 100644 index 0000000000..eb7050bfe5 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_infershape.cpp @@ -0,0 +1,56 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file sparse_flash_mla_infershape.cpp + * \brief + */ + +#include +#include + +#include + +#include "common/smla_infershape_common.h" +#include "sparse_flash_mla/op_host/common/log.h" +#include "sparse_flash_mla/op_host/common/ops_err.h" + +using namespace ge; + +namespace ops { +constexpr uint32_t RETURN_SOFTMAX_INDEX = 9; +constexpr uint32_t LAYOUT_Q_ATTR_INDEX = 6; +constexpr uint32_t LAYOUT_KV_ATTR_INDEX = 7; + +ge::graphStatus InferShapeSparseFlashMla(gert::InferShapeContext* context) { + OP_CHECK_IF( + context == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON("XllmKernelSparseFlashMla", + "context", + "InferShapeContext is nullptr"), + return ge::GRAPH_FAILED); + return optiling::SMLAInferShape(context, + "XllmKernelSparseFlashMla", + RETURN_SOFTMAX_INDEX, + LAYOUT_Q_ATTR_INDEX, + LAYOUT_KV_ATTR_INDEX); +} + +ge::graphStatus InferDataTypeSparseFlashMla( + gert::InferDataTypeContext* context) { + return optiling::SMLAInferDataTypeByInput(context, + "XllmKernelSparseFlashMla"); +} + +IMPL_OP_INFERSHAPE(XllmKernelSparseFlashMla) + .InferShape(InferShapeSparseFlashMla) + .InferDataType(InferDataTypeSparseFlashMla); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_tiling.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_tiling.cpp new file mode 100644 index 0000000000..18e2215009 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_tiling.cpp @@ -0,0 +1,3255 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file sparse_flash_mla_tiling.cpp + * \brief + */ + +#include "sparse_flash_mla_tiling.h" + +#include +#include + +#include "checkers/checker_adapter.h" +#include "checkers/sparse_flash_mla_checker.h" +#include "register/op_def_registry.h" +#include "sparse_flash_mla/op_host/common/log.h" +#include "sparse_flash_mla/op_host/common/ops_err.h" +#include "sparse_flash_mla/op_kernel/sparse_flash_mla_template_tiling_key.h" + +using namespace ge; +using namespace AscendC; +using std::map; +using std::pair; +using std::string; + +namespace optiling { + +static const std::string QUERY_NAME = "query"; + +static const std::string ORI_KV_NAME = "ori_kv"; +static const std::string CMP_KV_NAME = "cmp_kv"; +static const std::string CU_SEQLENS_ORI_KV_NAME = "cu_seqlens_ori_kv"; +static const std::string CU_SEQLENS_CMP_KV_NAME = "cu_seqlens_cmp_kv"; +static const std::string ORI_SPARSE_INDICES = "ori_sparse_indices"; +static const std::string CMP_SPARSE_INDICES = "cmp_sparse_indices"; +static const std::string ORI_BLOCK_TABLE_NAME = "ori_block_table"; +static const std::string CMP_BLOCK_TABLE_NAME = "cmp_block_table"; +static const std::string SINKS_NAME = "sinks"; +static const std::string METADATA_NAME = "metadata"; +static const std::string ATTEN_OUT_NAME = "attn_out"; +static const std::string CU_SEQLENS_Q_NAME = "cu_seqlens_q"; +static const std::string SEQUSED_Q_NAME = "seqused_q"; +static const std::string SEQUSED_ORI_KV_NAME = "seqused_ori_kv"; +static const std::string SEQUSED_CMP_KV_NAME = "seqused_cmp_kv"; +static const std::string CMP_RESIDUAL_KV_NAME = "cmp_residual_kv"; +static const std::string ORI_TOPK_LENGTH_NAME = "ori_topk_length"; +static const std::string CMP_TOPK_LENGTH_NAME = "cmp_topk_length"; +static const std::string A2_A3_PLATFORM_LOG = "A2/A3"; +static const std::string A5_PLATFORM_LOG = "A5"; +static const std::string A6_PLATFORM_LOG = "A6"; +constexpr uint32_t FD_MAX_S2_SPLIT_NUM = 2U; +constexpr uint32_t BATCH_CONSISTENCY_MAX_REDUCE_BLOCK_NUM = 33U; +constexpr uint32_t FD_BROADCAST_ELEMS = 8U; +constexpr int64_t BATCH_CONSISTENCY_LEVEL = 3; + +static std::vector ToVector(const gert::Shape& shape) { + size_t shapeSize = shape.GetDimNum(); + std::vector shapeVec(shapeSize, 0); + + for (size_t i = 0; i < shapeSize; i++) { + shapeVec[i] = shape.GetDim(i); + } + return shapeVec; +} + +static std::string ToStringRaw(const gert::Shape& shape) { + std::ostringstream oss; + const size_t dimCount = shape.GetDimNum(); + for (size_t dimIndex = 0; dimIndex < dimCount; ++dimIndex) { + if (dimIndex != 0U) { + oss << ", "; + } + oss << shape.GetDim(dimIndex); + } + return oss.str(); +} + +static bool IsNonEmptyOptionalTensor(const gert::Tensor* tensor) { + return tensor != nullptr && tensor->GetShapeSize() > 0; +} + +static bool IsPowerOfTwoInRange(uint32_t value, + uint32_t minValue, + uint32_t maxValue) { + return value >= minValue && value <= maxValue && (value & (value - 1U)) == 0U; +} + +static bool IsA5Arch(NpuArch npuArch) { return npuArch == NpuArch::DAV_3510; } +static bool IsA6Arch(NpuArch npuArch) { + return npuArch == NpuArch::DAV_9201 || npuArch == NpuArch::DAV_9202; +} + +static bool IsPowerOfTwo(uint64_t value) { + return value != 0U && (value & (value - 1U)) == 0U; +} + +static void CalcMagicP(uint32_t blockSize, + uint32_t& p, + uint32_t& mLow, + uint32_t& mHigh) { + constexpr uint32_t SHIFT_LOW_BOUND = 30U; + constexpr uint32_t SHIFT_UP_BOUND = 41U; + constexpr uint32_t HIGH_32BIT_SHIFT = 32U; + constexpr uint64_t X_MAX = (1ULL << 30U) - 1U; + uint64_t multiplier = 1U; + p = 0U; + if (IsPowerOfTwo(blockSize)) { + uint32_t value = blockSize; + while ((value >>= 1U) != 0U) { + ++p; + } + mLow = 1U; + mHigh = 0U; + return; + } + for (uint32_t shift = SHIFT_LOW_BOUND; shift < SHIFT_UP_BOUND; ++shift) { + const uint64_t power = 1ULL << shift; + const uint64_t remainder = power % blockSize; + const uint64_t error = (blockSize - remainder) % blockSize; + if (error == 0U || power > X_MAX * error) { + multiplier = (power + blockSize - 1U) / blockSize; + p = shift; + } + } + mLow = static_cast(multiplier); + mHigh = static_cast(multiplier >> HIGH_32BIT_SHIFT); +} + +static bool IsPaBlockSizeSupport(NpuArch npuArch, int32_t blockSize) { + if (IsA5Arch(npuArch) || IsA6Arch(npuArch)) { + return blockSize >= 1 && + blockSize <= static_cast(BLOCK_SIZE_LIMIT); + } + return blockSize >= 16U && + blockSize <= static_cast(BLOCK_SIZE_LIMIT) && + blockSize % 16U == 0; +} + +static const std::map> + DTYPE_SUPPORT_MAP = {{QUERY_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, + {ORI_KV_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, + {CMP_KV_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, + {CU_SEQLENS_ORI_KV_NAME, {ge::DT_INT32}}, + {CU_SEQLENS_CMP_KV_NAME, {ge::DT_INT32}}, + {ORI_SPARSE_INDICES, {ge::DT_INT32}}, + {CMP_SPARSE_INDICES, {ge::DT_INT32}}, + {ATTEN_OUT_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, + {ORI_BLOCK_TABLE_NAME, {ge::DT_INT32}}, + {CMP_BLOCK_TABLE_NAME, {ge::DT_INT32}}, + {SINKS_NAME, {ge::DT_FLOAT}}, + {METADATA_NAME, {ge::DT_INT32}}, + {CU_SEQLENS_Q_NAME, {ge::DT_INT32}}, + {SEQUSED_Q_NAME, {ge::DT_INT32}}, + {SEQUSED_ORI_KV_NAME, {ge::DT_INT32}}, + {SEQUSED_CMP_KV_NAME, {ge::DT_INT32}}, + {CMP_RESIDUAL_KV_NAME, {ge::DT_INT32}}, + {ORI_TOPK_LENGTH_NAME, {ge::DT_INT32}}, + {CMP_TOPK_LENGTH_NAME, {ge::DT_INT32}}}; + +static const std::map> LAYOUT_SUPPORT_MAP = + { + {QUERY_NAME, {SMLALayout::BSND, SMLALayout::TND}}, + {ORI_KV_NAME, {SMLALayout::PA_BBND, SMLALayout::TND, SMLALayout::BSND}}, + {CMP_KV_NAME, {SMLALayout::PA_BBND, SMLALayout::TND, SMLALayout::BSND}}, + {ATTEN_OUT_NAME, {SMLALayout::BSND, SMLALayout::TND}}, + {ORI_SPARSE_INDICES, {SMLALayout::BSND, SMLALayout::TND}}, + {CMP_SPARSE_INDICES, {SMLALayout::BSND, SMLALayout::TND}}, +}; + +static const std::map DATATYPE_TO_STRING_MAP = { + {ge::DT_UNDEFINED, + "DT_UNDEFINED"}, // Used to indicate a DataType field has not been set. + {ge::DT_FLOAT, "DT_FLOAT"}, // float type + {ge::DT_FLOAT16, "DT_FLOAT16"}, // fp16 type + {ge::DT_INT8, "DT_INT8"}, // int8 type + {ge::DT_INT16, "DT_INT16"}, // int16 type + {ge::DT_UINT16, "DT_UINT16"}, // uint16 type + {ge::DT_UINT8, "DT_UINT8"}, // uint8 type + {ge::DT_INT64, "DT_INT64"}, // int64 type + {ge::DT_INT32, "DT_INT32"}, // uint32 type + {ge::DT_UINT32, "DT_UINT32"}, // unsigned int32 + {ge::DT_UINT64, "DT_UINT64"}, // unsigned int64 + {ge::DT_DOUBLE, "DT_DOUBLE"}, // double type + {ge::DT_BOOL, "DT_BOOL"}, // bool type + {ge::DT_DUAL, "DT_DUAL"}, // dual output type + {ge::DT_DUAL_SUB_INT8, "DT_DUAL_SUB_INT8"}, // dual output int8 type + {ge::DT_DUAL_SUB_UINT8, "DT_DUAL_SUB_UINT8"}, // dual output uint8 type + {ge::DT_COMPLEX64, "DT_COMPLEX64"}, // complex64 type + {ge::DT_COMPLEX32, "DT_COMPLEX32"}, // complex32 type + {ge::DT_COMPLEX128, "DT_COMPLEX128"}, // complex128 type + {ge::DT_QINT8, "DT_QINT8"}, // qint8 type + {ge::DT_QINT16, "DT_QINT16"}, // qint16 type + {ge::DT_QINT32, "DT_QINT32"}, // qint32 type + {ge::DT_QUINT16, "DT_QUINT16"}, // quint16 type + {ge::DT_QUINT8, "DT_QUINT8"}, // quint8 type + {ge::DT_RESOURCE, "DT_RESOURCE"}, // resource type + {ge::DT_STRING_REF, "DT_STRING_REF"}, // string ref type + {ge::DT_STRING, "DT_STRING"}, // string type + {ge::DT_VARIANT, "DT_VARIANT"}, // dt_variant type + {ge::DT_BF16, "DT_BFLOAT16"}, // dt_bfloat16 type + {ge::DT_UINT1, "DT_UINT1"}, // dt_variant type + {ge::DT_INT4, "DT_INT4"}, // dt_variant type + {ge::DT_INT2, "DT_INT2"}, // dt_variant type + {ge::DT_UINT2, "DT_UINT2"} // dt_variant type +}; + +static uint64_t GetStorageShapeStride0(const gert::Shape& storageShape) { + if (storageShape.GetDimNum() <= DIM_NUM_ONE) { + return 0ULL; + } + + uint64_t stride0 = 1ULL; + for (size_t i = 1; i < storageShape.GetDimNum(); ++i) { + int64_t dim = storageShape.GetDim(i); + if (dim <= 0) { + return 0ULL; + } + stride0 *= static_cast(dim); + } + return stride0; +} + +template +static auto GetStride0FromStrideObject(const StrideT& stride, int) + -> decltype(stride.GetDimNum(), stride.GetStride(0), uint64_t()) { + if (stride.GetDimNum() <= 0) { + return 0ULL; + } + int64_t stride0 = stride.GetStride(0); + return stride0 > 0 ? static_cast(stride0) : 0ULL; +} + +template +static uint64_t GetStride0FromStrideObject(const StrideT&, ...) { + return 0ULL; +} + +template +static auto GetStride0FromStrideScalar(const StrideT& stride, int) + -> decltype(stride > 0, static_cast(stride)) { + return stride > 0 ? static_cast(stride) : 0ULL; +} + +template +static uint64_t GetStride0FromStrideScalar(const StrideT&, ...) { + return 0ULL; +} + +template +static uint64_t GetStride0FromStrideElement(const StrideT& stride) { + // CANN stride APIs return a dimension-wise stride array. In newer headers, + // stride[0] is scalar stride0. In compatibility headers it may be a stride + // object. Non-positive stride is treated as unavailable and falls back to the + // storage-shape contiguous calculation. + uint64_t stride0 = GetStride0FromStrideScalar(stride, 0); + if (stride0 > 0) { + return stride0; + } + return GetStride0FromStrideObject(stride, 0); +} + +template +static uint64_t GetStride0FromStrideArray(const StrideT* stride) { + if (stride == nullptr) { + return 0ULL; + } + return GetStride0FromStrideElement(stride[0]); +} + +template +static auto TryGetOptionalInputStride0(ContextT* context, + uint32_t inputIndex, + int) + -> decltype(context->GetOptionalInputStride(inputIndex), uint64_t()) { + return GetStride0FromStrideArray(context->GetOptionalInputStride(inputIndex)); +} + +template +static uint64_t TryGetOptionalInputStride0(ContextT*, uint32_t, ...) { + return 0ULL; +} + +// Compatibility path for CANN headers that do not expose +// GetOptionalInputStride. Some tiling contexts only provide real stride for +// view inputs through InputIsView/GetInputStride. Returning 0 means the stride +// is unavailable; the caller then falls back to storage-shape contiguous +// stride. +template +static auto TryGetInputViewStride0(ContextT* context, uint32_t inputIndex, int) + -> decltype(context->InputIsView(inputIndex), + context->GetInputStride(inputIndex), + uint64_t()) { + if (!context->InputIsView(inputIndex)) { + return 0ULL; + } + return GetStride0FromStrideArray(context->GetInputStride(inputIndex)); +} + +template +static uint64_t TryGetInputViewStride0(ContextT*, uint32_t, ...) { + return 0ULL; +} + +std::string SMLALayoutToSerialString(SMLALayout layout) { + switch (layout) { + case SMLALayout::BSND: + return "BSND"; + case SMLALayout::TND: + return "TND"; + case SMLALayout::PA_BBND: + return "PA_BBND"; + default: + return "UNKNOWN"; + } +} + +struct SMLACompileInfo { + int64_t core_num; +}; + +static const std::map> SMLA_LAYOUT_AXIS_MAP = + { + {SMLALayout::BSND, + {SMLAAxis::B, SMLAAxis::S, SMLAAxis::N, SMLAAxis::D}}, + {SMLALayout::TND, {SMLAAxis::T, SMLAAxis::N, SMLAAxis::D}}, + {SMLALayout::PA_BBND, + {SMLAAxis::Bn, SMLAAxis::Bs, SMLAAxis::N, SMLAAxis::D}}, +}; + +static const std::map SMLA_LAYOUT_DIM_MAP = { + {SMLALayout::BSND, DIM_NUM_FOUR}, + {SMLALayout::TND, DIM_NUM_THREE}, + {SMLALayout::PA_BBND, DIM_NUM_FOUR}, +}; + +static std::string SMLADataTypeToSerialString(ge::DataType type) { + const auto it = DATATYPE_TO_STRING_MAP.find(type); + if (it != DATATYPE_TO_STRING_MAP.end()) { + return it->second; + } else { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + "sparseFlashMla", + "data_type", + std::to_string(type), + "datatype " + std::to_string(type) + " not support"); + return "UNDEFINED"; + } +} + +// --------------------------SMLAInfoParser类成员函数定义------------------------------------ +ge::graphStatus SMLAInfoParser::CheckRequiredInOutExistence() const { + OP_CHECK_IF(opParamInfo_.q.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "query", "The shape of query is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.q.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "query", "The desc of query is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.oriKv.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "ori_kv", "The tensor of ori_kv is nullptr"), + return ge::GRAPH_FAILED); + if (perfMode_ == SMLATemplateMode::HCA_TEMPLATE_MODE) { + OP_CHECK_IF(opParamInfo_.cmpKv.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "cmp_kv", "The tensor of cmp_kv is nullptr"), + return ge::GRAPH_FAILED); + } + if (perfMode_ == SMLATemplateMode::CSA_TEMPLATE_MODE) { + OP_CHECK_IF(opParamInfo_.cmpKv.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "cmp_kv", "The tensor of cmp_kv is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.cmpSparseIndices.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cmp_sparse_indices", + "The tensor of cmp_sparse_indices is nullptr"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::CheckRequiredAttrExistence() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::CheckRequiredParaExistence() const { + if (CheckRequiredInOutExistence() != ge::GRAPH_SUCCESS || + CheckRequiredAttrExistence() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::CheckUnrequiredParaExistence() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetOpName() { + if (context_->GetNodeName() == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + "XllmKernelSparseFlashMla", + "TilingContext", + "opName got from TilingContext is nullptr"); + return ge::GRAPH_FAILED; + } + opName_ = context_->GetNodeName(); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetNpuInfo() { + platformInfo_ = context_->GetPlatformInfo(); + OP_CHECK_IF( + platformInfo_ == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(Ops::Base::GetOpInfo(opName_), + "platformInfo_", + "GetPlatformInfo is nullptr."), + return ge::GRAPH_FAILED); + + auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo_); + aivNum_ = ascendcPlatform.GetCoreNumAiv(); + aicNum_ = ascendcPlatform.GetCoreNumAic(); + if (aicNum_ == 0 || aivNum_ == 0) { + OP_LOGE_LIBOPAPI_REPORT( + Ops::Base::GetOpInfo(opName_), "%s", "num of core obtained is 0."); + REPORT_PREDEFINED_ERR_MSG( + "EZ1008", + std::vector({"opName", "reason"}), + std::vector( + {Ops::Base::GetOpInfo(opName_), "num of core obtained is 0."})); + return ge::GRAPH_FAILED; + } + + npuArch_ = ascendcPlatform.GetCurNpuArch(); + if (npuArch_ != NpuArch::DAV_2201 && npuArch_ != NpuArch::DAV_3510 && + npuArch_ != NpuArch::DAV_9201 && npuArch_ != NpuArch::DAV_9202) { + OP_LOGE(opName_, + "Npu Arch Version[%d] is not support.", + static_cast(npuArch_)); + return ge::GRAPH_FAILED; + } + batchConsistency_ = + (context_->GetDeterministicLevel() == BATCH_CONSISTENCY_LEVEL); + OP_LOGD(opName_, "deterministic_level=%d", context_->GetDeterministicLevel()); + + return ge::GRAPH_SUCCESS; +} + +void SMLAInfoParser::GetOptionalInputParaInfo() { + sparse_mla_checker::PopulateOptionalTensorParam( + context_, ORI_KV_INDEX, opParamInfo_.oriKv); + sparse_mla_checker::PopulateOptionalTensorParam( + context_, CMP_KV_INDEX, opParamInfo_.cmpKv); + sparse_mla_checker::PopulateOptionalTensorParam( + context_, ORI_SPARSE_INDICES_INDEX, opParamInfo_.oriSparseIndices); + sparse_mla_checker::PopulateOptionalTensorParam( + context_, CMP_SPARSE_INDICES_INDEX, opParamInfo_.cmpSparseIndices); + sparse_mla_checker::PopulateOptionalTensorParam( + context_, ORI_BLOCK_TABLE_INDEX, opParamInfo_.oriBlockTable); + sparse_mla_checker::PopulateOptionalTensorParam( + context_, CMP_BLOCK_TABLE_INDEX, opParamInfo_.cmpBlockTable); + sparse_mla_checker::PopulateOptionalTensorParam( + context_, SINKS_INDEX, opParamInfo_.sinks); + sparse_mla_checker::PopulateOptionalTensorParam( + context_, CU_SEQLENS_Q_INDEX, opParamInfo_.cuSeqLensQ); + sparse_mla_checker::PopulateOptionalTensorParam( + context_, CU_SEQLENS_ORI_KV_INDEX, opParamInfo_.cuSeqLensOriKv); + sparse_mla_checker::PopulateOptionalTensorParam( + context_, CU_SEQLENS_CMP_KV_INDEX, opParamInfo_.cuSeqLensCmpKv); + sparse_mla_checker::PopulateOptionalTensorParam( + context_, SEQUSED_Q_INDEX, opParamInfo_.seqUsedQ); + sparse_mla_checker::PopulateOptionalTensorParam( + context_, SEQUSED_ORI_KV_INDEX, opParamInfo_.sequsedOriKv); + sparse_mla_checker::PopulateOptionalTensorParam( + context_, SEQUSED_CMP_KV_INDEX, opParamInfo_.sequsedCmpKv); + sparse_mla_checker::PopulateOptionalTensorParam( + context_, CMP_RESIDUAL_KV_INDEX, opParamInfo_.cmpResidualKv); + sparse_mla_checker::PopulateOptionalTensorParam( + context_, ORI_TOPK_LENGTH_INDEX, opParamInfo_.oriTopkLength); + sparse_mla_checker::PopulateOptionalTensorParam( + context_, CMP_TOPK_LENGTH_INDEX, opParamInfo_.cmpTopkLength); + sparse_mla_checker::PopulateOptionalTensorParam( + context_, METADATA_INDEX, opParamInfo_.metadata); +} + +void SMLAInfoParser::GetInputParaInfo() { + opParamInfo_.q.desc = context_->GetInputDesc(Q_INDEX); + opParamInfo_.q.shape = context_->GetInputShape(Q_INDEX); + GetOptionalInputParaInfo(); +} + +void SMLAInfoParser::GetOutputParaInfo() { + opParamInfo_.attnOut.desc = context_->GetOutputDesc(ATTN_OUT_INDEX); + opParamInfo_.attnOut.shape = context_->GetOutputShape(ATTN_OUT_INDEX); + opParamInfo_.softmaxLse.desc = context_->GetOutputDesc(SOFTMAX_LSE_INDEX); + opParamInfo_.softmaxLse.shape = context_->GetOutputShape(SOFTMAX_LSE_INDEX); +} + +ge::graphStatus SMLAInfoParser::GetAttrParaInfo() { + auto attrs = context_->GetAttrs(); + OP_CHECK_IF( + attrs == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + context_->GetNodeName(), "attrs", "attrs got from ge is nullptr"), + return ge::GRAPH_FAILED); + OP_LOGI(context_->GetNodeName(), "GetAttrParaInfo start"); + opParamInfo_.softmaxScale = + attrs->GetAttrPointer(ATTR_SOFTMAX_SCALE_INDEX); + opParamInfo_.cmpRatio = attrs->GetAttrPointer(ATTR_CMP_RATIO_INDEX); + opParamInfo_.oriMaskMode = + attrs->GetAttrPointer(ATTR_ORI_MASK_MODE_INDEX); + opParamInfo_.cmpMaskMode = + attrs->GetAttrPointer(ATTR_CMP_MASK_MODE_INDEX); + opParamInfo_.oriWinLeft = + attrs->GetAttrPointer(ATTR_ORI_WIN_LEFT_INDEX); + opParamInfo_.oriWinRight = + attrs->GetAttrPointer(ATTR_ORI_WIN_RIGHT_INDEX); + opParamInfo_.layoutQ = attrs->GetStr(ATTR_LAYOUT_Q_INDEX); + opParamInfo_.layoutKv = attrs->GetStr(ATTR_LAYOUT_KV_INDEX); + opParamInfo_.topkValueMode = + attrs->GetAttrPointer(ATTR_TOPK_VALUE_MODE_INDEX); + opParamInfo_.returnSoftmaxLse = + attrs->GetAttrPointer(ATTR_RETURN_SOFTMAX_LSE_INDEX); + + auto oriKeyStrides = context_->GetDynamicInputStride(ORI_KV_INDEX, 0); + if (oriKeyStrides != nullptr && oriKeyStrides->GetDimNum() > 0) { + for (size_t i = 0; i < oriKeyStrides->GetDimNum(); i++) { + oriKeyStridesVec_.push_back(oriKeyStrides->GetStride(i)); + } + } + auto cmpKeyStrides = context_->GetDynamicInputStride(CMP_KV_INDEX, 0); + if (cmpKeyStrides != nullptr && cmpKeyStrides->GetDimNum() > 0) { + for (size_t i = 0; i < cmpKeyStrides->GetDimNum(); i++) { + cmpKeyStridesVec_.push_back(cmpKeyStrides->GetStride(i)); + } + } + + OP_LOGI(context_->GetNodeName(), "GetAttrParaInfo end"); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetOpParaInfo() { + GetInputParaInfo(); + GetOutputParaInfo(); + if (ge::GRAPH_SUCCESS != GetAttrParaInfo()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +uint64_t SMLAInfoParser::GetOptionalInputStride0(uint32_t inputIndex) const { + const gert::Tensor* inputTensor = nullptr; + if (inputIndex == ORI_KV_INDEX) { + inputTensor = opParamInfo_.oriKv.tensor; + } else if (inputIndex == CMP_KV_INDEX) { + inputTensor = opParamInfo_.cmpKv.tensor; + } + if (inputTensor == nullptr) { + return 0ULL; + } + + uint64_t stride0 = TryGetOptionalInputStride0(context_, inputIndex, 0); + if (stride0 > 0) { + return stride0; + } + + // Compatible with CANN packages that only expose view stride by normal input + // index. + stride0 = TryGetInputViewStride0(context_, inputIndex, 0); + if (stride0 > 0) { + return stride0; + } + + const gert::Shape& storageShape = inputTensor->GetStorageShape(); + stride0 = GetStorageShapeStride0(storageShape); + const char* inputName = inputIndex == ORI_KV_INDEX ? "ori_kv" : "cmp_kv"; + OP_LOGW(context_->GetNodeName(), + "Cannot get %s stride0 from tiling context stride APIs. Use storage " + "shape to infer contiguous " + "stride0(%lu). Non-contiguous %s requires GetOptionalInputStride or " + "GetInputStride support.", + inputName, + stride0, + inputName); + return stride0; +} +ge::graphStatus SMLAInfoParser::GetInOutDataType() { + qType_ = opParamInfo_.q.desc->GetDataType(); + outputType_ = opParamInfo_.attnOut.desc->GetDataType(); + if (opParamInfo_.oriKv.desc != nullptr) { + oriKvType_ = opParamInfo_.oriKv.desc->GetDataType(); + } + if (opParamInfo_.cmpKv.desc != nullptr) { + cmpKvType_ = opParamInfo_.cmpKv.desc->GetDataType(); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetSMLATemplateMode() { + if (opParamInfo_.oriKv.desc != nullptr) { + if (opParamInfo_.cmpKv.desc != nullptr && + opParamInfo_.cmpSparseIndices.tensor != nullptr) { + if (opParamInfo_.oriSparseIndices.tensor != nullptr) { + perfMode_ = SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE; + } else { + perfMode_ = SMLATemplateMode::CSA_TEMPLATE_MODE; + } + } else if (opParamInfo_.cmpKv.desc != nullptr && + opParamInfo_.cmpSparseIndices.tensor == nullptr) { + perfMode_ = SMLATemplateMode::HCA_TEMPLATE_MODE; + } else if (opParamInfo_.cmpKv.desc == nullptr && + opParamInfo_.cmpSparseIndices.tensor == nullptr) { + if (opParamInfo_.oriSparseIndices.tensor != nullptr) { + // A2A3此处dspark用 + // SWA_TEMPLATE_MODE+hasOri判断;给A5留ORI_SPARSE_TEMPLATE_MODE分支 + if (IsA5Arch(npuArch_) || IsA6Arch(npuArch_)) { + perfMode_ = SMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE; + } else { + // DSpark: oriMaskMode=0 + ori_sparse_indices on SWA kernel path. + if (opParamInfo_.oriMaskMode == nullptr || + *opParamInfo_.oriMaskMode != 0U) { + const std::string errorReason = + ("SWA ori sparse (DSpark) requires oriMaskMode 0, but got " + + std::to_string(opParamInfo_.oriMaskMode != nullptr + ? *opParamInfo_.oriMaskMode + : UINT32_MAX) + + "."); + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + Ops::Base::GetOpInfo(opName_), + "ori_sparse_indices, ori_mask_mode", + errorReason); + return ge::GRAPH_FAILED; + } + perfMode_ = SMLATemplateMode::SWA_TEMPLATE_MODE; + } + } else { + perfMode_ = SMLATemplateMode::SWA_TEMPLATE_MODE; + } + } else { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cmp_kv", + "When cmp_sparse_indices is not nullptr, cmp_kv cannot be nullptr"); + return ge::GRAPH_FAILED; + } + if (perfMode_ == SMLATemplateMode::HCA_TEMPLATE_MODE || + perfMode_ == SMLATemplateMode::CSA_TEMPLATE_MODE) { + if (kvLayout_ == SMLALayout::TND && + opParamInfo_.cuSeqLensCmpKv.tensor == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cu_seqlens_cmp_kv", + "The layout_kv is" + SMLALayoutToSerialString(kvLayout_) + + ", seqlens_cmp_kv must be provided"); + return ge::GRAPH_FAILED; + } + } + } else { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "ori_kv", "ori_kv is nullptr"); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetQueryAndOutLayout() { + const map> layoutMap = { + {"BSND", {SMLALayout::BSND, SMLALayout::BSND}}, + {"TND", {SMLALayout::TND, SMLALayout::TND}}, + }; + std::string layout(opParamInfo_.layoutQ); + auto it = layoutMap.find(layout); + if (it != layoutMap.end()) { + qLayout_ = it->second.first; + outLayout_ = it->second.second; + oriSparseIndicesLayout_ = qLayout_; + cmpSparseIndicesLayout_ = qLayout_; + } else { + OP_LOGE_FOR_INVALID_VALUE( + opName_, "layout_q", layout.c_str(), "BSND or TND"); + return ge::GRAPH_FAILED; + } + if (qLayout_ == SMLALayout::BSND) { + OP_CHECK_IF(opParamInfo_.cuSeqLensQ.tensor != nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cu_seqlens_q", + "When layout_q is BSND, cu_seqlens_q should be null"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetKvLayout() { + const map layoutKVMap = { + {"PA_BBND", SMLALayout::PA_BBND}, + {"TND", SMLALayout::TND}, + {"BSND", SMLALayout::BSND}, + }; + std::string layout(opParamInfo_.layoutKv); + auto it = layoutKVMap.find(layout); + if (it != layoutKVMap.end()) { + kvLayout_ = it->second; + } else { + OP_LOGE_FOR_INVALID_VALUE( + opName_, "layout_kv", layout.c_str(), "BSND, PA_BBND or TND"); + return ge::GRAPH_FAILED; + } + if (kvLayout_ != SMLALayout::PA_BBND && qLayout_ != kvLayout_) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + opName_, + "layout_q and layout_kv", + SMLALayoutToSerialString(qLayout_) + " and " + + SMLALayoutToSerialString(kvLayout_), + "Layout_q and layout_kv only support BSND/BSND, TND/TND, BSND/PA_BBND " + "or TND/PA_BBND"); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +// =============Parser function==================== +bool SMLAInfoParser::HasAxis(const SMLAAxis& axis, + const SMLALayout& layout, + const gert::Shape& shape) const { + const auto& layoutIt = SMLA_LAYOUT_AXIS_MAP.find(layout); + if (layoutIt == SMLA_LAYOUT_AXIS_MAP.end()) { + return false; + } + + const std::vector& axes = layoutIt->second; + const auto& axisIt = std::find(axes.begin(), axes.end(), axis); + if (axisIt == axes.end()) { + return false; + } + const auto& dimIt = SMLA_LAYOUT_DIM_MAP.find(layout); + if (dimIt == SMLA_LAYOUT_DIM_MAP.end() || + dimIt->second != shape.GetDimNum()) { + return false; + } + return true; +} + +size_t SMLAInfoParser::GetAxisIdx(const SMLAAxis& axis, + const SMLALayout& layout) const { + const std::vector& axes = SMLA_LAYOUT_AXIS_MAP.find(layout)->second; + const auto& axisIt = std::find(axes.begin(), axes.end(), axis); + return std::distance(axes.begin(), axisIt); +} + +int64_t SMLAInfoParser::GetAxisNum(const gert::Shape& shape, + const SMLAAxis& axis, + const SMLALayout& layout) const { + return HasAxis(axis, layout, shape) ? shape.GetDim(GetAxisIdx(axis, layout)) + : invalidDimValue_; +} + +ge::graphStatus SMLAInfoParser::SetSMLAShape() { + qShape_ = opParamInfo_.q.shape->GetStorageShape(); + if (opParamInfo_.oriKv.tensor != nullptr) { + oriKvShape_ = opParamInfo_.oriKv.tensor->GetStorageShape(); + } else { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "oriKv", "OriKv is nullptr, please check input parameters"); + return ge::GRAPH_FAILED; + } + if (opParamInfo_.cmpKv.tensor != nullptr) { + cmpKvShape_ = opParamInfo_.cmpKv.tensor->GetStorageShape(); + } + if (opParamInfo_.oriSparseIndices.tensor != nullptr) { + oriSparseIndicesShape_ = + opParamInfo_.oriSparseIndices.tensor->GetStorageShape(); + hasOriSparseIndices_ = true; + oriSparseIndexWidth_ = GetAxisNum( + oriSparseIndicesShape_, SMLAAxis::K, oriSparseIndicesLayout_); + } + if (perfMode_ == SMLATemplateMode::CSA_TEMPLATE_MODE || + perfMode_ == SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { + if (opParamInfo_.cmpSparseIndices.tensor != nullptr) { + cmpSparseIndicesShape_ = + opParamInfo_.cmpSparseIndices.tensor->GetStorageShape(); + } else { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cmp_sparse_indices", + "Cmp_sparse_indices is nullptr, please check input parameters"); + return ge::GRAPH_FAILED; + } + } + + if (perfMode_ == SMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE || + perfMode_ == SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { + if (opParamInfo_.oriSparseIndices.tensor != nullptr) { + oriSparseIndicesShape_ = + opParamInfo_.oriSparseIndices.tensor->GetStorageShape(); + } + } + + return ge::GRAPH_SUCCESS; +} + +// 根据layout计算期望的连续stride +std::vector SMLAInfoParser::GetKvstride( + const gert::Shape& shape, + const SMLALayout& layout) const { + std::vector expectedStrides; + if (layout == SMLALayout::BSND || layout == SMLALayout::PA_BBND) { + uint64_t dim1 = static_cast(shape.GetDim(1)); + uint64_t dim2 = static_cast(shape.GetDim(2)); + uint64_t dim3 = static_cast(shape.GetDim(3)); + expectedStrides = {dim1 * dim2 * dim3, dim2 * dim3, dim3, 1}; + } else if (layout == SMLALayout::TND) { + uint64_t dim1 = static_cast(shape.GetDim(1)); + uint64_t dim2 = static_cast(shape.GetDim(2)); + expectedStrides = {dim1 * dim2, dim2, 1}; + } + return expectedStrides; +} + +// 非连续校验:通过shape计算expected stride进行校验 +// PA_BBND时,只允许0轴非连续,其余轴必须连续 +// 非PA_BBND时,所有轴都必须连续 +ge::graphStatus SMLAInfoParser::CheckContiguous() const { + bool oriKeyNonContiguous = false; + bool cmpKeyNonContiguous = false; + size_t checkStartIdx = (kvLayout_ == SMLALayout::PA_BBND) ? 1 : 0; + if (opParamInfo_.oriKv.tensor != nullptr && !oriKeyStridesVec_.empty() && + opParamInfo_.oriKv.tensor->GetShapeSize() > 0) { + std::vector oriExpectedStrides = + GetKvstride(oriKvShape_, kvLayout_); + OP_CHECK_IF(oriKeyStridesVec_.size() != oriExpectedStrides.size(), + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "ori_kv", + "Ori_kv strideVec size[" + + std::to_string(oriKeyStridesVec_.size()) + + "] not match layout_kv expect len[" + + std::to_string(oriExpectedStrides.size()) + "]"), + return ge::GRAPH_FAILED); + oriKeyNonContiguous = + static_cast(oriKeyStridesVec_[checkStartIdx]) != + oriExpectedStrides[checkStartIdx]; + } + if (opParamInfo_.cmpKv.tensor != nullptr && !cmpKeyStridesVec_.empty() && + opParamInfo_.cmpKv.tensor->GetShapeSize() > 0) { + std::vector cmpExpectedStrides = + GetKvstride(cmpKvShape_, kvLayout_); + OP_CHECK_IF(cmpKeyStridesVec_.size() != cmpExpectedStrides.size(), + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cmp_kv", + "Cmp_kv strideVec size[" + + std::to_string(cmpKeyStridesVec_.size()) + + "] not match kvLayout expect len[" + + std::to_string(cmpExpectedStrides.size()) + "]"), + return ge::GRAPH_FAILED); + cmpKeyNonContiguous = + static_cast(cmpKeyStridesVec_[checkStartIdx]) != + cmpExpectedStrides[checkStartIdx]; + } + + OP_CHECK_IF(oriKeyNonContiguous, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "ori_kv", + "Ori_kv only support non-continuous keying on the 0-axis"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(cmpKeyNonContiguous, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cmp_kv", + "Cmp_kv only support non-continuous keying on the 0-axis"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetN1Size() { + n1Size_ = GetAxisNum(qShape_, SMLAAxis::N, qLayout_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetN2Size() { + if (opParamInfo_.oriKv.tensor != nullptr) { + n2Size_ = GetAxisNum(oriKvShape_, SMLAAxis::N, kvLayout_); + } + if (opParamInfo_.cmpKv.tensor != nullptr) { + n2Size_ = GetAxisNum(cmpKvShape_, SMLAAxis::N, kvLayout_); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetGSize() { + if (n2Size_ != 0) { + gSize_ = n1Size_ / n2Size_; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetActualSeqLenSize( + int64_t& size, + const gert::Tensor* tensor, + SMLALayout& layout, + const std::string& name) const { + if ((tensor == nullptr)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + name.c_str(), + "When layout_q is " + SMLALayoutToSerialString(layout) + ", " + name + + " must be provided"); + return ge::GRAPH_FAILED; + } + int64_t shapeSize = tensor->GetShapeSize(); + if (shapeSize <= 0) { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + name.c_str(), + std::to_string(shapeSize).c_str(), + "The shape size of " + name + " should be greater than 0"); + return ge::GRAPH_FAILED; + } + size = shapeSize - 1; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetActualSeqLenQSize(int64_t& size) { + return GetActualSeqLenSize( + size, opParamInfo_.cuSeqLensQ.tensor, qLayout_, "cu_seqlens_q"); +} + +ge::graphStatus SMLAInfoParser::GetBatchSize() { + // 获取B基准 // 1、非TND: 以query的batch_size维度为基 + // 2、TND: actual_seq_lens_q必须传入, 以actual_seq_lens_q数组的长度为B轴大小 + if (qLayout_ == SMLALayout::TND) { + return GetActualSeqLenQSize(bSize_); + } else { // BSND + bSize_ = GetAxisNum(qShape_, SMLAAxis::B, qLayout_); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetQTSize() { + // 获取query的T基准 // 1、非TND: 以query的batch_size维度为基准 + // 2、TND: actual_seq_lens_q必须传入, 以actual_seq_lens_q数组的长度为B轴大小 + qTSize_ = (qLayout_ == SMLALayout::TND) + ? GetAxisNum(qShape_, SMLAAxis::T, qLayout_) + : 0; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetS1Size() { + // 获取S1基准 // 1、非TND: 以query的S维度为基准 + // 2、TND: actual_seq_lens_q必须传入, 以actual_seq_lens_q数组中的最大值为基准 + if (qLayout_ == SMLALayout::TND) { + s1Size_ = GetAxisNum(qShape_, SMLAAxis::T, qLayout_); + } else { // BSND + s1Size_ = GetAxisNum(qShape_, SMLAAxis::S, qLayout_); + } + if (perfMode_ == SMLATemplateMode::CSA_TEMPLATE_MODE || + perfMode_ == SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { + if (cmpSparseIndicesLayout_ == SMLALayout::TND) { + uint32_t cmpSparseIndicesT = GetAxisNum( + cmpSparseIndicesShape_, SMLAAxis::T, cmpSparseIndicesLayout_); + OP_CHECK_IF(cmpSparseIndicesT != s1Size_, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "cmp_sparse_indices", + Ops::Base::ToString(cmpSparseIndicesShape_), + "T size check failed"), + return ge::GRAPH_FAILED); + } else { + uint32_t cmpSparseIndicesS1 = GetAxisNum( + cmpSparseIndicesShape_, SMLAAxis::S, cmpSparseIndicesLayout_); + OP_CHECK_IF(cmpSparseIndicesS1 != s1Size_, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "cmp_sparse_indices", + Ops::Base::ToString(cmpSparseIndicesShape_), + "S1 size check failed"), + return ge::GRAPH_FAILED); + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetMaxBlockNumPerBatch() { + if (opParamInfo_.oriBlockTable.tensor == nullptr) { + return ge::GRAPH_SUCCESS; + } + uint32_t oriDimNum = + opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDimNum(); + if (oriDimNum != DIM_NUM_TWO) { + OP_LOGE_FOR_INVALID_SHAPEDIM(opName_, + "ori_block_table", + std::to_string(oriDimNum).c_str(), + std::to_string(DIM_NUM_TWO).c_str()); + return ge::GRAPH_FAILED; + } + if (opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDim(1) < 0) { + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "ori_block_table", + ToStringRaw(opParamInfo_.oriBlockTable.tensor->GetStorageShape()) + .c_str(), + "Ori_block_table's second dimension(" + + std::to_string( + opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDim( + 1)) + + ") should be non-negative number"); + return ge::GRAPH_FAILED; + } + oriMaxBlockNumPerBatch_ = + opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDim(1); + + if (opParamInfo_.cmpBlockTable.tensor != nullptr) { + uint32_t cmpDimNum = + opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDimNum(); + if (cmpDimNum != DIM_NUM_TWO) { + OP_LOGE_FOR_INVALID_SHAPEDIM(opName_, + "cmp_block_table", + std::to_string(cmpDimNum).c_str(), + std::to_string(DIM_NUM_TWO).c_str()); + return ge::GRAPH_FAILED; + } + if (qLayout_ == SMLALayout::TND || qLayout_ == SMLALayout::BSND) { + if (opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim(0) != + bSize_) { + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "cmp_block_table", + ToStringRaw(opParamInfo_.cmpBlockTable.tensor->GetStorageShape()) + .c_str(), + "Cmp_block_table's first dimension(" + + std::to_string( + opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim( + 0)) + + ") should be equal to query's B(" + std::to_string(bSize_) + + ")"); + return ge::GRAPH_FAILED; + } + } + if (opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim(1) <= 0) { + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "cmp_block_table", + ToStringRaw(opParamInfo_.cmpBlockTable.tensor->GetStorageShape()) + .c_str(), + "cmp_block_table's second dimension(" + + std::to_string( + opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim( + 1)) + + ") should be greater than 0"); + return ge::GRAPH_FAILED; + } + cmpMaxBlockNumPerBatch_ = + opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim(1); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetBlockSize() { + if (kvLayout_ != SMLALayout::PA_BBND) { + return ge::GRAPH_SUCCESS; + } + if (opParamInfo_.oriKv.tensor != nullptr) { + oriBlockSize_ = GetAxisNum(oriKvShape_, SMLAAxis::Bs, kvLayout_); + } + if (opParamInfo_.cmpKv.tensor != nullptr) { + cmpBlockSize_ = GetAxisNum(cmpKvShape_, SMLAAxis::Bs, kvLayout_); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::SmlaGetMagicPM() { + if (!IsA6Arch(npuArch_) || kvLayout_ != SMLALayout::PA_BBND) { + return ge::GRAPH_SUCCESS; + } + if (oriBlockSize_ <= 0) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, + "ori_block_size", + "ori block size(" + + std::to_string(oriBlockSize_) + + ") must be greater than 0."); + return ge::GRAPH_FAILED; + } + CalcMagicP(static_cast(oriBlockSize_), oriP_, oriMLow_, oriMHigh_); + if (opParamInfo_.cmpKv.tensor != nullptr) { + if (cmpBlockSize_ <= 0) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cmp_block_size", + "cmp block size(" + std::to_string(cmpBlockSize_) + + ") must be greater than 0."); + return ge::GRAPH_FAILED; + } + CalcMagicP( + static_cast(cmpBlockSize_), cmpP_, cmpMLow_, cmpMHigh_); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetS2SizeForPageAttention() { + if (GetMaxBlockNumPerBatch() != ge::GRAPH_SUCCESS || + GetBlockSize() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + s2Size_ = oriMaxBlockNumPerBatch_ * oriBlockSize_; + cmpS2Size_ = cmpMaxBlockNumPerBatch_ * cmpBlockSize_; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetS2Size() { + if (kvLayout_ == SMLALayout::TND) { + s2Size_ = GetAxisNum(oriKvShape_, SMLAAxis::T, kvLayout_); + cmpS2Size_ = GetAxisNum(cmpKvShape_, SMLAAxis::T, kvLayout_); + return ge::GRAPH_SUCCESS; + } else if (kvLayout_ == SMLALayout::BSND) { + s2Size_ = GetAxisNum(oriKvShape_, SMLAAxis::S, kvLayout_); + cmpS2Size_ = GetAxisNum(cmpKvShape_, SMLAAxis::S, kvLayout_); + return ge::GRAPH_SUCCESS; + } else if (kvLayout_ == SMLALayout::PA_BBND) { + // 获取S2基准PAGE_ATTENTION S2 = block_table.dim1 * block_size + return GetS2SizeForPageAttention(); + } + return ge::GRAPH_FAILED; +} + +ge::graphStatus SMLAInfoParser::GetQHeadDim() { + qHeadDim_ = GetAxisNum(qShape_, SMLAAxis::D, qLayout_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetValueHeadDim() { + if (opParamInfo_.oriKv.tensor != nullptr) { + oriKvHeadDim_ = GetAxisNum(oriKvShape_, SMLAAxis::D, kvLayout_); + } + if (opParamInfo_.cmpKv.tensor != nullptr) { + cmpKvHeadDim_ = GetAxisNum(cmpKvShape_, SMLAAxis::D, kvLayout_); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetSparseBlockCount() { + if (opParamInfo_.oriSparseIndices.tensor != nullptr) { + oriSparseBlockCount_ = GetAxisNum( + oriSparseIndicesShape_, SMLAAxis::K, oriSparseIndicesLayout_); + } + if (opParamInfo_.cmpSparseIndices.tensor != nullptr) { + cmpSparseBlockCount_ = GetAxisNum( + cmpSparseIndicesShape_, SMLAAxis::K, cmpSparseIndicesLayout_); + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetSinks() { + if (opParamInfo_.sinks.tensor == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "sinks", "sinks must be provided"); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLAInfoParser::GetActualseqInfo() { + if (qLayout_ == SMLALayout::TND) { + if (opParamInfo_.cuSeqLensQ.tensor != nullptr) { + if (opParamInfo_.cuSeqLensQ.tensor->GetShapeSize() != bSize_ + 1) { + OP_LOGE_FOR_INVALID_SHAPESIZE( + opName_, + "cu_seqlens_q", + std::to_string(opParamInfo_.cuSeqLensQ.tensor->GetShapeSize()) + .c_str(), + std::to_string(bSize_ + 1)); + return ge::GRAPH_FAILED; + } + actualLenDimsQ_ = opParamInfo_.cuSeqLensQ.tensor->GetShapeSize() - + 1; // cuSeqLensQ shape is B+1 + } else { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cu_seqlens_q", + "When layout_q is TND, cu_seqlens_q must be provided"); + return ge::GRAPH_FAILED; + } + } else { + if (opParamInfo_.seqUsedQ.tensor != nullptr) { + actualLenDimsQ_ = opParamInfo_.seqUsedQ.tensor->GetShapeSize(); + } + } + if (kvLayout_ != SMLALayout::PA_BBND && kvLayout_ != SMLALayout::BSND && + kvLayout_ != SMLALayout::TND) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "layout_kv", + SMLALayoutToSerialString(kvLayout_), + "Ori_kv and cmp_kv only support PA_BBND, BSND and TND"); + return ge::GRAPH_FAILED; + } + if (opParamInfo_.sequsedOriKv.tensor != nullptr) { + actualLenDimsOriKV_ = opParamInfo_.sequsedOriKv.tensor->GetShapeSize(); + } + if (opParamInfo_.sequsedCmpKv.tensor != nullptr) { + actualLenDimsCmpKV_ = opParamInfo_.sequsedCmpKv.tensor->GetShapeSize(); + if (opParamInfo_.sequsedCmpKv.tensor->GetShapeSize() != bSize_) { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "seqused_cmp_kv", + std::to_string(opParamInfo_.sequsedCmpKv.tensor->GetShapeSize()), + "Seqused_cmp_kv's dimension should be equal to " + + std::to_string(bSize_)); + return ge::GRAPH_FAILED; + } + } + if (opParamInfo_.cmpResidualKv.tensor != nullptr) { + cmpResidualKVSize_ = opParamInfo_.cmpResidualKv.tensor->GetShapeSize(); + if (opParamInfo_.cmpResidualKv.tensor->GetShapeSize() != bSize_) { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "cmp_residual_kv", + std::to_string(opParamInfo_.cmpResidualKv.tensor->GetShapeSize()), + "Cmp_residual_kv's dimension should be equal to " + + std::to_string(bSize_)); + return ge::GRAPH_FAILED; + } + } + if (!IsA5Arch(npuArch_) && !IsA6Arch(npuArch_) && + IsNonEmptyOptionalTensor(opParamInfo_.cmpTopkLength.tensor)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cmp_topk_length", + "cmp_topk_length is reserved and does not support non-empty tensor " + "on " + + std::string(A2_A3_PLATFORM_LOG.c_str()) + "."); + return ge::GRAPH_FAILED; + } + if (kvLayout_ == SMLALayout::PA_BBND) { + if (opParamInfo_.sequsedOriKv.tensor != nullptr) { + if (qLayout_ == SMLALayout::BSND) { + if (opParamInfo_.sequsedOriKv.tensor->GetShapeSize() != bSize_) { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "seqused_ori_kv", + std::to_string(opParamInfo_.sequsedOriKv.tensor->GetShapeSize()), + "Seqused_ori_kv's dimension should be equal to " + + std::to_string(bSize_)); + return ge::GRAPH_FAILED; + } + } else { + if (opParamInfo_.sequsedOriKv.tensor->GetShapeSize() != bSize_) { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "seqused_ori_kv", + std::to_string(opParamInfo_.sequsedOriKv.tensor->GetShapeSize()), + "Seqused_ori_kv's dimension should be equal to " + + std::to_string(bSize_)); + return ge::GRAPH_FAILED; + } + } + actualLenDimsKV_ = opParamInfo_.sequsedOriKv.tensor->GetShapeSize(); + } else if (perfMode_ != SMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE && + perfMode_ != SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "seqused_ori_kv", + "Seqused_ori_kv must be provided when layout_kv is PA_BBND"); + return ge::GRAPH_FAILED; + } + } else if (kvLayout_ == SMLALayout::TND) { + } else if (kvLayout_ == SMLALayout::BSND) { + actualLenDimsKV_ = actualLenDimsOriKV_; + } else { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "layout_kv", + SMLALayoutToSerialString(kvLayout_), + "Ori_kv and cmp_kv only support PA_BBND, TND and BSND"); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +void SMLAInfoParser::GenerateInfo(SMLATilingInfo& smlaInfo) { + smlaInfo.opName = opName_; + smlaInfo.platformInfo = platformInfo_; + smlaInfo.opParamInfo = opParamInfo_; + smlaInfo.npuArch = npuArch_; + + smlaInfo.bSize = bSize_; + smlaInfo.n1Size = n1Size_; + smlaInfo.n2Size = n2Size_; + smlaInfo.s1Size = s1Size_; + smlaInfo.s2Size = s2Size_; + smlaInfo.cmpS2Size = cmpS2Size_; + smlaInfo.gSize = gSize_; + smlaInfo.qHeadDim = qHeadDim_; + smlaInfo.oriKvHeadDim = oriKvHeadDim_; + smlaInfo.cmpKvHeadDim = cmpKvHeadDim_; + smlaInfo.qTSize = qTSize_; + smlaInfo.oriSparseBlockCount = oriSparseBlockCount_; + smlaInfo.cmpSparseBlockCount = cmpSparseBlockCount_; + smlaInfo.sparseBlockCount = cmpSparseBlockCount_; + smlaInfo.hasOriSparseIndices = hasOriSparseIndices_; + smlaInfo.oriSparseIndexWidth = oriSparseIndexWidth_; + smlaInfo.oriWinLeft = oriWinLeft_; + smlaInfo.oriWinRight = oriWinRight_; + smlaInfo.qType = qType_; + smlaInfo.oriKvType = oriKvType_; + smlaInfo.cmpKvType = cmpKvType_; + smlaInfo.outputType = outputType_; + smlaInfo.perfMode = perfMode_; + + smlaInfo.sparseBlockSize = 1; + smlaInfo.oriBlockSize = oriBlockSize_; + smlaInfo.cmpBlockSize = cmpBlockSize_; + smlaInfo.oriP = oriP_; + smlaInfo.oriMLow = oriMLow_; + smlaInfo.oriMHigh = oriMHigh_; + smlaInfo.cmpP = cmpP_; + smlaInfo.cmpMLow = cmpMLow_; + smlaInfo.cmpMHigh = cmpMHigh_; + smlaInfo.oriMaxBlockNumPerBatch = oriMaxBlockNumPerBatch_; + smlaInfo.cmpMaxBlockNumPerBatch = cmpMaxBlockNumPerBatch_; + + smlaInfo.actualLenDimsQ = actualLenDimsQ_; + smlaInfo.actualLenDimsKV = actualLenDimsKV_; + + smlaInfo.softmaxScale = *opParamInfo_.softmaxScale; + smlaInfo.cmpRatio = *opParamInfo_.cmpRatio; + smlaInfo.oriMaskMode = *opParamInfo_.oriMaskMode; + smlaInfo.cmpMaskMode = *opParamInfo_.cmpMaskMode; + smlaInfo.oriKvStride0 = GetOptionalInputStride0(ORI_KV_INDEX); + smlaInfo.cmpKvStride0 = GetOptionalInputStride0(CMP_KV_INDEX); + smlaInfo.oriWinLeft = *opParamInfo_.oriWinLeft; + smlaInfo.oriWinRight = *opParamInfo_.oriWinRight; + + smlaInfo.topkValueMode = *opParamInfo_.topkValueMode; + + smlaInfo.qLayout = qLayout_; + smlaInfo.oriSparseIndicesLayout = oriSparseIndicesLayout_; + smlaInfo.cmpSparseIndicesLayout = cmpSparseIndicesLayout_; + smlaInfo.kvLayout = kvLayout_; + smlaInfo.outLayout = outLayout_; + smlaInfo.returnSoftmaxLse = *opParamInfo_.returnSoftmaxLse; + smlaInfo.batchConsistency = batchConsistency_; + + smlaInfo.actualLenDimsOriKV = actualLenDimsOriKV_; + smlaInfo.actualLenDimsCmpKV = actualLenDimsCmpKV_; + smlaInfo.cmpResidualKVSize = cmpResidualKVSize_; + + if (!IsA5Arch(npuArch_) && !IsA6Arch(npuArch_)) { + smlaInfo.oriKeyStride0 = 0; + smlaInfo.cmpKeyStride0 = 0; + } else { + if (!oriKeyStridesVec_.empty()) { + smlaInfo.oriKeyStride0 = static_cast(oriKeyStridesVec_[0]); + } else { + smlaInfo.oriKeyStride0 = GetKvstride(oriKvShape_, kvLayout_)[0]; + } + + if (!cmpKeyStridesVec_.empty()) { + smlaInfo.cmpKeyStride0 = static_cast(cmpKeyStridesVec_[0]); + } else { + smlaInfo.cmpKeyStride0 = GetKvstride(cmpKvShape_, kvLayout_)[0]; + } + } +} + +ge::graphStatus SMLAInfoParser::Parse(SMLATilingInfo& smlaInfo) { + if (context_ == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + "SparseFlashAttention", "context_", "tiling context is nullptr!"); + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != GetOpName() || ge::GRAPH_SUCCESS != GetNpuInfo() || + ge::GRAPH_SUCCESS != GetOpParaInfo() || + ge::GRAPH_SUCCESS != CheckRequiredParaExistence() || + ge::GRAPH_SUCCESS != CheckUnrequiredParaExistence()) { + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != GetInOutDataType() || + ge::GRAPH_SUCCESS != GetQueryAndOutLayout() || + ge::GRAPH_SUCCESS != GetKvLayout() || + ge::GRAPH_SUCCESS != GetSMLATemplateMode()) { + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != SetSMLAShape()) { + return ge::GRAPH_FAILED; + } + if (ge::GRAPH_SUCCESS != GetN1Size() || ge::GRAPH_SUCCESS != GetN2Size() || + ge::GRAPH_SUCCESS != GetGSize() || ge::GRAPH_SUCCESS != GetBatchSize() || + ge::GRAPH_SUCCESS != GetQTSize() || ge::GRAPH_SUCCESS != GetS1Size() || + ge::GRAPH_SUCCESS != GetS2Size() || + ge::GRAPH_SUCCESS != SmlaGetMagicPM() || + ge::GRAPH_SUCCESS != GetQHeadDim() || + ge::GRAPH_SUCCESS != GetValueHeadDim() || + ge::GRAPH_SUCCESS != GetSparseBlockCount() || + ge::GRAPH_SUCCESS != GetSinks()) { + return ge::GRAPH_FAILED; + } + if (ge::GRAPH_SUCCESS != GetActualseqInfo()) { + return ge::GRAPH_FAILED; + } + if (ge::GRAPH_SUCCESS != CheckContiguous()) { + return ge::GRAPH_FAILED; + } + GenerateInfo(smlaInfo); + return ge::GRAPH_SUCCESS; +} + +void SMLATilingCheck::Init() { + opName_ = smlaInfo_.opName; + platformInfo_ = smlaInfo_.platformInfo; + opParamInfo_ = smlaInfo_.opParamInfo; + npuArch_ = smlaInfo_.npuArch; + bSize_ = smlaInfo_.bSize; + n1Size_ = smlaInfo_.n1Size; + n2Size_ = smlaInfo_.n2Size; + s1Size_ = smlaInfo_.s1Size; + s2Size_ = smlaInfo_.s2Size; + cmpS2Size_ = smlaInfo_.cmpS2Size; + gSize_ = smlaInfo_.gSize; + qHeadDim_ = smlaInfo_.qHeadDim; + oriKvHeadDim_ = smlaInfo_.oriKvHeadDim; + cmpKvHeadDim_ = smlaInfo_.cmpKvHeadDim; + oriBlockSize_ = smlaInfo_.oriBlockSize; + cmpBlockSize_ = smlaInfo_.cmpBlockSize; + qTSize_ = smlaInfo_.qTSize; + qType_ = smlaInfo_.qType; + oriKvType_ = smlaInfo_.oriKvType; + cmpKvType_ = smlaInfo_.cmpKvType; + outputType_ = smlaInfo_.outputType; + cmpRatio_ = smlaInfo_.cmpRatio; + qLayout_ = smlaInfo_.qLayout; + oriSparseIndicesLayout_ = smlaInfo_.oriSparseIndicesLayout; + cmpSparseIndicesLayout_ = smlaInfo_.cmpSparseIndicesLayout; + oriWinLeft_ = smlaInfo_.oriWinLeft; + oriWinRight_ = smlaInfo_.oriWinRight; + hasOriSparseIndices_ = smlaInfo_.hasOriSparseIndices; + oriSparseIndexWidth_ = smlaInfo_.oriSparseIndexWidth; + kvLayout_ = smlaInfo_.kvLayout; + outLayout_ = smlaInfo_.outLayout; + topkValueMode_ = smlaInfo_.topkValueMode; +} + +void SMLATilingCheck::LogErrorDtypeSupport( + const std::vector& expectDtypeList, + const ge::DataType& actualDtype, + const std::string& name) const { + std::ostringstream oss; + for (size_t i = 0; i < expectDtypeList.size(); ++i) { + oss << SMLADataTypeToSerialString(expectDtypeList[i]); + if (i < expectDtypeList.size() - 1) { + oss << ", "; + } + } + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + name.c_str(), + SMLADataTypeToSerialString(actualDtype).c_str(), + "The dtype of " + name + " only supports " + oss.str()); +} + +ge::graphStatus SMLATilingCheck::CheckDtypeSupport( + const gert::CompileTimeTensorDesc* desc, + const std::string& name) const { + if (desc != nullptr) { + const auto& it = DTYPE_SUPPORT_MAP.find(name); + if (it == DTYPE_SUPPORT_MAP.end()) { + const std::string errorReason = + (name + + " datatype support list should be specify in DTYPE_SUPPORT_MAP"); + OP_LOGE_LIBOPAPI_REPORT( + Ops::Base::GetOpInfo(opName_), "%s", errorReason.c_str()); + REPORT_PREDEFINED_ERR_MSG( + "EZ1008", + std::vector({"opName", "reason"}), + std::vector( + {Ops::Base::GetOpInfo(opName_), errorReason.c_str()})); + return ge::GRAPH_FAILED; + } + auto& expectDtypeList = it->second; + OP_CHECK_IF( + std::find(expectDtypeList.begin(), + expectDtypeList.end(), + desc->GetDataType()) == expectDtypeList.end(), + LogErrorDtypeSupport(expectDtypeList, desc->GetDataType(), name), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +void SMLATilingCheck::LogErrorLayoutSupport( + const std::vector& expectLayoutList, + const SMLALayout& actualLayout, + const std::string& name) const { + std::ostringstream oss; + for (size_t i = 0; i < expectLayoutList.size(); ++i) { + oss << SMLALayoutToSerialString(expectLayoutList[i]); + if (i < expectLayoutList.size() - 1) { + oss << ", "; + } + } + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + name.c_str(), + SMLALayoutToSerialString(actualLayout).c_str(), + "Tensor " + name + " only supports layout " + oss.str()); +} + +ge::graphStatus SMLATilingCheck::CheckLayoutSupport( + const SMLALayout& actualLayout, + const std::string& name) const { + const auto& it = LAYOUT_SUPPORT_MAP.find(name); + if (it == LAYOUT_SUPPORT_MAP.end()) { + const std::string errorReason = + (name + " layout support list should be specify in LAYOUT_SUPPORT_MAP"); + OP_LOGE_LIBOPAPI_REPORT( + Ops::Base::GetOpInfo(opName_), "%s", errorReason.c_str()); + REPORT_PREDEFINED_ERR_MSG( + "EZ1008", + std::vector({"opName", "reason"}), + std::vector( + {Ops::Base::GetOpInfo(opName_), errorReason.c_str()})); + return ge::GRAPH_FAILED; + } + auto& expectLayoutList = it->second; + OP_CHECK_IF(std::find(expectLayoutList.begin(), + expectLayoutList.end(), + actualLayout) == expectLayoutList.end(), + LogErrorLayoutSupport(expectLayoutList, actualLayout, name), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +template +void SMLATilingCheck::LogErrorNumberSupport( + const std::vector& expectNumberList, + const T& actualValue, + const std::string& name, + const std::string subName) const { + std::ostringstream oss; + for (size_t i = 0; i < expectNumberList.size(); ++i) { + oss << std::to_string(expectNumberList[i]); + if (i < expectNumberList.size() - 1) { + oss << ", "; + } + } + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + name, + name + " " + std::string(subName.c_str()) + " only supports " + + oss.str() + ", but got " + + std::string(std::to_string(actualValue).c_str())); +} + +template +void SMLATilingCheck::LogErrorDimNumSupport( + const std::vector& expectNumberList, + const T& actualValue, + const std::string& name) const { + LogErrorNumberSupport(expectNumberList, actualValue, name, "dimension"); +} + +ge::graphStatus SMLATilingCheck::CheckDimNumSupport( + const gert::StorageShape* shape, + const std::vector& expectDimNumList, + const std::string& name) const { + if (shape == nullptr) { + return ge::GRAPH_SUCCESS; + } + + if (std::find(expectDimNumList.begin(), + expectDimNumList.end(), + shape->GetStorageShape().GetDimNum()) == + expectDimNumList.end()) { + LogErrorDimNumSupport( + expectDimNumList, shape->GetStorageShape().GetDimNum(), name); + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckDimNumInLayoutSupport( + const SMLALayout& layout, + const gert::StorageShape* shape, + const std::string& name) const { + const auto& dimIt = SMLA_LAYOUT_DIM_MAP.find(layout); + OP_CHECK_IF(shape->GetStorageShape().GetDimNum() != dimIt->second, + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + opName_, + name.c_str(), + std::to_string(shape->GetStorageShape().GetDimNum()).c_str(), + "When layout is " + SMLALayoutToSerialString(layout) + + ", the shape dim of " + name + " should be " + + std::to_string(dimIt->second)), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaQuery() const { + if (opParamInfo_.q.desc == nullptr || opParamInfo_.q.shape == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "q", "Q must be provided"); + return ge::GRAPH_FAILED; + } + const std::vector queryDimNumList = {DIM_NUM_THREE, DIM_NUM_FOUR}; + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.q.desc, QUERY_NAME) || + ge::GRAPH_SUCCESS != CheckLayoutSupport(qLayout_, QUERY_NAME) || + ge::GRAPH_SUCCESS != CheckDimNumSupport(opParamInfo_.q.shape, + queryDimNumList, + QUERY_NAME) || + ge::GRAPH_SUCCESS != CheckDimNumInLayoutSupport( + qLayout_, opParamInfo_.q.shape, QUERY_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaOriKv() const { + const std::vector oriKvDimNumList = {DIM_NUM_THREE, DIM_NUM_FOUR}; + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(opParamInfo_.oriKv.desc, ORI_KV_NAME) || + ge::GRAPH_SUCCESS != CheckLayoutSupport(kvLayout_, ORI_KV_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(&opParamInfo_.oriKv.tensor->GetShape(), + oriKvDimNumList, + ORI_KV_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumInLayoutSupport( + kvLayout_, &opParamInfo_.oriKv.tensor->GetShape(), ORI_KV_NAME)) { + return ge::GRAPH_FAILED; + } + if (kvLayout_ == SMLALayout::BSND) { + OP_CHECK_IF( + opParamInfo_.oriKv.tensor->GetStorageShape().GetDim(0) != bSize_, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "ori_kv", + ToStringRaw(opParamInfo_.oriKv.tensor->GetStorageShape()), + "Ori_kv's batch dimension(" + + std::to_string( + opParamInfo_.oriKv.tensor->GetStorageShape().GetDim(0)) + + ") should be equal to B(" + std::to_string(bSize_) + ")"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaCmpKv() const { + if (smlaInfo_.perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE || + smlaInfo_.perfMode == SMLATemplateMode::HCA_TEMPLATE_MODE || + smlaInfo_.perfMode == SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { + const std::vector cmpKvDimNumList = {DIM_NUM_THREE, DIM_NUM_FOUR}; + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(opParamInfo_.cmpKv.desc, CMP_KV_NAME) || + ge::GRAPH_SUCCESS != CheckLayoutSupport(kvLayout_, CMP_KV_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(&opParamInfo_.cmpKv.tensor->GetShape(), + cmpKvDimNumList, + CMP_KV_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumInLayoutSupport(kvLayout_, + &opParamInfo_.cmpKv.tensor->GetShape(), + CMP_KV_NAME)) { + return ge::GRAPH_FAILED; + } + if (kvLayout_ == SMLALayout::BSND) { + OP_CHECK_IF( + opParamInfo_.cmpKv.tensor->GetStorageShape().GetDim(0) != bSize_, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "cmp_kv", + ToStringRaw(opParamInfo_.cmpKv.tensor->GetStorageShape()), + "Cmp_kv's batch dimension(" + + std::to_string( + opParamInfo_.cmpKv.tensor->GetStorageShape().GetDim(0)) + + ") should be equal to B(" + std::to_string(bSize_) + ")"), + return ge::GRAPH_FAILED); + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaCuSeqLensQ() const { + if (opParamInfo_.cuSeqLensQ.tensor == nullptr) { + return ge::GRAPH_SUCCESS; + } + const std::vector dimNumList = {DIM_NUM_ONE}; + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(opParamInfo_.cuSeqLensQ.desc, CU_SEQLENS_Q_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(&opParamInfo_.cuSeqLensQ.tensor->GetShape(), + dimNumList, + CU_SEQLENS_Q_NAME)) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF(opParamInfo_.cuSeqLensQ.tensor->GetShapeSize() != bSize_ + 1, + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "cu_seqlens_q", + std::to_string(opParamInfo_.cuSeqLensQ.tensor->GetShapeSize()) + .c_str(), + "The shape size of cu_seqlens_q is not equal to B + 1:" + + std::to_string(bSize_ + 1)), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaCuSeqLensOriKv() const { + if (opParamInfo_.cuSeqLensOriKv.tensor == nullptr) { + return ge::GRAPH_SUCCESS; + } + const std::vector dimNumList = {DIM_NUM_ONE}; + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.cuSeqLensOriKv.desc, + CU_SEQLENS_ORI_KV_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(&opParamInfo_.cuSeqLensOriKv.tensor->GetShape(), + dimNumList, + CU_SEQLENS_ORI_KV_NAME)) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + opParamInfo_.cuSeqLensOriKv.tensor->GetShapeSize() != bSize_ + 1, + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "cu_seqlens_ori_kv", + std::to_string(opParamInfo_.cuSeqLensOriKv.tensor->GetShapeSize()) + .c_str(), + "The shape size of cu_seqlens_ori_kv is not equal to B + 1:" + + std::to_string(bSize_ + 1)), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaCuSeqLensCmpKv() const { + if (opParamInfo_.cuSeqLensCmpKv.tensor == nullptr) { + return ge::GRAPH_SUCCESS; + } + const std::vector dimNumList = {DIM_NUM_ONE}; + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.cuSeqLensCmpKv.desc, + CU_SEQLENS_CMP_KV_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(&opParamInfo_.cuSeqLensCmpKv.tensor->GetShape(), + dimNumList, + CU_SEQLENS_CMP_KV_NAME)) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + opParamInfo_.cuSeqLensCmpKv.tensor->GetShapeSize() != bSize_ + 1, + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "cu_seqlens_cmp_kv", + std::to_string(opParamInfo_.cuSeqLensCmpKv.tensor->GetShapeSize()) + .c_str(), + "The shape size of cu_seqlens_cmp_kv is not equal to B + 1:" + + std::to_string(bSize_ + 1)), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaNumHeads() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaKvHeadNums() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaOriSparseIndices() const { + if (opParamInfo_.oriSparseIndices.tensor == nullptr) { + return ge::GRAPH_SUCCESS; + } + if (!IsA5Arch(npuArch_) && !IsA6Arch(npuArch_)) { + OP_CHECK_IF(smlaInfo_.perfMode != SMLATemplateMode::SWA_TEMPLATE_MODE, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "ori_sparse_indices", + "ori_sparse_indices is only supported in SWA mode."), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.oriMaskMode == nullptr || *opParamInfo_.oriMaskMode != 0U, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "ori_sparse_indices, ori_mask_mode", + "ori_sparse_indices SWA (DSpark) requires oriMaskMode 0."), + return ge::GRAPH_FAILED); + } + OP_CHECK_IF( + opParamInfo_.oriSparseIndices.tensor->GetStorageShape().GetShapeSize() == + 0, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "ori_sparse_indices", + "Ori_sparse_indices cannot be empty tensor"), + return ge::GRAPH_FAILED); + const std::vector oriSparseIndicesDimNumList = {DIM_NUM_THREE, + DIM_NUM_FOUR}; + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.oriSparseIndices.desc, + ORI_SPARSE_INDICES) || + ge::GRAPH_SUCCESS != + CheckLayoutSupport(oriSparseIndicesLayout_, ORI_SPARSE_INDICES) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(&opParamInfo_.oriSparseIndices.tensor->GetShape(), + oriSparseIndicesDimNumList, + ORI_SPARSE_INDICES) || + ge::GRAPH_SUCCESS != + CheckDimNumInLayoutSupport( + oriSparseIndicesLayout_, + &opParamInfo_.oriSparseIndices.tensor->GetShape(), + ORI_SPARSE_INDICES)) { + return ge::GRAPH_FAILED; + } + if (oriSparseIndicesLayout_ == SMLALayout::BSND) { + OP_CHECK_IF( + opParamInfo_.oriSparseIndices.tensor->GetStorageShape().GetDim(0) != + bSize_, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "ori_sparse_indices", + ToStringRaw( + opParamInfo_.oriSparseIndices.tensor->GetStorageShape()), + "Ori_sparse_indices's batch dimension(" + + std::to_string( + opParamInfo_.oriSparseIndices.tensor->GetStorageShape() + .GetDim(0)) + + ") should be equal to B(" + std::to_string(bSize_) + ")"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaCmpSparseIndices() const { + if (smlaInfo_.perfMode == optiling::SMLATemplateMode::CSA_TEMPLATE_MODE || + smlaInfo_.perfMode == + optiling::SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { + OP_CHECK_IF(opParamInfo_.cmpSparseIndices.tensor->GetStorageShape() + .GetShapeSize() == 0, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cmp_sparse_indices", + "When cmp_sparse_indices is not nullptr(CSA), " + "cmp_sparse_indices cannot be empty tensor"), + return ge::GRAPH_FAILED); + const std::vector cmpSparseIndicesDimNumList = {DIM_NUM_THREE, + DIM_NUM_FOUR}; + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(opParamInfo_.cmpSparseIndices.desc, + CMP_SPARSE_INDICES) || + ge::GRAPH_SUCCESS != + CheckLayoutSupport(cmpSparseIndicesLayout_, CMP_SPARSE_INDICES) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport( + &opParamInfo_.cmpSparseIndices.tensor->GetShape(), + cmpSparseIndicesDimNumList, + CMP_SPARSE_INDICES) || + ge::GRAPH_SUCCESS != + CheckDimNumInLayoutSupport( + cmpSparseIndicesLayout_, + &opParamInfo_.cmpSparseIndices.tensor->GetShape(), + CMP_SPARSE_INDICES)) { + return ge::GRAPH_FAILED; + } + const auto& indicesShape = + opParamInfo_.cmpSparseIndices.tensor->GetStorageShape(); + const int64_t topk = indicesShape.GetDim(indicesShape.GetDimNum() - 1); + OP_CHECK_IF( + npuArch_ == NpuArch::DAV_2201 && (topk < 1 || topk > TOPK_LIMIT), + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cmp_sparse_indices", + "cmp_sparse_indices last dimension must be in [1, " + + std::to_string(TOPK_LIMIT) + "], but got " + + std::to_string(static_cast(topk)) + "."), + return ge::GRAPH_FAILED); + if (cmpSparseIndicesLayout_ == SMLALayout::BSND) { + OP_CHECK_IF( + opParamInfo_.cmpSparseIndices.tensor->GetStorageShape().GetDim(0) != + bSize_, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "cmp_sparse_indices", + ToStringRaw( + opParamInfo_.cmpSparseIndices.tensor->GetStorageShape()), + "Cmp_sparse_indices's batch dimension(" + + std::to_string( + opParamInfo_.cmpSparseIndices.tensor->GetStorageShape() + .GetDim(0)) + + ") should be equal to B(" + std::to_string(bSize_) + ")"), + return ge::GRAPH_FAILED); + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaOriBlockTable() const { + if (kvLayout_ != SMLALayout::PA_BBND) { + return ge::GRAPH_SUCCESS; + } + const std::vector oriBlockTableDimNumList = {DIM_NUM_TWO}; + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.oriBlockTable.desc, + ORI_BLOCK_TABLE_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(&opParamInfo_.oriBlockTable.tensor->GetShape(), + oriBlockTableDimNumList, + ORI_BLOCK_TABLE_NAME)) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDim(0) != bSize_, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "ori_block_table", + ToStringRaw(opParamInfo_.oriBlockTable.tensor->GetStorageShape()), + "Ori_block_table's first dimension(" + + std::to_string( + opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDim( + 0)) + + ") should be equal to B(" + std::to_string(bSize_) + ")"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + !IsPaBlockSizeSupport(npuArch_, oriBlockSize_), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "ori_kv", + ToStringRaw(opParamInfo_.oriKv.tensor->GetStorageShape()).c_str(), + "OriBlockSize_ should be in [1, 1024] on " + + (IsA6Arch(npuArch_) ? A6_PLATFORM_LOG : A5_PLATFORM_LOG) + + " or 16-aligned [16, 1024] on " + A2_A3_PLATFORM_LOG + + ", but got: " + std::to_string(oriBlockSize_)), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaCmpBlockTable() const { + if (kvLayout_ != SMLALayout::PA_BBND) { + return ge::GRAPH_SUCCESS; + } + if (smlaInfo_.perfMode == optiling::SMLATemplateMode::CSA_TEMPLATE_MODE || + smlaInfo_.perfMode == optiling::SMLATemplateMode::HCA_TEMPLATE_MODE || + smlaInfo_.perfMode == + optiling::SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { + OP_CHECK_IF(opParamInfo_.cmpBlockTable.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cmp_block_table", + "Cmp_block_table must be provided when layout_kv is " + "PA_BBND in CSA/HCA/ORI_CMP_SPARSE mode"), + return ge::GRAPH_FAILED); + const std::vector cmpBlockTableDimNumList = {DIM_NUM_TWO}; + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.cmpBlockTable.desc, + CMP_BLOCK_TABLE_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(&opParamInfo_.cmpBlockTable.tensor->GetShape(), + cmpBlockTableDimNumList, + CMP_BLOCK_TABLE_NAME)) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim(0) != + bSize_, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "cmp_block_table", + ToStringRaw(opParamInfo_.cmpBlockTable.tensor->GetStorageShape()), + "cmp_block_table's first dimension(" + + std::to_string( + opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim( + 0)) + + ") should be equal to B(" + std::to_string(bSize_) + ")"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + !IsPaBlockSizeSupport(npuArch_, cmpBlockSize_), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "cmp_kv", + ToStringRaw(opParamInfo_.oriKv.tensor->GetStorageShape()).c_str(), + "CmpBlockSize should be in [1, 1024] on " + + (IsA6Arch(npuArch_) ? A6_PLATFORM_LOG : A5_PLATFORM_LOG) + + " or 16-aligned [16, 1024] on " + A2_A3_PLATFORM_LOG + + ", but got: " + std::to_string(cmpBlockSize_)), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaSinks() const { + OP_CHECK_IF(opParamInfo_.sinks.tensor->GetStorageShape().GetShapeSize() == 0, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "sinks", "Sinks cannot be empty tensor"), + return ge::GRAPH_FAILED); + if (opParamInfo_.sinks.tensor->GetStorageShape().GetDimNum() != DIM_NUM_ONE) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + SINKS_NAME.c_str(), + std::to_string(opParamInfo_.sinks.tensor->GetStorageShape().GetDimNum()) + .c_str(), + std::to_string(DIM_NUM_ONE).c_str()); + return ge::GRAPH_FAILED; + } + if (opParamInfo_.sinks.tensor->GetStorageShape().GetDim(0) != n1Size_) { + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "sinks", + ToStringRaw(opParamInfo_.sinks.tensor->GetStorageShape()), + "Sinks's dimension(" + + std::to_string( + opParamInfo_.sinks.tensor->GetStorageShape().GetDim(0)) + + ") should be equal to the head num of query(" + + std::to_string(n1Size_) + ")"); + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + opParamInfo_.sinks.desc->GetDataType() != ge::DT_FLOAT, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "sinks", + SMLADataTypeToSerialString(opParamInfo_.sinks.desc->GetDataType()) + .c_str(), + "The dtype of sinks must be DT_FLOAT"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaMetadata() const { + if (opParamInfo_.metadata.tensor == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "metadata", "Metadata must be provided"); + return ge::GRAPH_FAILED; + } + const std::vector dimNumList = {DIM_NUM_ONE}; + if (ge::GRAPH_SUCCESS != + CheckDimNumSupport(&opParamInfo_.metadata.tensor->GetShape(), + dimNumList, + METADATA_NAME)) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF((opParamInfo_.metadata.tensor->GetShapeSize() != METADATA_LIMIT), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "metadata", + ToStringRaw(opParamInfo_.metadata.tensor->GetStorageShape()), + "metadata dim 0 must be" + std::to_string(METADATA_LIMIT)), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.metadata.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "metadata", + SMLADataTypeToSerialString(opParamInfo_.metadata.desc->GetDataType()) + .c_str(), + "The dtype of metadata must be DT_INT32"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaCmpRatio() const { + const auto checkRatio = [this](bool isSupported, + const char* expectedRatios, + const char* modeName, + const char* modeReason) { + OP_CHECK_IF(!isSupported, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cmp_ratio", + "cmpRatio should be " + std::string(expectedRatios) + + " in " + std::string(modeName) + " on " + + std::string(A2_A3_PLATFORM_LOG.c_str()) + " " + + std::string(modeReason) + ", but got " + + std::to_string(cmpRatio_) + "."), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; + }; + + switch (smlaInfo_.perfMode) { + case SMLATemplateMode::CSA_TEMPLATE_MODE: + // {2, 4}:压缩比倍数 + return checkRatio(cmpRatio_ == 1 || cmpRatio_ == 2 || cmpRatio_ == 4, + "1, 2 or 4", + "CSA", + "when cmp_sparse_indices is provided"); + case SMLATemplateMode::HCA_TEMPLATE_MODE: + // 128:压缩比倍数 + return checkRatio(cmpRatio_ == 128, + "128", + "HCA", + "when cmp_sparse_indices is not provided"); + default: + return ge::GRAPH_SUCCESS; + } +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaOriMaskMode() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaCmpMaskMode() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaOriWinLeft() const { + OP_CHECK_IF(oriWinLeft_ < -1, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "ori_win_left", + std::to_string(oriWinLeft_).c_str(), + "Ori_win_left should be -1(unlimited) or non-negative"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaOriWinRight() const { + OP_CHECK_IF(oriWinRight_ < -1, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "ori_win_right", + std::to_string(oriWinRight_).c_str(), + "Ori_win_right should be -1(unlimited) or non-negative"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaCmpResidualKv() const { + bool isCmpTemplate = + smlaInfo_.perfMode == SMLATemplateMode::HCA_TEMPLATE_MODE || + smlaInfo_.perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE; + if (isCmpTemplate && *opParamInfo_.cmpMaskMode == 3 && + cmpRatio_ != 1) { // 3: RightDownCausal模式 + OP_CHECK_IF(opParamInfo_.cmpResidualKv.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cmp_residual_kv", + "Cmp_residual_kv is required when cmp_mask_mode=3 and " + "cmp_ratio != 1"), + return ge::GRAPH_FAILED); + } + if (opParamInfo_.cmpResidualKv.tensor == nullptr) { + return ge::GRAPH_SUCCESS; + } + const std::vector dimNumList = {DIM_NUM_ONE}; + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.cmpResidualKv.desc, + CMP_RESIDUAL_KV_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(&opParamInfo_.cmpResidualKv.tensor->GetShape(), + dimNumList, + CMP_RESIDUAL_KV_NAME)) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + opParamInfo_.cmpResidualKv.tensor->GetShapeSize() != bSize_, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "cmp_residual_kv", + ToStringRaw(opParamInfo_.cmpResidualKv.tensor->GetStorageShape()), + "Cmp_residual_kv's first dimension(" + + std::to_string( + opParamInfo_.cmpResidualKv.tensor->GetShapeSize()) + + ") should be equal to B(" + std::to_string(bSize_) + ")"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSingleParaTopkLength() const { + if (IsA5Arch(npuArch_) || IsA6Arch(npuArch_)) { + if (opParamInfo_.oriTopkLength.tensor != nullptr) { + const std::vector dimNumList = {DIM_NUM_TWO, DIM_NUM_THREE}; + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(opParamInfo_.oriTopkLength.desc, + ORI_TOPK_LENGTH_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(&opParamInfo_.oriTopkLength.tensor->GetShape(), + dimNumList, + ORI_TOPK_LENGTH_NAME)) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + opParamInfo_.oriTopkLength.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "ori_topk_length", + SMLADataTypeToSerialString( + opParamInfo_.oriTopkLength.desc->GetDataType()) + .c_str(), + "The dtype of ori_topk_length must be DT_INT32"), + return ge::GRAPH_FAILED); + } + if (opParamInfo_.cmpTopkLength.tensor != nullptr) { + const std::vector dimNumList = {DIM_NUM_TWO, DIM_NUM_THREE}; + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(opParamInfo_.cmpTopkLength.desc, + CMP_TOPK_LENGTH_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(&opParamInfo_.cmpTopkLength.tensor->GetShape(), + dimNumList, + CMP_TOPK_LENGTH_NAME)) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + opParamInfo_.cmpTopkLength.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "cmp_topk_length", + SMLADataTypeToSerialString( + opParamInfo_.cmpTopkLength.desc->GetDataType()) + .c_str(), + "The dtype of cmp_topk_length must be DT_INT32"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; + } + if (IsNonEmptyOptionalTensor(opParamInfo_.cmpTopkLength.tensor)) { + OP_CHECK_IF(smlaInfo_.perfMode != SMLATemplateMode::CSA_TEMPLATE_MODE, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cmp_topk_length", + "Cmp_topk_length is only supported in CSA mode"), + return ge::GRAPH_FAILED); + } + if (!IsNonEmptyOptionalTensor(opParamInfo_.oriTopkLength.tensor)) { + OP_CHECK_IF(hasOriSparseIndices_ && + smlaInfo_.perfMode == SMLATemplateMode::SWA_TEMPLATE_MODE, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "ori_topk_length", + "Ori_topk_length is required for SWA ori sparse"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; + } + OP_CHECK_IF(opParamInfo_.oriSparseIndices.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "ori_sparse_indices", + "Ori_topk_length requires ori_sparse_indices"), + return ge::GRAPH_FAILED); + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.oriTopkLength.desc, + ORI_TOPK_LENGTH_NAME)) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF(opParamInfo_.oriTopkLength.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "ori_topk_length", + SMLADataTypeToSerialString( + opParamInfo_.oriTopkLength.desc->GetDataType()) + .c_str(), + "The dtype of ori_topk_length must be DT_INT32"), + return ge::GRAPH_FAILED); + const gert::Shape& topkLenShape = + opParamInfo_.oriTopkLength.tensor->GetStorageShape(); + const gert::Shape& sparseShape = + opParamInfo_.oriSparseIndices.tensor->GetStorageShape(); + if (oriSparseIndicesLayout_ == SMLALayout::TND) { + OP_CHECK_IF(topkLenShape.GetDimNum() != 2 || sparseShape.GetDimNum() != 3, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "ori_topk_length and ori_sparse_indices", + Ops::Base::ToString(topkLenShape) + " and " + + Ops::Base::ToString(sparseShape), + "TND ori_topk_length shape must be [T, N2], " + "ori_sparse_indices [T, N2, K]"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(topkLenShape.GetDim(0) != sparseShape.GetDim(0) || + topkLenShape.GetDim(1) != sparseShape.GetDim(1), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "ori_topk_length and ori_sparse_indices", + Ops::Base::ToString(topkLenShape) + " and " + + Ops::Base::ToString(sparseShape), + "Ori_topk_length shape must match ori_sparse_indices " + "without K dim"), + return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF(topkLenShape.GetDimNum() != 3 || sparseShape.GetDimNum() != 4, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "ori_topk_length", + Ops::Base::ToString(topkLenShape), + "BSND ori_topk_length shape must be [B, S1, N2]"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(topkLenShape.GetDim(0) != sparseShape.GetDim(0) || + topkLenShape.GetDim(1) != sparseShape.GetDim(1) || + topkLenShape.GetDim(2) != sparseShape.GetDim(2), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "ori_topk_length and ori_sparse_indices", + Ops::Base::ToString(topkLenShape) + " and " + + Ops::Base::ToString(sparseShape), + "Ori_topk_length shape must match ori_sparse_indices " + "without K dim"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckSinglePara() const { + if (ge::GRAPH_SUCCESS != CheckSingleParaQuery() || + ge::GRAPH_SUCCESS != CheckSingleParaOriKv() || + ge::GRAPH_SUCCESS != CheckSingleParaCmpKv() || + ge::GRAPH_SUCCESS != CheckSingleParaCuSeqLensQ() || + ge::GRAPH_SUCCESS != CheckSingleParaCuSeqLensOriKv() || + ge::GRAPH_SUCCESS != CheckSingleParaCuSeqLensCmpKv() || + ge::GRAPH_SUCCESS != CheckSingleParaCmpRatio() || + ge::GRAPH_SUCCESS != CheckSingleParaCmpResidualKv() || + ge::GRAPH_SUCCESS != CheckSingleParaTopkLength() || + ge::GRAPH_SUCCESS != CheckSingleParaNumHeads() || + ge::GRAPH_SUCCESS != CheckSingleParaKvHeadNums() || + ge::GRAPH_SUCCESS != CheckSingleParaOriSparseIndices() || + ge::GRAPH_SUCCESS != CheckSingleParaCmpSparseIndices() || + ge::GRAPH_SUCCESS != CheckSingleParaOriBlockTable() || + ge::GRAPH_SUCCESS != CheckSingleParaCmpBlockTable() || + ge::GRAPH_SUCCESS != CheckSingleParaSinks() || + ge::GRAPH_SUCCESS != CheckSingleParaMetadata() || + ge::GRAPH_SUCCESS != CheckSingleParaOriMaskMode() || + ge::GRAPH_SUCCESS != CheckSingleParaCmpMaskMode() || + ge::GRAPH_SUCCESS != CheckSingleParaOriWinLeft() || + ge::GRAPH_SUCCESS != CheckSingleParaOriWinRight()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckExists(const void* pointer, + const std::string& name) const { + OP_CHECK_IF(pointer == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, name.c_str(), name + " should not be null"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckNotExists(const void* pointer, + const std::string& name) const { + OP_CHECK_IF(pointer != nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, name.c_str(), name + " should not be null"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckExistsByMap( + const std::map& paramMap) const { + for (const auto& kv : paramMap) { + if (CheckExists(kv.second, kv.first) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckNotExistsByMap( + const std::map& paramMap) const { + for (const auto& kv : paramMap) { + if (CheckNotExists(kv.second, kv.first) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckExistenceByMap( + std::map& existMap, + std::map& notExistMap) const { + if (CheckExistsByMap(existMap) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + if (CheckNotExistsByMap(notExistMap) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckParaExistence() const { + if (IsA5Arch(npuArch_) || IsA6Arch(npuArch_)) { + OP_CHECK_IF((kvLayout_ == SMLALayout::TND && + opParamInfo_.cuSeqLensOriKv.tensor == nullptr), + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cu_seqlens_ori_kv", + "cu_seqlens_ori_kv must be provided when kv layout is TND"), + return ge::GRAPH_FAILED); + } else { + if (kvLayout_ == SMLALayout::PA_BBND) { + std::map ParamExistMap = { + {"actualSeqLengths", opParamInfo_.sequsedOriKv.tensor}, + {"oriBlockTable", opParamInfo_.oriBlockTable.tensor}, + }; + std::map ParamNotExistMap = {}; + if (CheckExistenceByMap(ParamExistMap, ParamNotExistMap) != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckFeatureShape() const { + if (qLayout_ == SMLALayout::TND) { + OP_CHECK_IF( + bSize_ <= 0, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "cu_seqlens_q", + ToStringRaw(opParamInfo_.cuSeqLensQ.tensor->GetStorageShape()) + .c_str(), + "Batch_size should be greater than 0, but got " + + std::to_string(bSize_)), + return ge::GRAPH_FAILED); + } else { // BSND + OP_CHECK_IF( + bSize_ <= 0, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "q", + ToStringRaw(opParamInfo_.q.shape->GetStorageShape()).c_str(), + "Batch_size should be greater than 0, but got " + + std::to_string(bSize_)), + return ge::GRAPH_FAILED); + } + + OP_CHECK_IF(qTSize_ <= 0 && (qLayout_ == SMLALayout::TND), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "q", + ToStringRaw(opParamInfo_.q.shape->GetStorageShape()).c_str(), + "T_size of q should be greater than 0, but got " + + std::to_string(qTSize_)), + return ge::GRAPH_FAILED); + + if (IsA5Arch(npuArch_) || IsA6Arch(npuArch_)) { + OP_CHECK_IF( + n1Size_ < 1 || n1Size_ > 128, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "q", + ToStringRaw(opParamInfo_.q.shape->GetStorageShape()).c_str(), + "The head num of q should be in [1, 128] on" + + (IsA6Arch(npuArch_) ? A6_PLATFORM_LOG : A5_PLATFORM_LOG) + + ", but got " + std::to_string(n1Size_)), + return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF(!IsPowerOfTwoInRange(n1Size_, 1, 128), + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "query", + "q_head_num should be power of two in [1, 128] on " + + std::string(A2_A3_PLATFORM_LOG.c_str()) + ", but got " + + std::to_string(n1Size_)), + return ge::GRAPH_FAILED); + } + + if (opParamInfo_.oriKv.tensor != nullptr) { + OP_CHECK_IF( + n2Size_ != 1, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "ori_kv", + ToStringRaw(opParamInfo_.oriKv.tensor->GetStorageShape()).c_str(), + "The head num of ori_kv should be 1, but got " + + std::to_string(n2Size_)), + return ge::GRAPH_FAILED); + + OP_CHECK_IF( + n1Size_ % n2Size_ != 0, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and ori_kv", + Ops::Base::ToString(opParamInfo_.q.shape->GetStorageShape()) + + " and " + + Ops::Base::ToString( + opParamInfo_.oriKv.tensor->GetStorageShape()), + "The head num of q(" + std::to_string(n1Size_) + + ") must be divisible by the head num of ori_kv(" + + std::to_string(n2Size_) + ")"), + return ge::GRAPH_FAILED); + } + if (opParamInfo_.cmpKv.tensor != nullptr) { + OP_CHECK_IF( + n2Size_ != 1, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "cmp_kv", + ToStringRaw(opParamInfo_.cmpKv.tensor->GetStorageShape()).c_str(), + "The head num of cmp_kv should be 1, but got " + + std::to_string(n2Size_)), + return ge::GRAPH_FAILED); + + OP_CHECK_IF( + n1Size_ % n2Size_ != 0, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and cmp_kv", + Ops::Base::ToString(opParamInfo_.q.shape->GetStorageShape()) + + " and " + + Ops::Base::ToString( + opParamInfo_.cmpKv.tensor->GetStorageShape()), + "The head num of q(" + std::to_string(n1Size_) + + ") must be divisible by the head num of cmp_kv(" + + std::to_string(n2Size_) + ")"), + return ge::GRAPH_FAILED); + } + + if (IsA5Arch(npuArch_) || IsA6Arch(npuArch_)) { + if (opParamInfo_.oriKv.tensor != nullptr) { + OP_CHECK_IF( + gSize_ < 1 || gSize_ > 128, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and ori_kv", + Ops::Base::ToString(opParamInfo_.q.shape->GetStorageShape()) + + " and " + + Ops::Base::ToString( + opParamInfo_.oriKv.tensor->GetStorageShape()), + "The value of (the head num of q ceildivided by the head num of " + "ori_kv) " + "should be in [1, 128] on " + + (IsA6Arch(npuArch_) ? A6_PLATFORM_LOG : A5_PLATFORM_LOG) + + ", but got " + std::to_string(gSize_)), + return ge::GRAPH_FAILED); + } + if (opParamInfo_.cmpKv.tensor != nullptr) { + OP_CHECK_IF( + gSize_ < 1 || gSize_ > 128, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and cmp_kv", + Ops::Base::ToString(opParamInfo_.q.shape->GetStorageShape()) + + " and " + + Ops::Base::ToString( + opParamInfo_.cmpKv.tensor->GetStorageShape()), + "The value of (the head num of q ceildivided by the head num of " + "cmp_kv) " + "should be in [1, 128] on " + + (IsA6Arch(npuArch_) ? A6_PLATFORM_LOG : A5_PLATFORM_LOG) + + ", but got " + std::to_string(gSize_)), + return ge::GRAPH_FAILED); + } + } else { + OP_CHECK_IF(!IsPowerOfTwoInRange(gSize_, 1, 128), + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "query, key", + "group num should be power of two in [1, 128] on " + + std::string(A2_A3_PLATFORM_LOG.c_str()) + ", but got " + + std::to_string(gSize_)), + return ge::GRAPH_FAILED); + } + + OP_CHECK_IF( + qHeadDim_ != DIM_LIMIT, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "q", + ToStringRaw(opParamInfo_.q.shape->GetStorageShape()).c_str(), + "The head num of q only support " + std::to_string(DIM_LIMIT) + + ", but got " + std::to_string(qHeadDim_)), + return ge::GRAPH_FAILED); + + if (opParamInfo_.oriKv.tensor != nullptr) { + OP_CHECK_IF( + oriKvHeadDim_ != DIM_LIMIT, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "ori_kv", + ToStringRaw(opParamInfo_.oriKv.tensor->GetStorageShape()).c_str(), + "The head num of ori_kv only support " + std::to_string(DIM_LIMIT) + + ", but got " + std::to_string(oriKvHeadDim_)), + return ge::GRAPH_FAILED); + } + if (!(smlaInfo_.perfMode == SMLATemplateMode::SWA_TEMPLATE_MODE || + smlaInfo_.perfMode == SMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE) && + (opParamInfo_.cmpKv.tensor != nullptr)) { + OP_CHECK_IF( + cmpKvHeadDim_ != DIM_LIMIT, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "cmp_kv", + ToStringRaw(opParamInfo_.cmpKv.tensor->GetStorageShape()).c_str(), + "The head num of cmp_kv only support " + std::to_string(DIM_LIMIT) + + ", but got " + std::to_string(cmpKvHeadDim_)), + return ge::GRAPH_FAILED); + } + + OP_CHECK_IF(!(qType_ == oriKvType_), + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( + opName_, + "q and ori_kv", + SMLADataTypeToSerialString(qType_) + " and " + + SMLADataTypeToSerialString(oriKvType_), + "The dtype of q and ori_kv must be same"), + return ge::GRAPH_FAILED); + + if (IsA5Arch(npuArch_) || IsA6Arch(npuArch_)) { + OP_CHECK_IF( + *opParamInfo_.oriMaskMode != 0 && *opParamInfo_.oriMaskMode != 3 && + *opParamInfo_.oriMaskMode != 4, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "ori_mask_mode", + std::to_string(*opParamInfo_.oriMaskMode).c_str(), + "Ori_mask_mode should be {0, 3, 4} on " + + (IsA6Arch(npuArch_) ? A6_PLATFORM_LOG : A5_PLATFORM_LOG)), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + *opParamInfo_.cmpMaskMode != 0 && *opParamInfo_.cmpMaskMode != 3, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "cmp_mask_mode", + std::to_string(*opParamInfo_.cmpMaskMode).c_str(), + "Cmp_mask_mode should be {0, 3} on " + + (IsA6Arch(npuArch_) ? A6_PLATFORM_LOG : A5_PLATFORM_LOG)), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + oriWinLeft_ < -1, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "ori_win_left", + std::to_string(oriWinLeft_).c_str(), + "Ori_win_left should be -1(unlimited) or non-negative on " + + (IsA6Arch(npuArch_) ? A6_PLATFORM_LOG : A5_PLATFORM_LOG)), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + oriWinRight_ < -1, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "ori_win_right", + std::to_string(oriWinRight_).c_str(), + "Ori_win_right should be -1(unlimited) or non-negative on " + + (IsA6Arch(npuArch_) ? A6_PLATFORM_LOG : A5_PLATFORM_LOG)), + return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF(topkValueMode_ != 1, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "topk_value_mode", + std::to_string(topkValueMode_).c_str(), + "Topk_value_mode should be 1 on " + A2_A3_PLATFORM_LOG), + return ge::GRAPH_FAILED); + if (smlaInfo_.perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE || + smlaInfo_.perfMode == SMLATemplateMode::HCA_TEMPLATE_MODE) { + OP_CHECK_IF( + *opParamInfo_.cmpMaskMode != 3, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "cmp_mask_mode", + "cmpMaskMode should be 3 on " + + std::string(A2_A3_PLATFORM_LOG.c_str()) + ", but got " + + std::to_string(*opParamInfo_.cmpMaskMode)), + return ge::GRAPH_FAILED); + } + if (hasOriSparseIndices_) { + OP_CHECK_IF( + *opParamInfo_.oriMaskMode != 0U, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "ori_mask_mode", + "oriMaskMode must be 0 for SWA ori sparse (DSpark) on " + + std::string(A2_A3_PLATFORM_LOG.c_str()) + ", but got " + + std::to_string(*opParamInfo_.oriMaskMode) + "."), + return ge::GRAPH_FAILED); + OP_CHECK_IF(oriWinLeft_ < 0 || oriWinRight_ < 0, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "ori_win_left", + "ori_win_left/right should be non-negative for ori " + "sparse SWA on " + + std::string(A2_A3_PLATFORM_LOG.c_str()) + "."), + return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF(*opParamInfo_.oriMaskMode != 4U, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "ori_sparse_indices, ori_mask_mode", + "oriMaskMode should be 4 on " + + std::string(A2_A3_PLATFORM_LOG.c_str()) + + " when ori_sparse_indices is empty, but got " + + std::to_string(*opParamInfo_.oriMaskMode)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(oriWinLeft_ != 127, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "ori_sparse_indices, ori_win_left", + "oriWinLeft_ should be 127 on " + + std::string(A2_A3_PLATFORM_LOG.c_str()) + + " when ori_sparse_indices is empty, but got " + + std::to_string(oriWinLeft_)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(oriWinRight_ != 0, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "ori_sparse_indices, ori_win_right", + "oriWinRight_ should be 0 on " + + std::string(A2_A3_PLATFORM_LOG.c_str()) + + " when ori_sparse_indices is empty, but got " + + std::to_string(oriWinRight_)), + return ge::GRAPH_FAILED); + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckFeatureLayout() const { + const std::vector layoutQuerySupportList = {"BSND", "TND"}; + std::string layoutQuery = opParamInfo_.layoutQ; + OP_CHECK_IF(std::find(layoutQuerySupportList.begin(), + layoutQuerySupportList.end(), + layoutQuery) == layoutQuerySupportList.end(), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "layout_q", + layoutQuery.c_str(), + "Layout_q only supports BSND or TND"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckFeatureDtype() const { + OP_CHECK_IF(qType_ != ge::DT_BF16 && qType_ != ge::DT_FLOAT16, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "q", + SMLADataTypeToSerialString(qType_).c_str(), + "The dtype of q only supports " + + SMLADataTypeToSerialString(ge::DT_BF16) + " and " + + SMLADataTypeToSerialString(ge::DT_FLOAT16)), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckFeaturePa() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckFeature() const { + if (ge::GRAPH_SUCCESS != CheckFeatureShape() || + ge::GRAPH_SUCCESS != CheckFeatureLayout() || + ge::GRAPH_SUCCESS != CheckFeatureDtype() || + ge::GRAPH_SUCCESS != CheckFeaturePa()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckDTypeConsistency( + const ge::DataType& actualDtype, + const ge::DataType& expectDtype, + const std::string& name) const { + if (actualDtype != expectDtype) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + name.c_str(), + SMLADataTypeToSerialString(actualDtype).c_str(), + "The dtype of " + name + " should be " + + SMLADataTypeToSerialString(expectDtype)); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckOriAndCmpKv() const { + if (smlaInfo_.perfMode == SMLATemplateMode::HCA_TEMPLATE_MODE || + smlaInfo_.perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE || + smlaInfo_.perfMode == SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { + if (ge::GRAPH_SUCCESS != + CheckDTypeConsistency(cmpKvType_, oriKvType_, CMP_KV_NAME)) { + return ge::GRAPH_FAILED; + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckAttenOut() const { + if (opParamInfo_.attnOut.desc == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "attn_out", "Attn_out must be provided"); + return ge::GRAPH_FAILED; + } + const std::vector dimNumList = {DIM_NUM_THREE, DIM_NUM_FOUR}; + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(opParamInfo_.attnOut.desc, ATTEN_OUT_NAME) || + ge::GRAPH_SUCCESS != CheckLayoutSupport(outLayout_, ATTEN_OUT_NAME) || + ge::GRAPH_SUCCESS != CheckDimNumSupport(opParamInfo_.attnOut.shape, + dimNumList, + ATTEN_OUT_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumInLayoutSupport( + outLayout_, opParamInfo_.attnOut.shape, ATTEN_OUT_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckActualSeqLensQ() const { + if (opParamInfo_.seqUsedQ.tensor == nullptr) { + return ge::GRAPH_SUCCESS; + } + const std::vector dimNumList = {DIM_NUM_ONE}; + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(opParamInfo_.seqUsedQ.desc, SEQUSED_Q_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(&opParamInfo_.seqUsedQ.tensor->GetShape(), + dimNumList, + SEQUSED_Q_NAME)) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + opParamInfo_.seqUsedQ.tensor->GetShapeSize() != bSize_, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "seqused_q", + ToStringRaw(opParamInfo_.seqUsedQ.tensor->GetStorageShape()), + "Seqused_q's first dimension(" + + std::to_string(opParamInfo_.seqUsedQ.tensor->GetShapeSize()) + + ") should be equal to B(" + std::to_string(bSize_) + ")"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::CheckActualSeqLens() const { + if (opParamInfo_.sequsedOriKv.tensor != nullptr) { + const std::vector dimNumList = {DIM_NUM_ONE}; + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.sequsedOriKv.desc, + SEQUSED_ORI_KV_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(&opParamInfo_.sequsedOriKv.tensor->GetShape(), + dimNumList, + SEQUSED_ORI_KV_NAME)) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + opParamInfo_.sequsedOriKv.tensor->GetShapeSize() != bSize_, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "seqused_ori_kv", + ToStringRaw(opParamInfo_.sequsedOriKv.tensor->GetStorageShape()), + "Seqused_ori_kv's first dimension(" + + std::to_string( + opParamInfo_.sequsedOriKv.tensor->GetShapeSize()) + + ") should be equal to B(" + std::to_string(bSize_) + ")"), + return ge::GRAPH_FAILED); + } + if (opParamInfo_.sequsedCmpKv.tensor != nullptr) { + const std::vector dimNumList = {DIM_NUM_ONE}; + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.sequsedCmpKv.desc, + SEQUSED_CMP_KV_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(&opParamInfo_.sequsedCmpKv.tensor->GetShape(), + dimNumList, + SEQUSED_CMP_KV_NAME)) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + opParamInfo_.sequsedCmpKv.tensor->GetShapeSize() != bSize_, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "seqused_cmp_kv", + ToStringRaw(opParamInfo_.sequsedCmpKv.tensor->GetStorageShape()), + "Seqused_cmp_kv's first dimension(" + + std::to_string( + opParamInfo_.sequsedCmpKv.tensor->GetShapeSize()) + + ") should be equal to B(" + std::to_string(bSize_) + ")"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} +ge::graphStatus SMLATilingCheck::CheckMultiParaConsistency() const { + if (ge::GRAPH_SUCCESS != CheckOriAndCmpKv() || + ge::GRAPH_SUCCESS != CheckAttenOut() || + ge::GRAPH_SUCCESS != CheckActualSeqLensQ() || + ge::GRAPH_SUCCESS != CheckActualSeqLens()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SMLATilingCheck::Process() { + Init(); + if (CheckSinglePara() != ge::GRAPH_SUCCESS || + CheckParaExistence() != ge::GRAPH_SUCCESS || + CheckFeature() != ge::GRAPH_SUCCESS || + CheckMultiParaConsistency() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +void SparseFlashMlaTiling::CalcUbBmm(const SMLATilingInfo* tilingInfo) { + uint32_t cubeMSize = tilingInfo->gSize * tilingInfo->s1Size; + uint32_t maxMSize = mBaseSize_; + if (cubeMSize > maxMSize) { + cubeMSize = maxMSize; + } + mmResUbSize_ = + sInnerSizeAlign_ * + Align(cubeMSize, + 16U); // kernel按照16对齐写出,tiling按照这个原则分配内存 + bmm2ResUbSize_ = + headDimAlign_ * + Align(cubeMSize, + 16U); // kernel按照16对齐写出,tiling按照这个原则分配内存 +} + +void SparseFlashMlaTiling::SplitBalanced(SMLATilingInfo* tilingInfo) { + sInnerSizeAlign_ = Align(sInnerSize_, BYTE_BLOCK); + if (tilingInfo->npuArch == NpuArch::DAV_2201) { + mBaseSize_ = + tilingInfo->perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE + ? tilingInfo->gSize + : (256 / tilingInfo->gSize) * + tilingInfo->gSize; // 256:DAV_2201架构下的基础计算块大小 + // DSpark ori_sparse_indices are per query token; keep one S1 row per M + // block. + if (tilingInfo->hasOriSparseIndices && + tilingInfo->perfMode == SMLATemplateMode::SWA_TEMPLATE_MODE) { + mBaseSize_ = tilingInfo->gSize; + } + } + headDimAlign_ = Align(tilingInfo->qHeadDim, BYTE_BLOCK); + CalcUbBmm(tilingInfo); + + tilingData_.baseParams.set_mBaseSize(mBaseSize_); + tilingData_.baseParams.set_s2BaseSize(sInnerSize_); + tilingData_.baseParams.set_mmResUbSize(mmResUbSize_); + tilingData_.baseParams.set_bmm2ResUbSize(bmm2ResUbSize_); +} + +uint32_t SparseFlashMlaTiling::CalcFdLogicalSlotCount( + const SMLATilingInfo* tilingInfo, + uint32_t aicNum) const { + bool isSplitG = + (IsA5Arch(tilingInfo->npuArch) || IsA6Arch(tilingInfo->npuArch)) && + tilingInfo->gSize > 64; + if (isSplitG) { + return aicNum >> 1U; + } + return aicNum; +} + +uint64_t SparseFlashMlaTiling::CalcFdStagingWorkspaceSize( + const SMLATilingInfo* tilingInfo, + uint32_t aicNum) const { + if ((!IsA5Arch(tilingInfo->npuArch) && !IsA6Arch(tilingInfo->npuArch)) || + aicNum == 0U) { + return 0ULL; + } + + const uint64_t logicalCoreSlots = CalcFdLogicalSlotCount(tilingInfo, aicNum); + const uint64_t bytesPerSlot = tilingInfo->gSize * sizeof(float) * + (headDimAlign_ + 2ULL * FD_BROADCAST_ELEMS); + if (tilingInfo->batchConsistency) { + // Intra-core reduction ping-pongs by multiCoreIdxMod2. Cross-core staging + // keeps one reduce-block range for every physical AIC. + const uint64_t intraCoreSlots = 2ULL * logicalCoreSlots; + const uint64_t crossCoreSlots = + static_cast(aicNum) * BATCH_CONSISTENCY_MAX_REDUCE_BLOCK_NUM; + return (intraCoreSlots + crossCoreSlots) * bytesPerSlot; + } + return logicalCoreSlots * FD_MAX_S2_SPLIT_NUM * bytesPerSlot; +} + +uint64_t SparseFlashMlaTiling::CalcVectorizeKvPhyAddrWorkspaceSize( + const SMLATilingInfo* tilingInfo, + uint32_t& vectorizeFlag) const { + vectorizeFlag = 0U; + if (!IsA5Arch(tilingInfo->npuArch) && !IsA6Arch(tilingInfo->npuArch)) { + return 0ULL; + } + constexpr uint32_t SPARSE_BLOCK_ALIGN_NUM = 128; + constexpr uint32_t A5_SIZE = 184 * 1024; + constexpr uint32_t A6_SIZE = 376 * 1024; + const uint32_t SIZE = IsA6Arch(tilingInfo->npuArch) ? A6_SIZE : A5_SIZE; + uint32_t alignedOriSparseBlockCount = + (tilingInfo->oriSparseBlockCount + SPARSE_BLOCK_ALIGN_NUM - 1) / + SPARSE_BLOCK_ALIGN_NUM * SPARSE_BLOCK_ALIGN_NUM; + uint32_t alignedCmpSparseBlockCount = + (tilingInfo->cmpSparseBlockCount + SPARSE_BLOCK_ALIGN_NUM - 1) / + SPARSE_BLOCK_ALIGN_NUM * SPARSE_BLOCK_ALIGN_NUM; + bool isPa = (tilingInfo->kvLayout == SMLALayout::PA_BBND); + uint32_t oriBlockSize = static_cast(tilingInfo->oriBlockSize); + uint32_t cmpBlockSize = static_cast(tilingInfo->cmpBlockSize); + uint32_t oriBlocksizeFlag = + static_cast(oriBlockSize & (oriBlockSize - 1)) == 0; + uint32_t cmpBlocksizeFlag = + static_cast(cmpBlockSize & (cmpBlockSize - 1)) == 0; + uint32_t blocksizeFlag = + isPa ? ((tilingInfo->perfMode == + SMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE) + ? oriBlocksizeFlag + : (oriBlocksizeFlag != 0 && cmpBlocksizeFlag != 0)) + : 1U; + uint64_t paExtraUb = + std::max(static_cast(tilingInfo->oriMaxBlockNumPerBatch) * + sizeof(int32_t), + static_cast(tilingInfo->cmpMaxBlockNumPerBatch) * + sizeof(int32_t)); + uint64_t cmpUbSize = + (isPa ? paExtraUb : 0U) + + static_cast(alignedCmpSparseBlockCount) * sizeof(int32_t) + + static_cast(alignedCmpSparseBlockCount) * sizeof(int64_t); + uint64_t oriUbSize = + (isPa ? paExtraUb : 0U) + + static_cast(alignedOriSparseBlockCount) * sizeof(int32_t) + + static_cast(alignedOriSparseBlockCount) * sizeof(int64_t); + uint64_t vectorizeUbSize = std::max(cmpUbSize, oriUbSize); + vectorizeFlag = static_cast( + (tilingInfo->perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE || + tilingInfo->perfMode == SMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE || + tilingInfo->perfMode == + SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) && + tilingInfo->topkValueMode == 1 && (vectorizeUbSize <= SIZE) && + (blocksizeFlag != 0)); + + if (vectorizeFlag == 0U) { + return 0ULL; + } + uint32_t totalBS1 = (tilingInfo->qLayout == SMLALayout::TND) + ? tilingInfo->s1Size + : (tilingInfo->bSize * tilingInfo->s1Size); + uint64_t oriPhyAddrSize = 0; + if (tilingInfo->perfMode == SMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE || + tilingInfo->perfMode == SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { + oriPhyAddrSize = static_cast(totalBS1) * + alignedOriSparseBlockCount * sizeof(int64_t); + } + uint64_t cmpPhyAddrSize = 0; + if (tilingInfo->perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE || + tilingInfo->perfMode == SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { + cmpPhyAddrSize = static_cast(totalBS1) * + alignedCmpSparseBlockCount * sizeof(int64_t); + } + return oriPhyAddrSize + cmpPhyAddrSize; +} + +// --------------------------SparseFlashMlaTiling类成员函数定义---------------------- +ge::graphStatus SparseFlashMlaTiling::DoOpTiling(SMLATilingInfo* tilingInfo) { + auto ascendcPlatform = + platform_ascendc::PlatformAscendC(tilingInfo->platformInfo); + uint32_t aivNum = ascendcPlatform.GetCoreNumAiv(); + uint32_t aicNum = ascendcPlatform.GetCoreNumAic(); + uint32_t blockDim = ascendcPlatform.CalcTschBlockDim(aivNum, aicNum, aivNum); + context_->SetBlockDim(blockDim); + OP_LOGI(tilingInfo->opName, + "SMLA block dim: %u aiv Num: %u aic Num: %u.", + blockDim, + aivNum, + aicNum); + + SplitBalanced(tilingInfo); + + constexpr uint32_t MM1_RES_ELEM_SIZE = 4; + constexpr uint32_t VEC1_RES_ELEM_SIZE = 2; + constexpr uint32_t MM2_RES_ELEM_SIZE = 4; + constexpr uint32_t VEC2_RES_ELEM_SIZE = 4; + constexpr uint32_t PRELOAD_NUM = 2; + + size_t workspaceSize = ascendcPlatform.GetLibApiWorkSpaceSize(); + if (IsA5Arch(tilingInfo->npuArch) || IsA6Arch(tilingInfo->npuArch)) { + bool isSplitG = tilingInfo->gSize > 64; + if (isSplitG || + tilingInfo->perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE || + tilingInfo->perfMode == SMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE || + tilingInfo->perfMode == + SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { + constexpr uint32_t TRIPLE_BUFFER_NUM = 3; + constexpr uint32_t S2_BASE_SIZE = 128; + constexpr uint32_t D_SIZE = 512; + constexpr uint32_t VEC_RES_ELEM_SIZE = 2; + uint32_t gmSize = + S2_BASE_SIZE * D_SIZE * VEC_RES_ELEM_SIZE * TRIPLE_BUFFER_NUM; + if (isSplitG) { + gmSize *= (aicNum >> 1U); + } else { + gmSize *= aicNum; + } + workspaceSize += gmSize; + constexpr uint32_t S2_REAL_BUF_LEN = 128; + workspaceSize += + TRIPLE_BUFFER_NUM * S2_REAL_BUF_LEN * sizeof(int32_t) * aivNum; + } + } else { + workspaceSize += PRELOAD_NUM * mmResUbSize_ * MM1_RES_ELEM_SIZE * aicNum; + workspaceSize += PRELOAD_NUM * mmResUbSize_ * VEC1_RES_ELEM_SIZE * aicNum; + workspaceSize += PRELOAD_NUM * bmm2ResUbSize_ * MM2_RES_ELEM_SIZE * aicNum; + workspaceSize += PRELOAD_NUM * bmm2ResUbSize_ * VEC2_RES_ELEM_SIZE * aicNum; + if (tilingInfo->perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE || + (tilingInfo->perfMode == SMLATemplateMode::SWA_TEMPLATE_MODE && + tilingInfo->hasOriSparseIndices)) { + constexpr uint32_t MERGE_CACHE_GM_BUF_NUM = 3; // 3:缓存缓冲区数量 + workspaceSize += MERGE_CACHE_GM_BUF_NUM * 512 * 512 * 2 * + aicNum; // 缓冲区的尺寸为512x512字节,2表示双缓冲 + } + } + + // 计算vectorizeFlag (稀疏KV物理地址向量化) + uint32_t vectorizeFlag = 0U; + workspaceSize += + CalcVectorizeKvPhyAddrWorkspaceSize(tilingInfo, vectorizeFlag); + + workspaceSize += CalcFdStagingWorkspaceSize(tilingInfo, aicNum); + size_t* workSpaces = context_->GetWorkspaceSizes(1); + workSpaces[0] = workspaceSize; + + tilingData_.baseParams.set_batchSize(tilingInfo->bSize); + tilingData_.baseParams.set_kvSeqSize(tilingInfo->s2Size); + tilingData_.baseParams.set_qSeqSize(tilingInfo->s1Size); + tilingData_.baseParams.set_nNumOfQInOneGroup(tilingInfo->gSize); + tilingData_.baseParams.set_paBlockSize(tilingInfo->blockSize); + tilingData_.baseParams.set_oriBlockSize(tilingInfo->oriBlockSize); + tilingData_.baseParams.set_cmpBlockSize(tilingInfo->cmpBlockSize); + tilingData_.baseParams.set_oriP(tilingInfo->oriP); + tilingData_.baseParams.set_oriMLow(tilingInfo->oriMLow); + tilingData_.baseParams.set_oriMHigh(tilingInfo->oriMHigh); + tilingData_.baseParams.set_oriMaxBlockNumPerBatch( + tilingInfo->oriMaxBlockNumPerBatch); + tilingData_.baseParams.set_actualLenDimsQ(tilingInfo->actualLenDimsQ); + tilingData_.baseParams.set_actualLenDimsKV(tilingInfo->actualLenDimsKV); + + tilingData_.baseParams.set_softmaxScale(tilingInfo->softmaxScale); + tilingData_.baseParams.set_outputLayout( + static_cast(tilingInfo->outLayout)); + tilingData_.baseParams.set_oriMaskMode(tilingInfo->oriMaskMode); + tilingData_.baseParams.set_oriKvStride0(tilingInfo->oriKvStride0); + tilingData_.baseParams.set_oriWinLeft(tilingInfo->oriWinLeft); + tilingData_.baseParams.set_oriWinRight(tilingInfo->oriWinRight); + tilingData_.baseParams.set_sparseBlockSize(tilingInfo->sparseBlockSize); + tilingData_.baseParams.set_returnSoftmaxLse(tilingInfo->returnSoftmaxLse); + + tilingData_.cmpParams.set_cmpMaxBlockNumPerBatch( + tilingInfo->cmpMaxBlockNumPerBatch); + tilingData_.cmpParams.set_cmpRatio(tilingInfo->cmpRatio); + tilingData_.cmpParams.set_cmpMaskMode(tilingInfo->cmpMaskMode); + tilingData_.cmpParams.set_cmpKvStride0(tilingInfo->cmpKvStride0); + tilingData_.cmpParams.set_cmpP(tilingInfo->cmpP); + tilingData_.cmpParams.set_cmpMLow(tilingInfo->cmpMLow); + tilingData_.cmpParams.set_cmpMHigh(tilingInfo->cmpMHigh); + tilingData_.cmpParams.set_cmpKvSeqSize(tilingInfo->cmpS2Size); + tilingData_.baseParams.set_actualLenDimsOriKV(tilingInfo->actualLenDimsOriKV); + tilingData_.baseParams.set_actualLenDimsCmpKV(tilingInfo->actualLenDimsCmpKV); + tilingData_.baseParams.set_cmpResidualKVSize(tilingInfo->cmpResidualKVSize); + tilingData_.baseParams.set_oriKeyStride0(tilingInfo->oriKeyStride0); + tilingData_.baseParams.set_hasOriSparseIndices( + tilingInfo->hasOriSparseIndices ? 1U : 0U); + tilingData_.baseParams.set_oriSparseIndexWidth( + tilingInfo->oriSparseIndexWidth); + tilingData_.cmpParams.set_cmpKeyStride0(tilingInfo->cmpKeyStride0); + + if (IsA5Arch(tilingInfo->npuArch) || IsA6Arch(tilingInfo->npuArch)) { + tilingData_.baseParams.set_oriSparseBlockCount( + tilingInfo->oriSparseBlockCount); + tilingData_.baseParams.set_topkValueMode(tilingInfo->topkValueMode); + tilingData_.cmpParams.set_cmpSparseBlockCount( + tilingInfo->cmpSparseBlockCount); + } else { + tilingData_.cmpParams.set_sparseBlockCount(tilingInfo->sparseBlockCount); + } + + usedCoreNum_ = aicNum; + tilingData_.baseParams.set_usedCoreNum(usedCoreNum_); + tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), + context_->GetRawTilingData()->GetCapacity()); + context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize()); + + uint32_t qLayout = static_cast(tilingInfo->qLayout); + uint32_t inputKvLayout = static_cast(tilingInfo->kvLayout); + + uint64_t tilingKey; + uint32_t splitG = 0U; + uint32_t headRatioOne = static_cast( + tilingInfo->npuArch == NpuArch::DAV_2201 && + tilingInfo->perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE && + tilingInfo->gSize == 1U); + if (IsA5Arch(tilingInfo->npuArch) || IsA6Arch(tilingInfo->npuArch)) { + splitG = static_cast(tilingInfo->gSize > 64); // 64:分组拆分阈值 + } + uint32_t isDspark = static_cast( + tilingInfo->npuArch == NpuArch::DAV_2201 && + tilingInfo->perfMode == SMLATemplateMode::SWA_TEMPLATE_MODE && + tilingInfo->hasOriSparseIndices); + tilingKey = + GET_TPL_TILING_KEY(0U, + qLayout, + inputKvLayout, + static_cast(tilingInfo->perfMode), + splitG, + headRatioOne, + static_cast(tilingInfo->batchConsistency), + vectorizeFlag, + static_cast(tilingInfo->topkValueMode), + isDspark); + context_->SetScheduleMode(1); + context_->SetTilingKey(tilingKey); + + return ge::GRAPH_SUCCESS; +} + +} // namespace optiling + +namespace optiling { +// --------------------------TilingPrepare函数定义------------------------------------- +static ge::graphStatus TilingPrepareForSparseFlashMla( + gert::TilingParseContext* /* context */) { + return ge::GRAPH_SUCCESS; +} + +// --------------------------Tiling函数定义--------------------------- +ge::graphStatus TilingForSparseFlashMla(gert::TilingContext* context) { + OP_CHECK_IF( + context == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + "XllmKernelSparseFlashMla", "context", "Tiling context is null."), + return ge::GRAPH_FAILED); + + SMLATilingInfo smlaInfo; + SMLAInfoParser smlaInfoParser(context); + if (smlaInfoParser.Parse(smlaInfo) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + if (smlaInfo.npuArch == NpuArch::DAV_2201) { + SMLATilingCheck smlaTilingChecker(smlaInfo); + if (smlaTilingChecker.Process() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + } else { + SparseFlashMlaChecker smlaTilingChecker(smlaInfo); + if (smlaTilingChecker.Process() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + } + + SparseFlashMlaTiling tiling(context); + return tiling.DoOpTiling(&smlaInfo); +} +// --------------------------Tiling函数及TilingPrepare函数注册-------- +IMPL_OP_OPTILING(XllmKernelSparseFlashMla) + .Tiling(TilingForSparseFlashMla) + .TilingParse(TilingPrepareForSparseFlashMla); +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_tiling.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_tiling.h new file mode 100644 index 0000000000..a894c55ee0 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_tiling.h @@ -0,0 +1,567 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file sparse_flash_mla_tiling.h + * \brief + */ +#ifndef SPARSE_FLASH_MLA_TILING_H +#define SPARSE_FLASH_MLA_TILING_H + +#include "common/smla_host_common_defs.h" +#include "platform/soc_spec.h" + +namespace optiling { + +// ------------------算子原型索引常量定义---------------- +// Inputs Index (0-10, common) +constexpr uint32_t Q_INDEX = 0; +constexpr uint32_t ORI_KV_INDEX = 1; +constexpr uint32_t CMP_KV_INDEX = 2; +constexpr uint32_t ORI_SPARSE_INDICES_INDEX = 3; +constexpr uint32_t CMP_SPARSE_INDICES_INDEX = 4; +constexpr uint32_t ORI_BLOCK_TABLE_INDEX = 5; +constexpr uint32_t CMP_BLOCK_TABLE_INDEX = 6; +constexpr uint32_t CU_SEQLENS_Q_INDEX = 7; +constexpr uint32_t CU_SEQLENS_ORI_KV_INDEX = 8; +constexpr uint32_t CU_SEQLENS_CMP_KV_INDEX = 9; +constexpr uint32_t SEQUSED_Q_INDEX = 10; +constexpr uint32_t SEQUSED_ORI_KV_INDEX = 11; +constexpr uint32_t SEQUSED_CMP_KV_INDEX = 12; +constexpr uint32_t CMP_RESIDUAL_KV_INDEX = 13; +constexpr uint32_t ORI_TOPK_LENGTH_INDEX = 14; +constexpr uint32_t CMP_TOPK_LENGTH_INDEX = 15; +constexpr uint32_t SINKS_INDEX = 16; +constexpr uint32_t METADATA_INDEX = 17; + +// Attributes Index +constexpr uint32_t ATTR_SOFTMAX_SCALE_INDEX = 0; +constexpr uint32_t ATTR_CMP_RATIO_INDEX = 1; +constexpr uint32_t ATTR_ORI_MASK_MODE_INDEX = 2; +constexpr uint32_t ATTR_CMP_MASK_MODE_INDEX = 3; +constexpr uint32_t ATTR_ORI_WIN_LEFT_INDEX = 4; +constexpr uint32_t ATTR_ORI_WIN_RIGHT_INDEX = 5; +constexpr uint32_t ATTR_LAYOUT_Q_INDEX = 6; +constexpr uint32_t ATTR_LAYOUT_KV_INDEX = 7; +constexpr uint32_t ATTR_TOPK_VALUE_MODE_INDEX = 8; // A2/A3 +constexpr uint32_t ATTR_RETURN_SOFTMAX_LSE_INDEX = 9; + +// 常量 +constexpr uint32_t BYTE_BLOCK = 32; + +// 入参限制常量 +constexpr uint32_t METADATA_LIMIT = 2048; +constexpr uint32_t DIM_LIMIT = 512; +constexpr uint32_t TOPK_LIMIT = 8192; +constexpr uint32_t BLOCK_SIZE_LIMIT = 1024; + +// -----------算子TilingData定义(A2/A3字段顺序 + A5追加字段)--------------- +BEGIN_TILING_DATA_DEF(XllmKernelSparseFlashMlaSwaParams) +TILING_DATA_FIELD_DEF(uint32_t, batchSize) +TILING_DATA_FIELD_DEF(uint32_t, qSeqSize) +TILING_DATA_FIELD_DEF(uint32_t, kvSeqSize) +TILING_DATA_FIELD_DEF(int64_t, paBlockSize) +TILING_DATA_FIELD_DEF(int64_t, oriBlockSize) +TILING_DATA_FIELD_DEF(int64_t, cmpBlockSize) +TILING_DATA_FIELD_DEF(uint32_t, oriMaxBlockNumPerBatch) +TILING_DATA_FIELD_DEF(uint32_t, nNumOfQInOneGroup) +TILING_DATA_FIELD_DEF(uint32_t, actualLenDimsQ) +TILING_DATA_FIELD_DEF(uint32_t, actualLenDimsKV) +TILING_DATA_FIELD_DEF(float, softmaxScale) // 即 scaleValue +TILING_DATA_FIELD_DEF(uint32_t, outputLayout) +TILING_DATA_FIELD_DEF(uint64_t, oriMaskMode) +TILING_DATA_FIELD_DEF(int64_t, oriKvStride0) // A2/A3 +TILING_DATA_FIELD_DEF(int64_t, oriWinLeft) +TILING_DATA_FIELD_DEF(int64_t, oriWinRight) +TILING_DATA_FIELD_DEF(int64_t, sparseBlockSize) +TILING_DATA_FIELD_DEF(uint32_t, oriSparseBlockCount) // A5 + +TILING_DATA_FIELD_DEF(int64_t, topkValueMode) + +TILING_DATA_FIELD_DEF(uint32_t, usedCoreNum); + +TILING_DATA_FIELD_DEF(uint32_t, mmResUbSize); +TILING_DATA_FIELD_DEF(uint32_t, bmm2ResUbSize); +TILING_DATA_FIELD_DEF(uint32_t, returnSoftmaxLse) +TILING_DATA_FIELD_DEF(uint32_t, mBaseSize) +TILING_DATA_FIELD_DEF(uint32_t, s2BaseSize) + +TILING_DATA_FIELD_DEF(uint32_t, actualLenDimsOriKV) +TILING_DATA_FIELD_DEF(uint32_t, actualLenDimsCmpKV) +TILING_DATA_FIELD_DEF(uint32_t, cmpResidualKVSize) +TILING_DATA_FIELD_DEF(uint32_t, kvHeadNum) +TILING_DATA_FIELD_DEF(uint32_t, oriKeyStride0) // A5 +TILING_DATA_FIELD_DEF(uint32_t, hasOriSparseIndices) +TILING_DATA_FIELD_DEF(uint32_t, oriSparseIndexWidth) +TILING_DATA_FIELD_DEF(uint32_t, oriP) +TILING_DATA_FIELD_DEF(uint32_t, oriMLow) +TILING_DATA_FIELD_DEF(uint32_t, oriMHigh) +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(XllmKernelSparseFlashMlaSwaParamsOp, + XllmKernelSparseFlashMlaSwaParams) + +BEGIN_TILING_DATA_DEF(XllmKernelSparseFlashMlaCmpParams) +TILING_DATA_FIELD_DEF(uint32_t, cmpMaxBlockNumPerBatch) +TILING_DATA_FIELD_DEF(uint32_t, sparseBlockCount) // A2/A3 +TILING_DATA_FIELD_DEF(int64_t, cmpRatio) +TILING_DATA_FIELD_DEF(uint64_t, cmpMaskMode) +TILING_DATA_FIELD_DEF(int64_t, cmpKvStride0) // A2/A3 +TILING_DATA_FIELD_DEF(uint32_t, cmpSparseBlockCount) // A5 +TILING_DATA_FIELD_DEF(uint32_t, cmpKvSeqSize) // A5 +TILING_DATA_FIELD_DEF(uint32_t, cmpKeyStride0) // A5 +TILING_DATA_FIELD_DEF(uint32_t, cmpP) +TILING_DATA_FIELD_DEF(uint32_t, cmpMLow) +TILING_DATA_FIELD_DEF(uint32_t, cmpMHigh) +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(XllmKernelSparseFlashMlaCmpParamsOp, + XllmKernelSparseFlashMlaCmpParams) + +BEGIN_TILING_DATA_DEF(SparseFlashMlaTilingData) +TILING_DATA_FIELD_DEF_STRUCT(XllmKernelSparseFlashMlaSwaParams, baseParams); +TILING_DATA_FIELD_DEF_STRUCT(XllmKernelSparseFlashMlaCmpParams, cmpParams); +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(XllmKernelSparseFlashMla, SparseFlashMlaTilingData) + +struct SMLAParaInfo { + SMLATilingRequiredParaInfo q = {nullptr, nullptr}; + SMLATilingOptionalParaInfo oriKv = {nullptr, nullptr}; + SMLATilingOptionalParaInfo cmpKv = {nullptr, nullptr}; + SMLATilingOptionalParaInfo oriSparseIndices = {nullptr, nullptr}; + SMLATilingOptionalParaInfo cmpSparseIndices = {nullptr, nullptr}; + SMLATilingOptionalParaInfo oriBlockTable = {nullptr, nullptr}; + SMLATilingOptionalParaInfo cmpBlockTable = {nullptr, nullptr}; + SMLATilingOptionalParaInfo cuSeqLensQ = {nullptr, nullptr}; + SMLATilingOptionalParaInfo cuSeqLensOriKv = {nullptr, nullptr}; // A5 + SMLATilingOptionalParaInfo cuSeqLensCmpKv = {nullptr, nullptr}; // A5 + SMLATilingOptionalParaInfo cuSeqLensKv = {nullptr, nullptr}; // A2/A3 + SMLATilingOptionalParaInfo seqUsedQ = {nullptr, nullptr}; + SMLATilingOptionalParaInfo sequsedOriKv = {nullptr, nullptr}; + SMLATilingOptionalParaInfo sequsedCmpKv = {nullptr, nullptr}; + SMLATilingOptionalParaInfo cmpResidualKv = {nullptr, nullptr}; + SMLATilingOptionalParaInfo oriTopkLength = {nullptr, nullptr}; + SMLATilingOptionalParaInfo cmpTopkLength = {nullptr, nullptr}; + SMLATilingOptionalParaInfo sinks = {nullptr, nullptr}; + SMLATilingOptionalParaInfo metadata = {nullptr, nullptr}; + SMLATilingRequiredParaInfo attnOut = {nullptr, nullptr}; + SMLATilingRequiredParaInfo softmaxLse = {nullptr, nullptr}; + + const float* softmaxScale = nullptr; + const uint32_t* cmpRatio = nullptr; + const uint32_t* oriMaskMode = nullptr; + const uint32_t* cmpMaskMode = nullptr; + const int32_t* oriWinLeft = nullptr; + const int32_t* oriWinRight = nullptr; + const char* layoutQ = nullptr; + const char* layoutKv = nullptr; + const uint32_t* topkValueMode = nullptr; + const bool* returnSoftmaxLse = nullptr; +}; + +static std::string SMLADataTypeToSerialString(ge::DataType type); +std::string SMLALayoutToSerialString(SMLALayout layout); + +// -----------算子Tiling入参信息类--------------- +class SMLATilingInfo { + public: + const char* opName = nullptr; + fe::PlatFormInfos* platformInfo = nullptr; + SMLAParaInfo opParamInfo; + + // Base Param + NpuArch npuArch = NpuArch::DAV_2201; + uint32_t bSize = 0; + uint32_t n1Size = 0; + uint32_t n2Size = 0; + uint32_t s1Size = 0; + int64_t s2Size = 0; + int64_t cmpS2Size = 0; // A5 + uint32_t gSize = 0; + uint32_t qHeadDim = 0; + uint32_t oriKvHeadDim = 0; + uint32_t cmpKvHeadDim = 0; + uint32_t qTSize = 0; // 仅TND时生效 + + uint32_t actualLenDimsQ = 0; + uint32_t actualLenDimsKV = 0; + + uint32_t actualLenDimsOriKV = 0; + uint32_t actualLenDimsCmpKV = 0; + uint32_t cmpResidualKVSize = 0; + + uint32_t oriKeyStride0 = 0; // A5 + uint32_t cmpKeyStride0 = 0; // A5 + + float softmaxScale = 0; + int64_t cmpRatio = 1; + uint64_t oriMaskMode = 0; + uint64_t cmpMaskMode = 0; + uint64_t oriKvStride0 = 0; // A2/A3 + uint64_t cmpKvStride0 = 0; // A2/A3 + int64_t oriWinLeft = 0; + int64_t oriWinRight = 0; + int64_t sparseBlockSize = 0; + int64_t oriSparseBlockCount = 0; + int64_t cmpSparseBlockCount = 0; + int64_t sparseBlockCount = 0; // A2/A3 + bool hasOriSparseIndices = false; + uint32_t oriSparseIndexWidth = 0; + + int64_t topkValueMode = 0; + // Others Flag + bool returnSoftmaxLse = false; + bool batchConsistency = false; + + // PageAttention + uint32_t oriMaxBlockNumPerBatch = 0; + int32_t blockSize = 0; + int32_t oriBlockSize = 0; + int32_t cmpBlockSize = 0; + uint32_t cmpMaxBlockNumPerBatch = 0; + uint32_t oriP = 0; + uint32_t oriMLow = 0; + uint32_t oriMHigh = 0; + uint32_t cmpP = 0; + uint32_t cmpMLow = 0; + uint32_t cmpMHigh = 0; + + // DType + ge::DataType qType = ge::DT_FLOAT16; + ge::DataType oriKvType = ge::DT_FLOAT16; + ge::DataType cmpKvType = ge::DT_FLOAT16; + ge::DataType outputType = ge::DT_FLOAT16; + + // Layout + SMLALayout qLayout = SMLALayout::TND; + SMLALayout cmpSparseIndicesLayout = SMLALayout::TND; + SMLALayout oriSparseIndicesLayout = SMLALayout::TND; + SMLALayout kvLayout = SMLALayout::PA_BBND; + SMLALayout outLayout = SMLALayout::BSND; + + // template mode + SMLATemplateMode perfMode = SMLATemplateMode::SWA_TEMPLATE_MODE; +}; + +// -----------算子Tiling入参信息解析及Check类--------------- +class SMLATilingCheck { + public: + explicit SMLATilingCheck(const SMLATilingInfo& smlaInfo) + : smlaInfo_(smlaInfo) {}; + ~SMLATilingCheck() = default; + virtual ge::graphStatus Process(); + + private: + void Init(); + + void LogErrorDtypeSupport(const std::vector& expectDtypeList, + const ge::DataType& actualDtype, + const std::string& name) const; + ge::graphStatus CheckLayoutSupport(const SMLALayout& actualLayout, + const std::string& name) const; + template + void LogErrorDimNumSupport(const std::vector& expectNumberList, + const T& actualValue, + const std::string& name) const; + template + void LogErrorNumberSupport(const std::vector& expectNumberList, + const T& actualValue, + const std::string& name, + const std::string subName) const; + ge::graphStatus CheckDimNumSupport( + const gert::StorageShape* shape, + const std::vector& expectDimNumList, + const std::string& name) const; + void LogErrorLayoutSupport(const std::vector& expectLayoutList, + const SMLALayout& actualLayout, + const std::string& name) const; + ge::graphStatus CheckDimNumInLayoutSupport(const SMLALayout& layout, + const gert::StorageShape* shape, + const std::string& name) const; + ge::graphStatus CheckDtypeSupport(const gert::CompileTimeTensorDesc* desc, + const std::string& name) const; + ge::graphStatus CheckSinglePara() const; + ge::graphStatus CheckSingleParaQuery() const; + ge::graphStatus CheckSingleParaOriKv() const; + ge::graphStatus CheckSingleParaCmpKv() const; + ge::graphStatus CheckSingleParaCuSeqLensQ() const; + ge::graphStatus CheckSingleParaCuSeqLensOriKv() const; + ge::graphStatus CheckSingleParaCuSeqLensCmpKv() const; + ge::graphStatus CheckSingleParaCmpResidualKv() const; + ge::graphStatus CheckSingleParaTopkLength() const; + ge::graphStatus CheckSingleParaNumHeads() const; + ge::graphStatus CheckSingleParaKvHeadNums() const; + ge::graphStatus CheckSingleParaOriSparseIndices() const; + ge::graphStatus CheckSingleParaCmpSparseIndices() const; + ge::graphStatus CheckSingleParaSinks() const; + ge::graphStatus CheckSingleParaMetadata() const; + ge::graphStatus CheckSingleParaCmpRatio() const; + ge::graphStatus CheckSingleParaOriMaskMode() const; + ge::graphStatus CheckSingleParaCmpMaskMode() const; + ge::graphStatus CheckSingleParaOriKvStride0() const; // A2/A3 + ge::graphStatus CheckSingleParaCmpKvStride0() const; // A2/A3 + ge::graphStatus CheckSingleParaOriWinLeft() const; + ge::graphStatus CheckSingleParaOriWinRight() const; + ge::graphStatus CheckSingleParaOriBlockTable() const; + ge::graphStatus CheckSingleParaCmpBlockTable() const; + + ge::graphStatus CheckParaExistence() const; + ge::graphStatus CheckExists(const void* pointer, + const std::string& name) const; + ge::graphStatus CheckNotExists(const void* pointer, + const std::string& name) const; + ge::graphStatus CheckExistsByMap( + const std::map& paramMap) const; + ge::graphStatus CheckNotExistsByMap( + const std::map& paramMap) const; + ge::graphStatus CheckExistenceByMap( + std::map& existMap, + std::map& notExistMap) const; + + ge::graphStatus CheckFeature() const; + ge::graphStatus CheckFeatureShape() const; + ge::graphStatus CheckFeatureLayout() const; + ge::graphStatus CheckFeatureDtype() const; + ge::graphStatus CheckFeaturePa() const; + + ge::graphStatus CheckMultiParaConsistency() const; + ge::graphStatus CheckDTypeConsistency(const ge::DataType& actualDtype, + const ge::DataType& expectDtype, + const std::string& name) const; + ge::graphStatus CheckOriAndCmpKv() const; + ge::graphStatus CheckAttenOut() const; + ge::graphStatus CheckActualSeqLensQ() const; + ge::graphStatus CheckActualSeqLens() const; + + const char* opName_; + fe::PlatFormInfos* platformInfo_; + SMLAParaInfo opParamInfo_; + const SMLATilingInfo& smlaInfo_; + + int64_t bSize_ = 0; + int64_t n1Size_ = 0; + int64_t n2Size_ = 0; + int64_t gSize_ = 0; + int64_t s1Size_ = 0; + int64_t s2Size_ = 0; + int64_t cmpS2Size_ = 0; // A5 + int64_t qHeadDim_ = 0; + int64_t oriKvHeadDim_ = 0; + int64_t cmpKvHeadDim_ = 0; + + int64_t qTSize_ = 0; // 仅TND时生效 + int64_t cmpRatio_ = 1; + int64_t oriWinLeft_ = 0; + int64_t oriWinRight_ = 0; + bool hasOriSparseIndices_ = false; + int64_t oriSparseIndexWidth_ = 0; + + int64_t topkValueMode_; + + SMLALayout qLayout_ = SMLALayout::TND; + SMLALayout cmpSparseIndicesLayout_ = SMLALayout::TND; + SMLALayout oriSparseIndicesLayout_ = SMLALayout::TND; + SMLALayout outLayout_ = SMLALayout::TND; + SMLALayout kvLayout_ = SMLALayout::PA_BBND; + + int64_t oriBlockSize_ = 0; + int64_t cmpBlockSize_ = 0; + + NpuArch npuArch_ = NpuArch::DAV_2201; + + ge::DataType qType_ = ge::DT_FLOAT16; + ge::DataType oriKvType_ = ge::DT_FLOAT16; + ge::DataType cmpKvType_ = ge::DT_FLOAT16; + ge::DataType outputType_ = ge::DT_FLOAT16; +}; + +template +inline T Align(T num, T rnd) { + return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd) * (rnd))); +} + +class SMLAInfoParser { + public: + explicit SMLAInfoParser(gert::TilingContext* context) : context_(context) {} + ~SMLAInfoParser() = default; + + ge::graphStatus CheckRequiredInOutExistence() const; + ge::graphStatus CheckRequiredAttrExistence() const; + ge::graphStatus CheckRequiredParaExistence() const; + ge::graphStatus CheckUnrequiredParaExistence() const; + + ge::graphStatus GetActualSeqLenSize(int64_t& size, + const gert::Tensor* tensor, + SMLALayout& layout, + const std::string& name) const; + ge::graphStatus GetActualSeqLenQSize(int64_t& size); + ge::graphStatus GetOpName(); + ge::graphStatus GetNpuInfo(); + void GetOptionalInputParaInfo(); + void GetInputParaInfo(); + void GetOutputParaInfo(); + ge::graphStatus GetAttrParaInfo(); + ge::graphStatus GetOpParaInfo(); + + ge::graphStatus GetInOutDataType(); + ge::graphStatus GetQueryAndOutLayout(); + ge::graphStatus GetKvLayout(); + ge::graphStatus GetSMLATemplateMode(); + ge::graphStatus SetSMLAShape(); + ge::graphStatus GetN1Size(); + ge::graphStatus GetN2Size(); + ge::graphStatus GetGSize(); + ge::graphStatus GetBatchSize(); + ge::graphStatus GetQTSize(); + ge::graphStatus GetS1Size(); + ge::graphStatus GetS2SizeForPageAttention(); + ge::graphStatus GetS2SizeForTND(); // A2/A3 + ge::graphStatus GetS2Size(); + ge::graphStatus GetMaxBlockNumPerBatch(); + ge::graphStatus GetBlockSize(); + ge::graphStatus SmlaGetMagicPM(); + ge::graphStatus GetQHeadDim(); + ge::graphStatus GetValueHeadDim(); + ge::graphStatus GetSparseBlockCount(); + ge::graphStatus GetActualseqInfo(); + ge::graphStatus GetSinks(); + uint64_t GetOptionalInputStride0(uint32_t inputIndex) const; + void GenerateInfo(SMLATilingInfo& smlaInfo); + ge::graphStatus Parse(SMLATilingInfo& smlaInfo); + std::vector GetKvstride(const gert::Shape& shape, + const SMLALayout& layout) const; + ge::graphStatus CheckContiguous() const; // A5 + + gert::TilingContext* context_ = nullptr; + const char* opName_; + fe::PlatFormInfos* platformInfo_; + SMLAParaInfo opParamInfo_; + + bool HasAxis(const SMLAAxis& axis, + const SMLALayout& layout, + const gert::Shape& shape) const; + size_t GetAxisIdx(const SMLAAxis& axis, const SMLALayout& layout) const; + int64_t GetAxisNum(const gert::Shape& shape, + const SMLAAxis& axis, + const SMLALayout& layout) const; + static constexpr int64_t invalidDimValue_ = + std::numeric_limits::min(); + + // BaseParams + int64_t bSize_ = 0; + int64_t n1Size_ = 0; + int64_t n2Size_ = 0; + int64_t gSize_ = 0; + int64_t s1Size_ = 0; + int64_t s2Size_ = 0; + int64_t cmpS2Size_ = 0; // A5 + int64_t qTSize_ = 0; + int64_t qHeadDim_ = 0; + int64_t oriKvHeadDim_ = 0; + int64_t cmpKvHeadDim_ = 0; + int64_t sparseBlockSize_ = 0; + int64_t oriSparseBlockCount_ = 0; // A5 + int64_t cmpSparseBlockCount_ = 0; // A5 + int64_t oriWinLeft_ = 0; + int64_t oriWinRight_ = 0; + bool hasOriSparseIndices_ = false; + int64_t oriSparseIndexWidth_ = 0; + int64_t topkValueMode_ = 0; + int64_t actualLenDimsKV_ = 0; + int64_t actualLenDimsQ_ = 0; + bool batchConsistency_ = false; + + uint32_t actualLenDimsOriKV_ = 0; + uint32_t actualLenDimsCmpKV_ = 0; + uint32_t cmpResidualKVSize_ = 0; + + std::vector oriKeyStridesVec_; // A5 + std::vector cmpKeyStridesVec_; // A5 + + uint32_t aicNum_ = 0; + uint32_t aivNum_ = 0; + // Layout + SMLALayout qLayout_ = SMLALayout::TND; + SMLALayout cmpSparseIndicesLayout_ = SMLALayout::TND; + SMLALayout oriSparseIndicesLayout_ = SMLALayout::TND; + SMLALayout outLayout_ = SMLALayout::BSND; + SMLALayout kvLayout_ = SMLALayout::PA_BBND; + // PageAttention + uint32_t oriMaxBlockNumPerBatch_ = 0; + uint32_t cmpMaxBlockNumPerBatch_ = 0; + int64_t oriBlockSize_ = 0; + int64_t cmpBlockSize_ = 0; + uint32_t oriP_ = 0; + uint32_t oriMLow_ = 0; + uint32_t oriMHigh_ = 0; + uint32_t cmpP_ = 0; + uint32_t cmpMLow_ = 0; + uint32_t cmpMHigh_ = 0; + + // template mode + SMLATemplateMode perfMode_ = SMLATemplateMode::SWA_TEMPLATE_MODE; + + NpuArch npuArch_ = NpuArch::DAV_2201; + ge::DataType qType_ = ge::DT_FLOAT16; + ge::DataType oriKvType_ = ge::DT_FLOAT16; + ge::DataType cmpKvType_ = ge::DT_FLOAT16; + ge::DataType cmpSparseIndicesType_ = ge::DT_INT32; + ge::DataType oriBlockTableType_ = ge::DT_INT32; + ge::DataType cmpBlockTableType_ = ge::DT_INT32; + ge::DataType cuSeqLensQType_ = ge::DT_INT32; + ge::DataType seqsedKvType_ = ge::DT_INT32; + ge::DataType sinksType_ = ge::DT_INT32; + ge::DataType metadataType_ = ge::DT_INT32; + ge::DataType outputType_ = ge::DT_FLOAT16; + + gert::Shape qShape_{}; + gert::Shape oriKvShape_{}; + gert::Shape cmpKvShape_{}; + gert::Shape oriSparseIndicesShape_{}; + gert::Shape cmpSparseIndicesShape_{}; +}; + +// ---------------算子Tiling类--------------- +class SparseFlashMlaTiling { + public: + explicit SparseFlashMlaTiling(gert::TilingContext* context) + : context_(context) {}; + ge::graphStatus DoOpTiling(SMLATilingInfo* tilingInfo); + + private: + void SplitBalanced(SMLATilingInfo* tilingInfo); + void CalcUbBmm(const SMLATilingInfo* tilingInfo); + uint32_t CalcFdLogicalSlotCount(const SMLATilingInfo* tilingInfo, + uint32_t aicNum) const; + uint64_t CalcFdStagingWorkspaceSize(const SMLATilingInfo* tilingInfo, + uint32_t aicNum) const; + uint64_t CalcVectorizeKvPhyAddrWorkspaceSize(const SMLATilingInfo* tilingInfo, + uint32_t& vectorizeFlag) const; + gert::TilingContext* context_ = nullptr; + SMLATemplateMode perfMode_ = SMLATemplateMode::SWA_TEMPLATE_MODE; + SparseFlashMlaTilingData tilingData_; + uint32_t blockDim_{0}; + uint64_t workspaceSize_{0}; + uint64_t tilingKey_{0}; + + SMLATilingInfo* smlaInfo_ = nullptr; + + size_t mmResUbSize_ = 0; + size_t bmm2ResUbSize_ = 0; + uint32_t sInnerLoopTimes_ = 0; + uint32_t sInnerSize_ = 512; // s2固定切分512 + uint32_t sInnerSizeAlign_ = 0; + uint32_t usedCoreNum_ = 0; + + uint32_t headDimAlign_ = 0; + uint32_t mBaseSize_ = 64; +}; + +} // namespace optiling +#endif diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_arch22_metadata.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_arch22_metadata.h new file mode 100644 index 0000000000..6ac2600998 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_arch22_metadata.h @@ -0,0 +1,85 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file sparse_flash_mla_arch22_metadata.h + * \brief + */ + +#ifndef SPARSE_FLASH_MLA_ARCH22_METADATA_H +#define SPARSE_FLASH_MLA_ARCH22_METADATA_H + +#include + +namespace optiling { + +// Constants +constexpr uint32_t AIC_CORE_NUM = 80; +constexpr uint32_t AIV_CORE_NUM = 80; +constexpr uint32_t SMLA_META_SIZE = 2048; +using SMLA_METADATA_T = int32_t; + +constexpr uint32_t FA_METADATA_SIZE = 9; +constexpr uint32_t FD_METADATA_SIZE = 8; + +// FA Metadata Index Definitions +constexpr uint32_t FA_CORE_ENABLE_INDEX = 0; +constexpr uint32_t FA_BN2_START_INDEX = 1; +constexpr uint32_t FA_M_START_INDEX = 2; +constexpr uint32_t FA_S2_START_INDEX = 3; +constexpr uint32_t FA_BN2_END_INDEX = 4; +constexpr uint32_t FA_M_END_INDEX = 5; +constexpr uint32_t FA_S2_END_INDEX = 6; +constexpr uint32_t FA_FIRST_FD_DATA_WORKSPACE_IDX_INDEX = 7; +constexpr uint32_t FA_S2_MAX_NUM = 8; + +// FD Metadata Index Definitions +constexpr uint32_t FD_CORE_ENABLE_INDEX = 0; +constexpr uint32_t FD_BN2_IDX_INDEX = 1; +constexpr uint32_t FD_M_IDX_INDEX = 2; +constexpr uint32_t FD_WORKSPACE_IDX_INDEX = 3; +constexpr uint32_t FD_WORKSPACE_NUM_INDEX = 4; +constexpr uint32_t FD_M_START_INDEX = 5; +constexpr uint32_t FD_M_NUM_INDEX = 6; + +/** + * @brief 获取属性的绝对索引 + * @param coreIdx 核索引 + * @param metaIdx 元数据索引 + * @param isAIV 是否为AIV数据,默认为false + * @return 返回属性的绝对索引 + */ +#ifdef __CCE_AICORE__ +__aicore__ inline uint32_t GetAttrAbsIndex(uint32_t coreIdx, + uint32_t metaIdx, + bool isAIV = false) { + if (isAIV) { + return FA_METADATA_SIZE * AIC_CORE_NUM + FD_METADATA_SIZE * coreIdx + + metaIdx; + } else { + return FA_METADATA_SIZE * coreIdx + metaIdx; + } +} +#endif + +namespace detail { +struct SasMetadata { + uint32_t faMetadata[AIC_CORE_NUM][FA_METADATA_SIZE]; + uint32_t fdMetadata[AIV_CORE_NUM][FD_METADATA_SIZE]; +}; +} // namespace detail + +static_assert(SMLA_META_SIZE * sizeof(SMLA_METADATA_T) >= + sizeof(detail::SasMetadata)); +} // namespace optiling + +#endif // SPARSE_FLASH_MLA_ARCH22_METADATA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_common_arch22.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_common_arch22.h new file mode 100644 index 0000000000..c2d4085ddf --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_common_arch22.h @@ -0,0 +1,408 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file sparse_flash_mla_common_arch22.h + * \brief + */ + +#ifndef SPARSE_FLASH_MLA_COMMON_ARCH22_H +#define SPARSE_FLASH_MLA_COMMON_ARCH22_H + +#include "kernel_operator.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" + +namespace SMLAKernel { +using namespace AscendC; +// 将isCheckTiling设置为false, 输入输出的max&sum&exp的shape为(m, 1) +constexpr SoftmaxConfig SMLA_SOFTMAX_FLASHV2_CFG_WITHOUT_BRC = { + false, + 0, + 0, + SoftmaxMode::SOFTMAX_OUTPUT_WITHOUT_BRC}; + +enum class SMLA_RUN_MODE { + SWA_MODE = 0, + CSA_MODE = 1, + HCA_MODE = 2, +}; + +enum class SMLA_LAYOUT { BSND = 0, TND = 1, PA_BBND = 2 }; + +template +struct SMLAType { + using queryType = Q_T; + using kvType = KV_T; + using outputType = OUT_T; + static constexpr bool flashDecode = FLASH_DECODE; + static constexpr SMLA_LAYOUT layout = LAYOUT_T; + static constexpr SMLA_LAYOUT kvLayout = KV_LAYOUT_T; + static constexpr bool pageAttention = (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND); + static constexpr int templateMode = TEMPLATE_MODE; + static constexpr bool headRatioOne = HEAD_RATIO_ONE; + static constexpr bool isDspark = IS_DSPARK; +}; + +// ================================Util +// functions================================== +template +__aicore__ inline T1 SMLAAlign(T1 num, T2 rnd) { + return (rnd == 0) ? 0 : ((num + rnd - 1) / rnd * rnd); +} + +template +__aicore__ inline T1 CeilDiv(T1 num, T2 rnd) { + return (rnd == 0) ? 0 : ((num + rnd - 1) / rnd); +} + +template +__aicore__ inline T1 Min(T1 a, T2 b) { + return (a > b) ? b : a; +} + +template +__aicore__ inline T1 Max(T1 a, T2 b) { + return (a > b) ? a : b; +} + +template +__aicore__ inline size_t BlockAlign(size_t s) { + if constexpr (IsSameType::value) { + return (s + 63) / 64 * 64; + } + size_t n = (32 / sizeof(T)); + return (s + n - 1) / n * n; +} + +struct PAShape { + uint32_t blockSize; + uint32_t headNum; // 一般为kv的head num,对应n2 + uint32_t headDim; // 512 对应d + uint32_t kvStride; + uint32_t maxblockNumPerBatch; // block table 每一行的最大个数 + uint32_t actHeadDim; // 实际拷贝col大小,考虑到N切块 s*d, 对应d + uint32_t copyRowNum; // 总共要拷贝的行数 + uint32_t copyRowNumAlign; +}; + +struct Position { + uint32_t bIdx; + uint32_t n2Idx; + uint32_t s2Idx; + uint32_t dIdx; +}; + +// 场景:query、key、value GM to L1 +// GM按ND格式存储 +// L1按NZ格式存储 +// GM的行、列、列的stride +template +__aicore__ inline void DataCopyGmNDToL1(LocalTensor& l1Tensor, + GlobalTensor& gmTensor, + uint32_t rowAct, + uint32_t rowAlign, + uint32_t col, // D + uint32_t colStride) // D or N*D +{ + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = rowAct; // nd矩阵的行数 + // T为int4场景下,dValue = col / 2,srcDValue = colStride / 2 + nd2nzPara.dValue = col; // nd矩阵的列数 + nd2nzPara.srcDValue = colStride; // 同一nd矩阵相邻行起始地址间的偏移 + nd2nzPara.dstNzC0Stride = rowAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(l1Tensor, gmTensor, nd2nzPara); +} + +/* + 适用PA数据从GM拷贝到L1,支持ND、NZ数据; + PA的layout分 BBND(blockNum,N,blockSize,D) BBH(blockNum,blockSize,N*D + BSH\BSND\TND 为BBH + shape.copyRowNumAlign 需要16字节对齐,如拷贝k矩阵,一次拷贝128*512,遇到尾块 + 10*512 需对齐到16*512 +*/ +template +__aicore__ inline void DataCopyPA( + LocalTensor& dstTensor, // l1 + GlobalTensor& srcTensor, // gm + GlobalTensor& blockTableGm, + const PAShape& shape, // blockSize, headNum, headDim + const Position& startPos) // bacthIdx nIdx curSeqIdx +{ + uint32_t copyFinishRowCnt = 0; + uint64_t blockTableBaseOffset = startPos.bIdx * shape.maxblockNumPerBatch; + uint32_t curS2Idx = startPos.s2Idx; + uint32_t blockElementCnt = 32 / sizeof(T); + while (copyFinishRowCnt < shape.copyRowNum) { + uint64_t blockIdOffset = + curS2Idx / shape.blockSize; // 获取block table上的索引 + uint64_t reaminRowCnt = + curS2Idx % shape.blockSize; // 获取在单个块上超出的行数 + uint64_t idInBlockTable = blockTableGm.GetValue( + blockTableBaseOffset + blockIdOffset); // 从block table上的获取编号 + uint32_t copyRowCnt = + shape.blockSize - reaminRowCnt; // 一次只能处理一个Block + if (copyFinishRowCnt + copyRowCnt > shape.copyRowNum) { + copyRowCnt = shape.copyRowNum - copyFinishRowCnt; // 一个block未拷满 + } + uint64_t offset = idInBlockTable * shape.kvStride; // PA的偏移 + uint64_t dStride = shape.headDim; + if constexpr (SRC_LAYOUT == SMLA_LAYOUT::BSND || + SRC_LAYOUT == SMLA_LAYOUT::TND) { + offset += (uint64_t)(startPos.n2Idx * shape.headDim) + + reaminRowCnt * shape.headDim * shape.headNum + startPos.dIdx; + dStride = shape.headDim * shape.headNum; + } else { + offset += (uint64_t)(startPos.n2Idx * shape.headDim * shape.blockSize) + + reaminRowCnt * shape.headDim + startPos.dIdx; + } + + uint32_t dValue = shape.actHeadDim; + uint32_t srcDValue = dStride; + LocalTensor tmpDstTensor = dstTensor[copyFinishRowCnt * blockElementCnt]; + GlobalTensor tmpSrcTensor = srcTensor[offset]; + + DataCopyGmNDToL1(tmpDstTensor, + tmpSrcTensor, + copyRowCnt, + shape.copyRowNumAlign, + dValue, + srcDValue); + copyFinishRowCnt += copyRowCnt; + curS2Idx += copyRowCnt; + } +} + +template +__aicore__ inline void DataCopyPABySlots(LocalTensor& dstTensor, + GlobalTensor& srcTensor, + GlobalTensor& blockTableGm, + GlobalTensor& sparseIndicesGm, + const PAShape& shape, + const Position& startPos, + uint64_t sparseIndexBaseOffset, + uint32_t sparseIndexStart) { + uint32_t blockElementCnt = 32 / sizeof(T); + uint64_t blockTableBaseOffset = startPos.bIdx * shape.maxblockNumPerBatch; + for (uint32_t row = 0; row < shape.copyRowNum; ++row) { + int32_t logicalIdx = sparseIndicesGm.GetValue(sparseIndexBaseOffset + + sparseIndexStart + row); + if (logicalIdx < 0) { + continue; + } + uint64_t blockTableIdx = + static_cast(logicalIdx) / shape.blockSize; + uint64_t inBlockIdx = static_cast(logicalIdx) % shape.blockSize; + uint64_t idInBlockTable = + blockTableGm.GetValue(blockTableBaseOffset + blockTableIdx); + uint64_t offset = idInBlockTable * shape.kvStride; + offset += static_cast(startPos.n2Idx * shape.headDim * + shape.blockSize) + + inBlockIdx * shape.headDim + startPos.dIdx; + + LocalTensor tmpDstTensor = dstTensor[row * blockElementCnt]; + GlobalTensor tmpSrcTensor = srcTensor[offset]; + DataCopyGmNDToL1(tmpDstTensor, + tmpSrcTensor, + 1, + shape.copyRowNumAlign, + shape.actHeadDim, + shape.headDim); + } +} + +struct RunInfo { + uint32_t loop = 0; + uint32_t cmpLoop = 0; // 用于判断取 用于merge的4块GM 中的哪一块 + uint32_t bIdx = 0; + uint32_t gIdx = 0; + uint32_t s1Idx = 0; + uint32_t s2Idx = 0; + uint32_t n2IdxReal = 0; + uint32_t relativeS2Idx = 0; + uint32_t bn2IdxInCurCore = 0; + uint32_t curSInnerLoopTimes = 0; + uint64_t tndBIdxOffsetForQ = 0; + uint64_t tndBIdxOffsetForKV = 0; + uint64_t tensorCmpBOffset = 0; + uint64_t tensorAOffset = 0; + uint64_t tensorBOffset = 0; + uint64_t attenOutOffset = 0; + uint64_t qTokenOffset = 0; + uint64_t attenMaskOffset = 0; + uint64_t topKBaseOffset = 0; + uint32_t actualSingleProcessSInnerSize = 0; + uint32_t actualSingleProcessSInnerSizeAlign = 0; + uint32_t actualSingleProcessSInnerOriSize = 0; + uint32_t actualSingleProcessSInnerOriAlignSize = 0; + uint32_t actualSingleProcessSInnerCmpSize = 0; + uint32_t actualSingleProcessSInnerCmpAlignSize = 0; + uint32_t s2BatchOffset = 0; + uint32_t gSize = 0; + uint32_t s1Size = 0; + uint32_t s2Size = 0; + uint32_t mSize = 0; + uint32_t mSizeV = 0; + uint32_t mSizeVStart = 0; + uint32_t tndIsS2SplitCore = 0; + uint32_t tndCoreStartKVSplitPos = 0; + bool isFirstSInnerLoop = false; + bool isBmm2Output = false; + bool isValid = false; + bool isLastS2Loop = 0; + int64_t inValidRowCount = 0; + + uint64_t actS1Size = 1; + uint64_t actS2SizeOri = 0ULL; + static constexpr uint32_t n2Idx = 0; + uint32_t gS1Idx = 0; + uint64_t actS2Size = 1; + uint64_t actOriS2Size = 1; + uint32_t actMBaseSize = 0; + int32_t nextTokensPerBatch = 0; + int64_t threshold = 0; + uint64_t curOffsetInSparseBlock = 0; + uint32_t curTopKIdx = 0; + bool isOriOnly = true; // 判断当前块是在Ori部分还是Cmp部分 + bool isOriCmpMix = false; + uint8_t resv[2]; + uint64_t s2StartPoint = 0; + int64_t cmpS2IdStart = 0; + int64_t cmpS2IdLimit = 0; + int32_t v0S2DealSize = 0; + int32_t v0S2Start = 0; + uint32_t oriDealSize = 0; + int32_t cmpMaskRight = 0; +}; + +struct ConstInfo { + // CUBE与VEC核间同步的模式 + static constexpr uint32_t SMLA_SYNC_MODE2 = 2; + // BUFFER的字节数 + static constexpr uint32_t BUFFER_SIZE_BYTE_32B = 32; + static constexpr uint32_t BUFFER_SIZE_BYTE_64B = 64; + static constexpr uint32_t BUFFER_SIZE_BYTE_256B = 256; + static constexpr uint32_t BUFFER_SIZE_BYTE_512B = 512; + static constexpr uint32_t BUFFER_SIZE_BYTE_1K = 1024; + static constexpr uint32_t BUFFER_SIZE_BYTE_2K = 2048; + static constexpr uint32_t BUFFER_SIZE_BYTE_4K = 4096; + static constexpr uint32_t BUFFER_SIZE_BYTE_8K = 8192; + static constexpr uint32_t BUFFER_SIZE_BYTE_16K = 16384; + static constexpr uint32_t BUFFER_SIZE_BYTE_32K = 32768; + // FP32的0值和极大值 + static constexpr float FLOAT_ZERO = 0; + static constexpr float FLOAT_MAX = 3.402823466e+38F; + + // preLoad的总次数 + uint32_t preLoadNum = 0U; + uint32_t nBufferMBaseSize = 0U; + // CUBE和VEC的核间同步EventID + uint32_t syncV0C1 = 0U; + uint32_t syncC1V1 = 0U; + uint32_t syncV1C2 = 0U; + uint32_t syncC2V2 = 0U; + + uint32_t mmResUbSize = 0U; // Matmul1输出结果GM上的大小 + uint32_t vec1ResUbSize = 0U; // Vector1输出结果GM上的大小 + uint32_t bmm2ResUbSize = 0U; // Matmul2输出结果GM上的大小 + uint32_t usedCoreNum = 0U; + uint64_t batchSize = 0ULL; + uint64_t gSize = 0ULL; + uint64_t qHeadNum = 0ULL; + uint64_t kvHeadNum = 0; + uint64_t headDim = 0; + uint64_t kvSeqSize = 0ULL; // kv最大S长度 + uint64_t qSeqSize = 1ULL; // q最大S长度 + int64_t kvCacheBlockSize = 0; // PA场景的block size + uint64_t paCmpBlockSize = 0; + uint64_t paOriBlockSize = 0; + int64_t orikvCacheBlockSize = 0; + int64_t cmpkvCacheBlockSize = 0; + uint32_t oriMaxBlockNumPerBatch = 0; // PA场景的最大单batch block number + uint32_t cmpMaxBlockNumPerBatch = 0; + uint32_t splitKVNum = 0U; // S2核间切分的切分份数 + SMLA_LAYOUT outputLayout; // 输出的Transpose格式 + uint32_t oriMaskMode = 0; + uint32_t cmpMaskMode = 0; + uint64_t oriKvStride0 = 0; + uint64_t cmpKvStride0 = 0; + bool needInit = false; + uint32_t templateMode = 0; + + // FlashDecoding + uint32_t actualCombineLoopSize = + 0U; // FlashDecoding场景, S2在核间切分的最大份数 + uint64_t combineLseOffset = 0ULL; + uint64_t combineAccumOutOffset = 0ULL; + + uint32_t actualLenDimsQ = 0U; // query的actualSeqLength 的维度 + uint32_t actualLenDimsKV = 0U; // KV 的actualSeqLength 的维度 + + uint32_t actualLenDimsCmpKV = 0U; + uint32_t cmpResidualKVSize = 0U; + + // TND + uint32_t s2Start = 0U; // TND场景下,S2的起始位置 + uint32_t s2End = 0U; // 单核TND场景下S2循环index上限 + + uint32_t bN2Start = 0U; + uint32_t bN2End = 0U; + uint32_t gS1Start = 0U; + uint32_t gS1End = 0U; + + uint32_t tndFDCoreArrLen = 0U; // TNDFlashDecoding相关分核信息array的长度 + uint32_t coreStartKVSplitPos = 0U; // TNDFlashDecoding kv起始位置 + + uint32_t mBaseSize = 1ULL; + uint32_t s2BaseSize = 1ULL; + + // sparse attr + int64_t sparseBlockSize = 0; + uint32_t sparseBlockCount = 0; + bool hasOriSparseIndices = false; + bool hasOriTopkLength = false; + uint32_t oriSparseIndexWidth = 0; + + // cmp attr + int64_t cmpRatio = 0; + + uint64_t cmpSeqSize = 0ULL; + + // win + int32_t oriWinRight = 0; + int32_t oriWinLeft = 128; + + bool returnSoftmaxLse = false; +}; + +struct MSplitInfo { + uint32_t nBufferIdx = 0U; + uint32_t nBufferStartM = 0U; + uint32_t nBufferDealM = 0U; + uint32_t vecStartM = 0U; + uint32_t vecDealM = 0U; +}; +} // namespace SMLAKernel +#endif // SPARSE_FLASH_MLA_COMMON_ARCH22_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_block_cube.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_block_cube.h new file mode 100644 index 0000000000..d379cba1d5 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_block_cube.h @@ -0,0 +1,1013 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file sparse_flash_mla_csa_block_cube.h + * \brief use 7 buffer for matmul l1, better pipeline + */ +#ifndef SPARSE_FLASH_MLA_CSA_BLOCK_CUBE_H +#define SPARSE_FLASH_MLA_CSA_BLOCK_CUBE_H + +#include "kernel_operator.h" +#include "kernel_operator_list_tensor_intf.h" +#include "kernel_tiling/kernel_tiling.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" +#include "sparse_flash_mla_common_arch22.h" + +namespace SMLAKernel { +template +class SMLACubeBlock { + public: + // 中间计算数据类型为float, 高精度模式 + using T = float; + using Q_T = typename SMLAT::queryType; + using KV_T = typename SMLAT::kvType; + using OUT_T = typename SMLAT::outputType; + using MM_OUT_T = T; + + __aicore__ inline SMLACubeBlock(){}; + __aicore__ inline void InitParams(const ConstInfo& constInfo); + __aicore__ inline void InitMm1GlobalTensor(GlobalTensor queryGm, + GlobalTensor oriKvGm, + GlobalTensor cmpKV, + GlobalTensor mm1ResGm); + __aicore__ inline void InitMm2GlobalTensor( + GlobalTensor vec1ResGm, + GlobalTensor mm2ResGm, + GlobalTensor attentionOutGm); + __aicore__ inline void InitPageAttentionInfo( + GlobalTensor oriKvGm, + const GlobalTensor& kvMergeGm, + GlobalTensor oriBlockTableGm, + GlobalTensor cmpBlockTableGm); + __aicore__ inline void InitBuffers(TPipe* pipe); + + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + __aicore__ inline void ComputeMm1(const RunInfo& info, + const MSplitInfo mSplitInfo); + __aicore__ inline void ComputeMm2(const RunInfo& info, + const MSplitInfo mSplitInfo); + + private: + static constexpr bool PAGE_ATTENTION = SMLAT::pageAttention; + static constexpr int TEMPLATE_MODE = SMLAT::templateMode; + static constexpr bool FLASH_DECODE = SMLAT::flashDecode; + static constexpr SMLA_LAYOUT LAYOUT_T = SMLAT::layout; + static constexpr SMLA_LAYOUT KV_LAYOUT_T = SMLAT::kvLayout; + + static constexpr uint32_t MERGE_CACHE_GM_BUF_NUM = 3; + static constexpr uint32_t M_SPLIT_SIZE = 128; // m方向切分 + static constexpr uint32_t N_SPLIT_SIZE = 128; // n方向切分 + static constexpr uint32_t K_L0_SPLIT_SIZE = 128; // k方向L0切分 + static constexpr uint32_t K_L1_SPLIT_SIZE = 256; // k方向L1切分 + static constexpr uint32_t N_WORKSPACE_SIZE = 512; // n方向切分 + static constexpr uint32_t D_SPLIT_SIZE = 256; // d轴切分 + + static constexpr uint32_t L1_BLOCK_SIZE = (64 * 512 * sizeof(Q_T)); + static constexpr uint32_t L1_BLOCK_OFFSET = 64 * 512; + + static constexpr uint32_t L0A_PP_SIZE = (32 * 1024); + static constexpr uint32_t L0B_PP_SIZE = (32 * 1024); + static constexpr uint32_t L0C_PP_SIZE = (64 * 1024); + + // mte2 <> mte1 EventID + // L1 3buf, 使用3个eventId + static constexpr uint32_t L1_EVENT0 = EVENT_ID2; + static constexpr uint32_t L1_EVENT1 = EVENT_ID3; + static constexpr uint32_t L1_EVENT2 = EVENT_ID4; + static constexpr uint32_t L1_EVENT3 = EVENT_ID5; + static constexpr uint32_t L1_EVENT4 = EVENT_ID6; + static constexpr uint32_t L1_EVENT5 = EVENT_ID7; + static constexpr uint32_t L1_EVENT6 = EVENT_ID1; + + // m <> mte1 EventID + static constexpr uint32_t L0AB_EVENT0 = EVENT_ID3; + static constexpr uint32_t L0AB_EVENT1 = EVENT_ID4; + + static constexpr IsResetLoad3dConfig LOAD3DV2_CONFIG = { + true, + true}; // isSetFMatrix isSetPadding + static constexpr uint32_t mte21QPIds[4] = {L1_EVENT0, + L1_EVENT1, + L1_EVENT2, + L1_EVENT3}; // mte12复用 + static constexpr uint32_t mte21KVIds[3] = {L1_EVENT4, L1_EVENT5, L1_EVENT6}; + + ConstInfo constInfo{}; + + // L1分成3块buf, 用于记录 + uint32_t qpL1BufIter = 0; + uint32_t kvL1BufIter = -1; + uint32_t abL0BufIter = 0; + uint32_t cL0BufIter = 0; + + // mm1 + GlobalTensor queryGm; + GlobalTensor keyGm; + GlobalTensor mm1ResGm; + GlobalTensor oriKvGm; + GlobalTensor kvMergeGm_; + GlobalTensor cmpKvGm; + + // mm2 + GlobalTensor vec1ResGm; + GlobalTensor valueGm; + GlobalTensor mm2ResGm; + GlobalTensor attentionOutGm; + + // block_table + GlobalTensor oriBlockTableGm; + GlobalTensor cmpBlockTableGm; + + TBuf bufQPL1; + TBuf bufKVL1; + TBuf tmpBufL0A; + TBuf tmpBufL0B; + TBuf tmpBufL0C; + + LocalTensor l1QPTensor; + LocalTensor l1KVTensor; + LocalTensor aL0TensorPingPong; + LocalTensor bL0TensorPingPong; + LocalTensor cL0TensorPingPong; + + // L0AB m <> mte1 EventID + __aicore__ inline uint32_t Mte1MmABEventId(uint32_t idx) { + return (L0AB_EVENT0 + idx); + } + + __aicore__ inline uint32_t GetQPL1RealIdx(uint32_t mIdx, uint32_t k1Idx) { + uint32_t idxMap[] = { + 0, 2}; // 确保0块和1块连在一起, 2和3块连在一起, 来保证同一m块的地址相连 + return idxMap[mIdx % 2] + k1Idx; + } + + __aicore__ inline void CopyGmToL1(LocalTensor& l1Tensor, + GlobalTensor& gmSrcTensor, + uint32_t srcN, + uint32_t srcD, + uint32_t srcDstride); + __aicore__ inline void CopyInMm1AToL1(LocalTensor& aL1Tensor, + const RunInfo& info, + uint32_t mSeqIdx, + uint32_t mSizeAct, + uint32_t headSize, + uint32_t headOffset); + + __aicore__ inline void CopyInMm2AToL1(LocalTensor& aL1Tensor, + const RunInfo& info, + uint32_t mSeqIdx, + uint32_t subMSizeAct, + uint32_t nSize, + uint32_t nOffset); + __aicore__ inline void LoadDataMm1A(LocalTensor& aL0Tensor, + LocalTensor& aL1Tensor, + uint32_t idx, + uint32_t kSplitSize, + uint32_t mSize, + uint32_t kSize); + __aicore__ inline void LoadDataMm1B(LocalTensor& bL0Tensor, + LocalTensor& bL1Tensor, + uint32_t idx, + uint32_t kSplitSize, + uint32_t kSize, + uint32_t nSize); +}; + +template +__aicore__ inline void SMLACubeBlock::InitParams( + const ConstInfo& constInfo) { + this->constInfo = constInfo; +} + +template +__aicore__ inline void SMLACubeBlock::InitMm1GlobalTensor( + GlobalTensor queryGm, + GlobalTensor oriKvGm, + GlobalTensor cmpKvGm, + GlobalTensor mm1ResGm) { + // mm1 + this->queryGm = queryGm; + this->oriKvGm = oriKvGm; + this->cmpKvGm = cmpKvGm; + this->mm1ResGm = mm1ResGm; +} + +template +__aicore__ inline void SMLACubeBlock::InitMm2GlobalTensor( + GlobalTensor vec1ResGm, + GlobalTensor mm2ResGm, + GlobalTensor attentionOutGm) { + // mm2 + this->vec1ResGm = vec1ResGm; + this->mm2ResGm = mm2ResGm; + this->attentionOutGm = attentionOutGm; +} + +template +__aicore__ inline void SMLACubeBlock::InitPageAttentionInfo( + GlobalTensor oriKvGm, + const GlobalTensor& kvMergeGm, + GlobalTensor oriBlockTableGm, + GlobalTensor cmpBlockTableGm) { + this->oriKvGm = oriKvGm; + this->kvMergeGm_ = kvMergeGm; + this->oriBlockTableGm = oriBlockTableGm; + this->cmpBlockTableGm = cmpBlockTableGm; +} + +template +__aicore__ inline void SMLACubeBlock::InitBuffers(TPipe* pipe) { + pipe->InitBuffer(bufQPL1, L1_BLOCK_SIZE * 4); + l1QPTensor = bufQPL1.Get(); + pipe->InitBuffer(bufKVL1, L1_BLOCK_SIZE * 3); + l1KVTensor = bufKVL1.Get(); + + // L0A + pipe->InitBuffer(tmpBufL0A, L0A_PP_SIZE * 2); // 64K + aL0TensorPingPong = tmpBufL0A.Get(); + // L0B + pipe->InitBuffer(tmpBufL0B, L0B_PP_SIZE * 2); // 64K + bL0TensorPingPong = tmpBufL0B.Get(); + // L0C + pipe->InitBuffer(tmpBufL0C, L0C_PP_SIZE * 2); // 128K + cL0TensorPingPong = tmpBufL0C.Get(); +} + +template +__aicore__ inline void SMLACubeBlock::AllocEventID() { + SetFlag(L1_EVENT0); + SetFlag(L1_EVENT1); + SetFlag(L1_EVENT2); + SetFlag(L1_EVENT3); + SetFlag(L1_EVENT4); + SetFlag(L1_EVENT5); + SetFlag(L1_EVENT6); + SetFlag(L0AB_EVENT0); + SetFlag(L0AB_EVENT1); +} + +template +__aicore__ inline void SMLACubeBlock::FreeEventID() { + WaitFlag(L1_EVENT0); + WaitFlag(L1_EVENT1); + WaitFlag(L1_EVENT2); + WaitFlag(L1_EVENT3); + WaitFlag(L1_EVENT4); + WaitFlag(L1_EVENT5); + WaitFlag(L1_EVENT6); + WaitFlag(L0AB_EVENT0); + WaitFlag(L0AB_EVENT1); +} + +template +__aicore__ inline void SMLACubeBlock::CopyGmToL1( + LocalTensor& l1Tensor, + GlobalTensor& gmSrcTensor, + uint32_t srcN, + uint32_t srcD, + uint32_t srcDstride) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = srcN; // 行数 + nd2nzPara.dValue = srcD; + nd2nzPara.srcDValue = srcDstride; + nd2nzPara.dstNzC0Stride = (srcN + 15) / 16 * 16; // 对齐到16 单位block + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(l1Tensor, gmSrcTensor, nd2nzPara); +} + +template +__aicore__ inline void SMLACubeBlock::CopyInMm1AToL1( + LocalTensor& l1Tensor, + const RunInfo& info, + uint32_t mSeqIdx, + uint32_t mSizeAct, + uint32_t headSize, + uint32_t headOffset) { + auto srcGm = + queryGm[info.tensorAOffset + mSeqIdx * constInfo.headDim + headOffset]; + CopyGmToL1(l1Tensor, srcGm, mSizeAct, headSize, constInfo.headDim); +} + +template +__aicore__ inline void SMLACubeBlock::LoadDataMm1A( + LocalTensor& aL0Tensor, + LocalTensor& aL1Tensor, + uint32_t idx, + uint32_t kSplitSize, + uint32_t mSize, + uint32_t kSize) { + LocalTensor srcTensor = aL1Tensor[mSize * kSplitSize * idx]; + LoadData3DParamsV2 loadData3DParams; + // SetFmatrixParams + loadData3DParams.l1H = mSize / 16; // Hin=M1=8 + loadData3DParams.l1W = 16; // Win=M0 + loadData3DParams.padList[0] = 0; + loadData3DParams.padList[1] = 0; + loadData3DParams.padList[2] = 0; + loadData3DParams.padList[3] = 255; // 尾部数据不影响滑窗的结果 + + // SetLoadToA0Params + loadData3DParams.mExtension = mSize; // M + loadData3DParams.kExtension = kSize; // K + loadData3DParams.mStartPt = 0; + loadData3DParams.kStartPt = 0; + loadData3DParams.strideW = 1; + loadData3DParams.strideH = 1; + loadData3DParams.filterW = 1; + loadData3DParams.filterSizeW = (1 >> 8) & 255; + loadData3DParams.filterH = 1; + loadData3DParams.filterSizeH = (1 >> 8) & 255; + loadData3DParams.dilationFilterW = 1; + loadData3DParams.dilationFilterH = 1; + loadData3DParams.enTranspose = 0; + loadData3DParams.fMatrixCtrl = 0; + loadData3DParams.channelSize = kSize; // Cin=K + LoadData(aL0Tensor, srcTensor, loadData3DParams); +} + +template +__aicore__ inline void SMLACubeBlock::LoadDataMm1B( + LocalTensor& l0Tensor, + LocalTensor& l1Tensor, + uint32_t idx, + uint32_t kSplitSize, + uint32_t kSize, + uint32_t nSize) { + // N 方向全载 + LocalTensor srcTensor = l1Tensor[nSize * kSplitSize * idx]; + + LoadData2DParams loadData2DParams; + loadData2DParams.startIndex = 0; + loadData2DParams.repeatTimes = + (nSize + 15) / 16 * kSize / (32 / sizeof(KV_T)); + loadData2DParams.srcStride = 1; + loadData2DParams.dstGap = 0; + loadData2DParams.ifTranspose = false; + LoadData(l0Tensor, srcTensor, loadData2DParams); +} + +template +__aicore__ inline void SMLACubeBlock::CopyInMm2AToL1( + LocalTensor& aL1Tensor, + const RunInfo& info, + uint32_t mSeqIdx, + uint32_t subMSizeAct, + uint32_t nSize, + uint32_t nOffset) { + auto srcGm = + vec1ResGm[(info.loop % constInfo.preLoadNum) * constInfo.mmResUbSize + + mSeqIdx * info.actualSingleProcessSInnerSizeAlign + nOffset]; + CopyGmToL1(aL1Tensor, + srcGm, + subMSizeAct, + nSize, + info.actualSingleProcessSInnerSizeAlign); +} + +template +__aicore__ inline void SMLACubeBlock::ComputeMm1( + const RunInfo& info, + const MSplitInfo mSplitInfo) { + uint32_t mSize = mSplitInfo.nBufferDealM; + uint32_t mL1Size = M_SPLIT_SIZE; + uint32_t mL1SizeAlign = SMLAAlign(M_SPLIT_SIZE, 16); + uint32_t mL1Loops = CeilDiv(mSize, M_SPLIT_SIZE); + + uint32_t nSize = info.actualSingleProcessSInnerSize; + uint32_t nL1Size = N_SPLIT_SIZE; + uint32_t nL1SizeAlign = SMLAAlign(N_SPLIT_SIZE, 16); + uint32_t nL1Loops = CeilDiv(nSize, N_SPLIT_SIZE); + + uint32_t kSize = 512; + uint32_t kL1Size = 256; + uint32_t kL1Loops = 2; + uint32_t kL0Size = 128; + uint32_t kL0Loops = CeilDiv(kL1Size, kL0Size); + + LocalTensor bL1Tensor; + uint32_t ka = 0, kb = 0; + + // L1 切n切k + for (uint32_t nL1 = 0; nL1 < nL1Loops; nL1++) { + if (nL1 == (nL1Loops - 1)) { + // 尾块重新计算size + nL1Size = nSize - (nL1Loops - 1) * N_SPLIT_SIZE; + nL1SizeAlign = SMLAAlign(nL1Size, 16); + } + + for (uint32_t kL1 = 0; kL1 < kL1Loops; kL1++) { + kvL1BufIter++; + uint32_t kb = kvL1BufIter % 3; + WaitFlag(mte21KVIds[kb]); + // 从k当中取当前的块 + bL1Tensor = l1KVTensor[kb * L1_BLOCK_OFFSET]; + uint32_t curSeqIdx = info.s2BatchOffset + nL1 * N_SPLIT_SIZE; + if (info.isOriOnly) { + if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { + uint32_t curS2Offset = + info.s2Idx * constInfo.s2BaseSize + info.s2StartPoint; + uint32_t copyFinishRowCnt = 0; + LocalTensor kTensor; + uint32_t copyRowCnt = 0; + + while (copyFinishRowCnt < nL1Size) { + // 由于ori_left的存在, 即使第一块搬运也可能并非是pa_block的零点位 + copyRowCnt = constInfo.paOriBlockSize - + curS2Offset % constInfo.paOriBlockSize; + if (copyFinishRowCnt + copyRowCnt > nL1Size) { + copyRowCnt = nL1Size - copyFinishRowCnt; + } + PAShape shape; + shape.blockSize = constInfo.paOriBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.kvStride = constInfo.oriKvStride0; + shape.actHeadDim = D_SPLIT_SIZE; + shape.maxblockNumPerBatch = constInfo.oriMaxBlockNumPerBatch; + shape.copyRowNum = copyRowCnt; + shape.copyRowNumAlign = nL1SizeAlign; + kTensor = bL1Tensor[copyFinishRowCnt * 16]; + + Position startPos; + startPos.bIdx = info.bIdx; + startPos.n2Idx = info.n2Idx; + startPos.s2Idx = curS2Offset; + startPos.dIdx = + kL1 * D_SPLIT_SIZE; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 + // 右矩阵, s2为k轴, d轴切分 + DataCopyPA( + kTensor, oriKvGm, oriBlockTableGm, shape, startPos); + + // 更新循环变量 + copyFinishRowCnt += copyRowCnt; + curS2Offset += copyRowCnt; + } + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nL1Size; // 行数 + nd2nzPara.dValue = D_SPLIT_SIZE; // 256 + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = nL1SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + + uint32_t headStride = constInfo.headDim; + uint32_t seqStride = constInfo.kvHeadNum * constInfo.headDim; + uint64_t batchStride = + (constInfo.oriKvStride0 == 0) + ? static_cast(constInfo.kvSeqSize) * seqStride + : constInfo.oriKvStride0; + + uint32_t curS2 = + info.s2Idx * constInfo.s2BaseSize + info.s2StartPoint; + uint64_t offset = + (uint64_t)info.bIdx * batchStride + (uint64_t)curS2 * seqStride + + (uint64_t)info.n2Idx * headStride + kL1 * D_SPLIT_SIZE; + DataCopy(bL1Tensor, oriKvGm[offset], nd2nzPara); + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { + uint32_t curS2Offset = + info.s2Idx * constInfo.s2BaseSize + info.s2StartPoint; + if (kL1 == 0) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nL1Size; + nd2nzPara.dValue = constInfo.headDim >> 1; + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = nL1SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy( + bL1Tensor, + oriKvGm[info.tensorBOffset + curS2Offset * constInfo.headDim + + nL1 * N_SPLIT_SIZE * constInfo.headDim], + nd2nzPara); + } else { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nL1Size; + nd2nzPara.dValue = constInfo.headDim >> 1; + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = nL1SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy( + bL1Tensor, + oriKvGm[info.tensorBOffset + curS2Offset * constInfo.headDim + + (constInfo.headDim >> 1) + + nL1 * N_SPLIT_SIZE * constInfo.headDim], + nd2nzPara); + } + } + } else { + if (kL1 == 0) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nL1Size; + nd2nzPara.dValue = constInfo.headDim >> 1; + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = nL1SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(bL1Tensor, + kvMergeGm_[info.cmpLoop % MERGE_CACHE_GM_BUF_NUM * + N_WORKSPACE_SIZE * kSize + + nL1 * N_SPLIT_SIZE * constInfo.headDim], + nd2nzPara); + } else { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nL1Size; + nd2nzPara.dValue = constInfo.headDim >> 1; + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = nL1SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(bL1Tensor, + kvMergeGm_[info.cmpLoop % MERGE_CACHE_GM_BUF_NUM * + N_WORKSPACE_SIZE * kSize + + (constInfo.headDim >> 1) + + nL1 * N_SPLIT_SIZE * constInfo.headDim], + nd2nzPara); + } + } + SetFlag(mte21KVIds[kb]); + WaitFlag(mte21KVIds[kb]); + mL1Size = M_SPLIT_SIZE; + mL1SizeAlign = SMLAAlign(M_SPLIT_SIZE, 16U); + for (uint32_t mL1 = 0; mL1 < mL1Loops; mL1++) { + uint32_t aL1PaddingSize = + 0; // 用于使左矩阵对齐到尾部, 以保证两块32K内存连续 + if (mL1 == (mL1Loops - 1)) { + mL1Size = mSize - (mL1Loops - 1) * M_SPLIT_SIZE; + mL1SizeAlign = SMLAAlign(mL1Size, 16U); + aL1PaddingSize = (M_SPLIT_SIZE - mL1SizeAlign) * 256; + } + uint32_t mIdx = qpL1BufIter + mL1; + ka = GetQPL1RealIdx(mIdx, kL1); + LocalTensor aL1Tensor = + l1QPTensor[ka * L1_BLOCK_OFFSET + (1 - kL1) * aL1PaddingSize]; + if (nL1 == 0) { + if (kL1 == 0) { + WaitFlag(mte21QPIds[ka]); + WaitFlag(mte21QPIds[ka + 1]); + CopyInMm1AToL1(aL1Tensor, + info, + mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, + mL1Size, + 256, + 0); + } else { + LocalTensor qTmpTensor = aL1Tensor; + CopyInMm1AToL1(qTmpTensor, + info, + mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, + mL1Size, + 256, + 256); + } + SetFlag(mte21QPIds[ka]); + WaitFlag(mte21QPIds[ka]); + } + // 使用unitflag同步 + LocalTensor cL0Tensor = cL0TensorPingPong + [(cL0BufIter % 2) * + (L0C_PP_SIZE / + sizeof(MM_OUT_T))]; // 需要保证cL0BufIter和m步调一致 + for (uint32_t kL0 = 0; kL0 < kL0Loops; kL0++) { + WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); + LocalTensor aL0Tensor = + aL0TensorPingPong[(abL0BufIter % 2) * + (L0A_PP_SIZE / sizeof(KV_T))]; + LoadDataMm1A( + aL0Tensor, aL1Tensor, kL0, kL0Size, mL1SizeAlign, kL0Size); + LocalTensor bL0Tensor = + bL0TensorPingPong[(abL0BufIter % 2) * + (L0B_PP_SIZE / sizeof(KV_T))]; + LoadDataMm1B( + bL0Tensor, bL1Tensor, kL0, kL0Size, kL0Size, nL1SizeAlign); + SetFlag(Mte1MmABEventId(abL0BufIter % 2)); + WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); + + MmadParams mmadParams; + mmadParams.m = mL1SizeAlign; + mmadParams.n = nL1SizeAlign; + mmadParams.k = kL0Size; + mmadParams.cmatrixInitVal = (kL1 == 0 && kL0 == 0); + mmadParams.cmatrixSource = false; + mmadParams.unitFlag = + (kL1 == 1 && kL0 == (kL0Loops - 1)) + ? 0b11 + : 0b10; // 累加最后一次翻转flag, 表示可以搬出 + Mmad(cL0Tensor, aL0Tensor, bL0Tensor, mmadParams); + if ((mmadParams.m / 16) * (mmadParams.n / 16) < 10) { + PipeBarrier(); + } + SetFlag(Mte1MmABEventId(abL0BufIter % 2)); + abL0BufIter++; + } + + if (nL1 == (nL1Loops - 1)) { + SetFlag( + mte21QPIds[ka]); // 反向同步, 表示L1中的A已经被mte1消费完 + } + + if (kL1 == 1) { // 最后一轮kL1循环 + FixpipeParamsV220 fixParams; + fixParams.nSize = nL1SizeAlign; + fixParams.mSize = mL1SizeAlign; + fixParams.srcStride = mL1SizeAlign; + // 改成nSizeAlign + fixParams.dstStride = + info.actualSingleProcessSInnerSizeAlign; // mm1ResGm两行之间的间隔 + fixParams.unitFlag = 0b11; + fixParams.ndNum = 1; // 输出ND + + Fixpipe(mm1ResGm[(info.loop % (constInfo.preLoadNum)) * + constInfo.mmResUbSize + + nL1 * N_SPLIT_SIZE + + (mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE) * + info.actualSingleProcessSInnerSizeAlign], + cL0Tensor, + fixParams); + } + if (mL1Loops == 2) { + cL0BufIter++; + } + } + + SetFlag( + mte21KVIds[kb]); // 反向同步, 表示L1已经被mte1消费完 + } + if (mL1Loops == 1) { + cL0BufIter++; + } + } + qpL1BufIter += mL1Loops; +} + +template +__aicore__ inline void SMLACubeBlock::ComputeMm2( + const RunInfo& info, + const MSplitInfo mSplitInfo) { + uint32_t mSize = mSplitInfo.nBufferDealM; + uint32_t mSizeAlign = (mSize + 16 - 1) / 16; + uint32_t mL1Loops = (mSize + M_SPLIT_SIZE - 1) / M_SPLIT_SIZE; + uint32_t mL1SizeAlign = M_SPLIT_SIZE; // 16对齐 + uint32_t mL1Size = M_SPLIT_SIZE; // m的实际大小 + + uint32_t nSize = BlockAlign(constInfo.headDim); + uint32_t nL1Loops = (nSize + N_SPLIT_SIZE - 1) / N_SPLIT_SIZE; + uint32_t nL1SizeAlign = N_SPLIT_SIZE; // 16对齐 + uint32_t nL1Size = N_SPLIT_SIZE; // n的实际大小 + + uint32_t kSize = info.actualSingleProcessSInnerSize; + uint32_t kL1Size = 256; + uint32_t kL1SizeAlign = SMLAAlign(kL1Size, 16U); + uint32_t kL1Loops = (kSize + kL1Size - 1) / kL1Size; + uint32_t kL0Size = 128; + uint32_t kL0Loops = (kL1Size + kL0Size - 1) / kL0Size; + uint32_t kL0SizeAlign = kL0Size; + LocalTensor bL1Tensor; + LocalTensor subvTensor; + + // ka表示左矩阵4buf选择哪一块buf, kb表示右矩阵3buf选择哪一块buf + uint32_t ka = 0, kb = 0; + uint32_t mBaseIdx = qpL1BufIter; + for (uint32_t nL1 = 0; nL1 < nL1Loops; nL1++) { // n切L1 -> D + if (nL1 == (nL1Loops - 1)) { + // 尾块 + nL1Size = nSize - (nL1Loops - 1) * N_SPLIT_SIZE; + nL1SizeAlign = SMLAAlign(nL1Size, 16U); + } + // k l1写成一个循环, 和mm1保持一致 + kL1Size = 256; + kL1SizeAlign = SMLAAlign(kL1Size, 16U); + uint32_t copyRowCnt = 0; + + for (uint32_t k1 = 0; k1 < kL1Loops; + k1++) { // k切L1, 这里套了一层l0来操作 -> S2,每次256 + if (k1 == (kL1Loops - 1)) { + // 尾块 + kL1Size = kSize - (kL1Loops - 1) * 256; + kL1SizeAlign = SMLAAlign(kL1Size, 16U); + } + kvL1BufIter++; + uint32_t kb = kvL1BufIter % 3; + WaitFlag(mte21KVIds[kb]); + bL1Tensor = l1KVTensor[kb * L1_BLOCK_OFFSET]; + uint32_t kOffset = k1 * kL0Loops; + kL0Size = 128; + // 此处必须先初始化kL0Size, 再求kL0Loops, 否则由于循环会改变kL0Size大小, + // 导致kL0Loops错误 + kL0Loops = (kL1Size + kL0Size - 1) / kL0Size; + kL0SizeAlign = kL0Size; + for (uint32_t kL1 = kOffset; kL1 < kL0Loops + kOffset; + kL1++) { // 128 循环搬pa,每次128 + if (kL1 == kOffset + kL0Loops - 1) { + // 尾块 + kL0Size = kL1Size - (kL0Loops - 1) * kL0Size; + kL0SizeAlign = SMLAAlign(kL0Size, 16U); + } + + uint32_t curSeqIdx = + info.s2BatchOffset + (kL1 - kOffset) * 128 + k1 * 256; + if (info.isOriOnly) { + if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { + uint32_t copyFinishRowCnt = 0; + uint32_t curS2Offset = + info.s2Idx * constInfo.s2BaseSize + info.s2StartPoint; + while (copyFinishRowCnt < kL0Size) { + copyRowCnt = constInfo.paOriBlockSize - + curS2Offset % constInfo.paOriBlockSize; + if (copyFinishRowCnt + copyRowCnt > kL0Size) { + copyRowCnt = kL0Size - copyFinishRowCnt; + } + Position startPos; + startPos.bIdx = info.bIdx; + startPos.n2Idx = info.n2Idx; + startPos.s2Idx = curS2Offset; + startPos.dIdx = + nL1 * N_SPLIT_SIZE; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 + // 右矩阵, s2为k轴, d轴切分 + PAShape shape; + shape.blockSize = constInfo.paOriBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.kvStride = constInfo.oriKvStride0; + shape.actHeadDim = nL1Size; + shape.maxblockNumPerBatch = constInfo.oriMaxBlockNumPerBatch; + shape.copyRowNum = copyRowCnt; + shape.copyRowNumAlign = kL0SizeAlign; + subvTensor = bL1Tensor[(kL1 - kOffset) * 128 * N_SPLIT_SIZE + + copyFinishRowCnt * 16]; + + DataCopyPA( + subvTensor, oriKvGm, oriBlockTableGm, shape, startPos); + + // 更新循环变量 + copyFinishRowCnt += copyRowCnt; + curS2Offset += copyRowCnt; + } + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = kL0Size; // 行数 + nd2nzPara.dValue = N_SPLIT_SIZE; // constInfo.headDim; + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = kL0SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + + uint32_t headStride = constInfo.headDim; + uint32_t seqStride = constInfo.kvHeadNum * constInfo.headDim; + uint64_t batchStride = + (constInfo.oriKvStride0 == 0) + ? static_cast(constInfo.kvSeqSize) * seqStride + : constInfo.oriKvStride0; + + uint32_t curS2 = + info.s2Idx * constInfo.s2BaseSize + info.s2StartPoint; + uint64_t offset = (uint64_t)info.bIdx * batchStride + + (uint64_t)curS2 * seqStride + + (uint64_t)info.n2Idx * headStride + + nL1 * N_SPLIT_SIZE; + subvTensor = bL1Tensor[(kL1 - kOffset) * 128 * N_SPLIT_SIZE]; + DataCopy(subvTensor, oriKvGm[offset], nd2nzPara); + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { + uint32_t curS2Offset = + info.s2Idx * constInfo.s2BaseSize + info.s2StartPoint; + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = kL0Size; // 行数 + nd2nzPara.dValue = N_SPLIT_SIZE; // constInfo.headDim; + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = kL0SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy( + bL1Tensor[(kL1 - kOffset) * 128 * N_SPLIT_SIZE], + oriKvGm[info.tensorBOffset + curS2Offset * constInfo.headDim + + kL1 * 128 * constInfo.headDim + nL1 * N_SPLIT_SIZE], + nd2nzPara); + } + } else { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = kL0Size; // 行数 + nd2nzPara.dValue = N_SPLIT_SIZE; // constInfo.headDim; + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = kL0SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy( + bL1Tensor[(kL1 - kOffset) * 128 * N_SPLIT_SIZE], + kvMergeGm_[info.cmpLoop % MERGE_CACHE_GM_BUF_NUM * + N_WORKSPACE_SIZE * 512 + + kL1 * 128 * constInfo.headDim + nL1 * N_SPLIT_SIZE], + nd2nzPara); + } + } + SetFlag(mte21KVIds[kb]); + WaitFlag(mte21KVIds[kb]); + mL1SizeAlign = M_SPLIT_SIZE; + mL1Size = M_SPLIT_SIZE; // m的实际大小 + for (uint32_t mL1 = 0; mL1 < mL1Loops; mL1++) { + if (mL1 == (mL1Loops - 1)) { + // 尾块 + mL1Size = mSize - (mL1Loops - 1) * M_SPLIT_SIZE; + mL1SizeAlign = SMLAAlign(mL1Size, 16U); + } + + uint32_t mIdx = mBaseIdx + mL1; + ka = GetQPL1RealIdx(mIdx, k1); + LocalTensor aL1Tensor = l1QPTensor[ka * L1_BLOCK_OFFSET]; + if (nL1 == 0) { + WaitFlag(mte21QPIds[ka]); + CopyInMm2AToL1(aL1Tensor, + info, + mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, + mL1Size, + kL1Size, + 256 * k1); + SetFlag(mte21QPIds[ka]); + WaitFlag(mte21QPIds[ka]); + } + + LocalTensor cL0Tensor = cL0TensorPingPong + [(cL0BufIter % 2) * + (L0C_PP_SIZE / + sizeof(MM_OUT_T))]; // 需要保证cL0BufIter和m步调一致 + uint32_t baseK = 128; + uint32_t baseN = 128; + kL0Size = 128; + kL0SizeAlign = kL0Size; + for (uint32_t kL0 = 0; kL0 < kL0Loops; kL0++) { + if (kL0 + 1 == kL0Loops) { + kL0Size = kL1Size - (kL0Loops - 1) * kL0Size; + kL0SizeAlign = SMLAAlign(kL0Size, 16U); + } + WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); + LocalTensor bL0Tensor = + bL0TensorPingPong[(abL0BufIter % 2) * + (L0B_PP_SIZE / sizeof(KV_T))]; + LoadData3DParamsV2 loadData3DParamsForB; + loadData3DParamsForB.l1H = kL0SizeAlign / 16; // 源操作数height + loadData3DParamsForB.l1W = + 16; // 源操作数weight=16,目的height=l1H*L1W + loadData3DParamsForB.padList[0] = 0; + loadData3DParamsForB.padList[1] = 0; + loadData3DParamsForB.padList[2] = 0; + loadData3DParamsForB.padList[3] = 255; // 尾部数据不影响滑窗的结果 + + loadData3DParamsForB.mExtension = + kL0SizeAlign; // 在目的操作数height维度的传输长度 + loadData3DParamsForB.kExtension = + nL1SizeAlign; // 在目的操作数width维度的传输长度 + loadData3DParamsForB.mStartPt = + 0; // 卷积核在目的操作数width维度的起点 + loadData3DParamsForB.kStartPt = + 0; // 卷积核在目的操作数height维度的起点 + loadData3DParamsForB.strideW = 1; + loadData3DParamsForB.strideH = 1; + loadData3DParamsForB.filterW = 1; + loadData3DParamsForB.filterSizeW = + false; // 是否在filterW的基础上将卷积核width增加256个元素 + loadData3DParamsForB.filterH = 1; + loadData3DParamsForB.filterSizeH = + false; // 是否在filterH的基础上将卷积核height增加256个元素 + loadData3DParamsForB.dilationFilterW = 1; // 卷积核width膨胀系数 + loadData3DParamsForB.dilationFilterH = 1; // 卷积核height膨胀系数 + loadData3DParamsForB.enTranspose = 1; // 是否启用转置功能 + loadData3DParamsForB.fMatrixCtrl = + 0; // 使用FMATRIX_LEFT还是使用FMATRIX_RIGHT,=0使用FMATRIX_LEFT,=1使用FMATRIX_RIGHT + // 1 + loadData3DParamsForB.channelSize = + nL1SizeAlign; // 源操作数的通道数。膨胀系数为1时,目的weight为filterW*filterH*channelSize + LoadData( + bL0Tensor, bL1Tensor[kL0 * baseK * baseN], loadData3DParamsForB); + + LocalTensor aL0Tensor = + aL0TensorPingPong[(abL0BufIter % 2) * + (L0A_PP_SIZE / sizeof(KV_T))]; + LoadData3DParamsV2 loadData3DParamsForA; + loadData3DParamsForA.l1H = mL1SizeAlign / 16; // 源操作数height + loadData3DParamsForA.l1W = 16; // 源操作数weight + loadData3DParamsForA.padList[0] = 0; + loadData3DParamsForA.padList[1] = 0; + loadData3DParamsForA.padList[2] = 0; + loadData3DParamsForA.padList[3] = 255; // 尾部数据不影响滑窗的结果 + + loadData3DParamsForA.mExtension = + mL1SizeAlign; // 在目的操作数height维度的传输长度 + loadData3DParamsForA.kExtension = + kL0SizeAlign; // 在目的操作数width维度的传输长度 + loadData3DParamsForA.mStartPt = + 0; // 卷积核在目的操作数width维度的起点 + loadData3DParamsForA.kStartPt = + 0; // 卷积核在目的操作数height维度的起点 + loadData3DParamsForA.strideW = + 1; // 卷积核在源操作数width维度滑动的步长 + loadData3DParamsForA.strideH = + 1; // 卷积核在源操作数height维度滑动的步长 + loadData3DParamsForA.filterW = 1; // 卷积核width + loadData3DParamsForA.filterSizeW = + false; // 是否在filterW的基础上将卷积核width增加256个元素 + loadData3DParamsForA.filterH = 1; // 卷积核height + loadData3DParamsForA.filterSizeH = + false; // 是否在filterH的基础上将卷积核height增加256个元素 + loadData3DParamsForA.dilationFilterW = 1; // 卷积核width膨胀系数 + loadData3DParamsForA.dilationFilterH = 1; // 卷积核height膨胀系数 + loadData3DParamsForA.enTranspose = + 0; // 是否启用转置功能,对整个目标矩阵进行转置 + loadData3DParamsForA.fMatrixCtrl = 0; + loadData3DParamsForA.channelSize = + kL0SizeAlign; // 源操作数的通道数。膨胀系数为1时,目的weight为filterW*filterH*channelSize + LoadData(aL0Tensor, + aL1Tensor[kL0 * baseK * mL1SizeAlign], + loadData3DParamsForA); + SetFlag(Mte1MmABEventId(abL0BufIter % 2)); + WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); + + MmadParams mmadParams; + mmadParams.m = mL1SizeAlign; + mmadParams.n = nL1SizeAlign; + mmadParams.k = kL0Size; + mmadParams.cmatrixInitVal = (kL0 == 0 && k1 == 0); + mmadParams.cmatrixSource = false; + mmadParams.unitFlag = + ((k1 == (kL1Loops - 1)) && (kL0 == (kL0Loops - 1))) ? 0b11 : 0b10; + + Mmad(cL0Tensor, aL0Tensor, bL0Tensor, mmadParams); + if ((mmadParams.m / 16) * (mmadParams.n / 16) < 10) { + PipeBarrier(); + } + SetFlag(Mte1MmABEventId(abL0BufIter % 2)); + abL0BufIter++; + } + + if (nL1 == (nL1Loops - + 1)) { // nL1最后一轮, 需要将B驻留在L1中, 用于下一轮的计算? + SetFlag( + mte21QPIds[ka]); // 反向同步, 表示L1中的A已经被mte1消费完 + } + + if (k1 == (kL1Loops - 1)) { + // ND + FixpipeParamsV220 fixParams; + fixParams.nSize = nL1SizeAlign; + fixParams.mSize = mL1SizeAlign; + fixParams.srcStride = mL1SizeAlign; + fixParams.dstStride = nSize; // mm2ResGm两行之间的间隔 + fixParams.ndNum = 1; // 输出ND + fixParams.unitFlag = 0b11; + + uint64_t mm2Offset = + (mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE) * nSize + + nL1 * N_SPLIT_SIZE; + Fixpipe(mm2ResGm[(info.loop % (constInfo.preLoadNum)) * + constInfo.bmm2ResUbSize + + mm2Offset], + cL0Tensor, + fixParams); + } + + if (mL1Loops == 2) { + cL0BufIter++; + } + } + SetFlag( + mte21KVIds[kb]); // 反向同步, 表示L1已经被mte1消费完 + } + // cL0BufIter已经不在使用 + if (mL1Loops == 1) { + cL0BufIter++; + } + } + qpL1BufIter += mL1Loops; +} +} // namespace SMLAKernel +#endif // SPARSE_FLASH_MLA_CSA_BLOCK_CUBE_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_block_vector.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_block_vector.h new file mode 100644 index 0000000000..5008f01198 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_block_vector.h @@ -0,0 +1,1517 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file sparse_flash_mla_csa_block_vector.h + * \brief + */ +#ifndef SPARSE_FLASH_MLA_CSA_BLOCK_VECTOR_H +#define SPARSE_FLASH_MLA_CSA_BLOCK_VECTOR_H + +#include "kernel_operator.h" +#include "kernel_operator_list_tensor_intf.h" +#include "kernel_tiling/kernel_tiling.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" +#include "sparse_flash_mla_common_arch22.h" + +namespace SMLAKernel { +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +template +class SMLAVectorBlock { + public: + // 中间计算数据类型为float,高精度模式 + using T = float; + using KV_T = typename SMLAT::kvType; + using OUT_T = typename SMLAT::outputType; + using UPDATE_T = T; + using SINKS_T = T; + using MM1_OUT_T = float; + using MM2_OUT_T = float; + + __aicore__ inline SMLAVectorBlock(){}; + __aicore__ inline void ProcessVec0L(const RunInfo& runInfo); + __aicore__ inline void ProcessVec1L(const RunInfo& info); + __aicore__ inline void ProcessVec2L(const RunInfo& info); + __aicore__ inline void InitBuffers(TPipe* pipe); + __aicore__ inline void InitParams( + const struct ConstInfo& constInfo, + const SparseFlashMlaTilingData* __restrict tilingData); + __aicore__ inline void InitVec0GlobalTensor( + const GlobalTensor& kvMergeGm, + const GlobalTensor& oriKvGm, + const GlobalTensor& cmpKvGm, + const GlobalTensor& oriBlockTableGm, + const GlobalTensor& cmpBlockTableGm); + __aicore__ inline void InitVec1GlobalTensor( + GlobalTensor mm1ResGm, + GlobalTensor vec1ResGm, + GlobalTensor actualSeqLengthsQGm, + GlobalTensor actualSeqLengthsKVGm, + GlobalTensor topKGm, + GlobalTensor sinksGm, + GlobalTensor softmaxLseGm); + __aicore__ inline void InitVec2GlobalTensor( + GlobalTensor accumOutGm, + GlobalTensor vec2ResGm, + GlobalTensor mm2ResGm, + GlobalTensor attentionOutGm); + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + __aicore__ inline void CopySinksIn(); + __aicore__ inline void SliceAndContactSinksValue(uint32_t nIdx, + uint32_t dealRowCount); + __aicore__ inline void InitSoftmaxDefaultBuffer(); + // ================================Base + // Vector========================================== + __aicore__ inline void RowDivs(LocalTensor dstUb, + LocalTensor src0Ub, + LocalTensor src1Ub, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount); + __aicore__ inline void RowMuls(LocalTensor dstUb, + LocalTensor src0Ub, + LocalTensor src1Ub, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount); + // ================================Vector0========================================== + __aicore__ inline int64_t GetKeyGmOffset(int64_t realS2Idx, + const RunInfo& runInfo, + int64_t s2IdLimit); + __aicore__ inline void GetRealS2Idx(int64_t s2GmOffset, + int64_t& realS2Idx, + int64_t topkGmBaseOffset, + const RunInfo& runInfo); + __aicore__ inline void CopyInKv(int64_t& mte2Size, + int64_t mte3Size, + int64_t mergeMte3Idx, + int64_t realS2Idx1, + int64_t realS2Idx2, + const RunInfo& runInfo); + __aicore__ inline void CopyOutMrgeResult(int64_t mte2Size, + int64_t mte3Size, + int64_t s2StartGmOffset, + int64_t mergeMte3Idx, + const RunInfo& runInfo); + __aicore__ inline void CopyInSingleKv(int64_t& mte2Size, + int64_t mte3Size, + int64_t mergeMte3Idx, + int64_t realS2Idx, + int64_t keyBNBOffset, + int64_t s2IdLimit, + const RunInfo& runInfo); + // ================================Vector1========================================== + __aicore__ inline void ProcessVec1SingleBuf(const RunInfo& info, + const MSplitInfo& mSplitInfo); + __aicore__ inline void DealBmm1ResBaseBlock(const RunInfo& info, + const MSplitInfo& mSplitInfo, + uint32_t startRow, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t loopId); + __aicore__ inline void SoftmaxFlashV2Compute( + const RunInfo& info, + const MSplitInfo& mSplitInfo, + LocalTensor& mmResUb, + LocalTensor& softmaxTmpUb, + uint32_t startRow, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount); + + __aicore__ inline void ElewiseCompute(const RunInfo& info, + const LocalTensor& mmResUb, + uint32_t dealRowCount, + uint32_t columnCount); + __aicore__ inline void ProcessLse(const RunInfo& info, + const MSplitInfo& mSplitInfo); + // ================================Vecotr2========================================== + __aicore__ inline void ProcessVec2SingleBuf(const RunInfo& info, + const MSplitInfo& mSplitInfo); + __aicore__ inline void DealBmm2ResBaseBlock(const RunInfo& info, + const MSplitInfo& mSplitInfo, + uint32_t startRow, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount); + __aicore__ inline void ProcessVec2Inner(const RunInfo& info, + const MSplitInfo& mSplitInfo, + uint32_t mStartRow, + uint32_t mDealSize); + __aicore__ inline void Bmm2DataCopyOutTrans(const RunInfo& info, + LocalTensor& attenOutUb, + uint32_t wsMStart, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount); + __aicore__ inline void Bmm2ResCopyOut(const RunInfo& info, + LocalTensor& bmm2ResUb, + uint32_t wsMStart, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount); + __aicore__ inline void Bmm2CastAndCopyOut(const RunInfo& info, + LocalTensor& bmm2ResUb, + uint32_t wsMStart, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount); + __aicore__ inline void Bmm2FDDataCopyOut(const RunInfo& info, + LocalTensor& bmm2ResUb, + uint32_t wsMStart, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount); + __aicore__ inline uint64_t CalcAccumOffset(uint32_t bN2Idx, uint32_t gS1Idx); + + // BLOCK和REPEAT的字节数 + static constexpr uint64_t BYTE_BLOCK = 32UL; + static constexpr uint32_t REPEAT_BLOCK_BYTE = 256U; + // BLOCK和REPEAT的FP32元素数 + static constexpr uint32_t FP32_BLOCK_ELEMENT_NUM = BYTE_BLOCK / sizeof(float); + static constexpr uint32_t FP32_REPEAT_ELEMENT_NUM = + REPEAT_BLOCK_BYTE / sizeof(float); + // repeat stride不能超过256 + static constexpr uint32_t REPEATE_STRIDE_UP_BOUND = 256; + + private: + static constexpr bool PAGE_ATTENTION = SMLAT::pageAttention; + static constexpr int TEMPLATE_MODE = SMLAT::templateMode; + static constexpr bool FLASH_DECODE = SMLAT::flashDecode; + static constexpr SMLA_LAYOUT LAYOUT_T = SMLAT::layout; + static constexpr SMLA_LAYOUT KV_LAYOUT_T = SMLAT::kvLayout; + static constexpr bool HEAD_RATIO_ONE = SMLAT::headRatioOne; + + static constexpr uint64_t MERGE_CACHE_GM_BUF_NUM = 3; + static constexpr uint64_t SYNC_INPUT_BUF1_FLAG = 2; + static constexpr uint64_t SYNC_INPUT_BUF1_PONG_FLAG = 3; + static constexpr uint64_t SYNC_INPUT_BUF2_FLAG = 4; + static constexpr uint64_t SYNC_INPUT_BUF2_PONG_FLAG = 5; + static constexpr uint64_t SYNC_OUTPUT_BUF1_FLAG = 4; + static constexpr uint64_t SYNC_OUTPUT_BUF2_FLAG = 5; + static constexpr uint64_t SYNC_SINKS_BUF_FLAG = 6; + static constexpr uint64_t SYNC_INPUT_V0BUF_FLAG = 7; + static constexpr uint32_t INPUT1_BUFFER_OFFSET = + ConstInfo::BUFFER_SIZE_BYTE_32K; + static constexpr uint32_t INPUT2_BUFFER_OFFSET = + ConstInfo::BUFFER_SIZE_BYTE_16K; + static constexpr uint32_t SOFTMAX_TMP_BUFFER_OFFSET = + ConstInfo::BUFFER_SIZE_BYTE_1K; + static constexpr uint32_t BASE_BLOCK_MAX_ELEMENT_NUM = + ConstInfo::BUFFER_SIZE_BYTE_32K / sizeof(T); + static constexpr uint32_t BLOCK_ELEMENT_NUM = BYTE_BLOCK / sizeof(T); + static constexpr uint32_t MAX_N1_SIZE = 128U; + static constexpr T SOFTMAX_MIN_NUM = -2e38; + static constexpr SINKS_T R0 = 1.0f; + + const SparseFlashMlaTilingData* __restrict tilingData; + + uint32_t pingpongFlag = 0U; + ConstInfo constInfo = {}; + + GlobalTensor mm1ResGm; + GlobalTensor vec1ResGm; + GlobalTensor softmaxMaxGm; + GlobalTensor softmaxSumGm; + GlobalTensor sinksGm; + + GlobalTensor actualSeqLengthsQGm; + GlobalTensor actualSeqLengthsKVGm; + GlobalTensor vec2ResGm; + GlobalTensor mm2ResGm; + GlobalTensor accumOutGm; + GlobalTensor attentionOutGm; + GlobalTensor softmaxLseGm; + + GlobalTensor blkTableGm_; + GlobalTensor kvMergeGm_; + GlobalTensor keyGm_; + GlobalTensor topkGm_; + GlobalTensor oriKvGm_; + GlobalTensor cmpKvGm_; + GlobalTensor oriBlockTableGm_; + GlobalTensor cmpBlockTableGm_; + + // ================================Local + // Buffer区==================================== + TBuf<> inputBuff1; // 32K + TBuf<> inputBuff2; // 16K + TBuf<> outputBuff1; // 32K + TBuf<> outputBuff2; // 32K + + TBuf<> tmpBuff1; // 32K + TBuf<> v0ValidSizeBuff; // 8K + + TBuf<> sinksBuff; // 1K + TBuf<> sinksBrcbBuff; // 12K + + TBuf<> softmaxMaxBuff; // PRE_LOAD_NUM * 2K + TBuf<> softmaxExpBuff; // PRE_LOAD_NUM * 2K + TBuf<> softmaxSumBuff; // PRE_LOAD_NUM * 2K + TBuf<> softmaxMaxDefaultBuff; // 2K + TBuf<> softmaxSumDefaultBuff; // 2K + + LocalTensor softmaxMaxDefaultUb; + LocalTensor softmaxSumDefaultUb; + + LocalTensor softmaxMaxUb; + LocalTensor softmaxSumUb; + LocalTensor softmaxExpUb; + LocalTensor kvMergUb_; + LocalTensor v0ValidSizeUb_; + LocalTensor sinksUb; + LocalTensor sinksBrcbUb; + + uint32_t mergeMte3Idx = 0; +}; + +template +__aicore__ inline void SMLAVectorBlock::InitBuffers(TPipe* pipe) { + pipe->InitBuffer(inputBuff1, + ConstInfo::BUFFER_SIZE_BYTE_32K * 2); // 2:pingpong + pipe->InitBuffer(inputBuff2, + ConstInfo::BUFFER_SIZE_BYTE_16K * 2); // 2:pingpong + pipe->InitBuffer(outputBuff1, ConstInfo::BUFFER_SIZE_BYTE_32K); + if (constInfo.returnSoftmaxLse) { + pipe->InitBuffer(outputBuff2, ConstInfo::BUFFER_SIZE_BYTE_1K); + } + + pipe->InitBuffer(tmpBuff1, ConstInfo::BUFFER_SIZE_BYTE_32K); + pipe->InitBuffer(v0ValidSizeBuff, ConstInfo::BUFFER_SIZE_BYTE_8K); + + // M_MAX = 512/2vector = 256, 256 * sizeof(T) * N_Buffer + + pipe->InitBuffer(softmaxMaxBuff, + ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); + pipe->InitBuffer(softmaxExpBuff, + ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); + pipe->InitBuffer(softmaxSumBuff, + ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); + + pipe->InitBuffer(softmaxMaxDefaultBuff, ConstInfo::BUFFER_SIZE_BYTE_1K); + pipe->InitBuffer(softmaxSumDefaultBuff, ConstInfo::BUFFER_SIZE_BYTE_1K); + + pipe->InitBuffer(sinksBuff, MAX_N1_SIZE * sizeof(SINKS_T)); + // 分配256+N1大小内存,其中256是m轴VEC最大切块 + pipe->InitBuffer(sinksBrcbBuff, + MAX_N1_SIZE * sizeof(SINKS_T) * BLOCK_ELEMENT_NUM * 3U); + + softmaxMaxUb = softmaxMaxBuff.Get(); + softmaxSumUb = softmaxSumBuff.Get(); + softmaxExpUb = softmaxExpBuff.Get(); + + softmaxMaxDefaultUb = softmaxMaxDefaultBuff.Get(); + softmaxSumDefaultUb = softmaxSumDefaultBuff.Get(); + + kvMergUb_ = inputBuff2.Get(); + + v0ValidSizeUb_ = v0ValidSizeBuff.Get(); + + sinksUb = sinksBuff.Get(); + sinksBrcbUb = sinksBrcbBuff.Get(); +} + +template +__aicore__ inline void SMLAVectorBlock::InitParams( + const struct ConstInfo& constInfo, + const SparseFlashMlaTilingData* __restrict tilingData) { + this->constInfo = constInfo; + this->tilingData = tilingData; +} + +template +__aicore__ inline void SMLAVectorBlock::InitVec0GlobalTensor( + const GlobalTensor& kvMergeGm, + const GlobalTensor& oriKvGm, + const GlobalTensor& cmpKvGm, + const GlobalTensor& oriBlockTableGm, + const GlobalTensor& cmpBlockTableGm) { + this->kvMergeGm_ = kvMergeGm; + this->oriKvGm_ = oriKvGm; + this->cmpKvGm_ = cmpKvGm; + this->oriBlockTableGm_ = oriBlockTableGm; + this->cmpBlockTableGm_ = cmpBlockTableGm; +} + +template +__aicore__ inline void SMLAVectorBlock::InitVec1GlobalTensor( + GlobalTensor mm1ResGm, + GlobalTensor vec1ResGm, + GlobalTensor actualSeqLengthsQGm, + GlobalTensor actualSeqLengthsKVGm, + GlobalTensor topKGm, + GlobalTensor sinksGm, + GlobalTensor softmaxLseGm) { + this->mm1ResGm = mm1ResGm; + this->vec1ResGm = vec1ResGm; + this->actualSeqLengthsQGm = actualSeqLengthsQGm; + this->actualSeqLengthsKVGm = actualSeqLengthsKVGm; + this->topkGm_ = topKGm; + this->sinksGm = sinksGm; + this->softmaxLseGm = softmaxLseGm; +} + +template +__aicore__ inline void SMLAVectorBlock::InitVec2GlobalTensor( + GlobalTensor accumOutGm, + GlobalTensor vec2ResGm, + GlobalTensor mm2ResGm, + GlobalTensor attentionOutGm) { + this->accumOutGm = accumOutGm; + this->vec2ResGm = vec2ResGm; + this->mm2ResGm = mm2ResGm; + this->attentionOutGm = attentionOutGm; +} + +template +__aicore__ inline void SMLAVectorBlock::AllocEventID() { + SetFlag(SYNC_INPUT_BUF1_FLAG); + SetFlag(SYNC_INPUT_BUF1_PONG_FLAG); + SetFlag(SYNC_INPUT_BUF2_FLAG); + SetFlag(SYNC_INPUT_BUF2_PONG_FLAG); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); +} + +template +__aicore__ inline void SMLAVectorBlock::FreeEventID() { + WaitFlag(SYNC_INPUT_BUF1_FLAG); + WaitFlag(SYNC_INPUT_BUF1_PONG_FLAG); + WaitFlag(SYNC_INPUT_BUF2_FLAG); + WaitFlag(SYNC_INPUT_BUF2_PONG_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); +} + +template +__aicore__ inline void SMLAVectorBlock::CopySinksIn() { + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = 1U; + dataCopyParams.blockLen = constInfo.qHeadNum * sizeof(T); + dataCopyParams.srcStride = 0U; + dataCopyParams.dstStride = 0U; + DataCopyPadExtParams padParams; + DataCopyPad(sinksUb, sinksGm, dataCopyParams, padParams); + SetFlag(SYNC_SINKS_BUF_FLAG); + WaitFlag(SYNC_SINKS_BUF_FLAG); + uint32_t repeatTimes = + (constInfo.qHeadNum + BLOCK_ELEMENT_NUM - 1U) / BLOCK_ELEMENT_NUM; + Brcb(sinksBrcbUb, sinksUb, repeatTimes, {1, BLOCK_ELEMENT_NUM}); + PipeBarrier(); + + DataCopyParams repeatParams; + repeatParams.blockCount = + 1; // 搬到有一个块超过单个vec核减分核M轴大小即可,核间切分每个vec256 + repeatParams.blockLen = constInfo.qHeadNum; + repeatParams.srcStride = 0U; + repeatParams.dstStride = 0U; + for (uint32_t i = 1U; i <= 256U / constInfo.qHeadNum; i++) { + DataCopy(sinksBrcbUb[constInfo.qHeadNum * BLOCK_ELEMENT_NUM * i], + sinksBrcbUb, + repeatParams); + } + PipeBarrier(); +} + +template +__aicore__ inline void SMLAVectorBlock::SliceAndContactSinksValue( + uint32_t nIdx, + uint32_t dealRowCount) { + // WholeReduceMax接口中repeatTimes支持范围(0,255),因此需要分多次调用WholeReduceMax,每次repeatTime=128 + uint32_t repeatTimesOnce = 128; + uint32_t loopTimes = (dealRowCount + repeatTimesOnce - 1) / repeatTimesOnce; + uint32_t repeatTimes = repeatTimesOnce; + + for (uint32_t loop = 0; loop < loopTimes; ++loop) { + if (loop == loopTimes - 1) { + repeatTimes = dealRowCount - loop * repeatTimesOnce; + } + WholeReduceMax( + softmaxMaxDefaultUb[loop * repeatTimesOnce], + sinksBrcbUb[(nIdx + loop * repeatTimesOnce) * BLOCK_ELEMENT_NUM], + BLOCK_ELEMENT_NUM * BLOCK_ELEMENT_NUM, + repeatTimes, + 1, + 0, + 1, + ReduceOrder::ORDER_ONLY_VALUE); + PipeBarrier(); + } +} + +template +__aicore__ inline void SMLAVectorBlock::InitSoftmaxDefaultBuffer() { + CopySinksIn(); + Duplicate(softmaxMaxDefaultUb, + SOFTMAX_MIN_NUM, + SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)); + Duplicate(softmaxSumDefaultUb, R0, SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)); +} + +template +__aicore__ inline void SMLAVectorBlock::ElewiseCompute( + const RunInfo& info, + const LocalTensor& mmResUb, + uint32_t dealRowCount, + uint32_t columnCount) { + Muls(mmResUb, + mmResUb, + static_cast(tilingData->baseParams.softmaxScale), + dealRowCount * columnCount); +} + +template +__aicore__ inline void SMLAVectorBlock::ProcessLse( + const RunInfo& info, + const MSplitInfo& mSplitInfo) { + if (mSplitInfo.vecDealM == 0) { + return; + } + uint64_t lseOffset; + if (constInfo.outputLayout == SMLA_LAYOUT::TND) { + uint32_t tBase = actualSeqLengthsQGm.GetValue(info.bIdx); + lseOffset = + (tBase + info.s1Idx) * constInfo.gSize + // T轴、s1轴偏移 + info.n2IdxReal * constInfo.qSeqSize * constInfo.gSize; // N2轴偏移 + } else if (constInfo.outputLayout == SMLA_LAYOUT::BSND) { + lseOffset = + info.bIdx * constInfo.qSeqSize * constInfo.kvHeadNum * + constInfo.gSize + // B轴偏移 + info.n2IdxReal * constInfo.qSeqSize * constInfo.gSize + // N2轴偏移 + info.s1Idx * constInfo.gSize; // S1轴偏移 + } + lseOffset = lseOffset + mSplitInfo.nBufferStartM + mSplitInfo.vecStartM; + uint32_t baseOffset = mSplitInfo.nBufferStartM / 2; + uint32_t outIdx = info.loop % (constInfo.preLoadNum); + uint32_t softmaxOffset = + outIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset; + auto sumTensor = softmaxSumUb[softmaxOffset]; + auto maxTensor = softmaxMaxUb[softmaxOffset]; + auto outLSETensor = outputBuff2.Get(); + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = 1; + dataCopyParams.blockLen = mSplitInfo.vecDealM * sizeof(T); + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = 0; + + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + PipeBarrier(); + Log(outLSETensor, sumTensor, mSplitInfo.vecDealM); + PipeBarrier(); + Add(outLSETensor, outLSETensor, maxTensor, mSplitInfo.vecDealM); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + + DataCopyPad(softmaxLseGm[lseOffset], outLSETensor, dataCopyParams); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); +} + +template +__aicore__ inline void SMLAVectorBlock::SoftmaxFlashV2Compute( + const RunInfo& info, + const MSplitInfo& mSplitInfo, + LocalTensor& mmResUb, + LocalTensor& softmaxTmpUb, + uint32_t startRow, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + LocalTensor inSumTensor; + LocalTensor inMaxTensor; + uint32_t baseOffset = mSplitInfo.nBufferStartM / 2 + startRow; + uint32_t outIdx = info.loop % (constInfo.preLoadNum); + uint32_t softmaxOutOffset = + outIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset; + if (info.isFirstSInnerLoop) { + inMaxTensor = softmaxMaxDefaultUb[startRow]; + inSumTensor = softmaxSumDefaultUb; + } else { + uint32_t inIdx = (info.loop - 1) % (constInfo.preLoadNum); + inMaxTensor = softmaxMaxUb[inIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + + baseOffset]; + inSumTensor = softmaxSumUb[inIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + + baseOffset]; + } + if (actualColumnCount != 0) { + SoftMaxShapeInfo srcShape{ + dealRowCount, columnCount, dealRowCount, actualColumnCount}; + SoftMaxTiling newTiling = SoftMaxFlashV2TilingFunc( + srcShape, sizeof(T), sizeof(T), softmaxTmpUb.GetSize(), true, false); + SoftmaxFlashV2( + mmResUb, + softmaxSumUb[softmaxOutOffset], + softmaxMaxUb[softmaxOutOffset], + mmResUb, + softmaxExpUb[softmaxOutOffset], + inSumTensor, + inMaxTensor, + softmaxTmpUb, + newTiling, + srcShape); + } else { + uint32_t dealRowCountAlign = + SMLAAlign(dealRowCount, FP32_BLOCK_ELEMENT_NUM); + DataCopy(softmaxSumUb[softmaxOutOffset], inSumTensor, dealRowCountAlign); + PipeBarrier(); + DataCopy(softmaxMaxUb[softmaxOutOffset], inMaxTensor, dealRowCountAlign); + } +} + +template +__aicore__ inline void SMLAVectorBlock::DealBmm1ResBaseBlock( + const RunInfo& info, + const MSplitInfo& mSplitInfo, + uint32_t startRow, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t loopId) { + uint32_t computeSize = dealRowCount * columnCount; + uint64_t inOutGmOffset = + (info.loop % constInfo.preLoadNum) * constInfo.mmResUbSize + + (mSplitInfo.nBufferStartM + mSplitInfo.vecStartM + startRow) * + columnCount; + LocalTensor mmResUb = inputBuff1.Get(); + mmResUb = mmResUb[pingpongFlag * INPUT1_BUFFER_OFFSET / sizeof(MM1_OUT_T)]; + WaitFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); + + DataCopy(mmResUb, mm1ResGm[inOutGmOffset], computeSize); + SetFlag(SYNC_INPUT_BUF1_FLAG); + WaitFlag(SYNC_INPUT_BUF1_FLAG); + + ElewiseCompute(info, mmResUb, dealRowCount, columnCount); + + PipeBarrier(); + LocalTensor tmpAFloorUb = tmpBuff1.Get(); + LocalTensor softmaxTmpUb = + tmpAFloorUb.template ReinterpretCast(); + + SoftmaxFlashV2Compute(info, + mSplitInfo, + mmResUb, + softmaxTmpUb, + startRow, + dealRowCount, + columnCount, + info.actualSingleProcessSInnerSize); + + PipeBarrier(); + LocalTensor tmpMMResCastTensor = outputBuff1.Get(); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + + Cast( + tmpMMResCastTensor, mmResUb, AscendC::RoundMode::CAST_ROUND, computeSize); + SetFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); + pingpongFlag ^= 1; // pingpong 0 1 切换 + + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + DataCopy(vec1ResGm[inOutGmOffset], tmpMMResCastTensor, computeSize); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); +} + +template +__aicore__ inline void SMLAVectorBlock::ProcessVec1SingleBuf( + const RunInfo& info, + const MSplitInfo& mSplitInfo) { + if (mSplitInfo.vecDealM == 0) { + return; + } + uint32_t mSplitSize = info.actualSingleProcessSInnerSize == 0 + ? 16 + : BASE_BLOCK_MAX_ELEMENT_NUM / + info.actualSingleProcessSInnerSizeAlign; + // 1. 向下8对齐是因为UB操作至少32B + // 2. info.actualSingleProcessSInnerSizeAlign最大512, + // mSplitSize可以确保最小为16 + mSplitSize = mSplitSize / 8 * 8; + + if (mSplitSize > mSplitInfo.vecDealM) { + mSplitSize = mSplitInfo.vecDealM; + } + uint32_t loopCount = (mSplitInfo.vecDealM + mSplitSize - 1) / mSplitSize; + uint32_t tailSplitSize = mSplitInfo.vecDealM - (loopCount - 1) * mSplitSize; + + uint32_t sinkHeadIdx = (info.n2IdxReal * constInfo.gSize + + mSplitInfo.nBufferStartM + mSplitInfo.vecStartM) % + constInfo.qHeadNum; + SliceAndContactSinksValue(sinkHeadIdx, mSplitInfo.vecDealM); + + for (uint32_t i = 0, dealSize = mSplitSize; i < loopCount; i++) { + if (i == (loopCount - 1)) { + dealSize = tailSplitSize; + } + DealBmm1ResBaseBlock(info, + mSplitInfo, + i * mSplitSize, + dealSize, + info.actualSingleProcessSInnerSizeAlign, + i); + } +} + +template +__aicore__ inline void SMLAVectorBlock::GetRealS2Idx( + int64_t s2GmOffset, + int64_t& realS2Idx, + int64_t topkGmBaseOffset, + const RunInfo& runInfo) { + int64_t cmpS2Offset = s2GmOffset; + int64_t topkGmIdx = cmpS2Offset / constInfo.sparseBlockSize; + if (unlikely(topkGmIdx >= constInfo.sparseBlockCount || + s2GmOffset >= runInfo.v0S2DealSize)) { + realS2Idx = -1; + return; + } + realS2Idx = topkGm_.GetValue(topkGmBaseOffset + topkGmIdx) * + static_cast(constInfo.sparseBlockSize) + + static_cast(cmpS2Offset % constInfo.sparseBlockSize); +} + +template +__aicore__ inline int64_t SMLAVectorBlock::GetKeyGmOffset( + int64_t realS2Idx, + const RunInfo& runInfo, + int64_t s2IdLimit) { + if (realS2Idx < 0 || realS2Idx >= s2IdLimit) { + return -1; + } + int64_t realKeyGmOffset = 0; + if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { + int64_t blkTableIdx = realS2Idx / constInfo.paCmpBlockSize; + int64_t blkTableOffset = realS2Idx % constInfo.paCmpBlockSize; + realKeyGmOffset = + cmpBlockTableGm_.GetValue( + runInfo.bIdx * constInfo.cmpMaxBlockNumPerBatch + blkTableIdx) * + static_cast(constInfo.cmpKvStride0) + + blkTableOffset * static_cast(constInfo.kvHeadNum) * + static_cast(constInfo.headDim); + + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { + int64_t batchStride = (constInfo.cmpKvStride0 == 0) + ? static_cast(constInfo.cmpSeqSize) * + static_cast(constInfo.kvHeadNum) * + static_cast(constInfo.headDim) + : static_cast(constInfo.cmpKvStride0); + realKeyGmOffset = static_cast(runInfo.bIdx) * batchStride + + realS2Idx * static_cast(constInfo.kvHeadNum) * + static_cast(constInfo.headDim) + + static_cast(runInfo.n2Idx) * + static_cast(constInfo.headDim); + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { + realKeyGmOffset = runInfo.tensorCmpBOffset + + realS2Idx * static_cast(constInfo.kvHeadNum) * + static_cast(constInfo.headDim) + + static_cast(runInfo.n2Idx) * + static_cast(constInfo.headDim); + } + return realKeyGmOffset; +} + +template +__aicore__ inline void SMLAVectorBlock::CopyInSingleKv( + int64_t& mte2Size, + int64_t mte3Size, + int64_t mergeMte3Idx, + int64_t realS2Idx, + int64_t keyBNBOffset, + int64_t s2IdLimit, + const RunInfo& runInfo) { + if (keyBNBOffset < 0) { + return; + } + int64_t validS2Count = (realS2Idx + constInfo.sparseBlockSize > s2IdLimit + ? s2IdLimit - realS2Idx + : constInfo.sparseBlockSize); + DataCopyExtParams intriParams; + intriParams.blockLen = validS2Count * constInfo.headDim * sizeof(KV_T); + intriParams.blockCount = 1; + intriParams.dstStride = 0; + intriParams.srcStride = 0; + DataCopyPadExtParams padParams{false, 0, 0, 0}; + DataCopyPad(kvMergUb_[mergeMte3Idx % 2 * INPUT2_BUFFER_OFFSET / sizeof(KV_T) + + (mte2Size - mte3Size) * constInfo.headDim], + cmpKvGm_[keyBNBOffset], + intriParams, + padParams); + mte2Size += validS2Count; +} + +template +__aicore__ inline void SMLAVectorBlock::CopyInKv( + int64_t& mte2Size, + int64_t mte3Size, + int64_t mergeMte3Idx, + int64_t realS2Idx1, + int64_t realS2Idx2, + const RunInfo& runInfo) { + int64_t s2IdLimit = runInfo.cmpS2IdLimit; + + int64_t keyOffset1 = GetKeyGmOffset(realS2Idx1, runInfo, s2IdLimit); + int64_t keyOffset2 = GetKeyGmOffset(realS2Idx2, runInfo, s2IdLimit); + if (unlikely(keyOffset1 < 0 && keyOffset2 < 0)) { + return; + } + + int64_t keySrcStride = 0; + keySrcStride = ((keyOffset1 > keyOffset2 ? (keyOffset1 - keyOffset2) + : (keyOffset2 - keyOffset1)) - + constInfo.sparseBlockSize * constInfo.headDim) * + sizeof(KV_T); + if (unlikely(keySrcStride >= INT32_MAX || keySrcStride < 0 || + realS2Idx1 + constInfo.sparseBlockSize >= s2IdLimit || + realS2Idx2 + constInfo.sparseBlockSize >= s2IdLimit)) { + // stride溢出、stride为负数、s2超长等异常场景,还原成2条搬运指令 + // 因为需要拷贝两块 + CopyInSingleKv(mte2Size, + mte3Size, + mergeMte3Idx, + realS2Idx1, + keyOffset1, + s2IdLimit, + runInfo); + CopyInSingleKv(mte2Size, + mte3Size, + mergeMte3Idx, + realS2Idx2, + keyOffset2, + s2IdLimit, + runInfo); + } else { + DataCopyExtParams intriParams; + intriParams.blockLen = + constInfo.sparseBlockSize * constInfo.headDim * sizeof(KV_T); + intriParams.blockCount = (keyOffset1 >= 0) + (keyOffset2 >= 0); + intriParams.dstStride = 0; + intriParams.srcStride = keySrcStride; + DataCopyPadExtParams padParams{false, 0, 0, 0}; + + int64_t startGmOffset = keyOffset1 > -1 ? keyOffset1 : keyOffset2; + if (keyOffset2 > -1 && keyOffset2 < keyOffset1) { + startGmOffset = keyOffset2; + } + DataCopyPad( + kvMergUb_[mergeMte3Idx % 2 * INPUT2_BUFFER_OFFSET / sizeof(KV_T) + + (mte2Size - mte3Size) * constInfo.headDim], + cmpKvGm_[startGmOffset], + intriParams, + padParams); + mte2Size += + ((keyOffset1 > -1) + (keyOffset2 > -1)) * constInfo.sparseBlockSize; + } +} + +template +__aicore__ inline void SMLAVectorBlock::CopyOutMrgeResult( + int64_t mte2Size, + int64_t mte3Size, + int64_t s2GmStartOffset, + int64_t mergeMte3Idx, + const RunInfo& runInfo) { + if (mte2Size <= mte3Size) { + return; + } + SetFlag(mergeMte3Idx % 2 + + SYNC_INPUT_BUF2_FLAG); + WaitFlag(mergeMte3Idx % 2 + + SYNC_INPUT_BUF2_FLAG); + + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = mte2Size - mte3Size; + dataCopyParams.blockLen = constInfo.headDim * sizeof(KV_T); + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = 0; + + DataCopyPad(kvMergeGm_[runInfo.cmpLoop % MERGE_CACHE_GM_BUF_NUM * 512 * 512 + + (s2GmStartOffset + mte3Size) * constInfo.headDim], + kvMergUb_[mergeMte3Idx % 2 * INPUT2_BUFFER_OFFSET / sizeof(KV_T)], + dataCopyParams); +} + +// b s1 k +template +__aicore__ inline void SMLAVectorBlock::ProcessVec0L( + const RunInfo& runInfo) { + int64_t s2ProcessSize = runInfo.v0S2DealSize; + int64_t s2Pair = CeilDiv(s2ProcessSize, 2 * constInfo.sparseBlockSize); + int64_t topkGmBaseOffset = runInfo.topKBaseOffset + runInfo.v0S2Start; + int64_t mte2Size = 0; + int64_t mte3Size = 0; + int64_t s2IdxArray0 = -1; + int64_t s2IdxArray1 = -1; + bool needWaitMte3ToMte2 = true; + int64_t s2SplitPoint = SMLAAlign(s2Pair, 2) * constInfo.sparseBlockSize; + int64_t s2GmStartOffset = GetSubBlockIdx() == 0 ? 0 : s2SplitPoint; + int64_t s2GmLimit = GetSubBlockIdx() == 0 ? s2SplitPoint : s2ProcessSize; + if (s2GmLimit > s2ProcessSize) { + s2GmLimit = s2ProcessSize; + } + // 处理两个基本块 + for (int64_t s2GmOffsetArray = s2GmStartOffset; s2GmOffsetArray < s2GmLimit; + s2GmOffsetArray += 2 * constInfo.sparseBlockSize) { + if (needWaitMte3ToMte2) { + WaitFlag(mergeMte3Idx % 2 + + SYNC_INPUT_BUF2_FLAG); + needWaitMte3ToMte2 = false; + } + GetRealS2Idx(s2GmOffsetArray, s2IdxArray0, topkGmBaseOffset, runInfo); + if (unlikely(s2IdxArray0 < 0)) { + CopyOutMrgeResult( + mte2Size, mte3Size, s2GmStartOffset, mergeMte3Idx, runInfo); + SetFlag(mergeMte3Idx % 2 + + SYNC_INPUT_BUF2_FLAG); + mergeMte3Idx++; + break; + } + GetRealS2Idx(s2GmOffsetArray + constInfo.sparseBlockSize, + s2IdxArray1, + topkGmBaseOffset, + runInfo); + CopyInKv( + mte2Size, mte3Size, mergeMte3Idx, s2IdxArray0, s2IdxArray1, runInfo); + if ((mte2Size - mte3Size + 2 * constInfo.sparseBlockSize > 16) || + s2GmOffsetArray + 2 * constInfo.sparseBlockSize >= s2GmLimit) { + CopyOutMrgeResult( + mte2Size, mte3Size, s2GmStartOffset, mergeMte3Idx, runInfo); + mte3Size = mte2Size; + SetFlag(mergeMte3Idx % 2 + + SYNC_INPUT_BUF2_FLAG); + mergeMte3Idx++; + needWaitMte3ToMte2 = true; + } + } + return; +} + +template +__aicore__ inline void SMLAVectorBlock::ProcessVec1L( + const RunInfo& info) { + uint32_t nBufferLoopTimes = + (info.actMBaseSize + constInfo.nBufferMBaseSize - 1) / + constInfo.nBufferMBaseSize; + uint32_t nBufferTail = + info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; + for (uint32_t i = 0; i < nBufferLoopTimes; i++) { + MSplitInfo mSplitInfo; + mSplitInfo.nBufferIdx = i; + mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; + mSplitInfo.nBufferDealM = + (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; + + mSplitInfo.vecDealM = + (mSplitInfo.nBufferDealM <= 16) + ? mSplitInfo.nBufferDealM + : (((mSplitInfo.nBufferDealM + 15) / 16 + 1) / 2 * 16); + mSplitInfo.vecStartM = 0; + if (GetBlockIdx() % 2 == 1) { + mSplitInfo.vecStartM = mSplitInfo.vecDealM; + mSplitInfo.vecDealM = mSplitInfo.nBufferDealM - mSplitInfo.vecDealM; + } + + if constexpr (HEAD_RATIO_ONE) { + CrossCoreWaitFlag( + constInfo.syncC1V1); + } else { + CrossCoreWaitFlag(constInfo.syncC1V1); + } + // vec1 compute + ProcessVec1SingleBuf(info, mSplitInfo); + CrossCoreSetFlag(constInfo.syncV1C2); + + // move lse for flash decode or FA + if (constInfo.returnSoftmaxLse && + info.s2Idx == info.curSInnerLoopTimes - 1) { + ProcessLse(info, mSplitInfo); + } + } +} + +template +__aicore__ inline uint64_t SMLAVectorBlock::CalcAccumOffset( + uint32_t bN2Idx, + uint32_t gS1Idx) { + return 0; +} + +template +__aicore__ inline void SMLAVectorBlock::ProcessVec2SingleBuf( + const RunInfo& info, + const MSplitInfo& mSplitInfo) { + if (mSplitInfo.vecDealM == 0) { + return; + } + + ProcessVec2Inner(info, mSplitInfo, 0, mSplitInfo.vecDealM); +} + +template +__aicore__ inline void SMLAVectorBlock::ProcessVec2L( + const RunInfo& info) { + uint32_t nBufferLoopTimes = + (info.actMBaseSize + constInfo.nBufferMBaseSize - 1) / + constInfo.nBufferMBaseSize; + uint32_t nBufferTail = + info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; + for (uint32_t i = 0; i < nBufferLoopTimes; i++) { + MSplitInfo mSplitInfo; + mSplitInfo.nBufferIdx = i; + mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; + mSplitInfo.nBufferDealM = + (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; + + mSplitInfo.vecDealM = + (mSplitInfo.nBufferDealM <= 16) + ? mSplitInfo.nBufferDealM + : (((mSplitInfo.nBufferDealM + 15) / 16 + 1) / 2 * 16); + mSplitInfo.vecStartM = 0; + if (GetBlockIdx() % 2 == 1) { + mSplitInfo.vecStartM = mSplitInfo.vecDealM; + mSplitInfo.vecDealM = mSplitInfo.nBufferDealM - mSplitInfo.vecDealM; + } + if constexpr (HEAD_RATIO_ONE) { + CrossCoreWaitFlag( + constInfo.syncC2V2); + } else { + CrossCoreWaitFlag(constInfo.syncC2V2); + } + ProcessVec2SingleBuf(info, mSplitInfo); + } +} + +template +__aicore__ inline void SMLAVectorBlock::ProcessVec2Inner( + const RunInfo& info, + const MSplitInfo& mSplitInfo, + uint32_t mStartRow, + uint32_t mDealSize) { + uint32_t mSplitSize = BASE_BLOCK_MAX_ELEMENT_NUM / constInfo.headDim; + if (mSplitSize > mDealSize) { + mSplitSize = mDealSize; + } + + uint32_t loopCount = (mDealSize + mSplitSize - 1) / mSplitSize; + uint32_t tailSplitSize = mDealSize - (loopCount - 1) * mSplitSize; + for (uint32_t i = 0, dealSize = mSplitSize; i < loopCount; i++) { + if (i == (loopCount - 1)) { + dealSize = tailSplitSize; + } + DealBmm2ResBaseBlock(info, + mSplitInfo, + i * mSplitSize + mStartRow, + dealSize, + constInfo.headDim, + constInfo.headDim); + } +} + +template +__aicore__ inline void SMLAVectorBlock::Bmm2FDDataCopyOut( + const RunInfo& info, + LocalTensor& bmm2ResUb, + uint32_t wsMStart, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + LocalTensor tmp = outputBuff1.Get(); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + DataCopy(tmp, bmm2ResUb, columnCount * dealRowCount); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + uint64_t accumTmpOutNum = CalcAccumOffset(info.bIdx, info.gS1Idx); + uint64_t offset = accumTmpOutNum * constInfo.kvHeadNum * constInfo.mBaseSize * + constInfo.headDim + // taskoffset + info.tndCoreStartKVSplitPos * constInfo.kvHeadNum * + constInfo.mBaseSize * constInfo.headDim + // 份数offset + wsMStart * actualColumnCount; // m轴offset + GlobalTensor dst = accumOutGm[offset]; + if (info.actualSingleProcessSInnerSize == 0) { + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = dealRowCount; + dataCopyParams.blockLen = actualColumnCount * sizeof(T); + dataCopyParams.srcStride = + (columnCount - actualColumnCount) / (BYTE_BLOCK / sizeof(T)); + dataCopyParams.dstStride = 0; + DataCopyPad(dst, tmp, dataCopyParams); + } else { + matmul::InitOutput( + dst, dealRowCount * actualColumnCount, ConstInfo::FLOAT_ZERO); + } + SetFlag(SYNC_OUTPUT_BUF1_FLAG); +} + +template +__aicore__ inline void SMLAVectorBlock::Bmm2DataCopyOutTrans( + const RunInfo& info, + LocalTensor& attenOutUb, + uint32_t wsMStart, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = dealRowCount; + dataCopyParams.blockLen = actualColumnCount * sizeof(OUT_T); + dataCopyParams.srcStride = + (columnCount - actualColumnCount) / (BYTE_BLOCK / sizeof(OUT_T)); + dataCopyParams.dstStride = 0; + DataCopyPad( + attentionOutGm[info.attenOutOffset + wsMStart * actualColumnCount], + attenOutUb, + dataCopyParams); + return; +} + +template +__aicore__ inline void SMLAVectorBlock::Bmm2CastAndCopyOut( + const RunInfo& info, + LocalTensor& bmm2ResUb, + uint32_t wsMStart, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + LocalTensor tmpBmm2ResCastTensor = outputBuff1.Get(); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + if constexpr (IsSameType::value) { // bf16 采取四舍六入五成双模式 + Cast(tmpBmm2ResCastTensor, + bmm2ResUb, + AscendC::RoundMode::CAST_RINT, + dealRowCount * columnCount); + } else { + Cast(tmpBmm2ResCastTensor, + bmm2ResUb, + AscendC::RoundMode::CAST_ROUND, + dealRowCount * columnCount); + } + + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + Bmm2DataCopyOutTrans(info, + tmpBmm2ResCastTensor, + wsMStart, + dealRowCount, + columnCount, + actualColumnCount); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); +} + +template +__aicore__ inline void SMLAVectorBlock::Bmm2ResCopyOut( + const RunInfo& info, + LocalTensor& bmm2ResUb, + uint32_t wsMStart, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + if constexpr (FLASH_DECODE) { + if (info.tndIsS2SplitCore) { + Bmm2FDDataCopyOut(info, + bmm2ResUb, + wsMStart, + dealRowCount, + columnCount, + actualColumnCount); + } else { + Bmm2CastAndCopyOut(info, + bmm2ResUb, + wsMStart, + dealRowCount, + columnCount, + actualColumnCount); + } + } else { + Bmm2CastAndCopyOut(info, + bmm2ResUb, + wsMStart, + dealRowCount, + columnCount, + actualColumnCount); + } +} + +template +__aicore__ inline void SMLAVectorBlock::DealBmm2ResBaseBlock( + const RunInfo& info, + const MSplitInfo& mSplitInfo, + uint32_t startRow, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + uint32_t vec2ComputeSize = dealRowCount * columnCount; + uint32_t mStart = mSplitInfo.nBufferStartM + mSplitInfo.vecStartM + startRow; + uint64_t srcGmOffset = + (info.loop % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + + mStart * columnCount; + LocalTensor tmpBmm2ResUb = inputBuff1.Get(); + tmpBmm2ResUb = + tmpBmm2ResUb[pingpongFlag * INPUT1_BUFFER_OFFSET / sizeof(MM2_OUT_T)]; + WaitFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); + DataCopy(tmpBmm2ResUb, mm2ResGm[srcGmOffset], vec2ComputeSize); + + SetFlag(SYNC_INPUT_BUF1_FLAG); + WaitFlag(SYNC_INPUT_BUF1_FLAG); + + LocalTensor bmm2ResUb = tmpBuff1.Get(); + bmm2ResUb.SetSize(vec2ComputeSize); + DataCopy(bmm2ResUb, tmpBmm2ResUb, vec2ComputeSize); + SetFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); + pingpongFlag ^= 1; // pingpong 0 1切换 + + uint32_t inOutBaseOffset = mStart * columnCount; + uint32_t baseOffset = mSplitInfo.nBufferStartM / 2 + startRow; + + if constexpr (!HEAD_RATIO_ONE) { + if (!info.isFirstSInnerLoop) { + event_t eventIdMte2WaitMte3 = static_cast( + GetTPipePtr()->FetchEventID(HardEvent::MTE3_MTE2)); + SetFlag(eventIdMte2WaitMte3); + WaitFlag(eventIdMte2WaitMte3); + + LocalTensor bmm2ResPreUb = inputBuff1.Get(); + bmm2ResPreUb = + bmm2ResPreUb[pingpongFlag * INPUT1_BUFFER_OFFSET / sizeof(MM2_OUT_T)]; + WaitFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); + + uint64_t vec2ResGmOffset = + ((info.loop - 1) % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + + inOutBaseOffset; + DataCopy(bmm2ResPreUb, vec2ResGm[vec2ResGmOffset], vec2ComputeSize); + + SetFlag(SYNC_INPUT_BUF1_FLAG); + WaitFlag(SYNC_INPUT_BUF1_FLAG); + + uint32_t idx = info.loop % (constInfo.preLoadNum); + LocalTensor expUb = v0ValidSizeBuff.Get()[384]; + Brcb(expUb, + softmaxExpUb[idx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + + baseOffset], + (dealRowCount + 7) / 8, + {1, 8}); + PipeBarrier(); + + RowMuls(bmm2ResPreUb, + bmm2ResPreUb, + expUb, + dealRowCount, + columnCount, + actualColumnCount); + AscendC::PipeBarrier(); + Add(bmm2ResUb, bmm2ResUb, bmm2ResPreUb, vec2ComputeSize); + AscendC::PipeBarrier(); + + SetFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); + pingpongFlag ^= 1; + } + + if (info.isLastS2Loop) { + uint32_t idx = info.loop % (constInfo.preLoadNum); + LocalTensor tmpSumUb = v0ValidSizeBuff.Get()[384]; + Brcb(tmpSumUb, + softmaxSumUb[idx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + + baseOffset], + (dealRowCount + 7) / 8, + {1, 8}); + PipeBarrier(); + RowDivs(bmm2ResUb, + bmm2ResUb, + tmpSumUb, + dealRowCount, + columnCount, + actualColumnCount); + PipeBarrier(); + Bmm2ResCopyOut(info, + bmm2ResUb, + mStart, + dealRowCount, + columnCount, + actualColumnCount); + } else { + LocalTensor outUb = outputBuff1.Get(); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + DataCopy(outUb, bmm2ResUb, dealRowCount * columnCount); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + uint64_t vec2ResGmOffset = + (info.loop % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + + inOutBaseOffset; + DataCopy(vec2ResGm[vec2ResGmOffset], outUb, vec2ComputeSize); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + } + } else { + // 除第一个循环外,均需要更新中间计算结果 + if (!info.isFirstSInnerLoop) { + event_t eventIdMte2WaitMte3 = static_cast( + GetTPipePtr()->FetchEventID(HardEvent::MTE3_MTE2)); + SetFlag(eventIdMte2WaitMte3); + WaitFlag(eventIdMte2WaitMte3); + + LocalTensor bmm2ResPreUb = inputBuff1.Get(); + bmm2ResPreUb = + bmm2ResPreUb[pingpongFlag * INPUT1_BUFFER_OFFSET / sizeof(MM2_OUT_T)]; + WaitFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); + + uint64_t accumGmOffset = + ((info.loop - 1) % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + + inOutBaseOffset; + DataCopy(bmm2ResPreUb, mm2ResGm[accumGmOffset], vec2ComputeSize); + + SetFlag(SYNC_INPUT_BUF1_FLAG); + WaitFlag(SYNC_INPUT_BUF1_FLAG); + + uint32_t idx = info.loop % (constInfo.preLoadNum); + LocalTensor expUb = + v0ValidSizeBuff.Get()[384]; // sumUb用临时内存 16 * 32B = 512B + Brcb(expUb, + softmaxExpUb[idx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + + baseOffset], + (dealRowCount + 7) / 8, + {1, 8}); + PipeBarrier(); + + RowMuls(bmm2ResPreUb, + bmm2ResPreUb, + expUb, + dealRowCount, + columnCount, + actualColumnCount); + AscendC::PipeBarrier(); + Add(bmm2ResUb, bmm2ResUb, bmm2ResPreUb, vec2ComputeSize); + AscendC::PipeBarrier(); + + SetFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); + pingpongFlag ^= 1; // pingpong 0 1 切换 + } + + // 最后一次输出计算结果,否则将中间结果暂存至workspace + if (info.isLastS2Loop) { + uint32_t idx = info.loop % (constInfo.preLoadNum); + LocalTensor tmpSumUb = + v0ValidSizeBuff.Get()[384]; // sumUb用临时内存 16 * 32B = 512B + Brcb(tmpSumUb, + softmaxSumUb[idx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + + baseOffset], + (dealRowCount + 7) / 8, + {1, 8}); + PipeBarrier(); + RowDivs(bmm2ResUb, + bmm2ResUb, + tmpSumUb, + dealRowCount, + columnCount, + actualColumnCount); + PipeBarrier(); + Bmm2ResCopyOut(info, + bmm2ResUb, + mStart, + dealRowCount, + columnCount, + actualColumnCount); + } else if (!info.isFirstSInnerLoop) { + LocalTensor outUb = outputBuff1.Get(); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + DataCopy(outUb, bmm2ResUb, dealRowCount * columnCount); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + uint64_t accumGmOffset = + (info.loop % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + + inOutBaseOffset; + DataCopy(mm2ResGm[accumGmOffset], outUb, vec2ComputeSize); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + } + } +} + +template +__aicore__ inline void SMLAVectorBlock::RowDivs( + LocalTensor dstUb, + LocalTensor src0Ub, + LocalTensor src1Ub, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + // divs by row, 每行的元素除以相同的元素 + // dstUb[i, (j * 8) : (j * 8 + 7)] = src0Ub[i, (j * 8) : (j * 8 + 7)] / + // src1Ub[i, 0 : 7] src0Ub:[dealRowCount, columnCount], src1Ub:[dealRowCount, + // FP32_BLOCK_ELEMENT_NUM] dstUb:[dealRowCount, columnCount] + uint32_t dtypeMask = FP32_REPEAT_ELEMENT_NUM; + uint32_t dLoop = actualColumnCount / dtypeMask; + uint32_t dRemain = actualColumnCount % dtypeMask; + + BinaryRepeatParams repeatParamsDiv; + repeatParamsDiv.src0BlkStride = 1; + repeatParamsDiv.src1BlkStride = 0; + repeatParamsDiv.dstBlkStride = 1; + repeatParamsDiv.src0RepStride = columnCount / FP32_BLOCK_ELEMENT_NUM; + repeatParamsDiv.src1RepStride = 1; + repeatParamsDiv.dstRepStride = columnCount / FP32_BLOCK_ELEMENT_NUM; + uint32_t columnRepeatCount = dLoop; + if (columnRepeatCount <= dealRowCount) { + uint32_t offset = 0; + for (uint32_t i = 0; i < dLoop; i++) { + Div(dstUb[offset], + src0Ub[offset], + src1Ub, + dtypeMask, + dealRowCount, + repeatParamsDiv); + offset += dtypeMask; + } + } else { + BinaryRepeatParams columnRepeatParams; + columnRepeatParams.src0BlkStride = 1; + columnRepeatParams.src1BlkStride = 0; + columnRepeatParams.dstBlkStride = 1; + columnRepeatParams.src0RepStride = + 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block + columnRepeatParams.src1RepStride = 0; + columnRepeatParams.dstRepStride = + 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block + uint32_t offset = 0; + for (uint32_t i = 0; i < dealRowCount; i++) { + Div(dstUb[offset], + src0Ub[offset], + src1Ub[i * FP32_BLOCK_ELEMENT_NUM], + dtypeMask, + columnRepeatCount, + columnRepeatParams); + offset += columnCount; + } + } + if (dRemain > 0) { + Div(dstUb[dLoop * dtypeMask], + src0Ub[dLoop * dtypeMask], + src1Ub, + dRemain, + dealRowCount, + repeatParamsDiv); + } +} + +template +__aicore__ inline void SMLAVectorBlock::RowMuls( + LocalTensor dstUb, + LocalTensor src0Ub, + LocalTensor src1Ub, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + // muls by row, 每行的元素乘以相同的元素 + // dstUb[i, (j * 8) : (j * 8 + 7)] = src0Ub[i, (j * 8) : (j * 8 + 7)] * + // src1Ub[i, 0 : 7] src0Ub:[dealRowCount, columnCount] src1Ub:[dealRowCount, + // FP32_BLOCK_ELEMENT_NUM] dstUb:[dealRowCount, columnCount] dealRowCount is + // repeat times, must be less 256 + uint32_t repeatElementNum = FP32_REPEAT_ELEMENT_NUM; + uint32_t blockElementNum = FP32_BLOCK_ELEMENT_NUM; + + if constexpr (std::is_same::value) { + // 此限制由于每个repeat至多连续读取256B数据 + repeatElementNum = FP32_REPEAT_ELEMENT_NUM * 2; // 256/4 * 2=128 + blockElementNum = FP32_BLOCK_ELEMENT_NUM * 2; // 32/4 * 2 = 16 + } + + // 每次只能连续读取256B的数据进行计算,故每次只能处理256B/sizeof(dType)= + // 列方向分dLoop次,每次处理8列数据 + uint32_t dLoop = actualColumnCount / repeatElementNum; + uint32_t dRemain = actualColumnCount % repeatElementNum; + // REPEATE_STRIDE_UP_BOUND=256, + // 此限制由于src0RepStride数据类型为uint8之多256个datablock间距 + if (columnCount < REPEATE_STRIDE_UP_BOUND * blockElementNum) { + BinaryRepeatParams repeatParams; + repeatParams.src0BlkStride = 1; + repeatParams.src1BlkStride = 0; + repeatParams.dstBlkStride = 1; + repeatParams.src0RepStride = columnCount / blockElementNum; + repeatParams.src1RepStride = 1; + repeatParams.dstRepStride = columnCount / blockElementNum; + + // 如果以列为repeat所处理的次数小于行处理次数,则以列方式处理。反之则以行进行repeat处理 + if (dLoop <= dealRowCount) { + uint32_t offset = 0; + for (uint32_t i = 0; i < dLoop; i++) { + Mul(dstUb[offset], + src0Ub[offset], + src1Ub, + repeatElementNum, + dealRowCount, + repeatParams); + offset += repeatElementNum; + } + } else { + BinaryRepeatParams columnRepeatParams; + columnRepeatParams.src0BlkStride = 1; + columnRepeatParams.src1BlkStride = 0; + columnRepeatParams.dstBlkStride = 1; + columnRepeatParams.src0RepStride = + 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block + columnRepeatParams.src1RepStride = 0; + columnRepeatParams.dstRepStride = + 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block + for (uint32_t i = 0; i < dealRowCount; i++) { + Mul(dstUb[i * columnCount], + src0Ub[i * columnCount], + src1Ub[i * blockElementNum], + repeatElementNum, + dLoop, + columnRepeatParams); + } + } + + // 最后一次完成[dealRowCount, dRemain] * [dealRowCount, blockElementNum] + // 只计算有效部分 + if (dRemain > 0) { + Mul(dstUb[dLoop * repeatElementNum], + src0Ub[dLoop * repeatElementNum], + src1Ub, + dRemain, + dealRowCount, + repeatParams); + } + } else { + BinaryRepeatParams repeatParams; + repeatParams.src0RepStride = 8; // 每个repeat为256B数据,正好8个datablock + repeatParams.src0BlkStride = 1; + repeatParams.src1RepStride = 0; + repeatParams.src1BlkStride = 0; + repeatParams.dstRepStride = 8; + repeatParams.dstBlkStride = 1; + // 每次计算一行,共计算dealRowCount行 + for (uint32_t i = 0; i < dealRowCount; i++) { + // 计算一行中的dLoop个repeat, 每个repeat计算256/block_size 个data_block + Mul(dstUb[i * columnCount], + src0Ub[i * columnCount], + src1Ub[i * blockElementNum], + repeatElementNum, + dLoop, + repeatParams); + // 计算一行中的尾块 + if (dRemain > 0) { + Mul(dstUb[i * columnCount + dLoop * repeatElementNum], + src0Ub[i * columnCount + dLoop * repeatElementNum], + src1Ub[i * blockElementNum], + dRemain, + 1, + repeatParams); + } + } + } +} +} // namespace SMLAKernel +#endif // SPARSE_FLASH_MLA_CSA_BLOCK_VECTOR_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_kernel.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_kernel.h new file mode 100644 index 0000000000..7b450273df --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_kernel.h @@ -0,0 +1,1123 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file sparse_flash_mla_csa_kernel.h + * \brief + */ + +#ifndef SPARSE_FLASH_MLA_CSA_KERNEL_H +#define SPARSE_FLASH_MLA_CSA_KERNEL_H + +#include "kernel_operator.h" +#include "kernel_operator_list_tensor_intf.h" +#include "kernel_tiling/kernel_tiling.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" +#include "sparse_flash_mla_arch22_metadata.h" +#include "sparse_flash_mla_common_arch22.h" +#include "sparse_flash_mla_csa_block_cube.h" +#include "sparse_flash_mla_csa_block_vector.h" + +namespace SMLAKernel { +using namespace matmul; +using namespace optiling; +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +// 由于S2循环前,RunInfo还没有赋值,使用Bngs1Param临时存放B、N、S1轴相关的信息;同时减少重复计算 +struct TempLoopInfo { + uint32_t bn2IdxInCurCore = 0; + uint32_t bIdx = 0U; + uint32_t n2Idx = 0U; + uint64_t s2BasicSizeTail = 0U; // S2方向循环的尾基本块大小 + uint32_t s2LoopTimes = + 0U; // S2方向循环的总次数,无论TND还是BXXD都是等于实际次数,不用减1 + + int32_t actS1Size = 0; // TND场景下当前Batch循环处理的S1轴的大小 + int32_t actOriS2Size = 0; + int32_t actCmpS2Size = 0; + + bool curActSeqLenIsZero = false; + + uint32_t tndCoreStartKVSplitPos = 0; + bool tndIsS2SplitCore = false; + uint32_t gS1Idx = 0U; + uint32_t s1StartIdx = 0; + uint32_t s1EndIdx = 0; + uint64_t mBasicSizeTail = 0U; // gS1方向循环的尾基本块大小 + uint32_t cmpLoopTimes = 0; + uint32_t oriLoopTimes = 0; + uint32_t v0OriSize = 0; + uint32_t v0CmpSize = 0; + + // sparsemode = 4 + int32_t oriMaskRight = 0; + int32_t oriMaskLeft = 0; + + // sparsemode = 3 + int32_t cmpMaskRight = 0; + + uint64_t actualSeqQPrefixSum = 0; + uint64_t actualSeqKVPrefixSum = 0; + uint64_t actualSeqCmpKVPrefixSum = 0; +}; + +template +class SparseFlashMlaCsa { + public: + // 中间计算数据类型为float,高精度模式 + using T = float; + using Q_T = typename SMLAT::queryType; + using KV_T = typename SMLAT::kvType; + using OUT_T = typename SMLAT::outputType; + using SINKS_T = float; + using UPDATE_T = T; + using MM1_OUT_T = T; + using MM2_OUT_T = T; + + __aicore__ inline SparseFlashMlaCsa(){}; + __aicore__ inline void Init(__gm__ uint8_t* query, + __gm__ uint8_t* oriKV, + __gm__ uint8_t* cmpKV, + __gm__ uint8_t* oriSparseIndices, + __gm__ uint8_t* cmpSparseIndices, + __gm__ uint8_t* oriBlockTable, + __gm__ uint8_t* cmpBlockTable, + __gm__ uint8_t* cuSeqlensQ, + __gm__ uint8_t* cuSeqlensKV, + __gm__ uint8_t* cuSeqlensCmpKV, + __gm__ uint8_t* seqUsedQ, + __gm__ uint8_t* seqUsedKV, + __gm__ uint8_t* seqUsedCmpKV, + __gm__ uint8_t* cmpResidualKV, + __gm__ uint8_t* oriTopkLength, + __gm__ uint8_t* cmpTopkLength, + __gm__ uint8_t* sinks, + __gm__ uint8_t* metadata, + __gm__ uint8_t* attentionOut, + __gm__ uint8_t* softmaxLse, + __gm__ uint8_t* workspace, + const SparseFlashMlaTilingData* __restrict tiling, + __gm__ uint8_t* gmTiling, + TPipe* tPipe); + + __aicore__ inline void Process(); + + private: + static constexpr bool PAGE_ATTENTION = SMLAT::pageAttention; + static constexpr bool FLASH_DECODE = SMLAT::flashDecode; + static constexpr SMLA_LAYOUT LAYOUT_T = SMLAT::layout; + static constexpr SMLA_LAYOUT KV_LAYOUT_T = SMLAT::kvLayout; + static constexpr bool HEAD_RATIO_ONE = SMLAT::headRatioOne; + + static constexpr uint32_t PRELOAD_NUM = 2; + static constexpr uint32_t N_BUFFER_M_BASIC_SIZE = 256; + static constexpr uint32_t SMLA_PRELOAD_TASK_CACHE_SIZE = 3; + static constexpr uint32_t MERGE_CACHE_GM_BUF_NUM = 3; + + static constexpr uint32_t SYNC_V0_C1_FLAG = 6; + static constexpr uint32_t SYNC_C1_V1_FLAG = 7; + static constexpr uint32_t SYNC_V1_C2_FLAG = 8; + static constexpr uint32_t SYNC_C2_V2_FLAG = 9; + + static constexpr uint64_t headDim = 512ULL; + + static constexpr uint32_t dbWorkspaceRatio = PRELOAD_NUM; + + const SparseFlashMlaTilingData* __restrict tilingData = nullptr; + + TPipe* pipe = nullptr; + GlobalTensor metadataGm; + uint64_t mSizeVStart = 0ULL; + uint64_t topKBaseOffset = 0ULL; + uint64_t tensorACoreOffset = 0ULL; + uint64_t tensorBCoreOffset = 0ULL; + uint64_t tensorCmpBCoreOffset = 0ULL; + + uint32_t tmpBlockIdx = 0U; + uint32_t aiCoreIdx = 0U; + + ConstInfo constInfo{}; + TempLoopInfo tempLoopInfo{}; + + SMLACubeBlock cubeBlock; + SMLAVectorBlock vectorBlock; + + GlobalTensor queryGm; + GlobalTensor oriKvGm; + GlobalTensor cmpKvGm; + GlobalTensor sinksGm; + + GlobalTensor attentionOutGm; + GlobalTensor softmaxLseGm; + + GlobalTensor oriBlockTableGm; + GlobalTensor cmpBlockTableGm; + GlobalTensor topKGm; + + GlobalTensor actualSeqLengthsQGm; + GlobalTensor actualSeqLengthsKVGm; + GlobalTensor actualSeqLengthsCmpKVGm; + GlobalTensor cmpResidualKVGm; + + // workspace + GlobalTensor mm1ResGm; + GlobalTensor vec1ResGm; + GlobalTensor mm2ResGm; + GlobalTensor kvMergeGm_; + + GlobalTensor vec2ResGm; + + GlobalTensor accumOutGm; + + // ================================Init + // functions================================== + __aicore__ inline void InitTilingData(); + __aicore__ inline void InitCalcParamsEach(); + __aicore__ inline void InitBuffers(); + __aicore__ inline void InitActualSeqLen(__gm__ uint8_t* actualSeqLengthsQ, + __gm__ uint8_t* actualSeqLengthsKV); + __aicore__ inline void InitActualSeqLen( + __gm__ uint8_t* actualSeqLengthsQ, + __gm__ uint8_t* actualSeqLengthsKV, + __gm__ uint8_t* actualSeqLengthsCmpKV); + __aicore__ inline void InitOutputSingleCore(); + // ================================Process + // functions================================ + __aicore__ inline void ProcessBalance(); + __aicore__ inline void PreloadPipeline( + uint32_t loop, + uint32_t cmpLoop, + uint64_t s2Start, + uint64_t s2LoopIdx, + RunInfo extraInfo[SMLA_PRELOAD_TASK_CACHE_SIZE]); + // ================================Offset + // Calc===================================== + __aicore__ inline void GetSparseActualSeqLen(); + __aicore__ inline void UpdateInnerLoopCond(); + __aicore__ inline void CalcParams(uint32_t loop, + uint32_t cmpLoop, + uint64_t s2Start, + uint32_t s2LoopIdx, + RunInfo& info); + __aicore__ inline int32_t GetActualSeqLenQ(uint32_t bIdx); + __aicore__ inline int32_t GetActualSeqLenKV(uint32_t bIdx); + __aicore__ inline int32_t GetActualSeqLenCmpKV(uint32_t bIdx, + int32_t actualOriS2Size); + __aicore__ inline int32_t GetCmpMaskS2Size(uint32_t bIdx, + int32_t actualOriS2Size, + int32_t actualCmpS2Size); + __aicore__ inline void GetBN2Idx(uint32_t bN2Idx, + uint32_t& bIdx, + uint32_t& n2Idx); + // ================================Mm1============================================== + __aicore__ inline void ComputeMm1(const RunInfo& info); + // ================================Mm2============================================== + __aicore__ inline void ComputeMm2(const RunInfo& info); + __aicore__ inline void InitAllZeroOutput(uint32_t bIdx, + uint32_t s1Idx, + uint32_t n2Idx); +}; + +template +__aicore__ inline void SparseFlashMlaCsa::InitTilingData() { + // singleCoreParams + // singleCoreTensorSize + constInfo.mmResUbSize = tilingData->baseParams.mmResUbSize; + constInfo.bmm2ResUbSize = tilingData->baseParams.bmm2ResUbSize; + + // baseParams + constInfo.batchSize = tilingData->baseParams.batchSize; + constInfo.gSize = tilingData->baseParams.nNumOfQInOneGroup; + constInfo.kvHeadNum = (tilingData->baseParams.kvHeadNum == 0) + ? 1 + : tilingData->baseParams.kvHeadNum; + constInfo.qHeadNum = constInfo.gSize * constInfo.kvHeadNum; + constInfo.kvSeqSize = tilingData->baseParams.kvSeqSize; + constInfo.qSeqSize = tilingData->baseParams.qSeqSize; + constInfo.oriMaxBlockNumPerBatch = + tilingData->baseParams.oriMaxBlockNumPerBatch; + constInfo.cmpMaxBlockNumPerBatch = + tilingData->cmpParams.cmpMaxBlockNumPerBatch; + constInfo.kvCacheBlockSize = tilingData->baseParams.paBlockSize; + constInfo.paOriBlockSize = tilingData->baseParams.oriBlockSize; + constInfo.paCmpBlockSize = tilingData->baseParams.cmpBlockSize; + constInfo.outputLayout = + static_cast(tilingData->baseParams.outputLayout); + constInfo.headDim = headDim; + constInfo.oriMaskMode = tilingData->baseParams.oriMaskMode; + constInfo.oriKvStride0 = tilingData->baseParams.oriKvStride0; + constInfo.oriWinLeft = tilingData->baseParams.oriWinLeft; + constInfo.oriWinRight = tilingData->baseParams.oriWinRight; + + constInfo.actualLenDimsQ = tilingData->baseParams.actualLenDimsQ; + constInfo.actualLenDimsKV = tilingData->baseParams.actualLenDimsKV; + constInfo.actualLenDimsCmpKV = tilingData->baseParams.actualLenDimsCmpKV; + constInfo.cmpResidualKVSize = tilingData->baseParams.cmpResidualKVSize; + constInfo.returnSoftmaxLse = tilingData->baseParams.returnSoftmaxLse; + // innerSplitParams + constInfo.mBaseSize = constInfo.gSize; + constInfo.s2BaseSize = tilingData->baseParams.s2BaseSize; + + constInfo.preLoadNum = PRELOAD_NUM; + constInfo.nBufferMBaseSize = N_BUFFER_M_BASIC_SIZE; + constInfo.syncV0C1 = SYNC_V0_C1_FLAG; + constInfo.syncC1V1 = SYNC_C1_V1_FLAG; + constInfo.syncV1C2 = SYNC_V1_C2_FLAG; + constInfo.syncC2V2 = SYNC_C2_V2_FLAG; + + // cmp + constInfo.cmpRatio = tilingData->cmpParams.cmpRatio; + constInfo.sparseBlockCount = tilingData->cmpParams.sparseBlockCount; + constInfo.sparseBlockSize = 1; // sparseBlockSize 固定为1 + constInfo.cmpMaskMode = tilingData->cmpParams.cmpMaskMode; + constInfo.cmpKvStride0 = tilingData->cmpParams.cmpKvStride0; + constInfo.cmpSeqSize = tilingData->cmpParams.cmpKvSeqSize; +} + +template +__aicore__ inline void SparseFlashMlaCsa::InitBuffers() { + if ASCEND_IS_AIV { + vectorBlock.InitBuffers(pipe); + } else { + cubeBlock.InitBuffers(pipe); + } +} + +template +__aicore__ inline void SparseFlashMlaCsa::InitActualSeqLen( + __gm__ uint8_t* actualSeqLengthsQ, + __gm__ uint8_t* actualSeqLengthsKV) { + if (constInfo.actualLenDimsKV != 0) { + actualSeqLengthsKVGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsKV, + constInfo.actualLenDimsKV); + } + if (constInfo.actualLenDimsQ != 0) { + actualSeqLengthsQGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsQ, + constInfo.actualLenDimsQ); + } +} + +template +__aicore__ inline void SparseFlashMlaCsa::InitActualSeqLen( + __gm__ uint8_t* actualSeqLengthsQ, + __gm__ uint8_t* actualSeqLengthsKV, + __gm__ uint8_t* actualSeqLengthsCmpKV) { + if (constInfo.actualLenDimsKV != 0) { + actualSeqLengthsKVGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsKV, + constInfo.actualLenDimsKV); + } + if (constInfo.actualLenDimsCmpKV != 0) { + actualSeqLengthsCmpKVGm.SetGlobalBuffer( + (__gm__ int32_t*)actualSeqLengthsCmpKV, constInfo.actualLenDimsCmpKV); + } + if (constInfo.actualLenDimsQ != 0) { + actualSeqLengthsQGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsQ, + constInfo.actualLenDimsQ); + } +} + +template +__aicore__ inline void SparseFlashMlaCsa::InitAllZeroOutput( + uint32_t bIdx, + uint32_t s1Idx, + uint32_t n2Idx) { + if (constInfo.outputLayout == SMLA_LAYOUT::TND) { + if (tempLoopInfo.actS1Size == 0) { + return; + } + uint32_t tBase = actualSeqLengthsQGm.GetValue(bIdx); + uint32_t s1Count = tempLoopInfo.actS1Size; + + uint64_t attenOutOffset = (tBase + s1Idx) * constInfo.kvHeadNum * + constInfo.gSize * constInfo.headDim + + n2Idx * constInfo.gSize * constInfo.headDim; + uint64_t lseOffset = + (tBase + s1Idx) * constInfo.gSize + // T轴、s1轴偏移 + n2Idx * constInfo.qSeqSize * constInfo.gSize; // N2轴偏移 + matmul::InitOutput( + attentionOutGm[attenOutOffset], constInfo.gSize * constInfo.headDim, 0); + if (constInfo.returnSoftmaxLse) { + matmul::InitOutput(softmaxLseGm[lseOffset], constInfo.gSize, 0); + } + } else if (constInfo.outputLayout == SMLA_LAYOUT::BSND) { + uint64_t attenOutOffset = + bIdx * constInfo.qSeqSize * constInfo.kvHeadNum * constInfo.gSize * + constInfo.headDim + + s1Idx * constInfo.kvHeadNum * constInfo.gSize * constInfo.headDim + + n2Idx * constInfo.gSize * constInfo.headDim; + uint64_t lseOffset = + bIdx * constInfo.qSeqSize * constInfo.kvHeadNum * + constInfo.gSize + // B轴偏移 + n2Idx * constInfo.qSeqSize * constInfo.gSize + // N2轴偏移 + s1Idx * constInfo.gSize; // S1轴偏移 + matmul::InitOutput( + attentionOutGm[attenOutOffset], constInfo.gSize * constInfo.headDim, 0); + if (constInfo.returnSoftmaxLse) { + matmul::InitOutput(softmaxLseGm[lseOffset], constInfo.gSize, 0); + } + } +} + +template +__aicore__ inline void SparseFlashMlaCsa::InitOutputSingleCore() { + uint32_t coreNum = GetBlockNum(); + if (coreNum != 0) { + uint64_t totalOutputSize = constInfo.batchSize * constInfo.qHeadNum * + constInfo.qSeqSize * constInfo.headDim; + uint64_t singleCoreSize = (totalOutputSize + (2 * coreNum) - 1) / + (2 * coreNum); // 2 means c:v = 1:2 + uint64_t tailSize = totalOutputSize - tmpBlockIdx * singleCoreSize; + uint64_t singleInitOutputSize = + tailSize < singleCoreSize ? tailSize : singleCoreSize; + if (singleInitOutputSize > 0) { + matmul::InitOutput(attentionOutGm[tmpBlockIdx * singleCoreSize], + singleInitOutputSize, + 0); + } + SyncAll(); + } +} + +template +__aicore__ inline int32_t SparseFlashMlaCsa::GetActualSeqLenQ( + uint32_t bIdx) { + if constexpr (LAYOUT_T == SMLA_LAYOUT::TND) { + int32_t actualSeqQPrefixSum = actualSeqLengthsQGm.GetValue(bIdx); + int32_t actualSeqQNextSum = actualSeqLengthsQGm.GetValue(bIdx + 1); + tempLoopInfo.actualSeqQPrefixSum = + static_cast(actualSeqQPrefixSum); + return actualSeqQNextSum - actualSeqQPrefixSum; + } else { + tempLoopInfo.actualSeqQPrefixSum = + static_cast(bIdx * constInfo.qSeqSize); + if (constInfo.actualLenDimsQ == 0) { + return static_cast(constInfo.qSeqSize); + } else { + return actualSeqLengthsQGm.GetValue(bIdx); + } + } +} + +template +__aicore__ inline int32_t SparseFlashMlaCsa::GetActualSeqLenKV( + uint32_t bIdx) { + if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { + tempLoopInfo.actualSeqKVPrefixSum = + static_cast(bIdx * constInfo.kvSeqSize); + if (constInfo.actualLenDimsKV == 0) { + return static_cast(constInfo.kvSeqSize); + } + return actualSeqLengthsKVGm.GetValue(bIdx); + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { + tempLoopInfo.actualSeqKVPrefixSum = + static_cast(bIdx * constInfo.kvSeqSize); + if (constInfo.actualLenDimsKV != 0) { + return actualSeqLengthsKVGm.GetValue(bIdx); + } + return static_cast(constInfo.kvSeqSize); + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { + int32_t actualSeqKVPrefixSum = actualSeqLengthsKVGm.GetValue(bIdx); + int32_t actualSeqKVNextSum = actualSeqLengthsKVGm.GetValue(bIdx + 1); + tempLoopInfo.actualSeqKVPrefixSum = actualSeqKVPrefixSum; + return actualSeqKVNextSum - actualSeqKVPrefixSum; + } +} + +template +__aicore__ inline int32_t SparseFlashMlaCsa::GetActualSeqLenCmpKV( + uint32_t bIdx, + int32_t actualOriS2Size) { + (void)actualOriS2Size; + if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { + int32_t actualSeqCmpKVPrefixSum = actualSeqLengthsCmpKVGm.GetValue(bIdx); + int32_t actualSeqCmpKVNextSum = actualSeqLengthsCmpKVGm.GetValue(bIdx + 1); + tempLoopInfo.actualSeqCmpKVPrefixSum = actualSeqCmpKVPrefixSum; + return actualSeqCmpKVNextSum - actualSeqCmpKVPrefixSum; + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { + tempLoopInfo.actualSeqCmpKVPrefixSum = + static_cast(bIdx * constInfo.cmpSeqSize); + if (constInfo.actualLenDimsCmpKV != 0) { + return actualSeqLengthsCmpKVGm.GetValue(bIdx); + } + return static_cast(constInfo.cmpSeqSize); + } else { + tempLoopInfo.actualSeqCmpKVPrefixSum = + static_cast(bIdx * constInfo.cmpSeqSize); + if (constInfo.actualLenDimsCmpKV != 0) { + return actualSeqLengthsCmpKVGm.GetValue(bIdx); + } + return (constInfo.cmpSeqSize != 0) + ? static_cast(constInfo.cmpSeqSize) + : actualOriS2Size / static_cast(constInfo.cmpRatio); + } +} + +template +__aicore__ inline int32_t SparseFlashMlaCsa::GetCmpMaskS2Size( + uint32_t bIdx, + int32_t actualOriS2Size, + int32_t actualCmpS2Size) { + (void)actualOriS2Size; + int32_t residual = 0; + if (constInfo.cmpResidualKVSize != 0) { + residual = cmpResidualKVGm.GetValue(bIdx); + } + return actualCmpS2Size * static_cast(constInfo.cmpRatio) + residual; +} + +template +__aicore__ inline void SparseFlashMlaCsa::GetSparseActualSeqLen() { + // 行无效通过ori部分判断, ori部分如果有行无效那么ori和cmp都有 + if (static_cast(tempLoopInfo.s1EndIdx) < + -(tempLoopInfo.actOriS2Size - tempLoopInfo.actS1Size)) { + tempLoopInfo.actOriS2Size = 0; + tempLoopInfo.actCmpS2Size = 0; + return; + } + + // 对于cmp部分还有top k, tempLoopInfo.actS2Size只针对cmp + int32_t thresHold = (tempLoopInfo.cmpMaskRight + tempLoopInfo.s1EndIdx + 1) / + constInfo.cmpRatio; + tempLoopInfo.actCmpS2Size = + Min(tempLoopInfo.actCmpS2Size, + Min(constInfo.sparseBlockCount * constInfo.sparseBlockSize, + Max(thresHold, 0))); +} + +template +__aicore__ inline void SparseFlashMlaCsa::UpdateInnerLoopCond() { + if ((tempLoopInfo.actCmpS2Size == 0 && tempLoopInfo.actOriS2Size == 0) || + (tempLoopInfo.actS1Size == 0)) { + tempLoopInfo.curActSeqLenIsZero = true; + return; + } + tempLoopInfo.curActSeqLenIsZero = false; + tempLoopInfo.mBasicSizeTail = + (tempLoopInfo.actS1Size * constInfo.gSize) % constInfo.mBaseSize; + tempLoopInfo.mBasicSizeTail = (tempLoopInfo.mBasicSizeTail == 0) + ? constInfo.mBaseSize + : tempLoopInfo.mBasicSizeTail; +} + +template +__aicore__ inline void SparseFlashMlaCsa::Init( + __gm__ uint8_t* query, + __gm__ uint8_t* oriKV, + __gm__ uint8_t* cmpKV, + __gm__ uint8_t* oriSparseIndices, + __gm__ uint8_t* cmpSparseIndices, + __gm__ uint8_t* oriBlockTable, + __gm__ uint8_t* cmpBlockTable, + __gm__ uint8_t* cuSeqlensQ, + __gm__ uint8_t* cuSeqlensKV, + __gm__ uint8_t* cuSeqlensCmpKV, + __gm__ uint8_t* seqUsedQ, + __gm__ uint8_t* seqUsedKV, + __gm__ uint8_t* seqUsedCmpKV, + __gm__ uint8_t* cmpResidualKV, + __gm__ uint8_t* oriTopkLength, + __gm__ uint8_t* cmpTopkLength, + __gm__ uint8_t* sinks, + __gm__ uint8_t* metadata, + __gm__ uint8_t* attentionOut, + __gm__ uint8_t* softmaxLse, + __gm__ uint8_t* workspace, + const SparseFlashMlaTilingData* __restrict tiling, + __gm__ uint8_t* gmTiling, + TPipe* tPipe) { + if ASCEND_IS_AIV { + tmpBlockIdx = GetBlockIdx(); // vec:0-47 + aiCoreIdx = tmpBlockIdx / 2; + } else { + tmpBlockIdx = GetBlockIdx(); // cube:0-23 + aiCoreIdx = tmpBlockIdx; + } + + // init tiling data + tilingData = tiling; + InitTilingData(); + if (KV_LAYOUT_T == SMLA_LAYOUT::TND && LAYOUT_T == SMLA_LAYOUT::TND) { + InitActualSeqLen(cuSeqlensQ, cuSeqlensKV, cuSeqlensCmpKV); + } else if (KV_LAYOUT_T == SMLA_LAYOUT::TND) { + InitActualSeqLen(seqUsedQ, cuSeqlensKV, cuSeqlensCmpKV); + } else if ((KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND || + KV_LAYOUT_T == SMLA_LAYOUT::BSND) && + LAYOUT_T == SMLA_LAYOUT::TND) { + InitActualSeqLen(cuSeqlensQ, seqUsedKV, seqUsedCmpKV); + } else if ((KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND || + KV_LAYOUT_T == SMLA_LAYOUT::BSND)) { + InitActualSeqLen(seqUsedQ, seqUsedKV, seqUsedCmpKV); + } + + metadataGm.SetGlobalBuffer((__gm__ uint32_t*)metadata); + InitCalcParamsEach(); + + pipe = tPipe; + // init global buffer + queryGm.SetGlobalBuffer((__gm__ Q_T*)query); + oriKvGm.SetGlobalBuffer((__gm__ KV_T*)oriKV); + cmpKvGm.SetGlobalBuffer((__gm__ KV_T*)cmpKV); + if (constInfo.cmpResidualKVSize != 0) { + cmpResidualKVGm.SetGlobalBuffer((__gm__ int32_t*)cmpResidualKV, + constInfo.cmpResidualKVSize); + } + + if (sinks != nullptr) { + sinksGm.SetGlobalBuffer((__gm__ SINKS_T*)sinks); + } + + attentionOutGm.SetGlobalBuffer((__gm__ OUT_T*)attentionOut); + softmaxLseGm.SetGlobalBuffer((__gm__ T*)softmaxLse); + + if ASCEND_IS_AIV { + if (LAYOUT_T != SMLA_LAYOUT::TND) { + if (constInfo.needInit) { + InitOutputSingleCore(); + } + } + } + + if constexpr (PAGE_ATTENTION) { + oriBlockTableGm.SetGlobalBuffer((__gm__ int32_t*)oriBlockTable); + cmpBlockTableGm.SetGlobalBuffer((__gm__ int32_t*)cmpBlockTable); + } + topKGm.SetGlobalBuffer((__gm__ int32_t*)cmpSparseIndices); + + // workspace 内存排布 + // |Q--|mm1ResGm|vec1ResGm|mm2ResGm|vec2ResGm + // |Core0_Q1-Core0_Q2-Core1_Q1-Core1_Q2....Core32_Q1-Core32_Q2|Core0_mmRes + uint64_t offset = 0; + mm1ResGm.SetGlobalBuffer( + (__gm__ MM1_OUT_T*)(workspace + offset + + aiCoreIdx * dbWorkspaceRatio * constInfo.mmResUbSize * + sizeof(MM1_OUT_T))); + offset += GetBlockNum() * dbWorkspaceRatio * constInfo.mmResUbSize * + sizeof(MM1_OUT_T); + + vec1ResGm.SetGlobalBuffer( + (__gm__ Q_T*)(workspace + offset + + aiCoreIdx * dbWorkspaceRatio * constInfo.mmResUbSize * + sizeof(KV_T))); + offset += + GetBlockNum() * dbWorkspaceRatio * constInfo.mmResUbSize * sizeof(KV_T); + + mm2ResGm.SetGlobalBuffer((__gm__ MM2_OUT_T*)(workspace + offset + + aiCoreIdx * dbWorkspaceRatio * + constInfo.bmm2ResUbSize * + sizeof(MM2_OUT_T))); + offset += GetBlockNum() * dbWorkspaceRatio * constInfo.bmm2ResUbSize * + sizeof(MM2_OUT_T); + + vec2ResGm.SetGlobalBuffer( + (__gm__ T*)(workspace + offset + + aiCoreIdx * dbWorkspaceRatio * constInfo.bmm2ResUbSize * + sizeof(T))); + offset += + GetBlockNum() * dbWorkspaceRatio * constInfo.bmm2ResUbSize * sizeof(T); + + kvMergeGm_.SetGlobalBuffer( + (__gm__ KV_T*)(workspace + offset + + aiCoreIdx * 512 * 512 * MERGE_CACHE_GM_BUF_NUM * + sizeof(KV_T))); + offset += GetBlockNum() * 512 * 512 * 4 * sizeof(KV_T); + + if ASCEND_IS_AIV { + vectorBlock.InitParams(constInfo, tilingData); + vectorBlock.InitVec0GlobalTensor( + kvMergeGm_, oriKvGm, cmpKvGm, oriBlockTableGm, cmpBlockTableGm); + vectorBlock.InitVec1GlobalTensor(mm1ResGm, + vec1ResGm, + actualSeqLengthsQGm, + actualSeqLengthsKVGm, + topKGm, + sinksGm, + softmaxLseGm); + vectorBlock.InitVec2GlobalTensor( + accumOutGm, vec2ResGm, mm2ResGm, attentionOutGm); + } + + if ASCEND_IS_AIC { + cubeBlock.InitParams(constInfo); + cubeBlock.InitMm1GlobalTensor(queryGm, oriKvGm, cmpKvGm, mm1ResGm); + cubeBlock.InitMm2GlobalTensor(vec1ResGm, mm2ResGm, attentionOutGm); + cubeBlock.InitPageAttentionInfo( + oriKvGm, kvMergeGm_, oriBlockTableGm, cmpBlockTableGm); + } + // 要在InitParams之后执行 + if (pipe != nullptr) { + InitBuffers(); + } +} + +template +__aicore__ inline void SparseFlashMlaCsa::InitCalcParamsEach() { + if (aiCoreIdx != 0) { + constInfo.bN2Start = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, FA_BN2_START_INDEX, false)); + constInfo.gS1Start = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, FA_M_START_INDEX, false)); + constInfo.s2Start = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, FA_S2_START_INDEX, false)); + } + constInfo.bN2End = + metadataGm.GetValue(GetAttrAbsIndex(aiCoreIdx, FA_BN2_END_INDEX, false)); + constInfo.gS1End = + metadataGm.GetValue(GetAttrAbsIndex(aiCoreIdx, FA_M_END_INDEX, false)); + constInfo.s2End = + metadataGm.GetValue(GetAttrAbsIndex(aiCoreIdx, FA_S2_END_INDEX, false)); +} + +template +__aicore__ inline void SparseFlashMlaCsa::CalcParams(uint32_t loop, + uint32_t cmpLoop, + uint64_t s2Start, + uint32_t s2LoopIdx, + RunInfo& info) { + info.isValid = s2LoopIdx < tempLoopInfo.s2LoopTimes; + info.loop = loop; + info.cmpLoop = cmpLoop; + info.bIdx = tempLoopInfo.bIdx; + info.n2IdxReal = tempLoopInfo.n2Idx; + + info.gS1Idx = tempLoopInfo.gS1Idx; + info.s1Idx = tempLoopInfo.gS1Idx / constInfo.gSize; + info.s2Idx = s2LoopIdx; + info.curSInnerLoopTimes = tempLoopInfo.s2LoopTimes; + info.tndIsS2SplitCore = tempLoopInfo.tndIsS2SplitCore; + info.tndCoreStartKVSplitPos = tempLoopInfo.tndCoreStartKVSplitPos; + info.isBmm2Output = false; + info.actS1Size = tempLoopInfo.actS1Size; + + // M方向的尾块 + info.actMBaseSize = tempLoopInfo.mBasicSizeTail; + + if ASCEND_IS_AIV { + info.mSize = info.actMBaseSize; + info.mSizeV = (info.mSize <= 16) ? info.mSize + : ((CeilDiv(info.mSize, 16) + 1) / 2 * 16); + info.mSizeVStart = 0; + if (tmpBlockIdx % 2 == 1) { + info.mSizeVStart = info.mSizeV; + info.mSizeV = info.mSize - info.mSizeV; + } + } + + info.isFirstSInnerLoop = s2LoopIdx == s2Start; + if (info.isFirstSInnerLoop) { + tempLoopInfo.bn2IdxInCurCore++; + } + info.isLastS2Loop = (s2LoopIdx == (tempLoopInfo.s2LoopTimes - 1)); + info.bn2IdxInCurCore = tempLoopInfo.bn2IdxInCurCore - 1; + + uint64_t tndBIdxOffsetForQ = + tempLoopInfo.actualSeqQPrefixSum * constInfo.qHeadNum * constInfo.headDim; + uint64_t tndBIdxOffsetForKV = tempLoopInfo.actualSeqKVPrefixSum * + constInfo.kvHeadNum * constInfo.headDim; + uint64_t tndBIdxOffsetForCmpKV = tempLoopInfo.actualSeqCmpKVPrefixSum * + constInfo.kvHeadNum * constInfo.headDim; + + if (info.isFirstSInnerLoop) { + uint64_t s1HeadOffset = + (info.gS1Idx / constInfo.gSize) * constInfo.qHeadNum; + uint64_t qHeadOffset = + info.n2Idx * constInfo.gSize + info.gS1Idx % constInfo.gSize; + tensorACoreOffset = + tndBIdxOffsetForQ + (s1HeadOffset + qHeadOffset) * constInfo.headDim; + tensorBCoreOffset = + tndBIdxOffsetForKV + + info.n2Idx * constInfo.headDim; // 当前为PA场景,该变量失效 + tensorCmpBCoreOffset = + tndBIdxOffsetForCmpKV + info.n2Idx * constInfo.headDim; + if constexpr (LAYOUT_T == SMLA_LAYOUT::BSND) { // B,S1,N2 K + topKBaseOffset = + (info.bIdx * constInfo.qSeqSize + tempLoopInfo.s1StartIdx) * + constInfo.kvHeadNum * constInfo.sparseBlockCount + + info.n2Idx * constInfo.sparseBlockCount; + } else if (LAYOUT_T == SMLA_LAYOUT::TND) { // T N2 K + topKBaseOffset = + (tempLoopInfo.actualSeqQPrefixSum + tempLoopInfo.s1StartIdx) * + constInfo.kvHeadNum * constInfo.sparseBlockCount + + info.n2Idx * constInfo.sparseBlockCount; + } + } + info.tensorAOffset = tensorACoreOffset; + info.tensorBOffset = tensorBCoreOffset; + info.tensorCmpBOffset = tensorCmpBCoreOffset; + info.attenOutOffset = tensorACoreOffset; + info.topKBaseOffset = topKBaseOffset; + + if (s2LoopIdx < tempLoopInfo.oriLoopTimes) { + // S2首次循环只能在ori_kv + info.isOriOnly = true; + info.relativeS2Idx = 0; + uint64_t s2Offset = info.s2Idx * constInfo.s2BaseSize; + if (s2LoopIdx + 1 == tempLoopInfo.oriLoopTimes) { + info.actualSingleProcessSInnerSize = + (tempLoopInfo.oriMaskRight - tempLoopInfo.oriMaskLeft + 1) - s2Offset; + } else { + info.actualSingleProcessSInnerSize = constInfo.s2BaseSize; + } + info.s2StartPoint = tempLoopInfo.oriMaskLeft; + info.cmpS2IdLimit = + (tempLoopInfo.cmpMaskRight + tempLoopInfo.s1EndIdx + 1) / + constInfo.cmpRatio; + } else { + info.isOriOnly = false; + info.relativeS2Idx = info.s2Idx - tempLoopInfo.oriLoopTimes; + uint64_t s2Offset = + (info.s2Idx - tempLoopInfo.oriLoopTimes) * constInfo.s2BaseSize; + if (s2LoopIdx + 1 == tempLoopInfo.s2LoopTimes) { + info.actualSingleProcessSInnerSize = tempLoopInfo.actCmpS2Size - s2Offset; + } else { + info.actualSingleProcessSInnerSize = constInfo.s2BaseSize; + } + info.s2StartPoint = 0; + info.cmpS2IdLimit = + (tempLoopInfo.cmpMaskRight + tempLoopInfo.s1EndIdx + 1) / + constInfo.cmpRatio; + // Each compressed block reads its own slice, including a partial final + // block. + info.v0S2Start = static_cast(s2Offset); + info.v0S2DealSize = + static_cast(info.actualSingleProcessSInnerSize); + } + + info.actualSingleProcessSInnerSizeAlign = SMLAAlign( + info.actualSingleProcessSInnerSize, SMLAVectorBlock::BYTE_BLOCK); + if (info.isOriOnly) { + info.v0S2Start = 0; + info.v0S2DealSize = 0; + } +} + +template +__aicore__ inline void SparseFlashMlaCsa::ComputeMm1( + const RunInfo& info) { + uint32_t nBufferLoopTimes = + CeilDiv(info.actMBaseSize, constInfo.nBufferMBaseSize); + uint32_t nBufferTail = + info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; + for (uint32_t i = 0; i < nBufferLoopTimes; i++) { + MSplitInfo mSplitInfo; + mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; + mSplitInfo.nBufferDealM = + (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; + cubeBlock.ComputeMm1(info, mSplitInfo); + if constexpr (HEAD_RATIO_ONE) { + event_t eventIdFixWait = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::FIX_M)); + SetFlag(eventIdFixWait); + WaitFlag(eventIdFixWait); + } + CrossCoreSetFlag(constInfo.syncC1V1); + } +} + +template +__aicore__ inline void SparseFlashMlaCsa::ComputeMm2( + const RunInfo& info) { + uint32_t nBufferLoopTimes = + (info.actMBaseSize + constInfo.nBufferMBaseSize - 1) / + constInfo.nBufferMBaseSize; + uint32_t nBufferTail = + info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; + for (uint32_t i = 0; i < nBufferLoopTimes; i++) { + MSplitInfo mSplitInfo; + mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; + mSplitInfo.nBufferDealM = + (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; + if constexpr (HEAD_RATIO_ONE) { + CrossCoreWaitFlag( + constInfo.syncV1C2); + } else { + CrossCoreWaitFlag(constInfo.syncV1C2); + } + cubeBlock.ComputeMm2(info, mSplitInfo); + if constexpr (HEAD_RATIO_ONE) { + event_t eventIdFixWait = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::FIX_M)); + SetFlag(eventIdFixWait); + WaitFlag(eventIdFixWait); + } + CrossCoreSetFlag(constInfo.syncC2V2); + } +} + +template +__aicore__ inline void SparseFlashMlaCsa::Process() { + uint32_t hasLoad = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, FA_CORE_ENABLE_INDEX, false)); + if (hasLoad == 0) { + return; + } + if ASCEND_IS_AIV { + vectorBlock.AllocEventID(); + vectorBlock.InitSoftmaxDefaultBuffer(); + } else { + cubeBlock.AllocEventID(); + } + ProcessBalance(); + if ASCEND_IS_AIV { + vectorBlock.FreeEventID(); + } else { + cubeBlock.FreeEventID(); + } +} + +template +__aicore__ inline void SparseFlashMlaCsa::GetBN2Idx(uint32_t bN2Idx, + uint32_t& bIdx, + uint32_t& n2Idx) { + bIdx = bN2Idx / constInfo.kvHeadNum; + n2Idx = bN2Idx % constInfo.kvHeadNum; +} + +template +__aicore__ inline void SparseFlashMlaCsa::ProcessBalance() { + RunInfo extraInfo[SMLA_PRELOAD_TASK_CACHE_SIZE]; + uint32_t gloop = 0; + uint32_t cmpLoop = 0; + uint32_t gS1LoopEnd = 0; + bool globalLoopStart = true; + + if ASCEND_IS_AIC { + CrossCoreSetFlag(3); + CrossCoreSetFlag(3); + CrossCoreSetFlag(3); + CrossCoreSetFlag(3); + } + + // 适配左闭右开 + if (constInfo.bN2Start == constInfo.bN2End) { + if (constInfo.gS1Start != constInfo.gS1End || + constInfo.s2Start != constInfo.s2End) { + constInfo.bN2End += 1; + } + } else if ((constInfo.gS1End != 0) || (constInfo.s2End != 0)) { + constInfo.bN2End += 1; + } + + for (uint32_t bN2LoopIdx = constInfo.bN2Start; bN2LoopIdx < constInfo.bN2End; + bN2LoopIdx++) { + GetBN2Idx(bN2LoopIdx, tempLoopInfo.bIdx, tempLoopInfo.n2Idx); + tempLoopInfo.actS1Size = + GetActualSeqLenQ(tempLoopInfo.bIdx); // 获取actualSeqLength + bool isS1ZeroAndLastBatch = + (tempLoopInfo.actS1Size == 0) && + ((constInfo.outputLayout == SMLA_LAYOUT::BSND) || + (bN2LoopIdx + 1 == constInfo.bN2End)); + uint32_t gS1SplitNum = + CeilDiv(tempLoopInfo.actS1Size * constInfo.gSize, constInfo.mBaseSize); + + // 当处于最后一个BN2时, 且gS1End为0时, 说明当前BN2里的所有数据都在当前核处理 + gS1LoopEnd = (bN2LoopIdx + 1 == constInfo.bN2End && constInfo.gS1End != 0) + ? constInfo.gS1End + : gS1SplitNum; + // 当处于最后一个BN2且当前S1为0时,需要进入循环计算preload导致的未完成的部分 + gS1LoopEnd = isS1ZeroAndLastBatch ? gS1LoopEnd + 1 : gS1LoopEnd; + for (uint32_t gS1LoopIdx = constInfo.gS1Start; gS1LoopIdx < gS1LoopEnd; + gS1LoopIdx++) { + tempLoopInfo.actOriS2Size = GetActualSeqLenKV(tempLoopInfo.bIdx); + tempLoopInfo.actCmpS2Size = + GetActualSeqLenCmpKV(tempLoopInfo.bIdx, tempLoopInfo.actOriS2Size); + // 计算需要的数据, 避免重复计算 + tempLoopInfo.gS1Idx = gS1LoopIdx * constInfo.mBaseSize; + tempLoopInfo.s1StartIdx = tempLoopInfo.gS1Idx / constInfo.gSize; + tempLoopInfo.s1EndIdx = Min( + (tempLoopInfo.s1StartIdx + constInfo.mBaseSize / constInfo.gSize - 1), + tempLoopInfo.actS1Size - 1); + + // 此处均为闭区间 + tempLoopInfo.oriMaskRight = + tempLoopInfo.actOriS2Size - tempLoopInfo.actS1Size + + static_cast(tempLoopInfo.s1EndIdx) + constInfo.oriWinRight; + tempLoopInfo.oriMaskLeft = + Max(tempLoopInfo.actOriS2Size - tempLoopInfo.actS1Size + + static_cast(tempLoopInfo.s1EndIdx) - + constInfo.oriWinLeft, + 0); + int32_t cmpMaskS2Size = GetCmpMaskS2Size(tempLoopInfo.bIdx, + tempLoopInfo.actOriS2Size, + tempLoopInfo.actCmpS2Size); + tempLoopInfo.cmpMaskRight = cmpMaskS2Size - tempLoopInfo.actS1Size; + GetSparseActualSeqLen(); + UpdateInnerLoopCond(); + + uint32_t oriS2Size = + tempLoopInfo.oriMaskRight - tempLoopInfo.oriMaskLeft + 1; + uint32_t oriSplitNum = 0; + uint32_t cmpSplitNum = 0; + uint32_t cmpS2Size = 0; + bool isEnd = (bN2LoopIdx + 1 == constInfo.bN2End) && + (gS1LoopIdx + 1 == gS1LoopEnd); + if (tempLoopInfo.curActSeqLenIsZero) { + if ASCEND_IS_AIV { + InitAllZeroOutput( + tempLoopInfo.bIdx, tempLoopInfo.s1StartIdx, tempLoopInfo.n2Idx); + } + if (!isEnd) { + continue; + } + } else { + oriSplitNum = CeilDiv(oriS2Size, constInfo.s2BaseSize); + cmpS2Size = tempLoopInfo.actCmpS2Size; + cmpSplitNum = CeilDiv(cmpS2Size, constInfo.s2BaseSize); + } + + uint32_t s2SplitNum = oriSplitNum + cmpSplitNum; + constexpr uint32_t V0_SPLIT = 32; // align to 32 + uint32_t v0OriSize = + CeilDiv(oriS2Size * cmpS2Size, oriS2Size + cmpS2Size); + if (cmpS2Size > V0_SPLIT * oriSplitNum) { + v0OriSize = SMLAAlign(v0OriSize, V0_SPLIT * oriSplitNum); + } + uint32_t v0CmpSize = cmpS2Size - v0OriSize; + + tempLoopInfo.oriLoopTimes = oriSplitNum; + tempLoopInfo.cmpLoopTimes = cmpSplitNum; + tempLoopInfo.s2LoopTimes = s2SplitNum; + tempLoopInfo.v0OriSize = v0OriSize; + tempLoopInfo.v0CmpSize = v0CmpSize; + + uint32_t s2LoopEnd = (isEnd && constInfo.s2End != 0) + ? constInfo.s2End + : tempLoopInfo.s2LoopTimes; + tempLoopInfo.s2LoopTimes = s2LoopEnd; + // 分核修改后需要打开 + // 当前s2是否被切,决定了输出是否要写到attenOut上 + tempLoopInfo.tndIsS2SplitCore = + ((constInfo.s2Start == 0) && (s2LoopEnd == s2SplitNum)) ? false + : true; + tempLoopInfo.tndCoreStartKVSplitPos = + globalLoopStart ? constInfo.coreStartKVSplitPos : 0; + uint32_t extraLoop = isEnd ? 2 : 0; + uint32_t curTopKIdx = 0; + for (uint32_t s2LoopIdx = constInfo.s2Start; + s2LoopIdx < (s2LoopEnd + extraLoop); + s2LoopIdx++) { + PreloadPipeline( + gloop, cmpLoop, constInfo.s2Start, s2LoopIdx, extraInfo); + ++gloop; + if (s2LoopIdx >= tempLoopInfo.oriLoopTimes && + s2LoopIdx < s2LoopEnd) { // 用于判断v0使用的循环GM的id + ++cmpLoop; + } + } + globalLoopStart = false; + constInfo.s2Start = 0; + } + constInfo.gS1Start = 0; + } + if ASCEND_IS_AIV { + CrossCoreWaitFlag(3); + CrossCoreWaitFlag(3); + CrossCoreWaitFlag(3); + CrossCoreWaitFlag(3); + } +} + +template +__aicore__ inline void SparseFlashMlaCsa::PreloadPipeline( + uint32_t loop, + uint32_t cmpLoop, + uint64_t s2Start, + uint64_t s2LoopIdx, + RunInfo extraInfo[SMLA_PRELOAD_TASK_CACHE_SIZE]) { + RunInfo& extraInfo0 = + extraInfo[loop % SMLA_PRELOAD_TASK_CACHE_SIZE]; // 本轮任务 + RunInfo& extraInfo2 = + extraInfo[(loop + 2) % SMLA_PRELOAD_TASK_CACHE_SIZE]; // 上一轮任务 + RunInfo& extraInfo1 = + extraInfo[(loop + 1) % SMLA_PRELOAD_TASK_CACHE_SIZE]; // 上两轮任务 + + CalcParams(loop, cmpLoop, s2Start, s2LoopIdx, extraInfo0); + if constexpr (!HEAD_RATIO_ONE) { + if (extraInfo0.isValid) { + if ASCEND_IS_AIC { + if (!extraInfo0.isOriOnly) { + CrossCoreWaitFlag(constInfo.syncV0C1); + } + ComputeMm1(extraInfo0); + } else { + if (extraInfo0.isFirstSInnerLoop) { + CrossCoreWaitFlag(3); + } + vectorBlock.ProcessVec0L(extraInfo0); + if (!extraInfo0.isOriOnly) { + CrossCoreSetFlag( + constInfo.syncV0C1); + } + } + } + if (extraInfo2.isValid) { + if ASCEND_IS_AIV { + vectorBlock.ProcessVec1L(extraInfo2); + } + if ASCEND_IS_AIC { + ComputeMm2(extraInfo2); + if (extraInfo2.isLastS2Loop) { + CrossCoreSetFlag(3); + } + } + } + if (extraInfo1.isValid) { + if ASCEND_IS_AIV { + vectorBlock.ProcessVec2L(extraInfo1); + } + extraInfo1.isValid = false; + } + } else { + if (extraInfo0.isValid) { + if ASCEND_IS_AIV { + if (extraInfo0.isFirstSInnerLoop) { + CrossCoreWaitFlag(3); + } + vectorBlock.ProcessVec0L(extraInfo0); + if (!extraInfo0.isOriOnly) { + CrossCoreSetFlag( + constInfo.syncV0C1); + } + } + } + if (extraInfo2.isValid) { + if ASCEND_IS_AIV { + vectorBlock.ProcessVec1L(extraInfo2); + } + if ASCEND_IS_AIC { + ComputeMm2(extraInfo2); + if (extraInfo2.isLastS2Loop) { + CrossCoreSetFlag(3); + } + } + } + if (extraInfo1.isValid) { + if ASCEND_IS_AIV { + vectorBlock.ProcessVec2L(extraInfo1); + } + extraInfo1.isValid = false; + } + if (extraInfo0.isValid) { + if ASCEND_IS_AIC { + if (!extraInfo0.isOriOnly) { + CrossCoreWaitFlag( + constInfo.syncV0C1); + } + ComputeMm1(extraInfo0); + } + } + } +} + +} // namespace SMLAKernel +#endif // SPARSE_FLASH_MLA_CSA_KERNEL_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_block_cube.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_block_cube.h new file mode 100644 index 0000000000..cf92f16c83 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_block_cube.h @@ -0,0 +1,1539 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file sparse_flash_mla_swa_block_cube.h + * \brief use 7 buffer for matmul l1, better pipeline + */ +#ifndef SPARSE_FLASH_MLA_SWA_BLOCK_CUBE_H +#define SPARSE_FLASH_MLA_SWA_BLOCK_CUBE_H + +#include "kernel_operator.h" +#include "kernel_operator_list_tensor_intf.h" +#include "kernel_tiling/kernel_tiling.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" +#include "sparse_flash_mla_common_arch22.h" + +namespace SMLAKernel { +template +class SWACubeBlock { + public: + // 中间计算数据类型为float, 高精度模式 + using T = float; + using Q_T = typename SMLAT::queryType; + using KV_T = typename SMLAT::kvType; + using OUT_T = typename SMLAT::outputType; + using MM_OUT_T = T; + + __aicore__ inline SWACubeBlock(){}; + __aicore__ inline void InitParams(const ConstInfo& constInfo); + __aicore__ inline void InitMm1GlobalTensor(GlobalTensor queryGm, + GlobalTensor oriKvGm, + GlobalTensor cmpKV, + GlobalTensor mm1ResGm); + __aicore__ inline void InitMm2GlobalTensor( + GlobalTensor vec1ResGm, + GlobalTensor mm2ResGm, + GlobalTensor attentionOutGm); + __aicore__ inline void InitPageAttentionInfo( + GlobalTensor oriKvGm, + GlobalTensor oriBlockTableGm, + GlobalTensor cmpBlockTableGm); + __aicore__ inline void InitDsparkKvMerge(GlobalTensor kvMergeGm); + __aicore__ inline void InitBuffers(TPipe* pipe); + + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + __aicore__ inline void ComputeMm1(const RunInfo& info, + const MSplitInfo mSplitInfo); + __aicore__ inline void ComputeMm2(const RunInfo& info, + const MSplitInfo mSplitInfo); + + private: + static constexpr bool PAGE_ATTENTION = SMLAT::pageAttention; + static constexpr int TEMPLATE_MODE = SMLAT::templateMode; + static constexpr bool FLASH_DECODE = SMLAT::flashDecode; + static constexpr SMLA_LAYOUT LAYOUT_T = SMLAT::layout; + static constexpr SMLA_LAYOUT KV_LAYOUT_T = SMLAT::kvLayout; + static constexpr bool IS_DSPARK = SMLAT::isDspark; + + static constexpr uint32_t M_SPLIT_SIZE = 128; // m方向切分 + static constexpr uint32_t N_SPLIT_SIZE = 128; // n方向切分 + static constexpr uint32_t K_L0_SPLIT_SIZE = 128; // k方向L0切分 + static constexpr uint32_t K_L1_SPLIT_SIZE = 256; // k方向L1切分 + static constexpr uint32_t N_WORKSPACE_SIZE = 512; // n方向切分 + static constexpr uint32_t MERGE_CACHE_GM_BUF_NUM = 3; + static constexpr uint32_t D_SPLIT_SIZE = 256; // d轴切分 + + static constexpr uint32_t L1_BLOCK_SIZE = (64 * 512 * sizeof(Q_T)); + static constexpr uint32_t L1_BLOCK_OFFSET = 64 * 512; + + static constexpr uint32_t L0A_PP_SIZE = (32 * 1024); + static constexpr uint32_t L0B_PP_SIZE = (32 * 1024); + static constexpr uint32_t L0C_PP_SIZE = (64 * 1024); + + // mte2 <> mte1 EventID + // L1 3buf, 使用3个eventId + static constexpr uint32_t L1_EVENT0 = EVENT_ID2; + static constexpr uint32_t L1_EVENT1 = EVENT_ID3; + static constexpr uint32_t L1_EVENT2 = EVENT_ID4; + static constexpr uint32_t L1_EVENT3 = EVENT_ID5; + static constexpr uint32_t L1_EVENT4 = EVENT_ID6; + static constexpr uint32_t L1_EVENT5 = EVENT_ID7; + static constexpr uint32_t L1_EVENT6 = EVENT_ID1; + + // m <> mte1 EventID + static constexpr uint32_t L0AB_EVENT0 = EVENT_ID3; + static constexpr uint32_t L0AB_EVENT1 = EVENT_ID4; + + static constexpr IsResetLoad3dConfig LOAD3DV2_CONFIG = { + true, + true}; // isSetFMatrix isSetPadding; + static constexpr uint32_t mte21QPIds[4] = {L1_EVENT0, + L1_EVENT1, + L1_EVENT2, + L1_EVENT3}; // mte12复用 + static constexpr uint32_t mte21KVIds[3] = {L1_EVENT4, L1_EVENT5, L1_EVENT6}; + + ConstInfo constInfo{}; + + // L1分成3块buf, 用于记录 + uint32_t qpL1BufIter = 0; + uint32_t kvL1BufIter = -1; + uint32_t abL0BufIter = 0; + uint32_t cL0BufIter = 0; + + // mm1 + GlobalTensor queryGm; + GlobalTensor keyGm; + GlobalTensor mm1ResGm; + GlobalTensor kvMergeGm_; + GlobalTensor oriKvGm; + GlobalTensor cmpKvGm; + + // mm2 + GlobalTensor vec1ResGm; + GlobalTensor valueGm; + GlobalTensor mm2ResGm; + GlobalTensor attentionOutGm; + + // block_table + GlobalTensor oriBlockTableGm; + GlobalTensor cmpBlockTableGm; + + TBuf bufQPL1; + TBuf bufKVL1; + TBuf tmpBufL0A; + TBuf tmpBufL0B; + TBuf tmpBufL0C; + + LocalTensor l1QPTensor; + LocalTensor l1KVTensor; + LocalTensor aL0TensorPingPong; + LocalTensor bL0TensorPingPong; + LocalTensor cL0TensorPingPong; + + // L0AB m <> mte1 EventID + __aicore__ inline uint32_t Mte1MmABEventId(uint32_t idx) { + return (L0AB_EVENT0 + idx); + } + + __aicore__ inline uint32_t GetQPL1RealIdx(uint32_t mIdx, uint32_t k1Idx) { + uint32_t idxMap[] = { + 0, 2}; // 确保0块和1块连在一起, 2和3块连在一起, 来保证同一m块的地址相连 + return idxMap[mIdx % 2] + k1Idx; + } + + __aicore__ inline void CopyGmToL1(LocalTensor& l1Tensor, + GlobalTensor& gmSrcTensor, + uint32_t srcN, + uint32_t srcD, + uint32_t srcDstride); + __aicore__ inline void CopyInMm1AToL1(LocalTensor& aL1Tensor, + const RunInfo& info, + uint32_t mSeqIdx, + uint32_t mSizeAct, + uint32_t headSize, + uint32_t headOffset); + __aicore__ inline void CopyInMm2AToL1(LocalTensor& aL1Tensor, + const RunInfo& info, + uint32_t mSeqIdx, + uint32_t subMSizeAct, + uint32_t nSize, + uint32_t nOffset); + __aicore__ inline void LoadDataMm1A(LocalTensor& aL0Tensor, + LocalTensor& aL1Tensor, + uint32_t idx, + uint32_t kSplitSize, + uint32_t mSize, + uint32_t kSize); + __aicore__ inline void LoadDataMm1B(LocalTensor& bL0Tensor, + LocalTensor& bL1Tensor, + uint32_t idx, + uint32_t kSplitSize, + uint32_t kSize, + uint32_t nSize); +}; + +template +__aicore__ inline void SWACubeBlock::InitParams( + const ConstInfo& constInfo) { + this->constInfo = constInfo; +} + +template +__aicore__ inline void SWACubeBlock::InitMm1GlobalTensor( + GlobalTensor queryGm, + GlobalTensor oriKvGm, + GlobalTensor cmpKvGm, + GlobalTensor mm1ResGm) { + // mm1 + this->queryGm = queryGm; + this->oriKvGm = oriKvGm; + if constexpr (TEMPLATE_MODE == HCA_TEMPLATE) { + this->cmpKvGm = cmpKvGm; + } + this->mm1ResGm = mm1ResGm; +} + +template +__aicore__ inline void SWACubeBlock::InitMm2GlobalTensor( + GlobalTensor vec1ResGm, + GlobalTensor mm2ResGm, + GlobalTensor attentionOutGm) { + // mm2 + this->vec1ResGm = vec1ResGm; + this->mm2ResGm = mm2ResGm; + this->attentionOutGm = attentionOutGm; +} + +template +__aicore__ inline void SWACubeBlock::InitPageAttentionInfo( + GlobalTensor oriKvGm, + GlobalTensor oriBlockTableGm, + GlobalTensor cmpBlockTableGm) { + this->oriKvGm = oriKvGm; + this->oriBlockTableGm = oriBlockTableGm; + if constexpr (TEMPLATE_MODE == HCA_TEMPLATE) { + this->cmpBlockTableGm = cmpBlockTableGm; + } +} + +template +__aicore__ inline void SWACubeBlock::InitDsparkKvMerge( + GlobalTensor kvMergeGm) { + this->kvMergeGm_ = kvMergeGm; +} + +template +__aicore__ inline void SWACubeBlock::InitBuffers(TPipe* pipe) { + pipe->InitBuffer(bufQPL1, L1_BLOCK_SIZE * 4); + l1QPTensor = bufQPL1.Get(); + pipe->InitBuffer(bufKVL1, L1_BLOCK_SIZE * 3); + l1KVTensor = bufKVL1.Get(); + // L0A + pipe->InitBuffer(tmpBufL0A, L0A_PP_SIZE * 2); // 64K + aL0TensorPingPong = tmpBufL0A.Get(); + // L0B + pipe->InitBuffer(tmpBufL0B, L0B_PP_SIZE * 2); // 64K + bL0TensorPingPong = tmpBufL0B.Get(); + // L0C + pipe->InitBuffer(tmpBufL0C, L0C_PP_SIZE * 2); // 128K + cL0TensorPingPong = tmpBufL0C.Get(); +} + +template +__aicore__ inline void SWACubeBlock::AllocEventID() { + SetFlag(L1_EVENT0); + SetFlag(L1_EVENT1); + SetFlag(L1_EVENT2); + SetFlag(L1_EVENT3); + SetFlag(L1_EVENT4); + SetFlag(L1_EVENT5); + SetFlag(L1_EVENT6); + SetFlag(L0AB_EVENT0); + SetFlag(L0AB_EVENT1); +} + +template +__aicore__ inline void SWACubeBlock::FreeEventID() { + WaitFlag(L1_EVENT0); + WaitFlag(L1_EVENT1); + WaitFlag(L1_EVENT2); + WaitFlag(L1_EVENT3); + WaitFlag(L1_EVENT4); + WaitFlag(L1_EVENT5); + WaitFlag(L1_EVENT6); + WaitFlag(L0AB_EVENT0); + WaitFlag(L0AB_EVENT1); +} + +template +__aicore__ inline void SWACubeBlock::CopyGmToL1( + LocalTensor& l1Tensor, + GlobalTensor& gmSrcTensor, + uint32_t srcN, + uint32_t srcD, + uint32_t srcDstride) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = srcN; // 行数 + nd2nzPara.dValue = srcD; + nd2nzPara.srcDValue = srcDstride; + nd2nzPara.dstNzC0Stride = (srcN + 15) / 16 * 16; // 对齐到16 单位block + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(l1Tensor, gmSrcTensor, nd2nzPara); +} + +template +__aicore__ inline void SWACubeBlock::CopyInMm1AToL1( + LocalTensor& l1Tensor, + const RunInfo& info, + uint32_t mSeqIdx, + uint32_t mSizeAct, + uint32_t headSize, + uint32_t headOffset) { + auto srcGm = + queryGm[info.tensorAOffset + mSeqIdx * constInfo.headDim + headOffset]; + CopyGmToL1(l1Tensor, srcGm, mSizeAct, headSize, constInfo.headDim); +} + +template +__aicore__ inline void SWACubeBlock::LoadDataMm1A( + LocalTensor& aL0Tensor, + LocalTensor& aL1Tensor, + uint32_t idx, + uint32_t kSplitSize, + uint32_t mSize, + uint32_t kSize) { + LocalTensor srcTensor = aL1Tensor[mSize * kSplitSize * idx]; + LoadData3DParamsV2 loadData3DParams; + // SetFmatrixParams + loadData3DParams.l1H = mSize / 16; // Hin=M1=8 + loadData3DParams.l1W = 16; // Win=M0 + loadData3DParams.padList[0] = 0; + loadData3DParams.padList[1] = 0; + loadData3DParams.padList[2] = 0; + loadData3DParams.padList[3] = 255; // 尾部数据不影响滑窗的结果 + + // SetLoadToA0Params + loadData3DParams.mExtension = mSize; // M + loadData3DParams.kExtension = kSize; // K + loadData3DParams.mStartPt = 0; + loadData3DParams.kStartPt = 0; + loadData3DParams.strideW = 1; + loadData3DParams.strideH = 1; + loadData3DParams.filterW = 1; + loadData3DParams.filterSizeW = (1 >> 8) & 255; + loadData3DParams.filterH = 1; + loadData3DParams.filterSizeH = (1 >> 8) & 255; + loadData3DParams.dilationFilterW = 1; + loadData3DParams.dilationFilterH = 1; + loadData3DParams.enTranspose = 0; + loadData3DParams.fMatrixCtrl = 0; + loadData3DParams.channelSize = kSize; // Cin=K + LoadData(aL0Tensor, srcTensor, loadData3DParams); +} + +template +__aicore__ inline void SWACubeBlock::LoadDataMm1B( + LocalTensor& l0Tensor, + LocalTensor& l1Tensor, + uint32_t idx, + uint32_t kSplitSize, + uint32_t kSize, + uint32_t nSize) { + // N 方向全载 + LocalTensor srcTensor = l1Tensor[nSize * kSplitSize * idx]; + LoadData2DParams loadData2DParams; + loadData2DParams.startIndex = 0; + loadData2DParams.repeatTimes = + (nSize + 15) / 16 * kSize / (32 / sizeof(KV_T)); + loadData2DParams.srcStride = 1; + loadData2DParams.dstGap = 0; + loadData2DParams.ifTranspose = false; + LoadData(l0Tensor, srcTensor, loadData2DParams); +} + +template +__aicore__ inline void SWACubeBlock::CopyInMm2AToL1( + LocalTensor& aL1Tensor, + const RunInfo& info, + uint32_t mSeqIdx, + uint32_t subMSizeAct, + uint32_t nSize, + uint32_t nOffset) { + auto srcGm = + vec1ResGm[(info.loop % constInfo.preLoadNum) * constInfo.mmResUbSize + + mSeqIdx * info.actualSingleProcessSInnerSizeAlign + nOffset]; + CopyGmToL1(aL1Tensor, + srcGm, + subMSizeAct, + nSize, + info.actualSingleProcessSInnerSizeAlign); +} + +template +__aicore__ inline void SWACubeBlock::ComputeMm1( + const RunInfo& info, + const MSplitInfo mSplitInfo) { + uint32_t mSize = mSplitInfo.nBufferDealM; + uint32_t mL1Size = M_SPLIT_SIZE; + uint32_t mL1SizeAlign = SMLAAlign(M_SPLIT_SIZE, 16); + uint32_t mL1Loops = CeilDiv(mSize, M_SPLIT_SIZE); + + uint32_t nSize = info.actualSingleProcessSInnerSize; + uint32_t nL1Size = N_SPLIT_SIZE; + uint32_t nL1SizeAlign = SMLAAlign(N_SPLIT_SIZE, 16); + uint32_t nL1Loops = CeilDiv(nSize, N_SPLIT_SIZE); + + uint32_t kSize = 512; + uint32_t kL1Size = 256; + uint32_t kL1Loops = 2; + uint32_t kL0Size = 128; + uint32_t kL0Loops = CeilDiv(kL1Size, kL0Size); + + LocalTensor bL1Tensor; + LocalTensor kTensor; + uint32_t ka = 0, kb = 0; + uint32_t copyRowCnt = 0; + uint32_t copyRowCntTmp = 0; + // L1 切n切k + for (uint32_t nL1 = 0; nL1 < nL1Loops; nL1++) { // L1切n, 512/128=4 + if (nL1 == (nL1Loops - 1)) { + // 尾块重新计算size + nL1Size = nSize - (nL1Loops - 1) * N_SPLIT_SIZE; + nL1SizeAlign = SMLAAlign(nL1Size, 16); + } + + for (uint32_t kL1 = 0; kL1 < kL1Loops; kL1++) { + kvL1BufIter++; + uint32_t kb = kvL1BufIter % 3; + WaitFlag(mte21KVIds[kb]); + // 从k当中取当前的块 + bL1Tensor = l1KVTensor[kb * L1_BLOCK_OFFSET]; + uint32_t copyFinishRowCnt = 0; + + if (info.isOriOnly) { + if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { + uint64_t curS2Offset = + static_cast(info.s2Idx) * constInfo.s2BaseSize + + info.s2StartPoint + nL1 * N_SPLIT_SIZE; + uint32_t copyFinishRowCnt = 0; + LocalTensor kTensor; + uint32_t copyRowCnt = 0; + + if constexpr (IS_DSPARK) { + uint64_t mergeBase = + static_cast(info.cmpLoop % MERGE_CACHE_GM_BUF_NUM) * + N_WORKSPACE_SIZE * constInfo.headDim; + uint32_t blockElementCnt = 32U / sizeof(KV_T); + for (uint32_t row = 0; row < nL1Size; ++row) { + uint64_t mergeOffset = + mergeBase + + static_cast(nL1 * N_SPLIT_SIZE + row) * + constInfo.headDim + + kL1 * D_SPLIT_SIZE; + GlobalTensor mergeSrcGm = kvMergeGm_[mergeOffset]; + kTensor = bL1Tensor[row * blockElementCnt]; + DataCopyGmNDToL1(kTensor, + mergeSrcGm, + 1, + nL1SizeAlign, + D_SPLIT_SIZE, + constInfo.headDim); + } + } else + while (copyFinishRowCnt < nL1Size) { + // 由于ori_left的存在, 即使第一块搬运也可能并非是pa_block的零点位 + copyRowCnt = constInfo.paOriBlockSize - + curS2Offset % constInfo.paOriBlockSize; + if (copyFinishRowCnt + copyRowCnt > nL1Size) { + copyRowCnt = nL1Size - copyFinishRowCnt; + } + Position startPos; + startPos.bIdx = info.bIdx; + startPos.n2Idx = info.n2Idx; + startPos.s2Idx = curS2Offset; + // 256、32等待7buf命名更改 + startPos.dIdx = kL1 * 256; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 + // 右矩阵, s2为k轴, d轴切分 + PAShape shape; + shape.blockSize = constInfo.paOriBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.kvStride = constInfo.oriKvStride0; + shape.actHeadDim = 256; + shape.maxblockNumPerBatch = constInfo.oriMaxBlockNumPerBatch; + shape.copyRowNum = copyRowCnt; + shape.copyRowNumAlign = nL1SizeAlign; + kTensor = bL1Tensor[copyFinishRowCnt * 16]; + DataCopyPA( + kTensor, oriKvGm, oriBlockTableGm, shape, startPos); + // 更新循环变量 + copyFinishRowCnt += copyRowCnt; + curS2Offset += copyRowCnt; + } + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nL1Size; // 行数 + nd2nzPara.dValue = D_SPLIT_SIZE; // 256 + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = nL1SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + + uint32_t headStride = constInfo.headDim; + uint32_t seqStride = constInfo.kvHeadNum * constInfo.headDim; + uint64_t batchStride = + (constInfo.oriKvStride0 == 0) + ? static_cast(constInfo.kvSeqSize) * seqStride + : constInfo.oriKvStride0; + + uint64_t curS2 = info.s2StartPoint + nL1 * N_SPLIT_SIZE; + uint64_t offset = + (uint64_t)info.bIdx * batchStride + (uint64_t)curS2 * seqStride + + (uint64_t)info.n2Idx * headStride + kL1 * D_SPLIT_SIZE; + DataCopy(bL1Tensor, oriKvGm[offset], nd2nzPara); + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { + uint64_t curS2Offset = + static_cast(info.s2Idx) * + static_cast(constInfo.s2BaseSize) + + info.s2StartPoint + nL1 * N_SPLIT_SIZE; + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nL1Size; + nd2nzPara.dValue = constInfo.headDim >> 1; + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = nL1SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy( + bL1Tensor, + oriKvGm[info.tensorBOffset + curS2Offset * constInfo.headDim + + kL1 * D_SPLIT_SIZE], + nd2nzPara); + } + } else if (info.isOriCmpMix) { + uint32_t cumNl1LoopSize = nL1 * N_SPLIT_SIZE; + uint32_t oriSizeCur = + (info.actualSingleProcessSInnerOriSize < cumNl1LoopSize) + ? 0 + : (info.actualSingleProcessSInnerOriSize - cumNl1LoopSize); + oriSizeCur = (oriSizeCur > nL1Size) ? nL1Size : oriSizeCur; + uint32_t cmpSizeCur = nL1Size - oriSizeCur; + cmpSizeCur = (cmpSizeCur < info.actualSingleProcessSInnerCmpSize) + ? cmpSizeCur + : info.actualSingleProcessSInnerCmpSize; + if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { + LocalTensor kTensor; + uint32_t copyRowCnt = 0; + + if (oriSizeCur > 0) { + uint32_t copyFinishRowCnt = 0; + uint64_t curS2Offset = info.s2StartPoint + nL1 * N_SPLIT_SIZE; + while (copyFinishRowCnt < oriSizeCur) { + // 由于ori_left的存在, 即使第一块搬运也可能并非是pa_block的零点位 + copyRowCnt = constInfo.paOriBlockSize - + curS2Offset % constInfo.paOriBlockSize; + if (copyFinishRowCnt + copyRowCnt > oriSizeCur) { + copyRowCnt = oriSizeCur - copyFinishRowCnt; + } + Position startPos; + startPos.bIdx = info.bIdx; + startPos.n2Idx = info.n2Idx; + startPos.s2Idx = curS2Offset; + // 256、32等待7buf命名更改 + startPos.dIdx = kL1 * 256; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 + // 右矩阵, s2为k轴, d轴切分 + PAShape shape; + shape.blockSize = constInfo.paOriBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.kvStride = constInfo.oriKvStride0; + shape.actHeadDim = 256; + shape.maxblockNumPerBatch = constInfo.oriMaxBlockNumPerBatch; + shape.copyRowNum = copyRowCnt; + shape.copyRowNumAlign = nL1SizeAlign; + kTensor = bL1Tensor[copyFinishRowCnt * 16]; + DataCopyPA( + kTensor, oriKvGm, oriBlockTableGm, shape, startPos); + // 更新循环变量 + copyFinishRowCnt += copyRowCnt; + curS2Offset += copyRowCnt; + } + } + if (cmpSizeCur > 0) { + uint32_t cmpMixsizeCur = + N_SPLIT_SIZE - + info.actualSingleProcessSInnerOriSize % N_SPLIT_SIZE; + uint32_t oriOnlyLoopTimes = + info.actualSingleProcessSInnerOriSize / N_SPLIT_SIZE; + uint32_t cmpLoopTimes = nL1 - oriOnlyLoopTimes; + uint64_t curS2Offset = + (cmpLoopTimes == 0) + ? 0 + : (cmpMixsizeCur + + static_cast(cmpLoopTimes - 1) * N_SPLIT_SIZE); + uint32_t copyFinishRowCnt = 0; + while (copyFinishRowCnt < cmpSizeCur) { + // 由于ori_left的存在, 即使第一块搬运也可能并非是pa_block的零点位 + copyRowCnt = constInfo.paCmpBlockSize - + curS2Offset % constInfo.paCmpBlockSize; + if (copyFinishRowCnt + copyRowCnt > cmpSizeCur) { + copyRowCnt = cmpSizeCur - copyFinishRowCnt; + } + Position startPos; + startPos.bIdx = info.bIdx; + startPos.n2Idx = info.n2Idx; + startPos.s2Idx = curS2Offset; + // 256、32等待7buf命名更改 + startPos.dIdx = kL1 * 256; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 + // 右矩阵, s2为k轴, d轴切分 + PAShape shape; + shape.blockSize = constInfo.paCmpBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.kvStride = constInfo.cmpKvStride0; + shape.actHeadDim = 256; + shape.maxblockNumPerBatch = constInfo.cmpMaxBlockNumPerBatch; + shape.copyRowNum = copyRowCnt; + shape.copyRowNumAlign = nL1SizeAlign; + kTensor = bL1Tensor[copyFinishRowCnt * 16 + oriSizeCur * 16]; + DataCopyPA( + kTensor, cmpKvGm, cmpBlockTableGm, shape, startPos); + // 更新循环变量 + copyFinishRowCnt += copyRowCnt; + curS2Offset += copyRowCnt; + } + } + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nL1Size; // 行数 + nd2nzPara.dValue = D_SPLIT_SIZE; // 256 + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = nL1SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + + uint32_t headStride = constInfo.headDim; + uint32_t seqStride = constInfo.kvHeadNum * constInfo.headDim; + if (oriSizeCur > 0) { + nd2nzPara.nValue = oriSizeCur; + uint64_t batchStride = + (constInfo.oriKvStride0 == 0) + ? static_cast(constInfo.kvSeqSize) * seqStride + : constInfo.oriKvStride0; + uint64_t curS2 = info.s2StartPoint + nL1 * N_SPLIT_SIZE; + uint64_t offset = (uint64_t)info.bIdx * batchStride + + (uint64_t)curS2 * seqStride + + (uint64_t)info.n2Idx * headStride + + kL1 * D_SPLIT_SIZE; + DataCopy(bL1Tensor, oriKvGm[offset], nd2nzPara); + } + if (cmpSizeCur > 0) { + nd2nzPara.nValue = cmpSizeCur; + uint64_t batchStride = + (constInfo.cmpKvStride0 == 0) + ? static_cast(constInfo.cmpSeqSize) * seqStride + : constInfo.cmpKvStride0; + uint32_t cmpMixsizeCur = + N_SPLIT_SIZE - + info.actualSingleProcessSInnerOriSize % N_SPLIT_SIZE; + uint32_t oriOnlyLoopTimes = + info.actualSingleProcessSInnerOriSize / N_SPLIT_SIZE; + uint32_t cmpLoopTimes = nL1 - oriOnlyLoopTimes; + uint64_t curS2 = + (cmpLoopTimes == 0) + ? 0 + : (cmpMixsizeCur + (cmpLoopTimes - 1) * N_SPLIT_SIZE); + uint64_t offset = + (uint64_t)info.bIdx * batchStride + curS2 * seqStride + + (uint64_t)info.n2Idx * headStride + kL1 * D_SPLIT_SIZE; + DataCopy(bL1Tensor[oriSizeCur * 16], cmpKvGm[offset], nd2nzPara); + } + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nL1Size; + nd2nzPara.dValue = constInfo.headDim >> 1; + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = nL1SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + + if (oriSizeCur > 0) { + nd2nzPara.nValue = oriSizeCur; + uint64_t curS2Offset = info.s2StartPoint + nL1 * N_SPLIT_SIZE; + DataCopy( + bL1Tensor, + oriKvGm[info.tensorBOffset + curS2Offset * constInfo.headDim + + kL1 * D_SPLIT_SIZE], + nd2nzPara); + } + if (cmpSizeCur > 0) { + nd2nzPara.nValue = cmpSizeCur; + uint32_t cmpMixsizeCur = + N_SPLIT_SIZE - + info.actualSingleProcessSInnerOriSize % N_SPLIT_SIZE; + uint32_t oriOnlyLoopTimes = + info.actualSingleProcessSInnerOriSize / N_SPLIT_SIZE; + uint32_t cmpLoopTimes = nL1 - oriOnlyLoopTimes; + uint64_t curS2Offset = + (cmpLoopTimes == 0) + ? 0 + : (cmpMixsizeCur + + static_cast(cmpLoopTimes - 1) * N_SPLIT_SIZE); + DataCopy( + bL1Tensor[oriSizeCur * 16], + cmpKvGm[info.tensorCmpBOffset + + curS2Offset * constInfo.headDim + kL1 * D_SPLIT_SIZE], + nd2nzPara); + } + } + } else { + if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { + uint64_t curS2Offset = + static_cast(info.relativeS2Idx) * constInfo.s2BaseSize + + info.s2StartPoint + nL1 * N_SPLIT_SIZE; + while (copyFinishRowCnt < nL1Size) { + // 由于ori_left的存在, 即使第一块搬运也可能并非是pa_block的零点位 + copyRowCnt = constInfo.paCmpBlockSize - + curS2Offset % constInfo.paCmpBlockSize; + if (copyFinishRowCnt + copyRowCnt > nL1Size) { + copyRowCnt = nL1Size - copyFinishRowCnt; + } + + Position startPos; + startPos.bIdx = info.bIdx; + startPos.n2Idx = info.n2Idx; + startPos.s2Idx = curS2Offset; + // 256、32等待7buf命名更改 + startPos.dIdx = kL1 * 256; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 + // 右矩阵, s2为k轴, d轴切分 + + PAShape shape; + shape.blockSize = constInfo.paCmpBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.kvStride = constInfo.cmpKvStride0; + shape.actHeadDim = 256; + shape.maxblockNumPerBatch = constInfo.cmpMaxBlockNumPerBatch; + shape.copyRowNum = copyRowCnt; + shape.copyRowNumAlign = nL1SizeAlign; + kTensor = bL1Tensor[copyFinishRowCnt * 16]; + DataCopyPA( + kTensor, cmpKvGm, cmpBlockTableGm, shape, startPos); + // 更新循环变量 + copyFinishRowCnt += copyRowCnt; + curS2Offset += copyRowCnt; + } + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nL1Size; // 行数 + nd2nzPara.dValue = D_SPLIT_SIZE; // 256 + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = nL1SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + + uint32_t headStride = constInfo.headDim; + uint32_t seqStride = constInfo.kvHeadNum * constInfo.headDim; + uint64_t batchStride = + (constInfo.cmpKvStride0 == 0) + ? static_cast(constInfo.cmpSeqSize) * seqStride + : constInfo.cmpKvStride0; + + uint64_t curS2 = + static_cast(info.relativeS2Idx) * constInfo.s2BaseSize + + info.s2StartPoint + nL1 * N_SPLIT_SIZE; + uint64_t offset = + (uint64_t)info.bIdx * batchStride + (uint64_t)curS2 * seqStride + + (uint64_t)info.n2Idx * headStride + kL1 * D_SPLIT_SIZE; + DataCopy(bL1Tensor, cmpKvGm[offset], nd2nzPara); + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { + uint64_t curS2Offset = + static_cast(info.relativeS2Idx) * constInfo.s2BaseSize + + info.s2StartPoint + nL1 * N_SPLIT_SIZE; + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nL1Size; + nd2nzPara.dValue = constInfo.headDim >> 1; + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = nL1SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy( + bL1Tensor, + cmpKvGm[info.tensorCmpBOffset + curS2Offset * constInfo.headDim + + +kL1 * D_SPLIT_SIZE], + nd2nzPara); + } + } + + SetFlag(mte21KVIds[kb]); + WaitFlag(mte21KVIds[kb]); + mL1Size = M_SPLIT_SIZE; + mL1SizeAlign = SMLAAlign(M_SPLIT_SIZE, 16U); + for (uint32_t mL1 = 0; mL1 < mL1Loops; mL1++) { + uint32_t aL1PaddingSize = + 0; // 用于使左矩阵对齐到尾部, 以保证两块32K内存连续 + if (mL1 == (mL1Loops - 1)) { + mL1Size = mSize - (mL1Loops - 1) * M_SPLIT_SIZE; + mL1SizeAlign = SMLAAlign(mL1Size, 16U); + aL1PaddingSize = (M_SPLIT_SIZE - mL1SizeAlign) * 256; + } + uint32_t mIdx = qpL1BufIter + mL1; + ka = GetQPL1RealIdx(mIdx, kL1); + LocalTensor aL1Tensor = + l1QPTensor[ka * L1_BLOCK_OFFSET + (1 - kL1) * aL1PaddingSize]; + if (nL1 == 0) { + if (kL1 == 0) { + WaitFlag(mte21QPIds[ka]); + WaitFlag(mte21QPIds[ka + 1]); + CopyInMm1AToL1(aL1Tensor, + info, + mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, + mL1Size, + 256, + 0); + } else { + LocalTensor qTmpTensor = aL1Tensor; + CopyInMm1AToL1(qTmpTensor, + info, + mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, + mL1Size, + 256, + 256); + } + SetFlag(mte21QPIds[ka]); + WaitFlag(mte21QPIds[ka]); + } + // 使用unitflag同步 + LocalTensor cL0Tensor = cL0TensorPingPong + [(cL0BufIter % 2) * + (L0C_PP_SIZE / + sizeof(MM_OUT_T))]; // 需要保证cL0BufIter和m步调一致 + for (uint32_t kL0 = 0; kL0 < kL0Loops; kL0++) { + WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); + LocalTensor aL0Tensor = + aL0TensorPingPong[(abL0BufIter % 2) * + (L0A_PP_SIZE / sizeof(KV_T))]; + LoadDataMm1A( + aL0Tensor, aL1Tensor, kL0, kL0Size, mL1SizeAlign, kL0Size); + LocalTensor bL0Tensor = + bL0TensorPingPong[(abL0BufIter % 2) * + (L0B_PP_SIZE / sizeof(KV_T))]; + if (mL1 == 0) { + LoadDataMm1B( + bL0Tensor, bL1Tensor, kL0, kL0Size, kL0Size, nL1SizeAlign); + } + SetFlag(Mte1MmABEventId(abL0BufIter % 2)); + WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); + + MmadParams mmadParams; + mmadParams.m = mL1SizeAlign; + mmadParams.n = nL1SizeAlign; + mmadParams.k = kL0Size; + mmadParams.cmatrixInitVal = (kL1 == 0 && kL0 == 0); + mmadParams.cmatrixSource = false; + mmadParams.unitFlag = + (kL1 == 1 && kL0 == (kL0Loops - 1)) + ? 0b11 + : 0b10; // 累加最后一次翻转flag, 表示可以搬出 + Mmad(cL0Tensor, aL0Tensor, bL0Tensor, mmadParams); + if ((mmadParams.m / 16) * (mmadParams.n / 16) < 10) { + PipeBarrier(); + } + SetFlag(Mte1MmABEventId(abL0BufIter % 2)); + abL0BufIter++; + } + + if (nL1 == (nL1Loops - 1)) { + SetFlag( + mte21QPIds[ka]); // 反向同步, 表示L1中的A已经被mte1消费完 + } + + if (kL1 == 1) { // 最后一轮kL1循环 + FixpipeParamsV220 fixParams; + fixParams.nSize = nL1SizeAlign; + fixParams.mSize = mL1SizeAlign; + fixParams.srcStride = mL1SizeAlign; + // 改成nSizeAlign + fixParams.dstStride = + info.actualSingleProcessSInnerSizeAlign; // mm1ResGm两行之间的间隔 + fixParams.unitFlag = 0b11; + fixParams.ndNum = 1; // 输出ND + + Fixpipe(mm1ResGm[(info.loop % (constInfo.preLoadNum)) * + constInfo.mmResUbSize + + nL1 * N_SPLIT_SIZE + + (mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE) * + info.actualSingleProcessSInnerSizeAlign], + cL0Tensor, + fixParams); + } + if (mL1Loops == 2) { + cL0BufIter++; + } + } + + SetFlag( + mte21KVIds[kb]); // 反向同步, 表示L1已经被mte1消费完 + } + if (mL1Loops == 1) { + cL0BufIter++; + } + } + qpL1BufIter += mL1Loops; +} + +template +__aicore__ inline void SWACubeBlock::ComputeMm2( + const RunInfo& info, + const MSplitInfo mSplitInfo) { + uint32_t mSize = mSplitInfo.nBufferDealM; + uint32_t mSizeAlign = (mSize + 16 - 1) / 16; + uint32_t mL1Loops = (mSize + M_SPLIT_SIZE - 1) / M_SPLIT_SIZE; + uint32_t mL1SizeAlign = M_SPLIT_SIZE; // 16对齐 + uint32_t mL1Size = M_SPLIT_SIZE; // m的实际大小 + + uint32_t nSize = BlockAlign(constInfo.headDim); + uint32_t nL1Loops = (nSize + N_SPLIT_SIZE - 1) / N_SPLIT_SIZE; + uint32_t nL1SizeAlign = N_SPLIT_SIZE; // 16对齐 + uint32_t nL1Size = N_SPLIT_SIZE; // n的实际大小 + + uint32_t kSize = info.actualSingleProcessSInnerSize; + uint32_t kL1Size = K_L1_SPLIT_SIZE; + uint32_t kL1SizeAlign = SMLAAlign(kL1Size, 16U); + uint32_t kL1Loops = (kSize + kL1Size - 1) / kL1Size; + uint32_t kL0Size = K_L0_SPLIT_SIZE; + uint32_t kL0Loops = (kL1Size + kL0Size - 1) / kL0Size; + uint32_t kL0SizeAlign = kL0Size; + LocalTensor bL1Tensor; + LocalTensor subvTensor; + // ka表示左矩阵4buf选择哪一块buf, kb表示右矩阵3buf选择哪一块buf + uint32_t ka = 0, kb = 0; + uint32_t mBaseIdx = qpL1BufIter; + for (uint32_t nL1 = 0; nL1 < nL1Loops; nL1++) { // n切L1 + if (nL1 == (nL1Loops - 1)) { + // 尾块 + nL1Size = nSize - (nL1Loops - 1) * N_SPLIT_SIZE; + nL1SizeAlign = SMLAAlign(nL1Size, 16U); + } + // k l1写成一个循环, 和mm1保持一致 + kL1Size = K_L1_SPLIT_SIZE; + kL1SizeAlign = SMLAAlign(kL1Size, 16U); + uint32_t copyRowCnt = 0; + for (uint32_t k1 = 0; k1 < kL1Loops; k1++) { // k切L1, 这里套了一层l0来操作 + if (k1 == (kL1Loops - 1)) { + // 尾块 + kL1Size = kSize - (kL1Loops - 1) * K_L1_SPLIT_SIZE; + kL1SizeAlign = SMLAAlign(kL1Size, 16U); + } + kvL1BufIter++; + uint32_t kb = kvL1BufIter % 3; + WaitFlag(mte21KVIds[kb]); + bL1Tensor = l1KVTensor[kb * L1_BLOCK_OFFSET]; + uint32_t kOffset = k1 * kL0Loops; + kL0Size = K_L0_SPLIT_SIZE; + // 此处必须先初始化kL0Size, 再求kL0Loops, 否则由于循环会改变kL0Size大小, + // 导致kL0Loops错误 + kL0Loops = (kL1Size + kL0Size - 1) / kL0Size; + kL0SizeAlign = kL0Size; + for (uint32_t kL1 = kOffset; kL1 < kL0Loops + kOffset; + kL1++) { // 128 循环搬pa + if (kL1 == kOffset + kL0Loops - 1) { + // 尾块 + kL0Size = kL1Size - (kL0Loops - 1) * kL0Size; + kL0SizeAlign = SMLAAlign(kL0Size, 16U); + } + + uint32_t copyFinishRowCnt = 0; + if (info.isOriOnly) { + if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { + uint64_t curS2Offset = + static_cast(info.s2Idx) * constInfo.s2BaseSize + + info.s2StartPoint + kL1 * K_L0_SPLIT_SIZE; + if constexpr (IS_DSPARK) { + uint64_t mergeBase = + static_cast(info.cmpLoop % MERGE_CACHE_GM_BUF_NUM) * + N_WORKSPACE_SIZE * constInfo.headDim; + uint32_t blockElementCnt = 32U / sizeof(KV_T); + subvTensor = + bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE]; + for (uint32_t row = 0; row < kL0Size; ++row) { + uint64_t mergeOffset = + mergeBase + + static_cast(kL1 * K_L0_SPLIT_SIZE + row) * + constInfo.headDim + + nL1 * N_SPLIT_SIZE; + GlobalTensor mergeSrcGm = kvMergeGm_[mergeOffset]; + LocalTensor dstTensor = subvTensor[row * blockElementCnt]; + DataCopyGmNDToL1(dstTensor, + mergeSrcGm, + 1, + kL0SizeAlign, + nL1Size, + constInfo.headDim); + } + } else + while (copyFinishRowCnt < kL0Size) { + copyRowCnt = constInfo.paOriBlockSize - + curS2Offset % constInfo.paOriBlockSize; + if (copyFinishRowCnt + copyRowCnt > kL0Size) { + copyRowCnt = kL0Size - copyFinishRowCnt; + } + Position startPos; + startPos.bIdx = info.bIdx; + startPos.n2Idx = info.n2Idx; + startPos.s2Idx = curS2Offset; + startPos.dIdx = + nL1 * N_SPLIT_SIZE; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 + // 右矩阵, s2为k轴, d轴切分 + PAShape shape; + shape.blockSize = constInfo.paOriBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.kvStride = constInfo.oriKvStride0; + shape.actHeadDim = nL1Size; + shape.maxblockNumPerBatch = constInfo.oriMaxBlockNumPerBatch; + shape.copyRowNum = copyRowCnt; + shape.copyRowNumAlign = kL0SizeAlign; + subvTensor = + bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE + + copyFinishRowCnt * 16]; + DataCopyPA( + subvTensor, oriKvGm, oriBlockTableGm, shape, startPos); + + // 更新循环变量 + copyFinishRowCnt += copyRowCnt; + curS2Offset += copyRowCnt; + } + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { + subvTensor = + bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE]; + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = kL0Size; // 行数 + nd2nzPara.dValue = nL1Size; // 256 + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = kL0SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + + uint32_t headStride = constInfo.headDim; + uint32_t seqStride = constInfo.kvHeadNum * constInfo.headDim; + uint64_t batchStride = + (constInfo.oriKvStride0 == 0) + ? static_cast(constInfo.kvSeqSize) * seqStride + : constInfo.oriKvStride0; + + uint64_t curS2 = info.s2StartPoint + kL1 * K_L0_SPLIT_SIZE; + uint64_t offset = (uint64_t)info.bIdx * batchStride + + (uint64_t)curS2 * seqStride + + (uint64_t)info.n2Idx * headStride + + nL1 * N_SPLIT_SIZE; + DataCopy(subvTensor, oriKvGm[offset], nd2nzPara); + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { + uint64_t curS2Offset = + static_cast(info.s2Idx) * constInfo.s2BaseSize + + info.s2StartPoint + kL1 * K_L0_SPLIT_SIZE; + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = kL0Size; // 行数 + nd2nzPara.dValue = N_SPLIT_SIZE; // constInfo.headDim; + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = kL0SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy( + bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE], + oriKvGm[info.tensorBOffset + curS2Offset * constInfo.headDim + + nL1 * N_SPLIT_SIZE], + nd2nzPara); + } + } else if (info.isOriCmpMix) { + uint32_t cumKl0LoopSize = kL1 * K_L0_SPLIT_SIZE; + uint32_t oriSizeCur = + (info.actualSingleProcessSInnerOriSize < cumKl0LoopSize) + ? 0 + : (info.actualSingleProcessSInnerOriSize - cumKl0LoopSize); + oriSizeCur = (oriSizeCur > kL0Size) ? kL0Size : oriSizeCur; + uint32_t cmpSizeCur = kL0Size - oriSizeCur; + cmpSizeCur = (cmpSizeCur < info.actualSingleProcessSInnerCmpSize) + ? cmpSizeCur + : info.actualSingleProcessSInnerCmpSize; + if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { + if (oriSizeCur > 0) { + copyFinishRowCnt = 0; + uint64_t curS2Offset = info.s2StartPoint + kL1 * K_L0_SPLIT_SIZE; + while (copyFinishRowCnt < oriSizeCur) { + copyRowCnt = constInfo.paOriBlockSize - + curS2Offset % constInfo.paOriBlockSize; + if (copyFinishRowCnt + copyRowCnt > oriSizeCur) { + copyRowCnt = oriSizeCur - copyFinishRowCnt; + } + Position startPos; + startPos.bIdx = info.bIdx; + startPos.n2Idx = info.n2Idx; + startPos.s2Idx = curS2Offset; + startPos.dIdx = + nL1 * N_SPLIT_SIZE; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 + // 右矩阵, s2为k轴, d轴切分 + PAShape shape; + shape.blockSize = constInfo.paOriBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.kvStride = constInfo.oriKvStride0; + shape.actHeadDim = nL1Size; + shape.maxblockNumPerBatch = constInfo.oriMaxBlockNumPerBatch; + shape.copyRowNum = copyRowCnt; + shape.copyRowNumAlign = kL0SizeAlign; + subvTensor = + bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE + + copyFinishRowCnt * 16]; + DataCopyPA( + subvTensor, oriKvGm, oriBlockTableGm, shape, startPos); + + // 更新循环变量 + copyFinishRowCnt += copyRowCnt; + curS2Offset += copyRowCnt; + } + } + if (cmpSizeCur > 0) { + copyFinishRowCnt = 0; + uint32_t cmpMixsizeCur = + K_L0_SPLIT_SIZE - + info.actualSingleProcessSInnerOriSize % K_L0_SPLIT_SIZE; + uint32_t oriOnlyLoopTimes = + info.actualSingleProcessSInnerOriSize / K_L0_SPLIT_SIZE; + uint32_t cmpLoopTimes = kL1 - oriOnlyLoopTimes; + uint64_t curS2Offset = + (cmpLoopTimes == 0) + ? 0 + : (cmpMixsizeCur + + static_cast(cmpLoopTimes - 1) * + K_L0_SPLIT_SIZE); + while (copyFinishRowCnt < cmpSizeCur) { + copyRowCnt = constInfo.paCmpBlockSize - + curS2Offset % constInfo.paCmpBlockSize; + if (copyFinishRowCnt + copyRowCnt > cmpSizeCur) { + copyRowCnt = cmpSizeCur - copyFinishRowCnt; + } + + Position startPos; + startPos.bIdx = info.bIdx; + startPos.n2Idx = info.n2Idx; + startPos.s2Idx = curS2Offset; + // 256、32等待7buf命名更改 + startPos.dIdx = + nL1 * N_SPLIT_SIZE; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 + // 右矩阵, s2为k轴, d轴切分 + + PAShape shape; + shape.blockSize = constInfo.paCmpBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.kvStride = constInfo.cmpKvStride0; + shape.actHeadDim = nL1Size; + shape.maxblockNumPerBatch = constInfo.cmpMaxBlockNumPerBatch; + shape.copyRowNum = copyRowCnt; + shape.copyRowNumAlign = kL0SizeAlign; + subvTensor = + bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE + + oriSizeCur * 16 + copyFinishRowCnt * 16]; + DataCopyPA( + subvTensor, cmpKvGm, cmpBlockTableGm, shape, startPos); + // 更新循环变量 + copyFinishRowCnt += copyRowCnt; + curS2Offset += copyRowCnt; + } + } + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = kL0Size; // 行数 + nd2nzPara.dValue = nL1Size; // 256 + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = kL0SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + + uint32_t headStride = constInfo.headDim; + uint32_t seqStride = constInfo.kvHeadNum * constInfo.headDim; + if (oriSizeCur > 0) { + subvTensor = + bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE]; + nd2nzPara.nValue = oriSizeCur; + uint64_t batchStride = + (constInfo.oriKvStride0 == 0) + ? static_cast(constInfo.kvSeqSize) * seqStride + : constInfo.oriKvStride0; + uint64_t curS2 = info.s2StartPoint + kL1 * K_L0_SPLIT_SIZE; + uint64_t offset = (uint64_t)info.bIdx * batchStride + + (uint64_t)curS2 * seqStride + + (uint64_t)info.n2Idx * headStride + + nL1 * N_SPLIT_SIZE; + DataCopy(subvTensor, oriKvGm[offset], nd2nzPara); + } + if (cmpSizeCur > 0) { + nd2nzPara.nValue = cmpSizeCur; + subvTensor = + bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE + + oriSizeCur * 16]; + uint64_t batchStride = + (constInfo.cmpKvStride0 == 0) + ? static_cast(constInfo.cmpSeqSize) * seqStride + : constInfo.cmpKvStride0; + uint32_t cmpMixsizeCur = + K_L0_SPLIT_SIZE - + info.actualSingleProcessSInnerOriSize % K_L0_SPLIT_SIZE; + uint32_t oriOnlyLoopTimes = + info.actualSingleProcessSInnerOriSize / K_L0_SPLIT_SIZE; + uint32_t cmpLoopTimes = kL1 - oriOnlyLoopTimes; + uint64_t curS2 = (cmpLoopTimes == 0) + ? 0 + : (cmpMixsizeCur + + static_cast(cmpLoopTimes - 1) * + K_L0_SPLIT_SIZE); + uint64_t offset = (uint64_t)info.bIdx * batchStride + + (uint64_t)curS2 * seqStride + + (uint64_t)info.n2Idx * headStride + + nL1 * N_SPLIT_SIZE; + DataCopy(subvTensor, cmpKvGm[offset], nd2nzPara); + } + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = kL0Size; // 行数 + nd2nzPara.dValue = N_SPLIT_SIZE; // constInfo.headDim; + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = kL0SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + + if (oriSizeCur > 0) { + nd2nzPara.nValue = oriSizeCur; + uint64_t curS2Offset = info.s2StartPoint + kL1 * K_L0_SPLIT_SIZE; + DataCopy( + bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE], + oriKvGm[info.tensorBOffset + curS2Offset * constInfo.headDim + + nL1 * N_SPLIT_SIZE], + nd2nzPara); + } + if (cmpSizeCur > 0) { + nd2nzPara.nValue = cmpSizeCur; + uint32_t cmpMixsizeCur = + K_L0_SPLIT_SIZE - + info.actualSingleProcessSInnerOriSize % K_L0_SPLIT_SIZE; + uint32_t oriOnlyLoopTimes = + info.actualSingleProcessSInnerOriSize / K_L0_SPLIT_SIZE; + uint32_t cmpLoopTimes = kL1 - oriOnlyLoopTimes; + uint64_t curS2Offset = + (cmpLoopTimes == 0) + ? 0 + : (cmpMixsizeCur + + static_cast(cmpLoopTimes - 1) * + K_L0_SPLIT_SIZE); + DataCopy( + bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE + + oriSizeCur * 16], + cmpKvGm[info.tensorCmpBOffset + + curS2Offset * constInfo.headDim + nL1 * N_SPLIT_SIZE], + nd2nzPara); + } + } + } else { + if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { + uint64_t curS2Offset = static_cast(info.relativeS2Idx) * + constInfo.s2BaseSize + + info.s2StartPoint + K_L0_SPLIT_SIZE * kL1; + while (copyFinishRowCnt < kL0Size) { + copyRowCnt = constInfo.paCmpBlockSize - + curS2Offset % constInfo.paCmpBlockSize; + if (copyFinishRowCnt + copyRowCnt > kL0Size) { + copyRowCnt = kL0Size - copyFinishRowCnt; + } + + Position startPos; + startPos.bIdx = info.bIdx; + startPos.n2Idx = info.n2Idx; + startPos.s2Idx = curS2Offset; + // 256、32等待7buf命名更改 + startPos.dIdx = + nL1 * N_SPLIT_SIZE; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 + // 右矩阵, s2为k轴, d轴切分 + + PAShape shape; + shape.blockSize = constInfo.paCmpBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.kvStride = constInfo.cmpKvStride0; + shape.actHeadDim = nL1Size; + shape.maxblockNumPerBatch = constInfo.cmpMaxBlockNumPerBatch; + shape.copyRowNum = copyRowCnt; + shape.copyRowNumAlign = kL0SizeAlign; + subvTensor = + bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE + + copyFinishRowCnt * 16]; + DataCopyPA( + subvTensor, cmpKvGm, cmpBlockTableGm, shape, startPos); + // 更新循环变量 + copyFinishRowCnt += copyRowCnt; + curS2Offset += copyRowCnt; + } + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { + subvTensor = + bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE]; + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = kL0Size; // 行数 + nd2nzPara.dValue = nL1Size; // 256 + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = kL0SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + + uint32_t headStride = constInfo.headDim; + uint32_t seqStride = constInfo.kvHeadNum * constInfo.headDim; + uint64_t batchStride = + (constInfo.cmpKvStride0 == 0) + ? static_cast(constInfo.cmpSeqSize) * seqStride + : constInfo.cmpKvStride0; + + uint64_t curS2 = + (uint64_t)info.relativeS2Idx * constInfo.s2BaseSize + + info.s2StartPoint + K_L0_SPLIT_SIZE * kL1; + uint64_t offset = (uint64_t)info.bIdx * batchStride + + (uint64_t)curS2 * seqStride + + (uint64_t)info.n2Idx * headStride + + nL1 * N_SPLIT_SIZE; + DataCopy(subvTensor, cmpKvGm[offset], nd2nzPara); + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { + uint64_t curS2Offset = static_cast(info.relativeS2Idx) * + constInfo.s2BaseSize + + info.s2StartPoint + K_L0_SPLIT_SIZE * kL1; + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = kL0Size; // 行数 + nd2nzPara.dValue = N_SPLIT_SIZE; // constInfo.headDim; + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = kL0SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy( + bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE], + cmpKvGm[info.tensorCmpBOffset + + curS2Offset * constInfo.headDim + nL1 * N_SPLIT_SIZE], + nd2nzPara); + } + } + } + SetFlag(mte21KVIds[kb]); + WaitFlag(mte21KVIds[kb]); + mL1SizeAlign = M_SPLIT_SIZE; + mL1Size = M_SPLIT_SIZE; // m的实际大小 + for (uint32_t mL1 = 0; mL1 < mL1Loops; mL1++) { + if (mL1 == (mL1Loops - 1)) { + // 尾块 + mL1Size = mSize - (mL1Loops - 1) * M_SPLIT_SIZE; + mL1SizeAlign = SMLAAlign(mL1Size, 16U); + } + + uint32_t mIdx = mBaseIdx + mL1; + ka = GetQPL1RealIdx(mIdx, k1); + LocalTensor aL1Tensor = l1QPTensor[ka * L1_BLOCK_OFFSET]; + if (nL1 == 0) { + WaitFlag(mte21QPIds[ka]); + CopyInMm2AToL1(aL1Tensor, + info, + mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, + mL1Size, + kL1Size, + 256 * k1); + SetFlag(mte21QPIds[ka]); + WaitFlag(mte21QPIds[ka]); + } + + LocalTensor cL0Tensor = cL0TensorPingPong + [(cL0BufIter % 2) * + (L0C_PP_SIZE / + sizeof(MM_OUT_T))]; // 需要保证cL0BufIter和m步调一致 + uint32_t baseK = 128; + uint32_t baseN = 128; + kL0Size = 128; + kL0SizeAlign = kL0Size; + for (uint32_t kL0 = 0; kL0 < kL0Loops; kL0++) { + if (kL0 + 1 == kL0Loops) { + kL0Size = kL1Size - (kL0Loops - 1) * kL0Size; + kL0SizeAlign = SMLAAlign(kL0Size, 16U); + } + WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); + LocalTensor bL0Tensor = + bL0TensorPingPong[(abL0BufIter % 2) * + (L0B_PP_SIZE / sizeof(KV_T))]; + LoadData3DParamsV2 loadData3DParamsForB; + loadData3DParamsForB.l1H = kL0SizeAlign / 16; // 源操作数height + loadData3DParamsForB.l1W = + 16; // 源操作数weight=16,目的height=l1H*L1W + loadData3DParamsForB.padList[0] = 0; + loadData3DParamsForB.padList[1] = 0; + loadData3DParamsForB.padList[2] = 0; + loadData3DParamsForB.padList[3] = 255; // 尾部数据不影响滑窗的结果 + + loadData3DParamsForB.mExtension = + kL0SizeAlign; // 在目的操作数height维度的传输长度 + loadData3DParamsForB.kExtension = + nL1SizeAlign; // 在目的操作数width维度的传输长度 + loadData3DParamsForB.mStartPt = + 0; // 卷积核在目的操作数width维度的起点 + loadData3DParamsForB.kStartPt = + 0; // 卷积核在目的操作数height维度的起点 + loadData3DParamsForB.strideW = 1; + loadData3DParamsForB.strideH = 1; + loadData3DParamsForB.filterW = 1; + loadData3DParamsForB.filterSizeW = + false; // 是否在filterW的基础上将卷积核width增加256个元素 + loadData3DParamsForB.filterH = 1; + loadData3DParamsForB.filterSizeH = + false; // 是否在filterH的基础上将卷积核height增加256个元素 + loadData3DParamsForB.dilationFilterW = 1; // 卷积核width膨胀系数 + loadData3DParamsForB.dilationFilterH = 1; // 卷积核height膨胀系数 + loadData3DParamsForB.enTranspose = 1; // 是否启用转置功能 + loadData3DParamsForB.fMatrixCtrl = + 0; // 使用FMATRIX_LEFT还是使用FMATRIX_RIGHT,=0使用FMATRIX_LEFT,=1使用FMATRIX_RIGHT + // 1 + loadData3DParamsForB.channelSize = + nL1SizeAlign; // 源操作数的通道数。膨胀系数为1时,目的weight为filterW*filterH*channelSize + LoadData( + bL0Tensor, bL1Tensor[kL0 * baseK * baseN], loadData3DParamsForB); + + LocalTensor aL0Tensor = + aL0TensorPingPong[(abL0BufIter % 2) * + (L0A_PP_SIZE / sizeof(KV_T))]; + LoadData3DParamsV2 loadData3DParamsForA; + loadData3DParamsForA.l1H = mL1SizeAlign / 16; // 源操作数height + loadData3DParamsForA.l1W = 16; // 源操作数weight + loadData3DParamsForA.padList[0] = 0; + loadData3DParamsForA.padList[1] = 0; + loadData3DParamsForA.padList[2] = 0; + loadData3DParamsForA.padList[3] = 255; // 尾部数据不影响滑窗的结果 + + loadData3DParamsForA.mExtension = + mL1SizeAlign; // 在目的操作数height维度的传输长度 + loadData3DParamsForA.kExtension = + kL0SizeAlign; // 在目的操作数width维度的传输长度 + loadData3DParamsForA.mStartPt = + 0; // 卷积核在目的操作数width维度的起点 + loadData3DParamsForA.kStartPt = + 0; // 卷积核在目的操作数height维度的起点 + loadData3DParamsForA.strideW = + 1; // 卷积核在源操作数width维度滑动的步长 + loadData3DParamsForA.strideH = + 1; // 卷积核在源操作数height维度滑动的步长 + loadData3DParamsForA.filterW = 1; // 卷积核width + loadData3DParamsForA.filterSizeW = + false; // 是否在filterW的基础上将卷积核width增加256个元素 + loadData3DParamsForA.filterH = 1; // 卷积核height + loadData3DParamsForA.filterSizeH = + false; // 是否在filterH的基础上将卷积核height增加256个元素 + loadData3DParamsForA.dilationFilterW = 1; // 卷积核width膨胀系数 + loadData3DParamsForA.dilationFilterH = 1; // 卷积核height膨胀系数 + loadData3DParamsForA.enTranspose = + 0; // 是否启用转置功能,对整个目标矩阵进行转置 + loadData3DParamsForA.fMatrixCtrl = 0; + loadData3DParamsForA.channelSize = + kL0SizeAlign; // 源操作数的通道数。膨胀系数为1时,目的weight为filterW*filterH*channelSize + LoadData(aL0Tensor, + aL1Tensor[kL0 * baseK * mL1SizeAlign], + loadData3DParamsForA); + SetFlag(Mte1MmABEventId(abL0BufIter % 2)); + WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); + + MmadParams mmadParams; + mmadParams.m = mL1SizeAlign; + mmadParams.n = nL1SizeAlign; + mmadParams.k = kL0Size; + mmadParams.cmatrixInitVal = (kL0 == 0 && k1 == 0); + mmadParams.cmatrixSource = false; + mmadParams.unitFlag = + ((k1 == (kL1Loops - 1)) && (kL0 == (kL0Loops - 1))) ? 0b11 : 0b10; + + Mmad(cL0Tensor, aL0Tensor, bL0Tensor, mmadParams); + if ((mmadParams.m / 16) * (mmadParams.n / 16) < 10) { + PipeBarrier(); + } + SetFlag(Mte1MmABEventId(abL0BufIter % 2)); + abL0BufIter++; + } + + if (nL1 == (nL1Loops - + 1)) { // nL1最后一轮, 需要将B驻留在L1中, 用于下一轮的计算? + SetFlag( + mte21QPIds[ka]); // 反向同步, 表示L1中的A已经被mte1消费完 + } + + if (k1 == (kL1Loops - 1)) { + // ND + FixpipeParamsV220 fixParams; + fixParams.nSize = nL1SizeAlign; + fixParams.mSize = mL1SizeAlign; + fixParams.srcStride = mL1SizeAlign; + fixParams.dstStride = nSize; // mm2ResGm两行之间的间隔 + fixParams.ndNum = 1; // 输出ND + fixParams.unitFlag = 0b11; + + uint64_t mm2Offset = + (mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE) * nSize + + nL1 * N_SPLIT_SIZE; + Fixpipe(mm2ResGm[(info.loop % (constInfo.preLoadNum)) * + constInfo.bmm2ResUbSize + + mm2Offset], + cL0Tensor, + fixParams); + } + + if (mL1Loops == 2) { + cL0BufIter++; + } + } + SetFlag( + mte21KVIds[kb]); // 反向同步, 表示L1已经被mte1消费完 + } + // cL0BufIter已经不在使用 + if (mL1Loops == 1) { + cL0BufIter++; + } + } + qpL1BufIter += mL1Loops; +} +} // namespace SMLAKernel +#endif diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_block_vector.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_block_vector.h new file mode 100644 index 0000000000..0f21d91480 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_block_vector.h @@ -0,0 +1,1688 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file sparse_flash_mla_swa_block_vector.h + * \brief + */ +#ifndef SPARSE_FLASH_MLA_SWA_BLOCK_VECTOR_H +#define SPARSE_FLASH_MLA_SWA_BLOCK_VECTOR_H + +#include "kernel_operator.h" +#include "kernel_operator_list_tensor_intf.h" +#include "kernel_tiling/kernel_tiling.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" +#include "sparse_flash_mla_common_arch22.h" + +namespace SMLAKernel { +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +template +class SWAVectorBlock { + public: + // 中间计算数据类型为float,高精度模式 + using T = float; + using KV_T = typename SMLAT::kvType; + using OUT_T = typename SMLAT::outputType; + using UPDATE_T = T; + using SINKS_T = T; + using MM1_OUT_T = float; + using MM2_OUT_T = float; + + __aicore__ inline SWAVectorBlock(){}; + __aicore__ inline void ProcessVec0L(const RunInfo& runInfo); + __aicore__ inline void ProcessVec1L(const RunInfo& info); + __aicore__ inline void ProcessVec2L(const RunInfo& info); + __aicore__ inline void InitBuffers(TPipe* pipe); + __aicore__ inline void InitParams( + const struct ConstInfo& constInfo, + const SparseFlashMlaTilingData* __restrict tilingData); + __aicore__ inline void InitVec0GlobalTensor( + GlobalTensor kvMergeGm, + GlobalTensor oriKvGm, + GlobalTensor oriBlockTableGm, + GlobalTensor oriSparseIndicesGm, + GlobalTensor oriTopkLengthGm); + __aicore__ inline void InitVec1GlobalTensor( + GlobalTensor mm1ResGm, + GlobalTensor vec1ResGm, + GlobalTensor actualSeqLengthsQGm, + GlobalTensor actualSeqLengthsKVGm, + GlobalTensor sinksGm, + GlobalTensor softmaxLseGm); + __aicore__ inline void InitVec2GlobalTensor( + GlobalTensor accumOutGm, + GlobalTensor vec2ResGm, + GlobalTensor mm2ResGm, + GlobalTensor attentionOutGm); + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + __aicore__ inline void CopySinksIn(); + __aicore__ inline void SliceAndContactSinksValue(uint32_t nIdx, + uint32_t dealRowCount); + __aicore__ inline void InitSoftmaxDefaultBuffer(); + // ================================Base + // Vector========================================== + __aicore__ inline void RowDivs(LocalTensor dstUb, + LocalTensor src0Ub, + LocalTensor src1Ub, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount); + __aicore__ inline void RowMuls(LocalTensor dstUb, + LocalTensor src0Ub, + LocalTensor src1Ub, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount); + // ================================Vector1========================================== + __aicore__ inline void ProcessVec1SingleBuf(const RunInfo& info, + const MSplitInfo& mSplitInfo); + __aicore__ inline void DealBmm1ResBaseBlock(const RunInfo& info, + const MSplitInfo& mSplitInfo, + uint32_t startRow, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t loopId); + __aicore__ inline void SoftmaxFlashV2Compute( + const RunInfo& info, + const MSplitInfo& mSplitInfo, + LocalTensor& mmResUb, + LocalTensor& softmaxTmpUb, + uint32_t startRow, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount); + __aicore__ inline void ElewiseCompute(const RunInfo& info, + const MSplitInfo& mSplitInfo, + const LocalTensor& mmResUb, + uint32_t dealRowCount, + uint32_t startRow, + uint32_t columnCount); + __aicore__ inline void ProcessLse(const RunInfo& info, + const MSplitInfo& mSplitInfo); + // ================================Vecotr2========================================== + __aicore__ inline void ProcessVec2SingleBuf(const RunInfo& info, + const MSplitInfo& mSplitInfo); + __aicore__ inline void DealBmm2ResBaseBlock(const RunInfo& info, + const MSplitInfo& mSplitInfo, + uint32_t startRow, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount); + __aicore__ inline void ProcessVec2Inner(const RunInfo& info, + const MSplitInfo& mSplitInfo, + uint32_t mStartRow, + uint32_t mDealSize); + __aicore__ inline void Bmm2DataCopyOutTrans(const RunInfo& info, + LocalTensor& attenOutUb, + uint32_t wsMStart, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount); + __aicore__ inline void Bmm2ResCopyOut(const RunInfo& info, + LocalTensor& bmm2ResUb, + uint32_t wsMStart, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount); + __aicore__ inline void Bmm2CastAndCopyOut(const RunInfo& info, + LocalTensor& bmm2ResUb, + uint32_t wsMStart, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount); + __aicore__ inline void Bmm2FDDataCopyOut(const RunInfo& info, + LocalTensor& bmm2ResUb, + uint32_t wsMStart, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount); + __aicore__ inline uint64_t CalcAccumOffset(uint32_t bN2Idx, uint32_t gS1Idx); + __aicore__ inline void SetInfInBlk(const LocalTensor& mmResUb, + uint32_t dealRowCount, + uint32_t columnCount, + int64_t startId, + int64_t endId); + + // BLOCK和REPEAT的字节数 + static constexpr uint64_t BYTE_BLOCK = 32UL; + static constexpr uint32_t REPEAT_BLOCK_BYTE = 256U; + // BLOCK和REPEAT的FP32元素数 + static constexpr uint32_t FP32_BLOCK_ELEMENT_NUM = BYTE_BLOCK / sizeof(float); + static constexpr uint32_t FP32_REPEAT_ELEMENT_NUM = + REPEAT_BLOCK_BYTE / sizeof(float); + // repeat stride不能超过256 + static constexpr uint32_t REPEATE_STRIDE_UP_BOUND = 256; + static constexpr uint64_t MERGE_CACHE_GM_BUF_NUM = 3; + static constexpr uint64_t MERGE_WORKSPACE_ROW_NUM = 512; + + private: + __aicore__ inline int64_t GetOriSparseKeyGmOffset(int32_t logicalIdx, + const RunInfo& runInfo); + __aicore__ inline void CopyInSingleOriSparseRow(int64_t& mte2Size, + int64_t mte3Size, + int64_t mergeMte3Idx, + int32_t logicalIdx, + const RunInfo& runInfo); + __aicore__ inline void CopyInOriSparseKv(int64_t& mte2Size, + int64_t mte3Size, + int64_t mergeMte3Idx, + int32_t logicalIdx0, + int32_t logicalIdx1, + const RunInfo& runInfo); + __aicore__ inline void CopyOutOriSparseMerge(int64_t mte2Size, + int64_t mte3Size, + int64_t s2GmStartOffset, + int64_t mergeMte3Idx, + const RunInfo& runInfo); + __aicore__ inline int32_t AlignOriSparseIndexLoadCount(int32_t loadCount); + __aicore__ inline void LoadOriSparseIndicesGmToUb( + uint64_t qTokenOffset, + uint32_t n2Idx, + uint32_t gmColStart, + int32_t loadCount, + const LocalTensor& dstUb); + static constexpr bool PAGE_ATTENTION = SMLAT::pageAttention; + static constexpr bool FLASH_DECODE = SMLAT::flashDecode; + static constexpr SMLA_LAYOUT LAYOUT_T = SMLAT::layout; + static constexpr SMLA_LAYOUT KV_LAYOUT_T = SMLAT::kvLayout; + static constexpr bool IS_DSPARK = SMLAT::isDspark; + + static constexpr uint64_t SYNC_INPUT_BUF1_FLAG = 2; + static constexpr uint64_t SYNC_INPUT_BUF1_PONG_FLAG = 3; + static constexpr uint64_t SYNC_INPUT_BUF2_FLAG = 4; + static constexpr uint64_t SYNC_INPUT_BUF2_PONG_FLAG = 5; + static constexpr uint64_t SYNC_OUTPUT_BUF1_FLAG = 4; + static constexpr uint64_t SYNC_OUTPUT_BUF2_FLAG = 5; + static constexpr uint64_t SYNC_SINKS_BUF_FLAG = 6; + static constexpr uint32_t INPUT1_BUFFER_OFFSET = + ConstInfo::BUFFER_SIZE_BYTE_32K; + static constexpr uint32_t SOFTMAX_TMP_BUFFER_OFFSET = + ConstInfo::BUFFER_SIZE_BYTE_1K; + static constexpr uint32_t BASE_BLOCK_MAX_ELEMENT_NUM = + ConstInfo::BUFFER_SIZE_BYTE_32K / sizeof(T); + static constexpr uint32_t BLOCK_ELEMENT_NUM = BYTE_BLOCK / sizeof(T); + static constexpr uint32_t MAX_N1_SIZE = 128U; + static constexpr T SOFTMAX_MIN_NUM = -2e38; + static constexpr SINKS_T R0 = 1.0f; + + const SparseFlashMlaTilingData* __restrict tilingData; + + uint32_t pingpongFlag = 0U; + ConstInfo constInfo = {}; + + GlobalTensor mm1ResGm; + GlobalTensor vec1ResGm; + GlobalTensor softmaxMaxGm; + GlobalTensor softmaxSumGm; + GlobalTensor sinksGm; + + GlobalTensor actualSeqLengthsQGm; + GlobalTensor actualSeqLengthsKVGm; + GlobalTensor oriSparseIndicesGm; + GlobalTensor oriTopkLengthGm; + GlobalTensor vec2ResGm; + GlobalTensor mm2ResGm; + GlobalTensor accumOutGm; + GlobalTensor attentionOutGm; + GlobalTensor blkTableGm_; + GlobalTensor keyGm_; + GlobalTensor kvValidSizeGm_; + GlobalTensor oriKvGm_; + GlobalTensor cmpKvGm_; + GlobalTensor oriBlockTableGm_; + GlobalTensor cmpBlockTableGm_; + GlobalTensor kvMergeGm_; + GlobalTensor softmaxLseGm; + + // ================================Local + // Buffer区==================================== + TBuf<> inputBuff1; // 32K + TBuf<> inputBuff2; // 8K + TBuf<> outputBuff1; // 32K + TBuf<> outputBuff2; // 4K + + TBuf<> tmpBuff1; // 32K + TBuf<> v0ValidSizeBuff; // 8K + TBuf<> sinksBuff; // 1K + TBuf<> sinksBrcbBuff; // 12K + + TBuf<> softmaxMaxBuff; // PRE_LOAD_NUM * 2K + TBuf<> softmaxExpBuff; // PRE_LOAD_NUM * 2K + TBuf<> softmaxSumBuff; // PRE_LOAD_NUM * 2K + TBuf<> softmaxMaxDefaultBuff; // 2K + TBuf<> softmaxSumDefaultBuff; // 2K + + LocalTensor softmaxMaxDefaultUb; + LocalTensor softmaxSumDefaultUb; + + LocalTensor softmaxMaxUb; + LocalTensor softmaxSumUb; + LocalTensor softmaxExpUb; + LocalTensor sinksUb; + LocalTensor sinksBrcbUb; + LocalTensor kvMergUb_; + uint32_t mergeMte3Idx = 0; +}; + +// ============================== init +// ============================================== +template +__aicore__ inline void SWAVectorBlock::InitBuffers(TPipe* pipe) { + pipe->InitBuffer(inputBuff1, + ConstInfo::BUFFER_SIZE_BYTE_32K * 2); // 2:pingpong + pipe->InitBuffer(inputBuff2, + ConstInfo::BUFFER_SIZE_BYTE_8K * 2); // 2:pingpong + pipe->InitBuffer(outputBuff1, ConstInfo::BUFFER_SIZE_BYTE_32K); + pipe->InitBuffer(outputBuff2, ConstInfo::BUFFER_SIZE_BYTE_4K); + + pipe->InitBuffer(tmpBuff1, ConstInfo::BUFFER_SIZE_BYTE_32K); + pipe->InitBuffer(v0ValidSizeBuff, ConstInfo::BUFFER_SIZE_BYTE_8K); + // M_MAX = 512/2vector = 256, 256 * sizeof(T) * N_Buffer + pipe->InitBuffer(softmaxMaxBuff, + ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); + pipe->InitBuffer(softmaxExpBuff, + ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); + pipe->InitBuffer(softmaxSumBuff, + ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); + + pipe->InitBuffer(softmaxMaxDefaultBuff, ConstInfo::BUFFER_SIZE_BYTE_1K); + pipe->InitBuffer(softmaxSumDefaultBuff, ConstInfo::BUFFER_SIZE_BYTE_1K); + + pipe->InitBuffer(sinksBuff, MAX_N1_SIZE * sizeof(SINKS_T)); + // 分配256+N1大小内存,其中256是m轴VEC最大切块 + pipe->InitBuffer(sinksBrcbBuff, + MAX_N1_SIZE * sizeof(SINKS_T) * BLOCK_ELEMENT_NUM * 3U); + + softmaxMaxUb = softmaxMaxBuff.Get(); + softmaxSumUb = softmaxSumBuff.Get(); + softmaxExpUb = softmaxExpBuff.Get(); + + softmaxMaxDefaultUb = softmaxMaxDefaultBuff.Get(); + softmaxSumDefaultUb = softmaxSumDefaultBuff.Get(); + + sinksUb = sinksBuff.Get(); + sinksBrcbUb = sinksBrcbBuff.Get(); + if constexpr (IS_DSPARK) { + kvMergUb_ = inputBuff1.Get(); + } +} + +template +__aicore__ inline void SWAVectorBlock::InitParams( + const struct ConstInfo& constInfo, + const SparseFlashMlaTilingData* __restrict tilingData) { + this->constInfo = constInfo; + this->tilingData = tilingData; +} + +template +__aicore__ inline void SWAVectorBlock::InitVec0GlobalTensor( + GlobalTensor kvMergeGm, + GlobalTensor oriKvGm, + GlobalTensor oriBlockTableGm, + GlobalTensor oriSparseIndicesGm, + GlobalTensor oriTopkLengthGm) { + this->kvMergeGm_ = kvMergeGm; + this->oriKvGm_ = oriKvGm; + this->oriBlockTableGm_ = oriBlockTableGm; + this->oriSparseIndicesGm = oriSparseIndicesGm; + this->oriTopkLengthGm = oriTopkLengthGm; +} + +template +__aicore__ inline int64_t SWAVectorBlock::GetOriSparseKeyGmOffset( + int32_t logicalIdx, + const RunInfo& runInfo) { + if (logicalIdx < 0) { + return -1; + } + int32_t oriLenLimit = actualSeqLengthsKVGm.GetValue(runInfo.bIdx); + if (logicalIdx >= oriLenLimit) { + return -1; + } + uint64_t blockTableIdx = + static_cast(logicalIdx) / constInfo.paOriBlockSize; + uint64_t inBlockIdx = + static_cast(logicalIdx) % constInfo.paOriBlockSize; + uint64_t idInBlockTable = oriBlockTableGm_.GetValue( + runInfo.bIdx * constInfo.oriMaxBlockNumPerBatch + blockTableIdx); + return static_cast(idInBlockTable * constInfo.oriKvStride0 + + static_cast(runInfo.n2IdxReal) * + constInfo.headDim * constInfo.paOriBlockSize + + inBlockIdx * constInfo.headDim); +} + +template +__aicore__ inline void SWAVectorBlock::CopyInSingleOriSparseRow( + int64_t& mte2Size, + int64_t mte3Size, + int64_t mergeMte3Idx, + int32_t logicalIdx, + const RunInfo& runInfo) { + int64_t keyOffset = GetOriSparseKeyGmOffset(logicalIdx, runInfo); + if (keyOffset >= 0) { + int64_t ubRowOffset = + mergeMte3Idx % 2 * INPUT1_BUFFER_OFFSET / sizeof(KV_T) + + (mte2Size - mte3Size) * constInfo.headDim; + DataCopyExtParams copyInParams; + copyInParams.blockCount = 1; + copyInParams.blockLen = constInfo.headDim * sizeof(KV_T); + copyInParams.srcStride = 0; + copyInParams.dstStride = 0; + DataCopyPadExtParams padInParams{false, 0, 0, 0}; + DataCopyPad( + kvMergUb_[ubRowOffset], oriKvGm_[keyOffset], copyInParams, padInParams); + } + mte2Size += constInfo.sparseBlockSize; +} + +template +__aicore__ inline void SWAVectorBlock::CopyInOriSparseKv( + int64_t& mte2Size, + int64_t mte3Size, + int64_t mergeMte3Idx, + int32_t logicalIdx0, + int32_t logicalIdx1, + const RunInfo& runInfo) { + int64_t keyOffset1 = GetOriSparseKeyGmOffset(logicalIdx0, runInfo); + int64_t keyOffset2 = GetOriSparseKeyGmOffset(logicalIdx1, runInfo); + if (logicalIdx1 < 0) { + CopyInSingleOriSparseRow( + mte2Size, mte3Size, mergeMte3Idx, logicalIdx0, runInfo); + return; + } + if (unlikely(keyOffset1 < 0 && keyOffset2 < 0)) { + // invalid 行仅占 merge 行位,不搬 KV;V1 按索引刷 -inf,值无关 + mte2Size += 2 * constInfo.sparseBlockSize; + return; + } + + int64_t keySrcStride = + ((keyOffset1 > keyOffset2 ? (keyOffset1 - keyOffset2) + : (keyOffset2 - keyOffset1)) - + constInfo.sparseBlockSize * constInfo.headDim) * + static_cast(sizeof(KV_T)); + if (unlikely(keySrcStride >= INT32_MAX || keySrcStride < 0 || + keyOffset1 < 0 || keyOffset2 < 0)) { + CopyInSingleOriSparseRow( + mte2Size, mte3Size, mergeMte3Idx, logicalIdx0, runInfo); + CopyInSingleOriSparseRow( + mte2Size, mte3Size, mergeMte3Idx, logicalIdx1, runInfo); + } else { + DataCopyExtParams intriParams; + intriParams.blockLen = + constInfo.sparseBlockSize * constInfo.headDim * sizeof(KV_T); + intriParams.blockCount = (keyOffset1 >= 0) + (keyOffset2 >= 0); + intriParams.dstStride = 0; + intriParams.srcStride = keySrcStride; + DataCopyPadExtParams padParams{false, 0, 0, 0}; + int64_t startGmOffset = keyOffset1 > -1 ? keyOffset1 : keyOffset2; + if (keyOffset2 > -1 && keyOffset2 < keyOffset1) { + startGmOffset = keyOffset2; + } + DataCopyPad( + kvMergUb_[mergeMte3Idx % 2 * INPUT1_BUFFER_OFFSET / sizeof(KV_T) + + (mte2Size - mte3Size) * constInfo.headDim], + oriKvGm_[startGmOffset], + intriParams, + padParams); + mte2Size += 2 * constInfo.sparseBlockSize; + } +} + +template +__aicore__ inline void SWAVectorBlock::CopyOutOriSparseMerge( + int64_t mte2Size, + int64_t mte3Size, + int64_t s2GmStartOffset, + int64_t mergeMte3Idx, + const RunInfo& runInfo) { + if (mte2Size <= mte3Size) { + return; + } + SetFlag(mergeMte3Idx % 2 + + SYNC_INPUT_BUF2_FLAG); + WaitFlag(mergeMte3Idx % 2 + + SYNC_INPUT_BUF2_FLAG); + + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = static_cast(mte2Size - mte3Size); + dataCopyParams.blockLen = constInfo.headDim * sizeof(KV_T); + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = 0; + DataCopyPad(kvMergeGm_[runInfo.cmpLoop % MERGE_CACHE_GM_BUF_NUM * + MERGE_WORKSPACE_ROW_NUM * constInfo.headDim + + (s2GmStartOffset + mte3Size) * constInfo.headDim], + kvMergUb_[mergeMte3Idx % 2 * INPUT1_BUFFER_OFFSET / sizeof(KV_T)], + dataCopyParams); + SetFlag(mergeMte3Idx % 2 + + SYNC_INPUT_BUF2_FLAG); + WaitFlag(mergeMte3Idx % 2 + + SYNC_INPUT_BUF2_FLAG); +} + +template +__aicore__ inline int32_t SWAVectorBlock::AlignOriSparseIndexLoadCount( + int32_t loadCount) { + if (loadCount <= 0) { + return 0; + } + // MTE blockLen must be 32B-aligned; int32 slot count aligns to 8 elements. + return ((loadCount + 7) / 8) * 8; +} + +template +__aicore__ inline void SWAVectorBlock::LoadOriSparseIndicesGmToUb( + uint64_t qTokenOffset, + uint32_t n2Idx, + uint32_t gmColStart, + int32_t loadCount, + const LocalTensor& dstUb) { + if (loadCount <= 0 || constInfo.oriSparseIndexWidth == 0) { + return; + } + int32_t remain = static_cast(constInfo.oriSparseIndexWidth) - + static_cast(gmColStart); + int32_t validCount = (remain < loadCount) ? remain : loadCount; + if (validCount <= 0) { + return; + } + int32_t alignedCount = AlignOriSparseIndexLoadCount(loadCount); + uint64_t gmOffset = (qTokenOffset * constInfo.kvHeadNum + n2Idx) * + constInfo.oriSparseIndexWidth + + gmColStart; + + // dstUb来自tmpBuff1,需要上一轮的getvalue(S)结束再开始搬入 + event_t sToMte2 = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_MTE2)); + SetFlag(sToMte2); + WaitFlag(sToMte2); + + DataCopyExtParams copyParams; + copyParams.blockCount = 1; + copyParams.blockLen = static_cast(validCount) * sizeof(int32_t); + copyParams.srcStride = 0; + copyParams.dstStride = 0; + DataCopyPadExtParams padParams; + padParams.isPad = true; + padParams.leftPadding = 0; + padParams.rightPadding = static_cast(alignedCount - validCount); + padParams.paddingValue = -1; + DataCopyPad(dstUb, oriSparseIndicesGm[gmOffset], copyParams, padParams); + event_t mte2ToS = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_S)); + SetFlag(mte2ToS); + WaitFlag(mte2ToS); +} + +template +__aicore__ inline void SWAVectorBlock::ProcessVec0L( + const RunInfo& runInfo) { + int64_t s2ProcessSize = runInfo.v0S2DealSize; + if (s2ProcessSize <= 0) { + return; + } + uint32_t sparseColStart = runInfo.s2Idx * constInfo.s2BaseSize + + static_cast(runInfo.v0S2Start); + int64_t s2Pair = CeilDiv(s2ProcessSize, 2 * constInfo.sparseBlockSize); + int64_t s2SplitPoint = SMLAAlign(s2Pair, 2) * constInfo.sparseBlockSize; + int64_t s2GmStartOffset = GetSubBlockIdx() == 0 ? 0 : s2SplitPoint; + int64_t s2GmLimit = GetSubBlockIdx() == 0 ? s2SplitPoint : s2ProcessSize; + if (s2GmLimit > s2ProcessSize) { + s2GmLimit = s2ProcessSize; + } + if (s2GmStartOffset >= s2GmLimit) { + return; + } + // V0 reuses both inputBuff1 halves after V1/V2 release their MTE2 access. + WaitFlag(SYNC_INPUT_BUF1_FLAG); + WaitFlag(SYNC_INPUT_BUF1_PONG_FLAG); + + LocalTensor sliceUb = v0ValidSizeBuff.Get(); + LoadOriSparseIndicesGmToUb( + runInfo.qTokenOffset, + runInfo.n2IdxReal, + sparseColStart + static_cast(s2GmStartOffset), + static_cast(s2GmLimit - s2GmStartOffset), + sliceUb); + + int64_t s2LocalSize = s2GmLimit - s2GmStartOffset; + int64_t mte2Size = 0; + int64_t mte3Size = 0; + bool needWaitMte3ToMte2 = true; + for (int64_t s2GmOffsetArray = 0; s2GmOffsetArray < s2LocalSize; + s2GmOffsetArray += 2 * constInfo.sparseBlockSize) { + if (needWaitMte3ToMte2) { + WaitFlag(mergeMte3Idx % 2 + + SYNC_INPUT_BUF2_FLAG); + needWaitMte3ToMte2 = false; + } + int32_t logicalIdx0 = + sliceUb.GetValue(static_cast(s2GmOffsetArray)); + int32_t logicalIdx1 = -1; + if (s2GmOffsetArray + constInfo.sparseBlockSize < s2LocalSize) { + logicalIdx1 = sliceUb.GetValue( + static_cast(s2GmOffsetArray + constInfo.sparseBlockSize)); + } + CopyInOriSparseKv( + mte2Size, mte3Size, mergeMte3Idx, logicalIdx0, logicalIdx1, runInfo); + if ((mte2Size - mte3Size + 2 * constInfo.sparseBlockSize > 16) || + s2GmOffsetArray + 2 * constInfo.sparseBlockSize >= s2LocalSize) { + CopyOutOriSparseMerge( + mte2Size, mte3Size, s2GmStartOffset, mergeMte3Idx, runInfo); + mte3Size = mte2Size; + SetFlag(mergeMte3Idx % 2 + + SYNC_INPUT_BUF2_FLAG); + mergeMte3Idx++; + needWaitMte3ToMte2 = true; + } + } + // CopyOutOriSparseMerge drains V0's MTE3 read before V1/V2 reuse inputBuff1. + SetFlag(SYNC_INPUT_BUF1_FLAG); + SetFlag(SYNC_INPUT_BUF1_PONG_FLAG); +} + +template +__aicore__ inline void SWAVectorBlock::InitVec1GlobalTensor( + GlobalTensor mm1ResGm, + GlobalTensor vec1ResGm, + GlobalTensor actualSeqLengthsQGm, + GlobalTensor actualSeqLengthsKVGm, + GlobalTensor sinksGm, + GlobalTensor softmaxLseGm) { + this->mm1ResGm = mm1ResGm; + this->vec1ResGm = vec1ResGm; + this->actualSeqLengthsQGm = actualSeqLengthsQGm; + this->actualSeqLengthsKVGm = actualSeqLengthsKVGm; + this->sinksGm = sinksGm; + this->softmaxLseGm = softmaxLseGm; +} + +template +__aicore__ inline void SWAVectorBlock::InitVec2GlobalTensor( + GlobalTensor accumOutGm, + GlobalTensor vec2ResGm, + GlobalTensor mm2ResGm, + GlobalTensor attentionOutGm) { + this->accumOutGm = accumOutGm; + this->vec2ResGm = vec2ResGm; + this->mm2ResGm = mm2ResGm; + this->attentionOutGm = attentionOutGm; +} + +template +__aicore__ inline void SWAVectorBlock::AllocEventID() { + SetFlag(SYNC_INPUT_BUF1_FLAG); + SetFlag(SYNC_INPUT_BUF1_PONG_FLAG); + SetFlag(SYNC_INPUT_BUF2_FLAG); + SetFlag(SYNC_INPUT_BUF2_PONG_FLAG); + if constexpr (IS_DSPARK) { + SetFlag(SYNC_INPUT_BUF2_FLAG); + SetFlag(SYNC_INPUT_BUF2_PONG_FLAG); + } + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); +} + +template +__aicore__ inline void SWAVectorBlock::FreeEventID() { + WaitFlag(SYNC_INPUT_BUF1_FLAG); + WaitFlag(SYNC_INPUT_BUF1_PONG_FLAG); + WaitFlag(SYNC_INPUT_BUF2_FLAG); + WaitFlag(SYNC_INPUT_BUF2_PONG_FLAG); + if constexpr (IS_DSPARK) { + WaitFlag(SYNC_INPUT_BUF2_FLAG); + WaitFlag(SYNC_INPUT_BUF2_PONG_FLAG); + } + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); +} + +template +__aicore__ inline void SWAVectorBlock::CopySinksIn() { + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = 1U; + dataCopyParams.blockLen = constInfo.qHeadNum * sizeof(T); + dataCopyParams.srcStride = 0U; + dataCopyParams.dstStride = 0U; + DataCopyPadExtParams padParams; + DataCopyPad(sinksUb, sinksGm, dataCopyParams, padParams); + SetFlag(SYNC_SINKS_BUF_FLAG); + WaitFlag(SYNC_SINKS_BUF_FLAG); + uint32_t repeatTimes = + (constInfo.qHeadNum + BLOCK_ELEMENT_NUM - 1U) / BLOCK_ELEMENT_NUM; + Brcb(sinksBrcbUb, sinksUb, repeatTimes, {1, BLOCK_ELEMENT_NUM}); + PipeBarrier(); + + DataCopyParams repeatParams; + repeatParams.blockCount = + 1; // 搬到有一个块超过单个vec核减分核M轴大小即可,核间切分每个vec256 + repeatParams.blockLen = constInfo.qHeadNum; + repeatParams.srcStride = 0U; + repeatParams.dstStride = 0U; + for (uint32_t i = 1U; i <= 256U / constInfo.qHeadNum; i++) { + DataCopy(sinksBrcbUb[constInfo.qHeadNum * BLOCK_ELEMENT_NUM * i], + sinksBrcbUb, + repeatParams); + } + PipeBarrier(); +} + +template +__aicore__ inline void SWAVectorBlock::SliceAndContactSinksValue( + uint32_t nIdx, + uint32_t dealRowCount) { + // 由于WholeReduceMax接口中repeatTimes支持范围(0,255),因此需要分多次调用WholeReduceMax,这里就使用每次repeatTime=128 + uint32_t repeatTimesOnce = 128; + uint32_t loopTimes = (dealRowCount + repeatTimesOnce - 1) / repeatTimesOnce; + uint32_t repeatTimes = repeatTimesOnce; + + for (uint32_t loop = 0; loop < loopTimes; ++loop) { + if (loop == loopTimes - 1) { + repeatTimes = dealRowCount - loop * repeatTimesOnce; + } + WholeReduceMax( + softmaxMaxDefaultUb[loop * repeatTimesOnce], + sinksBrcbUb[(nIdx + loop * repeatTimesOnce) * BLOCK_ELEMENT_NUM], + BLOCK_ELEMENT_NUM * BLOCK_ELEMENT_NUM, + repeatTimes, + 1, + 0, + 1, + ReduceOrder::ORDER_ONLY_VALUE); + PipeBarrier(); + } +} + +template +__aicore__ inline void SWAVectorBlock::InitSoftmaxDefaultBuffer() { + CopySinksIn(); + Duplicate(softmaxMaxDefaultUb, + SOFTMAX_MIN_NUM, + SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)); + Duplicate(softmaxSumDefaultUb, R0, SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)); +} + +template +__aicore__ inline void SWAVectorBlock::ElewiseCompute( + const RunInfo& info, + const MSplitInfo& mSplitInfo, + const LocalTensor& mmResUb, + uint32_t startRow, + uint32_t dealRowCount, + uint32_t columnCount) { + Muls(mmResUb, + mmResUb, + static_cast(tilingData->baseParams.softmaxScale), + dealRowCount * columnCount); + uint32_t gs1StartIdx = + info.gS1Idx + mSplitInfo.nBufferStartM + mSplitInfo.vecStartM + startRow; + uint32_t gs1EndIdx = gs1StartIdx + dealRowCount; + uint32_t s1StartIdx = gs1StartIdx / constInfo.gSize; + uint32_t s1EndIdx = gs1EndIdx / constInfo.gSize; + uint32_t gStartIdx = gs1StartIdx % constInfo.gSize; + uint32_t gEndIdx = gs1EndIdx % constInfo.gSize; + uint32_t dealTempSize = 0; + uint32_t ubOffset = 0; + if (info.isOriOnly) { + if constexpr (IS_DSPARK) { + int32_t oriLenLimit = actualSeqLengthsKVGm.GetValue(info.bIdx); + uint32_t validCols = Min(info.actualSingleProcessSInnerSize, columnCount); + uint32_t sparseColStart = info.s2Idx * constInfo.s2BaseSize; + for (uint32_t i = s1StartIdx; i <= s1EndIdx; i++) { + dealTempSize = constInfo.gSize - gStartIdx; + if (i == s1EndIdx) { + dealTempSize = gEndIdx - gStartIdx; + } + if (dealTempSize == 0) { + continue; + } + uint64_t qTokenOffsetForS1 = 0; + if constexpr (LAYOUT_T == SMLA_LAYOUT::TND) { + qTokenOffsetForS1 = + static_cast(actualSeqLengthsQGm.GetValue(info.bIdx)) + + static_cast(i); + } else { + qTokenOffsetForS1 = + static_cast(info.bIdx) * constInfo.qSeqSize + + static_cast(i); + } + uint64_t topkLenOffset = + qTokenOffsetForS1 * constInfo.kvHeadNum + info.n2IdxReal; + int32_t rowLen = oriTopkLengthGm.GetValue(topkLenOffset); + if (rowLen <= 0) { + SetInfInBlk(mmResUb[ubOffset], + dealTempSize, + columnCount, + 0, + static_cast(columnCount - 1)); + ubOffset += dealTempSize * columnCount; + gStartIdx = 0; + continue; + } + uint32_t colEnd = 0; + uint32_t tailStart = 0; + if (static_cast(rowLen) > sparseColStart) { + colEnd = + Min(validCols, static_cast(rowLen) - sparseColStart); + tailStart = static_cast(rowLen) - sparseColStart; + } + if (colEnd > 0) { + LocalTensor rowIndexUb = tmpBuff1.Get(); + event_t vToMte2 = static_cast( + GetTPipePtr()->FetchEventID(HardEvent::V_MTE2)); + SetFlag(vToMte2); + WaitFlag(vToMte2); + LoadOriSparseIndicesGmToUb(qTokenOffsetForS1, + info.n2IdxReal, + sparseColStart, + static_cast(colEnd), + rowIndexUb); + for (uint32_t k = 0; k < colEnd; ++k) { + int32_t logicalIdx = rowIndexUb.GetValue(k); + if (logicalIdx < 0 || logicalIdx >= oriLenLimit) { + SetInfInBlk(mmResUb[ubOffset], + dealTempSize, + columnCount, + static_cast(k), + static_cast(k)); + } + } + } + if (tailStart < validCols) { + SetInfInBlk(mmResUb[ubOffset], + dealTempSize, + columnCount, + static_cast(tailStart), + static_cast(validCols - 1)); + } + if (info.actualSingleProcessSInnerSize < columnCount) { + SetInfInBlk(mmResUb[ubOffset], + dealTempSize, + columnCount, + static_cast(info.actualSingleProcessSInnerSize), + static_cast(columnCount - 1)); + } + ubOffset += dealTempSize * columnCount; + gStartIdx = 0; + } + // rowIndexUb来自tmpBuff1,后续的softmaxTmpUb(V)处理需要等此处getvalue(S)结束 + event_t sToV = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); + SetFlag(sToV); + WaitFlag(sToV); + + } else { + int32_t right = + info.oriDealSize + s1StartIdx - info.gS1Idx / constInfo.gSize; + int32_t left = Max(0, + static_cast(right) - constInfo.oriWinLeft + + constInfo.oriWinRight); + for (uint32_t i = s1StartIdx; i <= s1EndIdx; i++) { + dealTempSize = constInfo.gSize - gStartIdx; + if (i == s1EndIdx) { + dealTempSize = gEndIdx - gStartIdx; + } + if (dealTempSize == 0) { + continue; + } + SetInfInBlk(mmResUb[ubOffset], dealTempSize, columnCount, 0, left - 1); + SetInfInBlk(mmResUb[ubOffset], + dealTempSize, + columnCount, + right + 1, + columnCount - 1); + right = Min(right + 1, columnCount - 1); + left = Max(0, + static_cast(right) - constInfo.oriWinLeft + + constInfo.oriWinRight); + ubOffset += dealTempSize * columnCount; + gStartIdx = 0; + } + } + } else if (info.isOriCmpMix) { + int32_t oriRight = + info.oriDealSize + s1StartIdx - info.gS1Idx / constInfo.gSize; + int32_t oriLeft = Max(0, + static_cast(oriRight) - + constInfo.oriWinLeft + constInfo.oriWinRight); + int32_t noMaskCmpSize = info.cmpMaskRight + s1StartIdx + 1; + int32_t actNoMaskCmpSize = 0; + int32_t cmpRight = 0; + for (uint32_t i = s1StartIdx; i <= s1EndIdx; i++) { + dealTempSize = constInfo.gSize - gStartIdx; + if (i == s1EndIdx) { + dealTempSize = gEndIdx - gStartIdx; + } + if (dealTempSize == 0) { + continue; + } + actNoMaskCmpSize = noMaskCmpSize / constInfo.cmpRatio; + if (actNoMaskCmpSize <= 0) { + cmpRight = 0; + } else { + cmpRight = + Min(actNoMaskCmpSize, + constInfo.s2BaseSize - info.actualSingleProcessSInnerOriSize); + } + SetInfInBlk(mmResUb[ubOffset], dealTempSize, columnCount, 0, oriLeft - 1); + SetInfInBlk(mmResUb[ubOffset], + dealTempSize, + columnCount, + oriRight + 1, + info.actualSingleProcessSInnerOriSize - 1); + oriRight = Min(oriRight + 1, info.actualSingleProcessSInnerOriSize); + oriLeft = Max(0, + static_cast(oriRight) - constInfo.oriWinLeft + + constInfo.oriWinRight); + SetInfInBlk(mmResUb[ubOffset], + dealTempSize, + columnCount, + cmpRight + info.actualSingleProcessSInnerOriSize, + columnCount - 1); + noMaskCmpSize += 1; + ubOffset += dealTempSize * columnCount; + gStartIdx = 0; + } + } else { + int32_t noMaskCmpSize = info.cmpMaskRight + s1StartIdx + 1; + int32_t actNoMaskCmpSize = 0; + int32_t right = 0; + // relativeS2Idx is the cmp tile index relative to the current batch. + // s2Idx may include the global task index. + int64_t cmpTileStart = + static_cast(info.relativeS2Idx) * constInfo.s2BaseSize + + static_cast(info.s2StartPoint); + for (uint32_t i = s1StartIdx; i <= s1EndIdx; i++) { + actNoMaskCmpSize = noMaskCmpSize / constInfo.cmpRatio; + if (actNoMaskCmpSize <= 0) { + right = 0; + } else { + right = actNoMaskCmpSize - cmpTileStart; + } + dealTempSize = constInfo.gSize - gStartIdx; + if (i == s1EndIdx) { + dealTempSize = gEndIdx - gStartIdx; + } + if (dealTempSize == 0) { + continue; + } + SetInfInBlk( + mmResUb[ubOffset], dealTempSize, columnCount, right, columnCount - 1); + noMaskCmpSize += 1; + ubOffset += dealTempSize * columnCount; + gStartIdx = 0; + } + } +} + +template +__aicore__ inline void SWAVectorBlock::SetInfInBlk( + const LocalTensor& mmResUb, + uint32_t dealRowCount, + uint32_t columnCount, + int64_t startId, + int64_t endId) { + // startId endId + // x x x 0 0 0 x x x + // 从startId到endId部分置-inf, endId、startId为endId一个blk内部的下标 + // 左闭右闭 + if (startId > endId) { + return; + } + int64_t start = startId < 0 ? 0 : startId; + int64_t end = endId >= static_cast(columnCount) + ? static_cast(columnCount) - 1 + : endId; + if (start > end) { + return; + } + + uint64_t curStart = static_cast(start); + uint64_t curEnd = static_cast(end); + while (curStart <= curEnd) { + uint64_t blockStart = curStart / BLOCK_ELEMENT_NUM * BLOCK_ELEMENT_NUM; + uint64_t blockEnd = blockStart + BLOCK_ELEMENT_NUM - 1; + blockEnd = blockEnd > curEnd ? curEnd : blockEnd; + + uint64_t preMask = (1llu << (curStart - blockStart)) - 1; + uint64_t postMask = ~((1llu << (blockEnd - blockStart + 1)) - 1); + uint64_t mask[1] = {~(preMask | postMask)}; + Duplicate(mmResUb[blockStart], + SOFTMAX_MIN_NUM, + mask, + dealRowCount, + 1, + columnCount / BLOCK_ELEMENT_NUM); + if constexpr (IS_DSPARK) { + PipeBarrier(); + } + curStart = blockEnd + 1; + } +} + +template +__aicore__ inline void SWAVectorBlock::SoftmaxFlashV2Compute( + const RunInfo& info, + const MSplitInfo& mSplitInfo, + LocalTensor& mmResUb, + LocalTensor& softmaxTmpUb, + uint32_t startRow, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + LocalTensor inSumTensor; + LocalTensor inMaxTensor; + uint32_t baseOffset = mSplitInfo.nBufferStartM / 2 + startRow; + uint32_t outIdx = info.loop % (constInfo.preLoadNum); + uint32_t softmaxOutOffset = + outIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset; + if (info.isFirstSInnerLoop) { + inMaxTensor = softmaxMaxDefaultUb[startRow]; + inSumTensor = softmaxSumDefaultUb; + } else { + uint32_t inIdx = (info.loop - 1) % (constInfo.preLoadNum); + inMaxTensor = softmaxMaxUb[inIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + + baseOffset]; + inSumTensor = softmaxSumUb[inIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + + baseOffset]; + } + if (actualColumnCount != 0) { + SoftMaxShapeInfo srcShape{ + dealRowCount, columnCount, dealRowCount, actualColumnCount}; + SoftMaxTiling newTiling = SoftMaxFlashV2TilingFunc( + srcShape, sizeof(T), sizeof(T), softmaxTmpUb.GetSize(), true, false); + SoftmaxFlashV2( + mmResUb, + softmaxSumUb[softmaxOutOffset], + softmaxMaxUb[softmaxOutOffset], + mmResUb, + softmaxExpUb[softmaxOutOffset], + inSumTensor, + inMaxTensor, + softmaxTmpUb, + newTiling, + srcShape); + } else { + uint32_t dealRowCountAlign = + SMLAAlign(dealRowCount, FP32_BLOCK_ELEMENT_NUM); + DataCopy(softmaxSumUb[softmaxOutOffset], inSumTensor, dealRowCountAlign); + PipeBarrier(); + DataCopy(softmaxMaxUb[softmaxOutOffset], inMaxTensor, dealRowCountAlign); + } +} + +template +__aicore__ inline void SWAVectorBlock::ProcessLse( + const RunInfo& info, + const MSplitInfo& mSplitInfo) { + if (mSplitInfo.vecDealM == 0) { + return; + } + uint64_t lseOffset; + if (constInfo.outputLayout == SMLA_LAYOUT::TND) { + uint32_t tBase = actualSeqLengthsQGm.GetValue(info.bIdx); + lseOffset = (tBase + info.s1Idx) * constInfo.gSize + + info.n2IdxReal * constInfo.qSeqSize * constInfo.gSize; + } else if (constInfo.outputLayout == SMLA_LAYOUT::BSND) { + lseOffset = + info.bIdx * constInfo.qSeqSize * constInfo.kvHeadNum * constInfo.gSize + + info.n2IdxReal * constInfo.qSeqSize * constInfo.gSize + + info.s1Idx * constInfo.gSize; + } + lseOffset = lseOffset + mSplitInfo.nBufferStartM + mSplitInfo.vecStartM; + uint32_t baseOffset = mSplitInfo.nBufferStartM / 2; + uint32_t outIdx = info.loop % (constInfo.preLoadNum); + uint32_t softmaxOffset = + outIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset; + auto sumTensor = softmaxSumUb[softmaxOffset]; + auto maxTensor = softmaxMaxUb[softmaxOffset]; + auto outLSETensor = outputBuff2.Get(); + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = 1; + dataCopyParams.blockLen = mSplitInfo.vecDealM * sizeof(T); + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = 0; + + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + PipeBarrier(); + Log(outLSETensor, sumTensor, mSplitInfo.vecDealM); + PipeBarrier(); + Add(outLSETensor, outLSETensor, maxTensor, mSplitInfo.vecDealM); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + + DataCopyPad(softmaxLseGm[lseOffset], outLSETensor, dataCopyParams); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); +} + +template +__aicore__ inline void SWAVectorBlock::DealBmm1ResBaseBlock( + const RunInfo& info, + const MSplitInfo& mSplitInfo, + uint32_t startRow, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t loopId) { + uint32_t computeSize = dealRowCount * columnCount; + uint64_t inOutGmOffset = + (info.loop % constInfo.preLoadNum) * constInfo.mmResUbSize + + (mSplitInfo.nBufferStartM + mSplitInfo.vecStartM + startRow) * + columnCount; + LocalTensor mmResUb = inputBuff1.Get(); + mmResUb = mmResUb[pingpongFlag * INPUT1_BUFFER_OFFSET / sizeof(MM1_OUT_T)]; + WaitFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); + + DataCopy(mmResUb, mm1ResGm[inOutGmOffset], computeSize); + SetFlag(SYNC_INPUT_BUF1_FLAG); + WaitFlag(SYNC_INPUT_BUF1_FLAG); + + ElewiseCompute( + info, mSplitInfo, mmResUb, startRow, dealRowCount, columnCount); + + PipeBarrier(); + LocalTensor tmpAFloorUb = tmpBuff1.Get(); + LocalTensor softmaxTmpUb = + tmpAFloorUb.template ReinterpretCast(); + + SoftmaxFlashV2Compute(info, + mSplitInfo, + mmResUb, + softmaxTmpUb, + startRow, + dealRowCount, + columnCount, + info.actualSingleProcessSInnerSize); + PipeBarrier(); + LocalTensor tmpMMResCastTensor = outputBuff1.Get(); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + + Cast( + tmpMMResCastTensor, mmResUb, AscendC::RoundMode::CAST_ROUND, computeSize); + SetFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); + + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + DataCopy(vec1ResGm[inOutGmOffset], tmpMMResCastTensor, computeSize); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); +} + +template +__aicore__ inline void SWAVectorBlock::ProcessVec1SingleBuf( + const RunInfo& info, + const MSplitInfo& mSplitInfo) { + if (mSplitInfo.vecDealM == 0) { + return; + } + uint32_t mSplitSize = info.actualSingleProcessSInnerSize == 0 + ? 16 + : BASE_BLOCK_MAX_ELEMENT_NUM / + info.actualSingleProcessSInnerSizeAlign; + // 1. 向下8对齐是因为UB操作至少32B + // 2. info.actualSingleProcessSInnerSizeAlign最大512, + // mSplitSize可以确保最小为16 + mSplitSize = mSplitSize / 8 * 8; + + if (mSplitSize > mSplitInfo.vecDealM) { + mSplitSize = mSplitInfo.vecDealM; + } + uint32_t loopCount = (mSplitInfo.vecDealM + mSplitSize - 1) / mSplitSize; + uint32_t tailSplitSize = mSplitInfo.vecDealM - (loopCount - 1) * mSplitSize; + + uint32_t sinkHeadIdx = (info.n2IdxReal * constInfo.gSize + + mSplitInfo.nBufferStartM + mSplitInfo.vecStartM) % + constInfo.qHeadNum; + SliceAndContactSinksValue(sinkHeadIdx, mSplitInfo.vecDealM); + + for (uint32_t i = 0, dealSize = mSplitSize; i < loopCount; i++) { + if (i == (loopCount - 1)) { + dealSize = tailSplitSize; + } + DealBmm1ResBaseBlock(info, + mSplitInfo, + i * mSplitSize, + dealSize, + info.actualSingleProcessSInnerSizeAlign, + i); + pingpongFlag ^= 1; // pingpong 0 1切换 + } +} + +// =======================vec1============================= + +template +__aicore__ inline void SWAVectorBlock::ProcessVec1L( + const RunInfo& info) { + uint32_t nBufferLoopTimes = + (info.actMBaseSize + constInfo.nBufferMBaseSize - 1) / + constInfo.nBufferMBaseSize; + uint32_t nBufferTail = + info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; + for (uint32_t i = 0; i < nBufferLoopTimes; i++) { + MSplitInfo mSplitInfo; + mSplitInfo.nBufferIdx = i; + mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; + mSplitInfo.nBufferDealM = + (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; + + mSplitInfo.vecDealM = + (mSplitInfo.nBufferDealM <= 16) + ? mSplitInfo.nBufferDealM + : (((mSplitInfo.nBufferDealM + 15) / 16 + 1) / 2 * 16); + mSplitInfo.vecStartM = 0; + if (GetBlockIdx() % 2 == 1) { + mSplitInfo.vecStartM = mSplitInfo.vecDealM; + mSplitInfo.vecDealM = mSplitInfo.nBufferDealM - mSplitInfo.vecDealM; + } + + CrossCoreWaitFlag(constInfo.syncC1V1); + // vec1 compute + ProcessVec1SingleBuf(info, mSplitInfo); + CrossCoreSetFlag(constInfo.syncV1C2); + + // move lse for flash decode or FA + if (constInfo.returnSoftmaxLse && + info.s2Idx == info.curSInnerLoopTimes - 1) { + ProcessLse(info, mSplitInfo); + } + } +} + +// =======================vec2============================= + +template +__aicore__ inline uint64_t SWAVectorBlock::CalcAccumOffset( + uint32_t bN2Idx, + uint32_t gS1Idx) { + return 0; +} + +template +__aicore__ inline void SWAVectorBlock::ProcessVec2SingleBuf( + const RunInfo& info, + const MSplitInfo& mSplitInfo) { + if (mSplitInfo.vecDealM == 0) { + return; + } + + ProcessVec2Inner(info, mSplitInfo, 0, mSplitInfo.vecDealM); +} + +template +__aicore__ inline void SWAVectorBlock::ProcessVec2L( + const RunInfo& info) { + uint32_t nBufferLoopTimes = + (info.actMBaseSize + constInfo.nBufferMBaseSize - 1) / + constInfo.nBufferMBaseSize; + uint32_t nBufferTail = + info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; + for (uint32_t i = 0; i < nBufferLoopTimes; i++) { + MSplitInfo mSplitInfo; + mSplitInfo.nBufferIdx = i; + mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; + mSplitInfo.nBufferDealM = + (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; + + mSplitInfo.vecDealM = + (mSplitInfo.nBufferDealM <= 16) + ? mSplitInfo.nBufferDealM + : (((mSplitInfo.nBufferDealM + 15) / 16 + 1) / 2 * 16); + mSplitInfo.vecStartM = 0; + if (GetBlockIdx() % 2 == 1) { + mSplitInfo.vecStartM = mSplitInfo.vecDealM; + mSplitInfo.vecDealM = mSplitInfo.nBufferDealM - mSplitInfo.vecDealM; + } + CrossCoreWaitFlag(constInfo.syncC2V2); + ProcessVec2SingleBuf(info, mSplitInfo); + } +} + +template +__aicore__ inline void SWAVectorBlock::ProcessVec2Inner( + const RunInfo& info, + const MSplitInfo& mSplitInfo, + uint32_t mStartRow, + uint32_t mDealSize) { + uint32_t mSplitSize = BASE_BLOCK_MAX_ELEMENT_NUM / constInfo.headDim; + if (mSplitSize > mDealSize) { + mSplitSize = mDealSize; + } + + uint32_t loopCount = (mDealSize + mSplitSize - 1) / mSplitSize; + uint32_t tailSplitSize = mDealSize - (loopCount - 1) * mSplitSize; + for (uint32_t i = 0, dealSize = mSplitSize; i < loopCount; i++) { + if (i == (loopCount - 1)) { + dealSize = tailSplitSize; + } + DealBmm2ResBaseBlock(info, + mSplitInfo, + i * mSplitSize + mStartRow, + dealSize, + constInfo.headDim, + constInfo.headDim); + pingpongFlag ^= 1; // pingpong 0 1切换 + } +} + +template +__aicore__ inline void SWAVectorBlock::Bmm2FDDataCopyOut( + const RunInfo& info, + LocalTensor& bmm2ResUb, + uint32_t wsMStart, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + LocalTensor tmp = outputBuff1.Get(); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + DataCopy(tmp, bmm2ResUb, columnCount * dealRowCount); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + uint64_t accumTmpOutNum = CalcAccumOffset(info.bIdx, info.gS1Idx); + uint64_t offset = accumTmpOutNum * constInfo.kvHeadNum * constInfo.mBaseSize * + constInfo.headDim + // taskoffset + info.tndCoreStartKVSplitPos * constInfo.kvHeadNum * + constInfo.mBaseSize * constInfo.headDim + // 份数offset + wsMStart * actualColumnCount; // m轴offset + GlobalTensor dst = accumOutGm[offset]; + if (info.actualSingleProcessSInnerSize == 0) { + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = dealRowCount; + dataCopyParams.blockLen = actualColumnCount * sizeof(T); + dataCopyParams.srcStride = + (columnCount - actualColumnCount) / (BYTE_BLOCK / sizeof(T)); + dataCopyParams.dstStride = 0; + DataCopyPad(dst, tmp, dataCopyParams); + } else { + matmul::InitOutput( + dst, dealRowCount * actualColumnCount, ConstInfo::FLOAT_ZERO); + } + SetFlag(SYNC_OUTPUT_BUF1_FLAG); +} + +template +__aicore__ inline void SWAVectorBlock::Bmm2DataCopyOutTrans( + const RunInfo& info, + LocalTensor& attenOutUb, + uint32_t wsMStart, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = dealRowCount; + dataCopyParams.blockLen = actualColumnCount * sizeof(OUT_T); + dataCopyParams.srcStride = + (columnCount - actualColumnCount) / (BYTE_BLOCK / sizeof(OUT_T)); + dataCopyParams.dstStride = 0; + DataCopyPad( + attentionOutGm[info.attenOutOffset + wsMStart * actualColumnCount], + attenOutUb, + dataCopyParams); + return; +} + +template +__aicore__ inline void SWAVectorBlock::Bmm2CastAndCopyOut( + const RunInfo& info, + LocalTensor& bmm2ResUb, + uint32_t wsMStart, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + LocalTensor tmpBmm2ResCastTensor = outputBuff1.Get(); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + if constexpr (IsSameType::value) { // bf16 采取四舍六入五成双模式 + Cast(tmpBmm2ResCastTensor, + bmm2ResUb, + AscendC::RoundMode::CAST_RINT, + dealRowCount * columnCount); + } else { + Cast(tmpBmm2ResCastTensor, + bmm2ResUb, + AscendC::RoundMode::CAST_ROUND, + dealRowCount * columnCount); + } + + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + Bmm2DataCopyOutTrans(info, + tmpBmm2ResCastTensor, + wsMStart, + dealRowCount, + columnCount, + actualColumnCount); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); +} + +template +__aicore__ inline void SWAVectorBlock::Bmm2ResCopyOut( + const RunInfo& info, + LocalTensor& bmm2ResUb, + uint32_t wsMStart, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + if constexpr (FLASH_DECODE) { + if (info.tndIsS2SplitCore) { + Bmm2FDDataCopyOut(info, + bmm2ResUb, + wsMStart, + dealRowCount, + columnCount, + actualColumnCount); + } else { + Bmm2CastAndCopyOut(info, + bmm2ResUb, + wsMStart, + dealRowCount, + columnCount, + actualColumnCount); + } + } else { + Bmm2CastAndCopyOut(info, + bmm2ResUb, + wsMStart, + dealRowCount, + columnCount, + actualColumnCount); + } +} + +template +__aicore__ inline void SWAVectorBlock::DealBmm2ResBaseBlock( + const RunInfo& info, + const MSplitInfo& mSplitInfo, + uint32_t startRow, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + uint32_t vec2ComputeSize = dealRowCount * columnCount; + uint32_t mStart = mSplitInfo.nBufferStartM + mSplitInfo.vecStartM + startRow; + uint64_t srcGmOffset = + (info.loop % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + + mStart * columnCount; + LocalTensor tmpBmm2ResUb = inputBuff1.Get(); + tmpBmm2ResUb = + tmpBmm2ResUb[pingpongFlag * INPUT1_BUFFER_OFFSET / sizeof(MM2_OUT_T)]; + WaitFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); + DataCopy(tmpBmm2ResUb, mm2ResGm[srcGmOffset], vec2ComputeSize); + + SetFlag(SYNC_INPUT_BUF1_FLAG); + WaitFlag(SYNC_INPUT_BUF1_FLAG); + + LocalTensor bmm2ResUb = tmpBuff1.Get(); + bmm2ResUb.SetSize(vec2ComputeSize); + DataCopy(bmm2ResUb, tmpBmm2ResUb, vec2ComputeSize); + SetFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); + + uint32_t inOutBaseOffset = mStart * columnCount; + uint32_t baseOffset = mSplitInfo.nBufferStartM / 2 + startRow; + + // 除第一个循环外,均需要更新中间计算结果 + if (!info.isFirstSInnerLoop) { + event_t eventIdMte2WaitMte3 = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE3_MTE2)); + SetFlag(eventIdMte2WaitMte3); + WaitFlag(eventIdMte2WaitMte3); + + LocalTensor bmm2ResPreUb = inputBuff2.Get(); + WaitFlag(SYNC_INPUT_BUF2_FLAG); + + uint64_t vec2ResGmOffset = + ((info.loop - 1) % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + + inOutBaseOffset; + DataCopy(bmm2ResPreUb, vec2ResGm[vec2ResGmOffset], vec2ComputeSize); + + SetFlag(SYNC_INPUT_BUF2_FLAG); + WaitFlag(SYNC_INPUT_BUF2_FLAG); + + uint32_t idx = info.loop % (constInfo.preLoadNum); + LocalTensor expUb = + v0ValidSizeBuff.Get()[384]; // sumUb用临时内存 16 * 32B = 512B + Brcb(expUb, + softmaxExpUb[idx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset], + (dealRowCount + 7) / 8, + {1, 8}); + PipeBarrier(); + + RowMuls(bmm2ResPreUb, + bmm2ResPreUb, + expUb, + dealRowCount, + columnCount, + actualColumnCount); + AscendC::PipeBarrier(); + Add(bmm2ResUb, bmm2ResUb, bmm2ResPreUb, vec2ComputeSize); + AscendC::PipeBarrier(); + + SetFlag(SYNC_INPUT_BUF2_FLAG); + } + + // 最后一次输出计算结果,否则将中间结果暂存至workspace + if (info.isLastS2Loop) { + uint32_t idx = info.loop % (constInfo.preLoadNum); + LocalTensor tmpSumUb = + v0ValidSizeBuff.Get()[384]; // sumUb用临时内存 16 * 32B = 512B + Brcb(tmpSumUb, + softmaxSumUb[idx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset], + (dealRowCount + 7) / 8, + {1, 8}); + PipeBarrier(); + RowDivs(bmm2ResUb, + bmm2ResUb, + tmpSumUb, + dealRowCount, + columnCount, + actualColumnCount); + PipeBarrier(); + Bmm2ResCopyOut( + info, bmm2ResUb, mStart, dealRowCount, columnCount, actualColumnCount); + } else { + LocalTensor outUb = outputBuff1.Get(); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + PipeBarrier(); + DataCopy(outUb, bmm2ResUb, dealRowCount * columnCount); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + uint64_t vec2ResGmOffset = + (info.loop % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + + inOutBaseOffset; + DataCopy(vec2ResGm[vec2ResGmOffset], outUb, vec2ComputeSize); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + } +} + +template +__aicore__ inline void SWAVectorBlock::RowDivs( + LocalTensor dstUb, + LocalTensor src0Ub, + LocalTensor src1Ub, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + // divs by row, 每行的元素除以相同的元素 + // dstUb[i, (j * 8) : (j * 8 + 7)] = src0Ub[i, (j * 8) : (j * 8 + 7)] / + // src1Ub[i, 0 : 7] src0Ub:[dealRowCount, columnCount], src1Ub:[dealRowCount, + // FP32_BLOCK_ELEMENT_NUM] dstUb:[dealRowCount, columnCount] + uint32_t dtypeMask = FP32_REPEAT_ELEMENT_NUM; + uint32_t dLoop = actualColumnCount / dtypeMask; + uint32_t dRemain = actualColumnCount % dtypeMask; + + BinaryRepeatParams repeatParamsDiv; + repeatParamsDiv.src0BlkStride = 1; + repeatParamsDiv.src1BlkStride = 0; + repeatParamsDiv.dstBlkStride = 1; + repeatParamsDiv.src0RepStride = columnCount / FP32_BLOCK_ELEMENT_NUM; + repeatParamsDiv.src1RepStride = 1; + repeatParamsDiv.dstRepStride = columnCount / FP32_BLOCK_ELEMENT_NUM; + uint32_t columnRepeatCount = dLoop; + if (columnRepeatCount <= dealRowCount) { + uint32_t offset = 0; + for (uint32_t i = 0; i < dLoop; i++) { + Div(dstUb[offset], + src0Ub[offset], + src1Ub, + dtypeMask, + dealRowCount, + repeatParamsDiv); + offset += dtypeMask; + } + } else { + BinaryRepeatParams columnRepeatParams; + columnRepeatParams.src0BlkStride = 1; + columnRepeatParams.src1BlkStride = 0; + columnRepeatParams.dstBlkStride = 1; + columnRepeatParams.src0RepStride = + 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block + columnRepeatParams.src1RepStride = 0; + columnRepeatParams.dstRepStride = + 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block + uint32_t offset = 0; + for (uint32_t i = 0; i < dealRowCount; i++) { + Div(dstUb[offset], + src0Ub[offset], + src1Ub[i * FP32_BLOCK_ELEMENT_NUM], + dtypeMask, + columnRepeatCount, + columnRepeatParams); + offset += columnCount; + } + } + if (dRemain > 0) { + Div(dstUb[dLoop * dtypeMask], + src0Ub[dLoop * dtypeMask], + src1Ub, + dRemain, + dealRowCount, + repeatParamsDiv); + } +} + +template +__aicore__ inline void SWAVectorBlock::RowMuls( + LocalTensor dstUb, + LocalTensor src0Ub, + LocalTensor src1Ub, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + // muls by row, 每行的元素乘以相同的元素 + // dstUb[i, (j * 8) : (j * 8 + 7)] = src0Ub[i, (j * 8) : (j * 8 + 7)] * + // src1Ub[i, 0 : 7] src0Ub:[dealRowCount, columnCount] src1Ub:[dealRowCount, + // FP32_BLOCK_ELEMENT_NUM] dstUb:[dealRowCount, columnCount] dealRowCount is + // repeat times, must be less 256 + uint32_t repeatElementNum = FP32_REPEAT_ELEMENT_NUM; + uint32_t blockElementNum = FP32_BLOCK_ELEMENT_NUM; + + if constexpr (std::is_same::value) { + // 此限制由于每个repeat至多连续读取256B数据 + repeatElementNum = FP32_REPEAT_ELEMENT_NUM * 2; // 256/4 * 2=128 + blockElementNum = FP32_BLOCK_ELEMENT_NUM * 2; // 32/4 * 2 = 16 + } + + // 每次只能连续读取256B的数据进行计算,故每次只能处理256B/sizeof(dType)= + // 列方向分dLoop次,每次处理8列数据 + uint32_t dLoop = actualColumnCount / repeatElementNum; + uint32_t dRemain = actualColumnCount % repeatElementNum; + // REPEATE_STRIDE_UP_BOUND=256, + // 此限制由于src0RepStride数据类型为uint8之多256个datablock间距 + if (columnCount < REPEATE_STRIDE_UP_BOUND * blockElementNum) { + BinaryRepeatParams repeatParams; + repeatParams.src0BlkStride = 1; + repeatParams.src1BlkStride = 0; + repeatParams.dstBlkStride = 1; + repeatParams.src0RepStride = columnCount / blockElementNum; + repeatParams.src1RepStride = 1; + repeatParams.dstRepStride = columnCount / blockElementNum; + + // 如果以列为repeat所处理的次数小于行处理次数,则以列方式处理。反之则以行进行repeat处理 + if (dLoop <= dealRowCount) { + uint32_t offset = 0; + for (uint32_t i = 0; i < dLoop; i++) { + Mul(dstUb[offset], + src0Ub[offset], + src1Ub, + repeatElementNum, + dealRowCount, + repeatParams); + offset += repeatElementNum; + } + } else { + BinaryRepeatParams columnRepeatParams; + columnRepeatParams.src0BlkStride = 1; + columnRepeatParams.src1BlkStride = 0; + columnRepeatParams.dstBlkStride = 1; + columnRepeatParams.src0RepStride = + 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block + columnRepeatParams.src1RepStride = 0; + columnRepeatParams.dstRepStride = + 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block + for (uint32_t i = 0; i < dealRowCount; i++) { + Mul(dstUb[i * columnCount], + src0Ub[i * columnCount], + src1Ub[i * blockElementNum], + repeatElementNum, + dLoop, + columnRepeatParams); + } + } + + // 最后一次完成[dealRowCount, dRemain] * [dealRowCount, blockElementNum] + // 只计算有效部分 + if (dRemain > 0) { + Mul(dstUb[dLoop * repeatElementNum], + src0Ub[dLoop * repeatElementNum], + src1Ub, + dRemain, + dealRowCount, + repeatParams); + } + } else { + BinaryRepeatParams repeatParams; + repeatParams.src0RepStride = 8; // 每个repeat为256B数据,正好8个datablock + repeatParams.src0BlkStride = 1; + repeatParams.src1RepStride = 0; + repeatParams.src1BlkStride = 0; + repeatParams.dstRepStride = 8; + repeatParams.dstBlkStride = 1; + // 每次计算一行,共计算dealRowCount行 + for (uint32_t i = 0; i < dealRowCount; i++) { + // 计算一行中的dLoop个repeat, 每个repeat计算256/block_size 个data_block + Mul(dstUb[i * columnCount], + src0Ub[i * columnCount], + src1Ub[i * blockElementNum], + repeatElementNum, + dLoop, + repeatParams); + // 计算一行中的尾块 + if (dRemain > 0) { + Mul(dstUb[i * columnCount + dLoop * repeatElementNum], + src0Ub[i * columnCount + dLoop * repeatElementNum], + src1Ub[i * blockElementNum], + dRemain, + 1, + repeatParams); + } + } + } +} +} // namespace SMLAKernel +#endif diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_kernel.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_kernel.h new file mode 100644 index 0000000000..55263a7581 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_kernel.h @@ -0,0 +1,1238 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file sparse_flash_mla_swa_kernel.h + * \brief + */ + +#ifndef SPARSE_FLASH_MLA_SWA_KERNEL_H +#define SPARSE_FLASH_MLA_SWA_KERNEL_H + +#include "kernel_operator.h" +#include "kernel_operator_list_tensor_intf.h" +#include "kernel_tiling/kernel_tiling.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" +#include "sparse_flash_mla_arch22_metadata.h" +#include "sparse_flash_mla_common_arch22.h" +#include "sparse_flash_mla_swa_block_cube.h" +#include "sparse_flash_mla_swa_block_vector.h" + +namespace SMLAKernel { +using namespace matmul; +using namespace optiling; +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +// 由于S2循环前,RunInfo还没有赋值,使用Bngs1Param临时存放B、N、S1轴相关的信息;同时减少重复计算 +struct SwaTempLoopInfo { + uint32_t bn2IdxInCurCore = 0; + uint32_t bIdx = 0U; + uint32_t n2Idx = 0U; + uint32_t s2LoopTimes = + 0U; // S2方向循环的总次数,无论TND还是BXXD都是等于实际次数,不用减1 + uint64_t s2BasicSizeTail = 0U; // S2方向循环的尾基本块大小 + + int32_t actS1Size = 0; // TND场景下当前Batch循环处理的S1轴的大小 + int32_t actOriS2Size = 0; + int32_t actCmpS2Size = 0; + + bool curActSeqLenIsZero = false; + bool hasInvalidRow = false; + bool tndIsS2SplitCore = false; + bool resv; + uint32_t tndCoreStartKVSplitPos = 0; + uint32_t gS1Idx = 0U; + uint32_t s1StartIdx = 0; + uint32_t s1EndIdx = 0; + uint64_t mBasicSizeTail = 0U; // gS1方向循环的尾基本块大小 + uint32_t cmpLoopTimes = 0; + uint32_t oriLoopTimes = 0; + uint32_t oriCmpMixLoopTimes = 0; + uint32_t cmpMixSize = 0; + + int32_t oriMaskRight = 0; + int32_t oriMaskLeft = 0; + int32_t cmpMaskRight = 0; + + uint64_t actualSeqQPrefixSum = 0; + uint64_t actualSeqKVPrefixSum = 0; + uint64_t actualSeqCmpKVPrefixSum = 0; +}; + +template +class SparseFlashMlaSwa { + public: + // 中间计算数据类型为float,高精度模式 + using T = float; + using Q_T = typename SMLAT::queryType; + using KV_T = typename SMLAT::kvType; + using OUT_T = typename SMLAT::outputType; + using SINKS_T = float; + using UPDATE_T = T; + using MM1_OUT_T = T; + using MM2_OUT_T = T; + + __aicore__ inline SparseFlashMlaSwa(){}; + __aicore__ inline void Init(__gm__ uint8_t* query, + __gm__ uint8_t* oriKV, + __gm__ uint8_t* cmpKV, + __gm__ uint8_t* oriSparseIndices, + __gm__ uint8_t* cmpSparseIndices, + __gm__ uint8_t* oriBlockTable, + __gm__ uint8_t* cmpBlockTable, + __gm__ uint8_t* cuSeqlensQ, + __gm__ uint8_t* cuSeqlensKV, + __gm__ uint8_t* cuSeqlensCmpKV, + __gm__ uint8_t* seqUsedQ, + __gm__ uint8_t* seqUsedKV, + __gm__ uint8_t* seqUsedCmpKV, + __gm__ uint8_t* cmpResidualKV, + __gm__ uint8_t* oriTopkLength, + __gm__ uint8_t* cmpTopkLength, + __gm__ uint8_t* sinks, + __gm__ uint8_t* metadata, + __gm__ uint8_t* attentionOut, + __gm__ uint8_t* softmaxLse, + __gm__ uint8_t* workspace, + const SparseFlashMlaTilingData* __restrict tiling, + __gm__ uint8_t* gmTiling, + TPipe* tPipe); + + __aicore__ inline void Process(); + + private: + static constexpr bool PAGE_ATTENTION = SMLAT::pageAttention; + static constexpr int TEMPLATE_MODE = SMLAT::templateMode; + static constexpr bool FLASH_DECODE = SMLAT::flashDecode; + static constexpr SMLA_LAYOUT LAYOUT_T = SMLAT::layout; + static constexpr SMLA_LAYOUT KV_LAYOUT_T = SMLAT::kvLayout; + static constexpr bool IS_DSPARK = SMLAT::isDspark; + + static constexpr uint32_t PRELOAD_NUM = 2; + static constexpr uint32_t N_BUFFER_M_BASIC_SIZE = 256; + static constexpr uint32_t SMLA_PRELOAD_TASK_CACHE_SIZE = 3; + + static constexpr uint32_t SYNC_V0_C1_FLAG = 6; + static constexpr uint32_t SYNC_C1_V1_FLAG = 7; + static constexpr uint32_t SYNC_V1_C2_FLAG = 8; + static constexpr uint32_t SYNC_C2_V2_FLAG = 9; + static constexpr uint32_t MERGE_CACHE_GM_BUF_NUM = 3; + + static constexpr uint64_t SYNC_MM2RES_BUF1_FLAG = 10; + static constexpr uint64_t SYNC_MM2RES_BUF2_FLAG = 11; + static constexpr uint64_t SYNC_FDOUTPUT_BUF_FLAG = 12; + + static constexpr uint64_t headDim = 512ULL; + static constexpr uint64_t headDimAlign = 512ULL; + static constexpr uint32_t msdIterNum = 2U; + + static constexpr uint32_t dbWorkspaceRatio = PRELOAD_NUM; + + const SparseFlashMlaTilingData* __restrict tilingData = nullptr; + + TPipe* pipe = nullptr; + GlobalTensor metadataGm; + + uint64_t mSizeVStart = 0ULL; + int64_t threshold = 0; + uint64_t s2BatchBaseOffset = 0; + uint64_t tensorACoreOffset = 0ULL; + uint64_t tensorBCoreOffset = 0ULL; + uint64_t tensorCmpBCoreOffset = 0ULL; + uint64_t attenOutOffset = 0ULL; + + uint32_t tmpBlockIdx = 0U; + uint32_t aiCoreIdx = 0U; + + ConstInfo constInfo{}; + SwaTempLoopInfo tempLoopInfo{}; + + SWACubeBlock cubeBlock; + SWAVectorBlock vectorBlock; + + GlobalTensor queryGm; + GlobalTensor oriKvGm; + GlobalTensor cmpKvGm; + GlobalTensor sinksGm; + + GlobalTensor attentionOutGm; + GlobalTensor softmaxLseGm; + + GlobalTensor oriBlockTableGm; + GlobalTensor cmpBlockTableGm; + GlobalTensor oriSparseIndicesGm; + GlobalTensor oriTopkLengthGm; + + GlobalTensor actualSeqLengthsQGm; + GlobalTensor actualSeqLengthsKVGm; + GlobalTensor actualSeqLengthsCmpKVGm; + GlobalTensor cmpResidualKVGm; + + // workspace + GlobalTensor mm1ResGm; + GlobalTensor vec1ResGm; + GlobalTensor mm2ResGm; + + GlobalTensor vec2ResGm; + + GlobalTensor kvMergeGm_; + GlobalTensor accumOutGm; + // ================================Init + // functions================================== + __aicore__ inline void InitTilingData(); + __aicore__ inline void InitCalcParamsEach(); + __aicore__ inline void InitBuffers(); + __aicore__ inline void InitActualSeqLen(__gm__ uint8_t* actualSeqLengthsQ, + __gm__ uint8_t* actualSeqLengthsKv); + __aicore__ inline void InitActualSeqLen( + __gm__ uint8_t* actualSeqLengthsQ, + __gm__ uint8_t* actualSeqLengthsKV, + __gm__ uint8_t* actualSeqLengthsCmpKV); + __aicore__ inline void InitOutputSingleCore(); + // ================================Process + // functions================================ + __aicore__ inline void ProcessBalance(); + __aicore__ inline void PreloadPipeline( + uint32_t loop, + uint32_t cmpLoop, + uint64_t s2Start, + uint64_t s2LoopIdx, + RunInfo extraInfo[SMLA_PRELOAD_TASK_CACHE_SIZE]); + // ================================Offset + // Calc===================================== + __aicore__ inline void GetSparseActualSeqLen(); + __aicore__ inline void UpdateInnerLoopCond(); + __aicore__ inline void CalcParams(uint32_t loop, + uint32_t cmpLoop, + uint64_t s2Start, + uint32_t s2LoopIdx, + RunInfo& info); + __aicore__ inline int32_t GetActualSeqLenQ(uint32_t bIdx); + __aicore__ inline int32_t GetActualSeqLenKV(uint32_t bIdx); + __aicore__ inline uint32_t GetOriSparseActualSeqLen(); + __aicore__ inline int32_t GetActualSeqLenCmpKV(uint32_t bIdx, + int32_t actualOriS2Size); + __aicore__ inline int32_t GetCmpMaskS2Size(uint32_t bIdx, + int32_t actualOriS2Size, + int32_t actualCmpS2Size); + __aicore__ inline void GetBN2Idx(uint32_t bN2Idx, + uint32_t& bIdx, + uint32_t& n2Idx); + // ================================Mm1============================================== + __aicore__ inline void ComputeMm1(const RunInfo& info); + // ================================Mm2============================================== + __aicore__ inline void ComputeMm2(const RunInfo& info); + __aicore__ inline void InitAllZeroOutput(uint32_t bIdx, + uint32_t inValidRowS1StartIdx, + int32_t inValidRowCount, + uint32_t n2Idx); +}; + +template +__aicore__ inline void SparseFlashMlaSwa::InitTilingData() { + // singleCoreParams + // singleCoreTensorSize + constInfo.mmResUbSize = tilingData->baseParams.mmResUbSize; + constInfo.bmm2ResUbSize = tilingData->baseParams.bmm2ResUbSize; + constInfo.usedCoreNum = tilingData->baseParams.usedCoreNum; + // baseParams + constInfo.batchSize = tilingData->baseParams.batchSize; + constInfo.gSize = tilingData->baseParams.nNumOfQInOneGroup; + constInfo.kvHeadNum = (tilingData->baseParams.kvHeadNum == 0) + ? 1 + : tilingData->baseParams.kvHeadNum; + constInfo.qHeadNum = constInfo.gSize * constInfo.kvHeadNum; + constInfo.kvSeqSize = tilingData->baseParams.kvSeqSize; + constInfo.qSeqSize = tilingData->baseParams.qSeqSize; + constInfo.oriMaxBlockNumPerBatch = + tilingData->baseParams.oriMaxBlockNumPerBatch; + constInfo.kvCacheBlockSize = tilingData->baseParams.paBlockSize; + + constInfo.paOriBlockSize = tilingData->baseParams.oriBlockSize; + constInfo.paCmpBlockSize = tilingData->baseParams.cmpBlockSize; + constInfo.outputLayout = + static_cast(tilingData->baseParams.outputLayout); + constInfo.headDim = headDim; + constInfo.oriMaskMode = tilingData->baseParams.oriMaskMode; + constInfo.oriKvStride0 = tilingData->baseParams.oriKvStride0; + constInfo.oriWinLeft = tilingData->baseParams.oriWinLeft; + constInfo.oriWinRight = tilingData->baseParams.oriWinRight; + constInfo.hasOriSparseIndices = + tilingData->baseParams.hasOriSparseIndices != 0; + constInfo.oriSparseIndexWidth = tilingData->baseParams.oriSparseIndexWidth; + constInfo.returnSoftmaxLse = tilingData->baseParams.returnSoftmaxLse; + + constInfo.actualLenDimsQ = tilingData->baseParams.actualLenDimsQ; + constInfo.actualLenDimsKV = tilingData->baseParams.actualLenDimsKV; + constInfo.actualLenDimsCmpKV = tilingData->baseParams.actualLenDimsCmpKV; + constInfo.cmpResidualKVSize = tilingData->baseParams.cmpResidualKVSize; + + // innerSplitParams + constInfo.mBaseSize = tilingData->baseParams.mBaseSize; + constInfo.s2BaseSize = tilingData->baseParams.s2BaseSize; + constInfo.sparseBlockSize = tilingData->baseParams.sparseBlockSize; + + constInfo.preLoadNum = PRELOAD_NUM; + constInfo.nBufferMBaseSize = N_BUFFER_M_BASIC_SIZE; + constInfo.syncV0C1 = SYNC_V0_C1_FLAG; + constInfo.syncC1V1 = SYNC_C1_V1_FLAG; + constInfo.syncV1C2 = SYNC_V1_C2_FLAG; + constInfo.syncC2V2 = SYNC_C2_V2_FLAG; + constInfo.templateMode = TEMPLATE_MODE; + + // cmp + if constexpr (TEMPLATE_MODE == HCA_TEMPLATE) { + constInfo.cmpRatio = tilingData->cmpParams.cmpRatio; + constInfo.cmpMaskMode = tilingData->cmpParams.cmpMaskMode; + constInfo.cmpKvStride0 = tilingData->cmpParams.cmpKvStride0; + constInfo.cmpMaxBlockNumPerBatch = + tilingData->cmpParams.cmpMaxBlockNumPerBatch; + constInfo.cmpSeqSize = tilingData->cmpParams.cmpKvSeqSize; + } +} + +template +__aicore__ inline void SparseFlashMlaSwa::InitBuffers() { + if ASCEND_IS_AIV { + vectorBlock.InitBuffers(pipe); + } else { + cubeBlock.InitBuffers(pipe); + } +} + +template +__aicore__ inline void SparseFlashMlaSwa::InitActualSeqLen( + __gm__ uint8_t* actualSeqLengthsQ, + __gm__ uint8_t* actualSeqLengthsKv) { + if (constInfo.actualLenDimsKV != 0) { + actualSeqLengthsKVGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsKv, + constInfo.actualLenDimsKV); + } + if (constInfo.actualLenDimsQ != 0) { + actualSeqLengthsQGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsQ, + constInfo.actualLenDimsQ); + } +} + +template +__aicore__ inline void SparseFlashMlaSwa::InitActualSeqLen( + __gm__ uint8_t* actualSeqLengthsQ, + __gm__ uint8_t* actualSeqLengthsKV, + __gm__ uint8_t* actualSeqLengthsCmpKV) { + if (constInfo.actualLenDimsKV != 0) { + actualSeqLengthsKVGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsKV, + constInfo.actualLenDimsKV); + } + if constexpr (TEMPLATE_MODE == HCA_TEMPLATE) { + if (constInfo.actualLenDimsCmpKV != 0) { + actualSeqLengthsCmpKVGm.SetGlobalBuffer( + (__gm__ int32_t*)actualSeqLengthsCmpKV, constInfo.actualLenDimsCmpKV); + } + } + if (constInfo.actualLenDimsQ != 0) { + actualSeqLengthsQGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsQ, + constInfo.actualLenDimsQ); + } +} + +template +__aicore__ inline void SparseFlashMlaSwa::InitAllZeroOutput( + uint32_t bIdx, + uint32_t inValidRowS1StartIdx, + int32_t inValidRowCount, + uint32_t n2Idx) { + if (constInfo.outputLayout == SMLA_LAYOUT::TND) { + if (tempLoopInfo.actS1Size == 0) { + return; + } + uint32_t tBase = actualSeqLengthsQGm.GetValue(bIdx); + uint64_t attenOutOffset = + (tBase + inValidRowS1StartIdx) * constInfo.kvHeadNum * constInfo.gSize * + constInfo.headDim + + n2Idx * constInfo.gSize * constInfo.headDim; // N2轴偏移 + uint64_t lseOffset = + (tBase + inValidRowS1StartIdx) * constInfo.gSize + // T轴、s1轴偏移 + n2Idx * constInfo.qSeqSize * constInfo.gSize; // N2轴偏移 + if (constInfo.kvHeadNum == 1 || inValidRowCount <= 1) { + matmul::InitOutput( + attentionOutGm[attenOutOffset], + inValidRowCount * constInfo.gSize * constInfo.headDim, + 0); + } else { + uint64_t attenOutRowStride = constInfo.qHeadNum * constInfo.headDim; + for (int32_t rowIdx = 0; rowIdx < inValidRowCount; ++rowIdx) { + matmul::InitOutput( + attentionOutGm[attenOutOffset + + static_cast(rowIdx) * attenOutRowStride], + constInfo.gSize * constInfo.headDim, + 0); + } + } + if (constInfo.returnSoftmaxLse) { + matmul::InitOutput( + softmaxLseGm[lseOffset], inValidRowCount * constInfo.gSize, 0); + } + } else if (constInfo.outputLayout == SMLA_LAYOUT::BSND) { + uint64_t attenOutOffset = + bIdx * constInfo.qSeqSize * constInfo.kvHeadNum * constInfo.gSize * + constInfo.headDim + + inValidRowS1StartIdx * constInfo.kvHeadNum * constInfo.gSize * + constInfo.headDim + + n2Idx * constInfo.gSize * constInfo.headDim; // N2轴偏移 + uint64_t lseOffset = + bIdx * constInfo.qSeqSize * constInfo.kvHeadNum * + constInfo.gSize + // B轴偏移 + n2Idx * constInfo.qSeqSize * constInfo.gSize + // N2轴偏移 + inValidRowS1StartIdx * constInfo.gSize; // S1轴偏移 + if (constInfo.kvHeadNum == 1 || inValidRowCount <= 1) { + matmul::InitOutput( + attentionOutGm[attenOutOffset], + inValidRowCount * constInfo.gSize * constInfo.headDim, + 0); + } else { + uint64_t attenOutRowStride = constInfo.qHeadNum * constInfo.headDim; + for (int32_t rowIdx = 0; rowIdx < inValidRowCount; ++rowIdx) { + matmul::InitOutput( + attentionOutGm[attenOutOffset + + static_cast(rowIdx) * attenOutRowStride], + constInfo.gSize * constInfo.headDim, + 0); + } + } + if (constInfo.returnSoftmaxLse) { + matmul::InitOutput( + softmaxLseGm[lseOffset], inValidRowCount * constInfo.gSize, 0); + } + } +} + +template +__aicore__ inline void SparseFlashMlaSwa::InitOutputSingleCore() { + uint32_t coreNum = GetBlockNum(); + if (coreNum != 0) { + uint64_t totalOutputSize = constInfo.batchSize * constInfo.qHeadNum * + constInfo.qSeqSize * constInfo.headDim; + uint64_t singleCoreSize = (totalOutputSize + (2 * coreNum) - 1) / + (2 * coreNum); // 2 means c:v = 1:2 + uint64_t tailSize = totalOutputSize - tmpBlockIdx * singleCoreSize; + uint64_t singleInitOutputSize = + tailSize < singleCoreSize ? tailSize : singleCoreSize; + if (singleInitOutputSize > 0) { + matmul::InitOutput(attentionOutGm[tmpBlockIdx * singleCoreSize], + singleInitOutputSize, + 0); + } + SyncAll(); + } +} + +template +__aicore__ inline int32_t SparseFlashMlaSwa::GetActualSeqLenQ( + uint32_t bIdx) { + if constexpr (LAYOUT_T == SMLA_LAYOUT::TND) { + int32_t actualSeqQPrefixSum = actualSeqLengthsQGm.GetValue(bIdx); + int32_t actualSeqQNextSum = actualSeqLengthsQGm.GetValue(bIdx + 1); + tempLoopInfo.actualSeqQPrefixSum = + static_cast(actualSeqQPrefixSum); + return actualSeqQNextSum - actualSeqQPrefixSum; + } else { + tempLoopInfo.actualSeqQPrefixSum = + static_cast(bIdx * constInfo.qSeqSize); + if (constInfo.actualLenDimsQ == 0) { + return static_cast(constInfo.qSeqSize); + } else { + return actualSeqLengthsQGm.GetValue(bIdx); + } + } +} + +template +__aicore__ inline int32_t SparseFlashMlaSwa::GetActualSeqLenKV( + uint32_t bIdx) { + if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { + tempLoopInfo.actualSeqKVPrefixSum = + static_cast(bIdx * constInfo.kvSeqSize); + if (constInfo.actualLenDimsKV == 0) { + return static_cast(constInfo.kvSeqSize); + } + return actualSeqLengthsKVGm.GetValue(bIdx); + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { + tempLoopInfo.actualSeqKVPrefixSum = + static_cast(bIdx * constInfo.kvSeqSize); + if (constInfo.actualLenDimsKV != 0) { + return actualSeqLengthsKVGm.GetValue(bIdx); + } + return static_cast(constInfo.kvSeqSize); + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { + int32_t actualSeqKVPrefixSum = actualSeqLengthsKVGm.GetValue(bIdx); + int32_t actualSeqKVNextSum = actualSeqLengthsKVGm.GetValue(bIdx + 1); + tempLoopInfo.actualSeqKVPrefixSum = actualSeqKVPrefixSum; + return actualSeqKVNextSum - actualSeqKVPrefixSum; + } +} + +template +__aicore__ inline int32_t SparseFlashMlaSwa::GetActualSeqLenCmpKV( + uint32_t bIdx, + int32_t actualOriS2Size) { + (void)actualOriS2Size; + if constexpr (TEMPLATE_MODE != HCA_TEMPLATE) { + return 0; + } + if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { + int32_t actualSeqCmpKVPrefixSum = actualSeqLengthsCmpKVGm.GetValue(bIdx); + int32_t actualSeqCmpKVNextSum = actualSeqLengthsCmpKVGm.GetValue(bIdx + 1); + tempLoopInfo.actualSeqCmpKVPrefixSum = actualSeqCmpKVPrefixSum; + return actualSeqCmpKVNextSum - actualSeqCmpKVPrefixSum; + } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { + tempLoopInfo.actualSeqCmpKVPrefixSum = + static_cast(bIdx * constInfo.cmpSeqSize); + if (constInfo.actualLenDimsCmpKV != 0) { + return actualSeqLengthsCmpKVGm.GetValue(bIdx); + } + return static_cast(constInfo.cmpSeqSize); + } else { + tempLoopInfo.actualSeqCmpKVPrefixSum = + static_cast(bIdx * constInfo.cmpSeqSize); + if (constInfo.actualLenDimsCmpKV != 0) { + return actualSeqLengthsCmpKVGm.GetValue(bIdx); + } + return (constInfo.cmpSeqSize != 0) + ? static_cast(constInfo.cmpSeqSize) + : actualOriS2Size / static_cast(constInfo.cmpRatio); + } +} + +template +__aicore__ inline int32_t SparseFlashMlaSwa::GetCmpMaskS2Size( + uint32_t bIdx, + int32_t actualOriS2Size, + int32_t actualCmpS2Size) { + (void)actualOriS2Size; + if constexpr (TEMPLATE_MODE != HCA_TEMPLATE) { + return actualOriS2Size; + } + int32_t residual = 0; + if (constInfo.cmpResidualKVSize != 0) { + residual = cmpResidualKVGm.GetValue(bIdx); + } + return actualCmpS2Size * static_cast(constInfo.cmpRatio) + residual; +} + +template +__aicore__ inline uint32_t +SparseFlashMlaSwa::GetOriSparseActualSeqLen() { + if (constInfo.oriSparseIndexWidth == 0 || tempLoopInfo.actOriS2Size <= 0) { + return 0; + } + uint64_t qTokenOffset = + tempLoopInfo.actualSeqQPrefixSum + tempLoopInfo.s1StartIdx; + uint64_t topkLenOffset = + qTokenOffset * constInfo.kvHeadNum + tempLoopInfo.n2Idx; + if constexpr (IS_DSPARK) { + if (!constInfo.hasOriTopkLength) { + return 0; + } + int32_t topkLen = oriTopkLengthGm.GetValue(topkLenOffset); + if (topkLen <= 0) { + return 0; + } + return Min(static_cast(topkLen), constInfo.oriSparseIndexWidth); + } + return 0; +} + +template +__aicore__ inline void SparseFlashMlaSwa::GetSparseActualSeqLen() { + // 行无效通过ori部分判断, ori部分如果有行无效那么ori和cmp都有 + if (static_cast(tempLoopInfo.s1EndIdx) < + -(tempLoopInfo.actOriS2Size - tempLoopInfo.actS1Size)) { + tempLoopInfo.actOriS2Size = 0; + tempLoopInfo.actCmpS2Size = 0; + return; + } + + // 对于cmp部分还有top k, tempLoopInfo.actS2Size只针对cmp + if constexpr (TEMPLATE_MODE == HCA_TEMPLATE) { + int32_t thresHold = + (tempLoopInfo.cmpMaskRight + tempLoopInfo.s1EndIdx + 1) / + constInfo.cmpRatio; + tempLoopInfo.actCmpS2Size = + Min(tempLoopInfo.actCmpS2Size, Max(thresHold, 0)); + } +} + +template +__aicore__ inline void SparseFlashMlaSwa::UpdateInnerLoopCond() { + if ((tempLoopInfo.actCmpS2Size == 0 && tempLoopInfo.actOriS2Size == 0) || + (tempLoopInfo.actS1Size == 0)) { + tempLoopInfo.curActSeqLenIsZero = true; + return; + } + tempLoopInfo.curActSeqLenIsZero = false; + tempLoopInfo.mBasicSizeTail = + ((tempLoopInfo.s1EndIdx - tempLoopInfo.s1StartIdx + 1) * + constInfo.gSize) % + constInfo.mBaseSize; + tempLoopInfo.mBasicSizeTail = (tempLoopInfo.mBasicSizeTail == 0) + ? constInfo.mBaseSize + : tempLoopInfo.mBasicSizeTail; +} + +template +__aicore__ inline void SparseFlashMlaSwa::Init( + __gm__ uint8_t* query, + __gm__ uint8_t* oriKV, + __gm__ uint8_t* cmpKV, + __gm__ uint8_t* oriSparseIndices, + __gm__ uint8_t* cmpSparseIndices, + __gm__ uint8_t* oriBlockTable, + __gm__ uint8_t* cmpBlockTable, + __gm__ uint8_t* cuSeqlensQ, + __gm__ uint8_t* cuSeqlensKV, + __gm__ uint8_t* cuSeqlensCmpKV, + __gm__ uint8_t* seqUsedQ, + __gm__ uint8_t* seqUsedKV, + __gm__ uint8_t* seqUsedCmpKV, + __gm__ uint8_t* cmpResidualKV, + __gm__ uint8_t* oriTopkLength, + __gm__ uint8_t* cmpTopkLength, + __gm__ uint8_t* sinks, + __gm__ uint8_t* metadata, + __gm__ uint8_t* attentionOut, + __gm__ uint8_t* softmaxLse, + __gm__ uint8_t* workspace, + const SparseFlashMlaTilingData* __restrict tiling, + __gm__ uint8_t* gmTiling, + TPipe* tPipe) { + if ASCEND_IS_AIV { + tmpBlockIdx = GetBlockIdx(); // vec:0-47 + aiCoreIdx = tmpBlockIdx / 2; + } else { + tmpBlockIdx = GetBlockIdx(); // cube:0-23 + aiCoreIdx = tmpBlockIdx; + } + + // init tiling data + tilingData = tiling; + + InitTilingData(); + if constexpr (IS_DSPARK) { + constInfo.hasOriTopkLength = (oriTopkLength != nullptr); + if (constInfo.hasOriTopkLength) { + oriTopkLengthGm.SetGlobalBuffer((__gm__ int32_t*)oriTopkLength); + } + } + (void)cmpTopkLength; + if (KV_LAYOUT_T == SMLA_LAYOUT::TND && LAYOUT_T == SMLA_LAYOUT::TND) { + InitActualSeqLen(cuSeqlensQ, cuSeqlensKV, cuSeqlensCmpKV); + } else if (KV_LAYOUT_T == SMLA_LAYOUT::TND) { + InitActualSeqLen(seqUsedQ, cuSeqlensKV, cuSeqlensCmpKV); + } else if ((KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND || + KV_LAYOUT_T == SMLA_LAYOUT::BSND) && + LAYOUT_T == SMLA_LAYOUT::TND) { + InitActualSeqLen(cuSeqlensQ, seqUsedKV, seqUsedCmpKV); + } else if ((KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND || + KV_LAYOUT_T == SMLA_LAYOUT::BSND)) { + InitActualSeqLen(seqUsedQ, seqUsedKV, seqUsedCmpKV); + } + metadataGm.SetGlobalBuffer((__gm__ uint32_t*)metadata); + InitCalcParamsEach(); + + pipe = tPipe; + // init global buffer + queryGm.SetGlobalBuffer((__gm__ Q_T*)query); + oriKvGm.SetGlobalBuffer((__gm__ KV_T*)oriKV); + if constexpr (TEMPLATE_MODE == HCA_TEMPLATE) { + cmpKvGm.SetGlobalBuffer((__gm__ KV_T*)cmpKV); + if (constInfo.cmpResidualKVSize != 0) { + cmpResidualKVGm.SetGlobalBuffer((__gm__ int32_t*)cmpResidualKV, + constInfo.cmpResidualKVSize); + } + } + + if (sinks != nullptr) { + sinksGm.SetGlobalBuffer((__gm__ SINKS_T*)sinks); + } + + attentionOutGm.SetGlobalBuffer((__gm__ OUT_T*)attentionOut); + softmaxLseGm.SetGlobalBuffer((__gm__ T*)softmaxLse); + + if ASCEND_IS_AIV { + if (LAYOUT_T != SMLA_LAYOUT::TND) { + if (constInfo.needInit) { + InitOutputSingleCore(); + } + } + } + + if constexpr (PAGE_ATTENTION) { + oriBlockTableGm.SetGlobalBuffer((__gm__ int32_t*)oriBlockTable); + if constexpr (IS_DSPARK) { + oriSparseIndicesGm.SetGlobalBuffer((__gm__ int32_t*)oriSparseIndices); + } + if constexpr (TEMPLATE_MODE == HCA_TEMPLATE) { + cmpBlockTableGm.SetGlobalBuffer((__gm__ int32_t*)cmpBlockTable); + } + } + + // workspace 内存排布 + // |Q--|mm1ResGm|vec1ResGm|mm2ResGm|vec2ResGm + // |Core0_Q1-Core0_Q2-Core1_Q1-Core1_Q2....Core32_Q1-Core32_Q2|Core0_mmRes + uint64_t offset = 0; + mm1ResGm.SetGlobalBuffer( + (__gm__ MM1_OUT_T*)(workspace + offset + + aiCoreIdx * dbWorkspaceRatio * constInfo.mmResUbSize * + sizeof(MM1_OUT_T))); + offset += GetBlockNum() * dbWorkspaceRatio * constInfo.mmResUbSize * + sizeof(MM1_OUT_T); + + vec1ResGm.SetGlobalBuffer( + (__gm__ Q_T*)(workspace + offset + + aiCoreIdx * dbWorkspaceRatio * constInfo.mmResUbSize * + sizeof(KV_T))); + offset += + GetBlockNum() * dbWorkspaceRatio * constInfo.mmResUbSize * sizeof(KV_T); + + mm2ResGm.SetGlobalBuffer((__gm__ MM2_OUT_T*)(workspace + offset + + aiCoreIdx * dbWorkspaceRatio * + constInfo.bmm2ResUbSize * + sizeof(MM2_OUT_T))); + offset += GetBlockNum() * dbWorkspaceRatio * constInfo.bmm2ResUbSize * + sizeof(MM2_OUT_T); + + vec2ResGm.SetGlobalBuffer( + (__gm__ T*)(workspace + offset + + aiCoreIdx * dbWorkspaceRatio * constInfo.bmm2ResUbSize * + sizeof(T))); + offset += + GetBlockNum() * dbWorkspaceRatio * constInfo.bmm2ResUbSize * sizeof(T); + + if constexpr (IS_DSPARK) { + kvMergeGm_.SetGlobalBuffer( + (__gm__ KV_T*)(workspace + offset + + aiCoreIdx * 512 * 512 * MERGE_CACHE_GM_BUF_NUM * + sizeof(KV_T))); + offset += static_cast(GetBlockNum()) * 512 * 512 * + MERGE_CACHE_GM_BUF_NUM * sizeof(KV_T); + } + + if ASCEND_IS_AIV { + vectorBlock.InitParams(constInfo, tilingData); + if constexpr (IS_DSPARK) { + vectorBlock.InitVec0GlobalTensor(kvMergeGm_, + oriKvGm, + oriBlockTableGm, + oriSparseIndicesGm, + oriTopkLengthGm); + } + vectorBlock.InitVec1GlobalTensor(mm1ResGm, + vec1ResGm, + actualSeqLengthsQGm, + actualSeqLengthsKVGm, + sinksGm, + softmaxLseGm); + vectorBlock.InitVec2GlobalTensor( + accumOutGm, vec2ResGm, mm2ResGm, attentionOutGm); + } + + if ASCEND_IS_AIC { + cubeBlock.InitParams(constInfo); + cubeBlock.InitMm1GlobalTensor(queryGm, oriKvGm, cmpKvGm, mm1ResGm); + cubeBlock.InitMm2GlobalTensor(vec1ResGm, mm2ResGm, attentionOutGm); + cubeBlock.InitPageAttentionInfo(oriKvGm, oriBlockTableGm, cmpBlockTableGm); + if constexpr (IS_DSPARK) { + cubeBlock.InitDsparkKvMerge(kvMergeGm_); + } + } + // 要在InitParams之后执行 + if (pipe != nullptr) { + InitBuffers(); + } +} + +template +__aicore__ inline void SparseFlashMlaSwa::InitCalcParamsEach() { + if (aiCoreIdx != 0) { + constInfo.bN2Start = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, FA_BN2_START_INDEX, false)); + constInfo.gS1Start = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, FA_M_START_INDEX, false)); + constInfo.s2Start = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, FA_S2_START_INDEX, false)); + } + constInfo.bN2End = + metadataGm.GetValue(GetAttrAbsIndex(aiCoreIdx, FA_BN2_END_INDEX, false)); + constInfo.gS1End = + metadataGm.GetValue(GetAttrAbsIndex(aiCoreIdx, FA_M_END_INDEX, false)); + constInfo.s2End = + metadataGm.GetValue(GetAttrAbsIndex(aiCoreIdx, FA_S2_END_INDEX, false)); +} + +template +__aicore__ inline void SparseFlashMlaSwa::CalcParams(uint32_t loop, + uint32_t cmpLoop, + uint64_t s2Start, + uint32_t s2LoopIdx, + RunInfo& info) { + info.isValid = s2LoopIdx < tempLoopInfo.s2LoopTimes; + info.loop = loop; + info.cmpLoop = cmpLoop; + info.bIdx = tempLoopInfo.bIdx; + info.gS1Idx = tempLoopInfo.gS1Idx; + info.s1Idx = tempLoopInfo.gS1Idx / constInfo.gSize; + info.s2Idx = s2LoopIdx; + info.n2IdxReal = tempLoopInfo.n2Idx; + + info.curSInnerLoopTimes = tempLoopInfo.s2LoopTimes; + info.tndIsS2SplitCore = tempLoopInfo.tndIsS2SplitCore; + info.tndCoreStartKVSplitPos = tempLoopInfo.tndCoreStartKVSplitPos; + info.isBmm2Output = false; + info.actS1Size = tempLoopInfo.actS1Size; + info.oriDealSize = tempLoopInfo.oriMaskRight + tempLoopInfo.s1StartIdx - + tempLoopInfo.oriMaskLeft - tempLoopInfo.s1EndIdx; + info.cmpMaskRight = tempLoopInfo.cmpMaskRight; + + // M方向的尾块 + info.actMBaseSize = tempLoopInfo.mBasicSizeTail; + + if ASCEND_IS_AIV { + info.mSize = info.actMBaseSize; + info.mSizeV = (info.mSize <= 16) ? info.mSize + : ((CeilDiv(info.mSize, 16) + 1) / 2 * 16); + info.mSizeVStart = 0; + if (tmpBlockIdx % 2 == 1) { + info.mSizeVStart = info.mSizeV; + info.mSizeV = info.mSize - info.mSizeV; + } + } + + info.isFirstSInnerLoop = s2LoopIdx == s2Start; + if (info.isFirstSInnerLoop) { + tempLoopInfo.bn2IdxInCurCore++; + } + info.isLastS2Loop = (s2LoopIdx == (tempLoopInfo.s2LoopTimes - 1)); + info.bn2IdxInCurCore = tempLoopInfo.bn2IdxInCurCore - 1; + + uint64_t tndBIdxOffsetForQ = + tempLoopInfo.actualSeqQPrefixSum * constInfo.qHeadNum * constInfo.headDim; + uint64_t tndBIdxOffsetForKV = tempLoopInfo.actualSeqKVPrefixSum * + constInfo.kvHeadNum * constInfo.headDim; + uint64_t tndBIdxOffsetForCmpKV = tempLoopInfo.actualSeqCmpKVPrefixSum * + constInfo.kvHeadNum * constInfo.headDim; + + if (info.isFirstSInnerLoop) { + uint64_t s1HeadOffset = + (info.gS1Idx / constInfo.gSize) * constInfo.qHeadNum; + uint64_t qHeadOffset = + info.n2Idx * constInfo.gSize + info.gS1Idx % constInfo.gSize; + tensorACoreOffset = + tndBIdxOffsetForQ + (s1HeadOffset + qHeadOffset) * constInfo.headDim; + tensorBCoreOffset = tndBIdxOffsetForKV + info.n2Idx * constInfo.headDim; + tensorCmpBCoreOffset = + tndBIdxOffsetForCmpKV + info.n2Idx * constInfo.headDim; + } + info.tensorAOffset = tensorACoreOffset; + info.tensorBOffset = tensorBCoreOffset; + info.tensorCmpBOffset = tensorCmpBCoreOffset; + info.attenOutOffset = tensorACoreOffset; + if constexpr (IS_DSPARK) { + if constexpr (LAYOUT_T == SMLA_LAYOUT::TND) { + info.qTokenOffset = tempLoopInfo.actualSeqQPrefixSum + info.s1Idx; + } else { + info.qTokenOffset = info.bIdx * constInfo.qSeqSize + info.s1Idx; + } + } + + if constexpr (TEMPLATE_MODE == SWA_TEMPLATE) { + // SWA只有ori_kv + info.isOriOnly = true; + info.isOriCmpMix = false; + info.relativeS2Idx = 0; + uint64_t s2Offset = info.s2Idx * constInfo.s2BaseSize; + if (s2LoopIdx + 1 == tempLoopInfo.oriLoopTimes) { + info.actualSingleProcessSInnerOriSize = + (tempLoopInfo.oriMaskRight - tempLoopInfo.oriMaskLeft + 1) - s2Offset; + } else { + info.actualSingleProcessSInnerOriSize = constInfo.s2BaseSize; + } + info.actualSingleProcessSInnerSize = info.actualSingleProcessSInnerOriSize; + if constexpr (IS_DSPARK) { + info.s2StartPoint = 0; + } else { + info.s2StartPoint = tempLoopInfo.oriMaskLeft; + } + info.cmpS2IdLimit = 0; + } else { // HCA_TEMPLATE场景 + if (s2LoopIdx < tempLoopInfo.oriLoopTimes) { + // S2首次循环只能在ori_kv + info.isOriOnly = true; + info.isOriCmpMix = false; + info.relativeS2Idx = 0; + uint64_t s2Offset = info.s2Idx * constInfo.s2BaseSize; + if (s2LoopIdx + 1 == + tempLoopInfo + .oriLoopTimes) { // HCA场景可能处理oriLen / cmpRatio等于0的场景 + info.actualSingleProcessSInnerOriSize = + (tempLoopInfo.oriMaskRight - tempLoopInfo.oriMaskLeft + 1) - + s2Offset; + } else { + info.actualSingleProcessSInnerOriSize = constInfo.s2BaseSize; + } + info.actualSingleProcessSInnerSize = + info.actualSingleProcessSInnerOriSize; + info.s2StartPoint = tempLoopInfo.oriMaskLeft; + info.cmpS2IdLimit = 0; + } else if (s2LoopIdx - tempLoopInfo.oriLoopTimes < + tempLoopInfo.oriCmpMixLoopTimes) { + uint64_t s2Offset = info.s2Idx * constInfo.s2BaseSize; + info.isOriOnly = false; + info.isOriCmpMix = true; + info.relativeS2Idx = info.s2Idx - tempLoopInfo.oriLoopTimes; + info.actualSingleProcessSInnerOriSize = + (tempLoopInfo.oriMaskRight - tempLoopInfo.oriMaskLeft + 1) - s2Offset; + info.s2StartPoint = tempLoopInfo.oriMaskLeft + + tempLoopInfo.oriLoopTimes * constInfo.s2BaseSize; + info.actualSingleProcessSInnerCmpSize = tempLoopInfo.cmpMixSize; + info.cmpS2IdLimit = tempLoopInfo.cmpMixSize; + info.actualSingleProcessSInnerSize = + info.actualSingleProcessSInnerOriSize + + info.actualSingleProcessSInnerCmpSize; + } else { + info.isOriOnly = false; + info.isOriCmpMix = false; + info.relativeS2Idx = info.s2Idx - tempLoopInfo.oriLoopTimes - + tempLoopInfo.oriCmpMixLoopTimes; + uint64_t s2Offset = + info.relativeS2Idx * constInfo.s2BaseSize + tempLoopInfo.cmpMixSize; + if (s2LoopIdx + 1 == tempLoopInfo.s2LoopTimes) { + info.actualSingleProcessSInnerSize = + tempLoopInfo.actCmpS2Size - s2Offset; + } else { + info.actualSingleProcessSInnerSize = constInfo.s2BaseSize; + } + info.s2StartPoint = tempLoopInfo.cmpMixSize; + info.cmpS2IdLimit = + (tempLoopInfo.cmpMaskRight + tempLoopInfo.s1EndIdx + 1) / + constInfo.cmpRatio; + } + } + + info.inValidRowCount = tempLoopInfo.actS1Size - tempLoopInfo.actOriS2Size - + tempLoopInfo.s1StartIdx; + info.actualSingleProcessSInnerSizeAlign = SMLAAlign( + info.actualSingleProcessSInnerSize, SMLAVectorBlock::BYTE_BLOCK); + info.actualSingleProcessSInnerOriAlignSize = + SMLAAlign(info.actualSingleProcessSInnerOriSize, + SMLAVectorBlock::BYTE_BLOCK); + info.actualSingleProcessSInnerCmpAlignSize = + SMLAAlign(info.actualSingleProcessSInnerCmpSize, + SMLAVectorBlock::BYTE_BLOCK); + if constexpr (IS_DSPARK) { + if (info.isValid) { + info.v0S2Start = 0; + info.v0S2DealSize = + static_cast(info.actualSingleProcessSInnerOriSize); + } + } +} + +template +__aicore__ inline void SparseFlashMlaSwa::ComputeMm1( + const RunInfo& info) { + uint32_t nBufferLoopTimes = + CeilDiv(info.actMBaseSize, constInfo.nBufferMBaseSize); + uint32_t nBufferTail = + info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; + for (uint32_t i = 0; i < nBufferLoopTimes; i++) { + MSplitInfo mSplitInfo; + mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; + mSplitInfo.nBufferDealM = + (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; + cubeBlock.ComputeMm1(info, mSplitInfo); + CrossCoreSetFlag(constInfo.syncC1V1); + } +} + +template +__aicore__ inline void SparseFlashMlaSwa::ComputeMm2( + const RunInfo& info) { + uint32_t nBufferLoopTimes = + (info.actMBaseSize + constInfo.nBufferMBaseSize - 1) / + constInfo.nBufferMBaseSize; + uint32_t nBufferTail = + info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; + for (uint32_t i = 0; i < nBufferLoopTimes; i++) { + MSplitInfo mSplitInfo; + mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; + mSplitInfo.nBufferDealM = + (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; + CrossCoreWaitFlag(constInfo.syncV1C2); + cubeBlock.ComputeMm2(info, mSplitInfo); + CrossCoreSetFlag(constInfo.syncC2V2); + } +} + +template +__aicore__ inline void SparseFlashMlaSwa::Process() { + uint32_t hasLoad = metadataGm.GetValue( + GetAttrAbsIndex(aiCoreIdx, FA_CORE_ENABLE_INDEX, false)); + if (hasLoad == 0) { + return; + } + if ASCEND_IS_AIV { + vectorBlock.AllocEventID(); + vectorBlock.InitSoftmaxDefaultBuffer(); + } else { + cubeBlock.AllocEventID(); + } + ProcessBalance(); + if ASCEND_IS_AIV { + vectorBlock.FreeEventID(); + } else { + cubeBlock.FreeEventID(); + } +} + +template +__aicore__ inline void SparseFlashMlaSwa::GetBN2Idx(uint32_t bN2Idx, + uint32_t& bIdx, + uint32_t& n2Idx) { + bIdx = bN2Idx / constInfo.kvHeadNum; + n2Idx = bN2Idx % constInfo.kvHeadNum; +} + +template +__aicore__ inline void SparseFlashMlaSwa::ProcessBalance() { + RunInfo extraInfo[SMLA_PRELOAD_TASK_CACHE_SIZE]; + uint32_t gloop = 0; + uint32_t cmpLoop = 0; + uint32_t gS1LoopEnd = 0; + bool globalLoopStart = true; + // 适配左闭右开 + if (constInfo.bN2Start == constInfo.bN2End) { + if (constInfo.gS1Start != constInfo.gS1End || + constInfo.s2Start != constInfo.s2End) { + constInfo.bN2End += 1; + } + } else if ((constInfo.gS1End != 0) || (constInfo.s2End != 0)) { + constInfo.bN2End += 1; + } + for (uint32_t bN2LoopIdx = constInfo.bN2Start; bN2LoopIdx < constInfo.bN2End; + bN2LoopIdx++) { + GetBN2Idx(bN2LoopIdx, tempLoopInfo.bIdx, tempLoopInfo.n2Idx); + tempLoopInfo.actS1Size = + GetActualSeqLenQ(tempLoopInfo.bIdx); // 获取actualSeqLength + tempLoopInfo.actOriS2Size = + GetActualSeqLenKV(tempLoopInfo.bIdx); // 获取actualSeqLengthKV + // 判断是否存在行无效场景,直接全部刷零(DSpark 走 sparse topk,不做 dense + // 行无效清零) + int32_t inValidRowCount = 0; + int32_t inValidRowS1StartIdx = 0; + if constexpr (!IS_DSPARK) { + if (inValidRowS1StartIdx < + (tempLoopInfo.actS1Size - tempLoopInfo.actOriS2Size)) { + inValidRowCount = tempLoopInfo.actS1Size - tempLoopInfo.actOriS2Size; + tempLoopInfo.hasInvalidRow = true; + if ASCEND_IS_AIV { + InitAllZeroOutput(tempLoopInfo.bIdx, + inValidRowS1StartIdx, + inValidRowCount, + tempLoopInfo.n2Idx); + } + } + } + bool isS1S2ZeroAndLastBatch = + (tempLoopInfo.actS1Size == 0 || tempLoopInfo.actOriS2Size == 0) && + ((constInfo.outputLayout == SMLA_LAYOUT::BSND) || + (bN2LoopIdx + 1 == constInfo.bN2End)); + uint32_t gS1SplitNum = + CeilDiv((tempLoopInfo.actS1Size - inValidRowCount) * constInfo.gSize, + constInfo.mBaseSize); // gS1轴上有效基本块数量 + + // 当处于最后一个BN2时, 且gS1End为0时, 说明当前BN2里的所有数据都在当前核处理 + gS1LoopEnd = (bN2LoopIdx == constInfo.bN2End - 1 && constInfo.gS1End != 0) + ? constInfo.gS1End + : gS1SplitNum; + // 当处于最后一个BN2且当前S1为0时,需要进入循环计算preload导致的未完成的部分 + gS1LoopEnd = isS1S2ZeroAndLastBatch ? gS1LoopEnd + 1 : gS1LoopEnd; + for (uint32_t gS1LoopIdx = constInfo.gS1Start; gS1LoopIdx < gS1LoopEnd; + gS1LoopIdx++) { + tempLoopInfo.actOriS2Size = GetActualSeqLenKV(tempLoopInfo.bIdx); + if constexpr (TEMPLATE_MODE == HCA_TEMPLATE) { + tempLoopInfo.actCmpS2Size = + GetActualSeqLenCmpKV(tempLoopInfo.bIdx, tempLoopInfo.actOriS2Size); + } + // 对于各轴上的真实的idx, 采用左闭右闭的方案 + // 跳过行无效部分,从有效行开始后续计算 + tempLoopInfo.gS1Idx = + inValidRowCount * constInfo.gSize + gS1LoopIdx * constInfo.mBaseSize; + tempLoopInfo.s1StartIdx = tempLoopInfo.gS1Idx / constInfo.gSize; + tempLoopInfo.s1EndIdx = Min( + (tempLoopInfo.s1StartIdx + constInfo.mBaseSize / constInfo.gSize - 1), + tempLoopInfo.actS1Size - 1); + // 此处均为闭区间 + // oriMaskMode 0 (DSpark): effective ori S2 from sparse topk_length, not + // band window. + if constexpr (IS_DSPARK) { + uint32_t sparseOriS2Size = GetOriSparseActualSeqLen(); + tempLoopInfo.oriMaskLeft = 0; + tempLoopInfo.oriMaskRight = + sparseOriS2Size == 0 ? -1 + : static_cast(sparseOriS2Size - 1U); + } else { + // oriMaskMode 4 (Band): sliding window on dense ori_kv. + tempLoopInfo.oriMaskRight = + tempLoopInfo.actOriS2Size - tempLoopInfo.actS1Size + + static_cast(tempLoopInfo.s1EndIdx) + constInfo.oriWinRight; + tempLoopInfo.oriMaskRight = + Min(tempLoopInfo.oriMaskRight, tempLoopInfo.actOriS2Size - 1); + tempLoopInfo.oriMaskLeft = + Max(tempLoopInfo.actOriS2Size - tempLoopInfo.actS1Size + + static_cast(tempLoopInfo.s1StartIdx) - + constInfo.oriWinLeft, + 0); + } + if constexpr (TEMPLATE_MODE == HCA_TEMPLATE) { + int32_t cmpMaskS2Size = GetCmpMaskS2Size(tempLoopInfo.bIdx, + tempLoopInfo.actOriS2Size, + tempLoopInfo.actCmpS2Size); + tempLoopInfo.cmpMaskRight = cmpMaskS2Size - tempLoopInfo.actS1Size; + } + GetSparseActualSeqLen(); + UpdateInnerLoopCond(); + bool isEnd = (bN2LoopIdx + 1 == constInfo.bN2End) && + (gS1LoopIdx + 1 == gS1LoopEnd); + if (tempLoopInfo.curActSeqLenIsZero && !isEnd) { + continue; + } + if constexpr (TEMPLATE_MODE == SWA_TEMPLATE) { + uint32_t oriS2Size = + (tempLoopInfo.oriMaskRight >= tempLoopInfo.oriMaskLeft) + ? static_cast(tempLoopInfo.oriMaskRight - + tempLoopInfo.oriMaskLeft + 1) + : 0U; + tempLoopInfo.oriLoopTimes = CeilDiv(oriS2Size, constInfo.s2BaseSize); + tempLoopInfo.oriCmpMixLoopTimes = 0; + tempLoopInfo.cmpLoopTimes = 0; + tempLoopInfo.s2LoopTimes = tempLoopInfo.oriLoopTimes; + } else { // HCA_TEMPLATE + uint32_t oriLen = + tempLoopInfo.oriMaskRight - tempLoopInfo.oriMaskLeft + 1; + if (tempLoopInfo.actCmpS2Size == 0) { // ori/cmp_ratio长度等于0的场景 + tempLoopInfo.oriLoopTimes = + (oriLen + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize; + tempLoopInfo.oriCmpMixLoopTimes = 0; + tempLoopInfo.cmpLoopTimes = 0; + } else { + tempLoopInfo.oriLoopTimes = oriLen / constInfo.s2BaseSize; + tempLoopInfo.oriCmpMixLoopTimes = + (oriLen % constInfo.s2BaseSize == 0) ? 0 : 1; + if (tempLoopInfo.oriCmpMixLoopTimes == 0) { + tempLoopInfo.cmpMixSize = 0; + } else { + uint32_t cmpLeftSize = + constInfo.s2BaseSize - + (oriLen - tempLoopInfo.oriLoopTimes * constInfo.s2BaseSize); + tempLoopInfo.cmpMixSize = (cmpLeftSize < tempLoopInfo.actCmpS2Size) + ? cmpLeftSize + : tempLoopInfo.actCmpS2Size; + } + tempLoopInfo.cmpLoopTimes = + CeilDiv(tempLoopInfo.actCmpS2Size - tempLoopInfo.cmpMixSize, + constInfo.s2BaseSize); + } + tempLoopInfo.s2LoopTimes = tempLoopInfo.oriLoopTimes + + tempLoopInfo.oriCmpMixLoopTimes + + tempLoopInfo.cmpLoopTimes; + } + + tempLoopInfo.tndIsS2SplitCore = false; // 当前不支持核间切S2 + tempLoopInfo.tndCoreStartKVSplitPos = 0; + uint32_t extraLoop = isEnd ? PRELOAD_NUM : 0; + + for (uint32_t s2LoopIdx = constInfo.s2Start; + s2LoopIdx < (tempLoopInfo.s2LoopTimes + extraLoop); + s2LoopIdx++) { + PreloadPipeline( + gloop, cmpLoop, constInfo.s2Start, s2LoopIdx, extraInfo); + ++gloop; + if constexpr (IS_DSPARK) { + if (s2LoopIdx < tempLoopInfo.s2LoopTimes) { + ++cmpLoop; + } + } + } + globalLoopStart = false; + constInfo.s2Start = 0; + } + constInfo.gS1Start = 0; + tempLoopInfo.hasInvalidRow = false; + } +} + +template +__aicore__ inline void SparseFlashMlaSwa::PreloadPipeline( + uint32_t loop, + uint32_t cmpLoop, + uint64_t s2Start, + uint64_t s2LoopIdx, + RunInfo extraInfo[SMLA_PRELOAD_TASK_CACHE_SIZE]) { + RunInfo& extraInfo0 = + extraInfo[loop % SMLA_PRELOAD_TASK_CACHE_SIZE]; // 本轮任务 + RunInfo& extraInfo2 = + extraInfo[(loop + 2) % SMLA_PRELOAD_TASK_CACHE_SIZE]; // 上一轮任务 + RunInfo& extraInfo1 = + extraInfo[(loop + 1) % SMLA_PRELOAD_TASK_CACHE_SIZE]; // 上两轮任务 + + CalcParams(loop, cmpLoop, s2Start, s2LoopIdx, extraInfo0); + if (extraInfo0.isValid) { + if constexpr (IS_DSPARK) { + if ASCEND_IS_AIV { + vectorBlock.ProcessVec0L(extraInfo0); + CrossCoreSetFlag( + constInfo.syncV0C1); + } + } else { + if ASCEND_IS_AIC { + ComputeMm1(extraInfo0); + } + } + } + if (extraInfo2.isValid) { + if ASCEND_IS_AIV { + vectorBlock.ProcessVec1L(extraInfo2); + } + if ASCEND_IS_AIC { + ComputeMm2(extraInfo2); + } + } + if (extraInfo1.isValid) { + if ASCEND_IS_AIV { + vectorBlock.ProcessVec2L(extraInfo1); + } + extraInfo1.isValid = false; + } + if constexpr (IS_DSPARK) { + if (extraInfo0.isValid) { + if ASCEND_IS_AIC { + CrossCoreWaitFlag( + constInfo.syncV0C1); + ComputeMm1(extraInfo0); + } + } + } +} +} // namespace SMLAKernel +#endif // SPARSE_FLASH_MLA_SWA_KERNEL_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch35/common/smla_metadata_common.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch35/common/smla_metadata_common.h new file mode 100644 index 0000000000..c982ad9c33 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch35/common/smla_metadata_common.h @@ -0,0 +1,75 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file smla_metadata_common.h + * \brief sparse_flash_mla / mixed_quant_sparse_flash_mla / + * quant_sparse_flash_mla 三个算子共用的 metadata 常量与 GetAttrAbsIndex 定义。 + */ + +#ifndef SMLA_METADATA_COMMON_H +#define SMLA_METADATA_COMMON_H + +#include + +namespace optiling { + +// Constants +constexpr uint32_t AIC_CORE_MAX_NUM = 80; +constexpr uint32_t AIV_CORE_MAX_NUM = 80; + +constexpr uint32_t FA_METADATA_SIZE = 9; +constexpr uint32_t FD_METADATA_SIZE = 8; + +// FA Metadata Index Definitions +constexpr uint32_t FA_CORE_ENABLE_INDEX = 0; +constexpr uint32_t FA_BN2_START_INDEX = 1; +constexpr uint32_t FA_M_START_INDEX = 2; +constexpr uint32_t FA_S2_START_INDEX = 3; +constexpr uint32_t FA_BN2_END_INDEX = 4; +constexpr uint32_t FA_M_END_INDEX = 5; +constexpr uint32_t FA_S2_END_INDEX = 6; +constexpr uint32_t FA_FIRST_FD_DATA_WORKSPACE_IDX_INDEX = 7; +constexpr uint32_t FA_S2_MAX_NUM = 8; + +// FD Metadata Index Definitions +constexpr uint32_t FD_CORE_ENABLE_INDEX = 0; +constexpr uint32_t FD_BN2_IDX_INDEX = 1; +constexpr uint32_t FD_M_IDX_INDEX = 2; +constexpr uint32_t FD_WORKSPACE_IDX_INDEX = 3; +constexpr uint32_t FD_WORKSPACE_NUM_INDEX = 4; +constexpr uint32_t FD_M_START_INDEX = 5; +constexpr uint32_t FD_M_NUM_INDEX = 6; + +/** + * @brief 获取属性的绝对索引 + * @param coreIdx 核索引 + * @param metaIdx 元数据索引 + * @param isAIV 是否为AIV数据,默认为false + * @return 返回属性的绝对索引 + */ +#ifdef __CCE_AICORE__ +__aicore__ inline uint32_t GetAttrAbsIndex(uint32_t coreIdx, + uint32_t metaIdx, + bool isAIV = false) { + if (isAIV) { + return FA_METADATA_SIZE * AIC_CORE_MAX_NUM + FD_METADATA_SIZE * coreIdx + + metaIdx; + } else { + return FA_METADATA_SIZE * coreIdx + metaIdx; + } +} +#endif + +} // namespace optiling + +#endif // SMLA_METADATA_COMMON_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/sparse_flash_mla_kernel_metadata.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/sparse_flash_mla_kernel_metadata.h new file mode 100644 index 0000000000..70d26804a6 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/sparse_flash_mla_kernel_metadata.h @@ -0,0 +1,42 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file sparse_flash_mla_kernel_metadata.h + * \brief + */ + +#ifndef SPARSE_FLASH_MLA_KERNEL_METADATA_H +#define SPARSE_FLASH_MLA_KERNEL_METADATA_H + +#include + +#include "arch35/common/smla_metadata_common.h" + +namespace optiling { + +constexpr uint32_t SMLA_METADATA_TOTAL_SIZE = 2048; + +using SMLA_METADATA_T = int32_t; + +namespace detail { +struct SmlaMetadata { + uint32_t faMetadata[AIC_CORE_MAX_NUM][FA_METADATA_SIZE]; + uint32_t fdMetadata[AIV_CORE_MAX_NUM][FD_METADATA_SIZE]; +}; +}; // namespace detail + +static_assert(SMLA_METADATA_TOTAL_SIZE * sizeof(SMLA_METADATA_T) >= + sizeof(detail::SmlaMetadata)); +}; // namespace optiling + +#endif // SPARSE_FLASH_MLA_KERNEL_METADATA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/sparse_flash_mla_template_tiling_key.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/sparse_flash_mla_template_tiling_key.h new file mode 100644 index 0000000000..63e5ba6e40 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/sparse_flash_mla_template_tiling_key.h @@ -0,0 +1,140 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under +the terms and conditions of  * CANN Open Software License Agreement Version 2.0 +(the "License").  * Please refer to the License for details. You may not use +this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON +AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * +INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A +PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for +the full text of the License.  */ + +/*! + * \file sparse_flash_mla_template_tiling_key.h + * \brief + */ + +#ifndef SPARSE_ATTN_SHARED_TEMPLATE_TILING_KEY_H +#define SPARSE_ATTN_SHARED_TEMPLATE_TILING_KEY_H + +#include "ascendc/host_api/tiling/template_argument.h" + +#define SMLA_LAYOUT_BSND 0 +#define SMLA_LAYOUT_TND 1 +#define SMLA_LAYOUT_PA_BBND 2 + +#define ASCENDC_TPL_4_BW 4 + +#define SWA_TEMPLATE 0 +#define HCA_TEMPLATE 1 +#define CSA_TEMPLATE 2 +#define ORI_SPARSE_TEMPLATE 3 +#define ORI_CMP_SPARSE_TEMPLATE 4 + +#define TOPK_INDEX 1 +#define TOPK_OFFSET 2 + +// Keep the key layout identical across architectures; A2/A3 only builds index +// mode kernels. +#if defined(__CCE_AICORE__) && (__CCE_AICORE__ != 310) +#define SMLA_TOPK_VALUE_MODE_SEL \ + ASCENDC_TPL_UINT_SEL(TOPK_VALUE_MODE, ASCENDC_TPL_UI_LIST, TOPK_INDEX) +#else +#define SMLA_TOPK_VALUE_MODE_SEL \ + ASCENDC_TPL_UINT_SEL( \ + TOPK_VALUE_MODE, ASCENDC_TPL_UI_LIST, TOPK_INDEX, TOPK_OFFSET) +#endif + +// 模板参数支持的范围定义 +ASCENDC_TPL_ARGS_DECL(XllmKernelSparseFlashMla, // 算子OpType + ASCENDC_TPL_BOOL_DECL(FLASH_DECODE, 0, 1), + ASCENDC_TPL_UINT_DECL(LAYOUT_T, + ASCENDC_TPL_4_BW, + ASCENDC_TPL_UI_LIST, + SMLA_LAYOUT_BSND, + SMLA_LAYOUT_TND), + ASCENDC_TPL_UINT_DECL(KV_LAYOUT_T, + ASCENDC_TPL_4_BW, + ASCENDC_TPL_UI_LIST, + SMLA_LAYOUT_BSND, + SMLA_LAYOUT_TND, + SMLA_LAYOUT_PA_BBND), + ASCENDC_TPL_UINT_DECL(TEMPLATE_MODE, + ASCENDC_TPL_4_BW, + ASCENDC_TPL_UI_LIST, + SWA_TEMPLATE, + HCA_TEMPLATE, + CSA_TEMPLATE, + ORI_SPARSE_TEMPLATE, + ORI_CMP_SPARSE_TEMPLATE), + ASCENDC_TPL_BOOL_DECL(SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_DECL(HEAD_RATIO_ONE, 0, 1), + ASCENDC_TPL_BOOL_DECL(BATCH_CONSISTENCY, 0, 1), + ASCENDC_TPL_BOOL_DECL(IS_VEC_S2PHYADDR, 0, 1), + ASCENDC_TPL_UINT_DECL(TOPK_VALUE_MODE, + ASCENDC_TPL_4_BW, + ASCENDC_TPL_UI_LIST, + TOPK_INDEX, + TOPK_OFFSET), + ASCENDC_TPL_BOOL_DECL(IS_DSPARK, 0, 1)); + +// 支持的模板参数组合 +// 用于调用GET_TPL_TILING_KEY获取TilingKey时,接口内部校验TilingKey是否合法 +ASCENDC_TPL_SEL( + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SMLA_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SMLA_LAYOUT_BSND, + SMLA_LAYOUT_PA_BBND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, + ASCENDC_TPL_UI_LIST, + SWA_TEMPLATE, + HCA_TEMPLATE, + CSA_TEMPLATE, + ORI_SPARSE_TEMPLATE, + ORI_CMP_SPARSE_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HEAD_RATIO_ONE, 0, 1), + ASCENDC_TPL_BOOL_SEL(BATCH_CONSISTENCY, 0, 1), + ASCENDC_TPL_BOOL_SEL(IS_VEC_S2PHYADDR, 0, 1), + SMLA_TOPK_VALUE_MODE_SEL, + ASCENDC_TPL_BOOL_SEL(IS_DSPARK, 0)), + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SMLA_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SMLA_LAYOUT_TND, + SMLA_LAYOUT_PA_BBND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, + ASCENDC_TPL_UI_LIST, + SWA_TEMPLATE, + HCA_TEMPLATE, + CSA_TEMPLATE, + ORI_SPARSE_TEMPLATE, + ORI_CMP_SPARSE_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HEAD_RATIO_ONE, 0, 1), + ASCENDC_TPL_BOOL_SEL(BATCH_CONSISTENCY, 0, 1), + ASCENDC_TPL_BOOL_SEL(IS_VEC_S2PHYADDR, 0, 1), + SMLA_TOPK_VALUE_MODE_SEL, + ASCENDC_TPL_BOOL_SEL(IS_DSPARK, 0)), + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SMLA_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SMLA_LAYOUT_PA_BBND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, SWA_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HEAD_RATIO_ONE, 0, 1), + ASCENDC_TPL_BOOL_SEL(BATCH_CONSISTENCY, 0, 1), + ASCENDC_TPL_BOOL_SEL(IS_VEC_S2PHYADDR, 0, 1), + SMLA_TOPK_VALUE_MODE_SEL, + ASCENDC_TPL_BOOL_SEL(IS_DSPARK, 1))); + +#undef SMLA_TOPK_VALUE_MODE_SEL + +#endif // TEMPLATE_TILING_KEY diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/xllm_kernel_sparse_flash_mla.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/xllm_kernel_sparse_flash_mla.cpp new file mode 100644 index 0000000000..056707e79c --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/xllm_kernel_sparse_flash_mla.cpp @@ -0,0 +1,155 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file sparse_flash_mla.cpp + * \brief + */ +#include "kernel_operator.h" +#include "lib/matmul_intf.h" +#include "sparse_flash_mla_template_tiling_key.h" + +// The block templates below use the template-mode constants from the tiling +// key. +#include "arch22/sparse_flash_mla_csa_kernel.h" +#include "arch22/sparse_flash_mla_swa_kernel.h" + +using namespace AscendC; +using namespace optiling::detail; +using namespace SMLAKernel; + +#define SMLA_OP_IMPL(templateClass, tilingdataClass, ...) \ + do { \ + templateClass> op; \ + GET_TILING_DATA_WITH_STRUCT(tilingdataClass, tiling_data_in, tiling); \ + const tilingdataClass* __restrict tiling_data = &tiling_data_in; \ + op.Init(query, \ + oriKV, \ + cmpKV, \ + oriSparseIndices, \ + cmpSparseIndices, \ + oriBlockTable, \ + cmpBlockTable, \ + cuSeqlensQ, \ + cuSeqlensOriKv, \ + cuSeqlensCmpKv, \ + seqUsedQ, \ + seqUsedOriKV, \ + seqUsedCmpKV, \ + cmpResidualKV, \ + oriTopkLength, \ + cmpTopkLength, \ + sinks, \ + metadata, \ + attentionOut, \ + softmaxLse, \ + user, \ + tiling_data, \ + tiling, \ + &tPipe); \ + op.Process(); \ + } while (0) + +template +__global__ __aicore__ void xllm_kernel_sparse_flash_mla( + __gm__ uint8_t* query, + __gm__ uint8_t* oriKV, + __gm__ uint8_t* cmpKV, + __gm__ uint8_t* oriSparseIndices, + __gm__ uint8_t* cmpSparseIndices, + __gm__ uint8_t* oriBlockTable, + __gm__ uint8_t* cmpBlockTable, + __gm__ uint8_t* cuSeqlensQ, + __gm__ uint8_t* cuSeqlensOriKv, + __gm__ uint8_t* cuSeqlensCmpKv, + __gm__ uint8_t* seqUsedQ, + __gm__ uint8_t* seqUsedOriKV, + __gm__ uint8_t* seqUsedCmpKV, + __gm__ uint8_t* cmpResidualKV, + __gm__ uint8_t* oriTopkLength, + __gm__ uint8_t* cmpTopkLength, + __gm__ uint8_t* sinks, + __gm__ uint8_t* metadata, + __gm__ uint8_t* attentionOut, + __gm__ uint8_t* softmaxLse, + __gm__ uint8_t* workspace, + __gm__ uint8_t* tiling) { + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); + __gm__ uint8_t* user = GetUserWorkspace(workspace); + + TPipe tPipe; + if constexpr (ORIG_DTYPE_Q == DT_FLOAT16 && ORIG_DTYPE_ORI_KV == DT_FLOAT16 && + ORIG_DTYPE_ATTN_OUT == DT_FLOAT16) { + if constexpr (TEMPLATE_MODE == CSA_TEMPLATE) { + SMLA_OP_IMPL(SparseFlashMlaCsa, + SparseFlashMlaTilingData, + half, + half, + half, + FLASH_DECODE, + static_cast(LAYOUT_T), + static_cast(KV_LAYOUT_T), + TEMPLATE_MODE, + static_cast(HEAD_RATIO_ONE), + static_cast(IS_DSPARK)); + } else { + SMLA_OP_IMPL(SparseFlashMlaSwa, + SparseFlashMlaTilingData, + half, + half, + half, + FLASH_DECODE, + static_cast(LAYOUT_T), + static_cast(KV_LAYOUT_T), + TEMPLATE_MODE, + static_cast(HEAD_RATIO_ONE), + static_cast(IS_DSPARK)); + } + } + if constexpr (ORIG_DTYPE_Q == DT_BF16 && ORIG_DTYPE_ORI_KV == DT_BF16 && + ORIG_DTYPE_ATTN_OUT == DT_BF16) { + if constexpr (TEMPLATE_MODE == CSA_TEMPLATE) { + SMLA_OP_IMPL(SparseFlashMlaCsa, + SparseFlashMlaTilingData, + bfloat16_t, + bfloat16_t, + bfloat16_t, + FLASH_DECODE, + static_cast(LAYOUT_T), + static_cast(KV_LAYOUT_T), + TEMPLATE_MODE, + static_cast(HEAD_RATIO_ONE), + static_cast(IS_DSPARK)); + } else { + SMLA_OP_IMPL(SparseFlashMlaSwa, + SparseFlashMlaTilingData, + bfloat16_t, + bfloat16_t, + bfloat16_t, + FLASH_DECODE, + static_cast(LAYOUT_T), + static_cast(KV_LAYOUT_T), + TEMPLATE_MODE, + static_cast(HEAD_RATIO_ONE), + static_cast(IS_DSPARK)); + } + } +} diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/SOURCE.txt b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/SOURCE.txt new file mode 100644 index 0000000000..ff1e99e8ab --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/SOURCE.txt @@ -0,0 +1,5 @@ +Source: https://gitcode.com/cann/ops-transformer, commit 814116886e54f04053f8870a400dfd31c46bf53c +Directory: attention/sparse_flash_mla_metadata +License: CANN Open Software License Agreement Version 2.0 (see CANN_LICENSE.txt). +The xllm-kernel package builds the Ascend A3 implementation with a distinct +operator name. The metadata protocol and kernel inputs follow the upstream ABI. diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_graph/sparse_flash_mla_metadata_proto.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_graph/sparse_flash_mla_metadata_proto.cpp new file mode 100644 index 0000000000..6fb0d3120e --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_graph/sparse_flash_mla_metadata_proto.cpp @@ -0,0 +1,57 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file sparse_flash_mla_metadata_proto.cpp + * \brief + */ +#include "graph/operator_reg.h" +#include "graph/types.h" + +namespace ge { + +REG_OP(XllmKernelSparseFlashMlaMetadata) + .OPTIONAL_INPUT(cu_seqlens_q, TensorType({DT_INT32})) + .OPTIONAL_INPUT(cu_seqlens_ori_kv, TensorType({DT_INT32})) + .OPTIONAL_INPUT(cu_seqlens_cmp_kv, TensorType({DT_INT32})) + .OPTIONAL_INPUT(seqused_q, TensorType({DT_INT32})) + .OPTIONAL_INPUT(seqused_ori_kv, TensorType({DT_INT32})) + .OPTIONAL_INPUT(seqused_cmp_kv, TensorType({DT_INT32})) + .OPTIONAL_INPUT(cmp_residual_kv, TensorType({DT_INT32})) + .OPTIONAL_INPUT(ori_topk_length, TensorType({DT_INT32})) + .OPTIONAL_INPUT(cmp_topk_length, TensorType({DT_INT32})) + .OUTPUT(metadata, TensorType({DT_INT32})) + .REQUIRED_ATTR(num_heads_q, Int) + .REQUIRED_ATTR(num_heads_kv, Int) + .REQUIRED_ATTR(head_dim, Int) + .ATTR(batch_size, Int, 0) + .ATTR(max_seqlen_q, Int, 0) + .ATTR(max_seqlen_ori_kv, Int, 0) + .ATTR(max_seqlen_cmp_kv, Int, 0) + .ATTR(ori_topk, Int, 0) + .ATTR(cmp_topk, Int, 0) + .ATTR(cmp_ratio, Int, -1) + .ATTR(ori_mask_mode, Int, 4) + .ATTR(cmp_mask_mode, Int, 3) + .ATTR(ori_win_left, Int, 127) + .ATTR(ori_win_right, Int, 0) + .ATTR(layout_q, String, "BSND") + .ATTR(layout_kv, String, "PA_BBND") + .ATTR(has_ori_kv, Bool, true) + .ATTR(has_cmp_kv, Bool, true) + .REQUIRED_ATTR(soc_version, String) + .REQUIRED_ATTR(aic_core_num, Int) + .REQUIRED_ATTR(aiv_core_num, Int) + .REQUIRED_ATTR(is_batch_consistency, Bool) + .OP_END_FACTORY_REG(XllmKernelSparseFlashMlaMetadata) + +} // namespace ge diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/aclnn_sparse_flash_mla_metadata.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/aclnn_sparse_flash_mla_metadata.cpp new file mode 100644 index 0000000000..816540c415 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/aclnn_sparse_flash_mla_metadata.cpp @@ -0,0 +1,319 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file aclnn_sparse_flash_mla_metadata.cpp + * \brief + */ + +#include "aclnn_sparse_flash_mla_metadata.h" + +#include + +#include "acl/acl_rt.h" +#include "aclnn/aclnn_base.h" +#include "aclnn_kernels/common/op_error_check.h" +#include "aclnn_kernels/contiguous.h" +#include "aclnn_kernels/reshape.h" +#include "opdev/common_types.h" +#include "opdev/data_type_utils.h" +#include "opdev/format_utils.h" +#include "opdev/make_op_executor.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "opdev/op_log.h" +#include "opdev/tensor_view_utils.h" +#include "sparse_flash_mla/op_host/common/log.h" +#include "sparse_flash_mla_metadata.h" +#include "sparse_flash_mla_metadata/op_host/sparse_flash_mla_metadata_check.h" + +constexpr int64_t BATCH_CONSISTENCY_LEVEL = 3; + +#ifdef __cplusplus +extern "C" { +#endif + +aclnnStatus aclnnXllmKernelSparseFlashMlaMetadataGetWorkspaceSize( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensOriKvOptional, + const aclTensor* cuSeqlensCmpKvOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedOriKvOptional, + const aclTensor* sequsedCmpKvOptional, + const aclTensor* cmpResidualKvOptional, + const aclTensor* oriTopkLengthOptional, + const aclTensor* cmpTopkLengthOptional, + int64_t numHeadsQ, + int64_t numHeadsKv, + int64_t headDim, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenOriKv, + int64_t maxSeqlenCmpKv, + int64_t oriTopk, + int64_t cmpTopk, + int64_t cmpRatio, + int64_t oriMaskMode, + int64_t cmpMaskMode, + int64_t oriWinLeft, + int64_t oriWinRight, + const char* layoutQOptional, + const char* layoutKvOptional, + bool hasOriKv, + bool hasCmpKv, + const aclTensor* metaData, + uint64_t* workspaceSize, + aclOpExecutor** executor) { + if (workspaceSize == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + "XllmKernelSparseFlashMlaMetadata", "workspaceSize", "Null input"); + return ACLNN_ERR_INNER_NULLPTR; + } + if (executor == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + "XllmKernelSparseFlashMlaMetadata", "executor", "Null input"); + return ACLNN_ERR_INNER_NULLPTR; + } + L2_DFX_PHASE_1(aclnnXllmKernelSparseFlashMlaMetadata, + DFX_IN(cuSeqlensQOptional, + cuSeqlensOriKvOptional, + cuSeqlensCmpKvOptional, + sequsedQOptional, + sequsedOriKvOptional, + sequsedCmpKvOptional, + cmpResidualKvOptional, + oriTopkLengthOptional, + cmpTopkLengthOptional, + numHeadsQ, + numHeadsKv, + headDim, + batchSize, + maxSeqlenQ, + maxSeqlenOriKv, + maxSeqlenCmpKv, + oriTopk, + cmpTopk, + cmpRatio, + oriMaskMode, + cmpMaskMode, + oriWinLeft, + oriWinRight, + layoutQOptional, + layoutKvOptional, + hasOriKv, + hasCmpKv), + DFX_OUT(metaData)); + + auto uniqueExecutor = CREATE_EXECUTOR(); + CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + + const op::PlatformInfo& npuInfo = op::GetCurrentPlatformInfo(); + uint32_t aicCoreNum = 0; + uint32_t aivCoreNum = 0; + if (aclrtGetResInCurrentThread(ACL_RT_DEV_RES_CUBE_CORE, &aicCoreNum) != + ACL_SUCCESS) { + aicCoreNum = npuInfo.GetCubeCoreNum(); + } + if (aclrtGetResInCurrentThread(ACL_RT_DEV_RES_VECTOR_CORE, &aivCoreNum) != + ACL_SUCCESS) { + aivCoreNum = npuInfo.GetVectorCoreNum(); + } + std::string socVersionStr = npuInfo.GetSocLongVersion(); + const char* socVersion = socVersionStr.c_str(); + + int64_t batchConsistencyLevel = 0; + aclError aclRet = + aclrtGetSysParamOpt(ACL_OPT_DETERMINISTIC, &batchConsistencyLevel); + if (aclRet != ACL_SUCCESS) { + OP_LOGW( + "aclnnXllmKernelSparseFlashMlaMetadata unable to get system param " + "batch consistency level."); + } + OP_LOGD("deterministic_level=%lld", batchConsistencyLevel); + bool isBatchConsistency = (batchConsistencyLevel == BATCH_CONSISTENCY_LEVEL); + auto ret = ParamsCheck(cuSeqlensQOptional, + cuSeqlensOriKvOptional, + cuSeqlensCmpKvOptional, + sequsedQOptional, + sequsedOriKvOptional, + sequsedCmpKvOptional, + cmpResidualKvOptional, + oriTopkLengthOptional, + cmpTopkLengthOptional, + numHeadsQ, + numHeadsKv, + headDim, + batchSize, + maxSeqlenQ, + maxSeqlenOriKv, + maxSeqlenCmpKv, + oriTopk, + cmpTopk, + cmpRatio, + oriMaskMode, + cmpMaskMode, + oriWinLeft, + oriWinRight, + layoutQOptional, + layoutKvOptional, + hasOriKv, + hasCmpKv, + aicCoreNum, + aivCoreNum, + socVersion, + metaData); + CHECK_RET(ret == ACLNN_SUCCESS, ret); + + const aclTensor* cuSeqlensQOptionalContiguous = nullptr; + if (cuSeqlensQOptional != nullptr) { + cuSeqlensQOptionalContiguous = + l0op::Contiguous(cuSeqlensQOptional, uniqueExecutor.get()); + if (cuSeqlensQOptionalContiguous == nullptr) { + OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, + "cu_seqlens_q contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* cuSeqlensOriKvOptionalContiguous = nullptr; + if (cuSeqlensOriKvOptional != nullptr) { + cuSeqlensOriKvOptionalContiguous = + l0op::Contiguous(cuSeqlensOriKvOptional, uniqueExecutor.get()); + if (cuSeqlensOriKvOptionalContiguous == nullptr) { + OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, + "cu_seqlens_ori_kv contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* cuSeqlensCmpKvOptionalContiguous = nullptr; + if (cuSeqlensCmpKvOptional != nullptr) { + cuSeqlensCmpKvOptionalContiguous = + l0op::Contiguous(cuSeqlensCmpKvOptional, uniqueExecutor.get()); + if (cuSeqlensCmpKvOptionalContiguous == nullptr) { + OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, + "cu_seqlens_cmp_kv contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* sequsedQOptionalContiguous = nullptr; + if (sequsedQOptional != nullptr) { + sequsedQOptionalContiguous = + l0op::Contiguous(sequsedQOptional, uniqueExecutor.get()); + if (sequsedQOptionalContiguous == nullptr) { + OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, + "seqused_q contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* sequsedOriKvOptionalContiguous = nullptr; + if (sequsedOriKvOptional != nullptr) { + sequsedOriKvOptionalContiguous = + l0op::Contiguous(sequsedOriKvOptional, uniqueExecutor.get()); + if (sequsedOriKvOptionalContiguous == nullptr) { + OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, + "seqused_ori_kv contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* sequsedCmpKvOptionalContiguous = nullptr; + if (sequsedCmpKvOptional != nullptr) { + sequsedCmpKvOptionalContiguous = + l0op::Contiguous(sequsedCmpKvOptional, uniqueExecutor.get()); + if (sequsedCmpKvOptionalContiguous == nullptr) { + OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, + "seqused_cmp_kv contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* cmpResidualKvOptionalContiguous = nullptr; + if (cmpResidualKvOptional != nullptr) { + cmpResidualKvOptionalContiguous = + l0op::Contiguous(cmpResidualKvOptional, uniqueExecutor.get()); + if (cmpResidualKvOptionalContiguous == nullptr) { + OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, + "cmp_residual_kv contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* oriTopkLengthOptionalContiguous = nullptr; + if (oriTopkLengthOptional != nullptr) { + oriTopkLengthOptionalContiguous = + l0op::Contiguous(oriTopkLengthOptional, uniqueExecutor.get()); + if (oriTopkLengthOptionalContiguous == nullptr) { + OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, + "ori_topk_length contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* cmpTopkLengthOptionalContiguous = nullptr; + if (cmpTopkLengthOptional != nullptr) { + cmpTopkLengthOptionalContiguous = + l0op::Contiguous(cmpTopkLengthOptional, uniqueExecutor.get()); + if (cmpTopkLengthOptionalContiguous == nullptr) { + OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, + "cmp_topk_length contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + + auto output = + l0op::XllmKernelSparseFlashMlaMetadata(cuSeqlensQOptionalContiguous, + cuSeqlensOriKvOptionalContiguous, + cuSeqlensCmpKvOptionalContiguous, + sequsedQOptionalContiguous, + sequsedOriKvOptionalContiguous, + sequsedCmpKvOptionalContiguous, + cmpResidualKvOptionalContiguous, + oriTopkLengthOptionalContiguous, + cmpTopkLengthOptionalContiguous, + numHeadsQ, + numHeadsKv, + headDim, + batchSize, + maxSeqlenQ, + maxSeqlenOriKv, + maxSeqlenCmpKv, + oriTopk, + cmpTopk, + cmpRatio, + oriMaskMode, + cmpMaskMode, + oriWinLeft, + oriWinRight, + layoutQOptional, + layoutKvOptional, + hasOriKv, + hasCmpKv, + socVersion, + aicCoreNum, + aivCoreNum, + isBatchConsistency, + metaData, + uniqueExecutor.get()); + CHECK_RET(output != nullptr, ACLNN_ERR_INNER_NULLPTR); + + *workspaceSize = uniqueExecutor->GetWorkspaceSize(); + uniqueExecutor.ReleaseTo(executor); + return ACLNN_SUCCESS; +} + +__attribute__((visibility("default"))) aclnnStatus +aclnnXllmKernelSparseFlashMlaMetadata(void* workspace, + uint64_t workspaceSize, + aclOpExecutor* executor, + aclrtStream stream) { + L2_DFX_PHASE_2(aclnnXllmKernelSparseFlashMlaMetadata); + return CommonOpExecutorRun(workspace, workspaceSize, executor, stream); +} + +#ifdef __cplusplus +} +#endif diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/aclnn_sparse_flash_mla_metadata.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/aclnn_sparse_flash_mla_metadata.h new file mode 100644 index 0000000000..8a522405dc --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/aclnn_sparse_flash_mla_metadata.h @@ -0,0 +1,65 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef ACLNN_SPARSE_FLASH_MLA_METADATA_H +#define ACLNN_SPARSE_FLASH_MLA_METADATA_H + +#include "aclnn/aclnn_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +__attribute__((visibility("default"))) aclnnStatus +aclnnXllmKernelSparseFlashMlaMetadataGetWorkspaceSize( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensOriKvOptional, + const aclTensor* cuSeqlensCmpKvOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedOriKvOptional, + const aclTensor* sequsedCmpKvOptional, + const aclTensor* cmpResidualKvOptional, + const aclTensor* oriTopkLengthOptional, + const aclTensor* cmpTopkLengthOptional, + int64_t numHeadsQ, + int64_t numHeadsKv, + int64_t headDim, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenOriKv, + int64_t maxSeqlenCmpKv, + int64_t oriTopk, + int64_t cmpTopk, + int64_t cmpRatio, + int64_t oriMaskMode, + int64_t cmpMaskMode, + int64_t oriWinLeft, + int64_t oriWinRight, + const char* layoutQOptional, + const char* layoutKvOptional, + bool hasOriKv, + bool hasCmpKv, + const aclTensor* metaData, + uint64_t* workspaceSize, + aclOpExecutor** executor); + +__attribute__((visibility("default"))) aclnnStatus +aclnnXllmKernelSparseFlashMlaMetadata(void* workspace, + uint64_t workspaceSize, + aclOpExecutor* executor, + aclrtStream stream); + +#ifdef __cplusplus +} +#endif + +#endif // ACLNN_SPARSE_FLASH_MLA_METADATA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/sparse_flash_mla_metadata.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/sparse_flash_mla_metadata.cpp new file mode 100644 index 0000000000..a0e766e5c4 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/sparse_flash_mla_metadata.cpp @@ -0,0 +1,156 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file sparse_flash_mla_metadata.cpp + * \brief + */ + +#include "sparse_flash_mla_metadata.h" + +#include + +#include "opdev/aicpu/aicpu_task.h" +#include "opdev/make_op_executor.h" +#include "opdev/op_def.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "opdev/op_log.h" +#include "opdev/shape_utils.h" +#include "sparse_flash_mla/op_host/common/log.h" + +using namespace op; +namespace l0op { +OP_TYPE_REGISTER(XllmKernelSparseFlashMlaMetadata); + +const aclTensor* XllmKernelSparseFlashMlaMetadata( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensOriKvOptional, + const aclTensor* cuSeqlensCmpKvOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedOriKvOptional, + const aclTensor* sequsedCmpKvOptional, + const aclTensor* cmpResidualKvOptional, + const aclTensor* oriTopkLengthOptional, + const aclTensor* cmpTopkLengthOptional, + int64_t numHeadsQ, + int64_t numHeadsKv, + int64_t headDim, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenOriKv, + int64_t maxSeqlenCmpKv, + int64_t oriTopk, + int64_t cmpTopk, + int64_t cmpRatio, + int64_t oriMaskMode, + int64_t cmpMaskMode, + int64_t oriWinLeft, + int64_t oriWinRight, + const char* layoutQOptional, + const char* layoutKvOptional, + bool hasOriKv, + bool hasCmpKv, + const char* socVersion, + int64_t aicCoreNum, + int64_t aivCoreNum, + bool isBatchConsistency, + const aclTensor* metaData, + aclOpExecutor* executor) { + L0_DFX(XllmKernelSparseFlashMlaMetadata, + cuSeqlensQOptional, + cuSeqlensOriKvOptional, + cuSeqlensCmpKvOptional, + sequsedQOptional, + sequsedOriKvOptional, + sequsedCmpKvOptional, + cmpResidualKvOptional, + oriTopkLengthOptional, + cmpTopkLengthOptional, + numHeadsQ, + numHeadsKv, + headDim, + batchSize, + maxSeqlenQ, + maxSeqlenOriKv, + maxSeqlenCmpKv, + oriTopk, + cmpTopk, + cmpRatio, + oriMaskMode, + cmpMaskMode, + oriWinLeft, + oriWinRight, + layoutQOptional, + layoutKvOptional, + hasOriKv, + hasCmpKv, + socVersion, + aicCoreNum, + aivCoreNum, + isBatchConsistency, + metaData); + + static internal::AicpuTaskSpace space("XllmKernelSparseFlashMlaMetadata"); + + auto ret = ADD_TO_LAUNCHER_LIST_AICPU( + XllmKernelSparseFlashMlaMetadata, + OP_ATTR_NAMES( + {"num_heads_q", "num_heads_kv", "head_dim", + "batch_size", "max_seqlen_q", "max_seqlen_ori_kv", + "max_seqlen_cmp_kv", "ori_topk", "cmp_topk", + "cmp_ratio", "ori_mask_mode", "cmp_mask_mode", + "ori_win_left", "ori_win_right", "layout_q", + "layout_kv", "has_ori_kv", "has_cmp_kv", + "soc_version", "aic_core_num", "aiv_core_num", + "is_batch_consistency"}), + OP_INPUT(cuSeqlensQOptional, + cuSeqlensOriKvOptional, + cuSeqlensCmpKvOptional, + sequsedQOptional, + sequsedOriKvOptional, + sequsedCmpKvOptional, + cmpResidualKvOptional, + oriTopkLengthOptional, + cmpTopkLengthOptional), + OP_OUTPUT(metaData), + OP_ATTR(numHeadsQ, + numHeadsKv, + headDim, + batchSize, + maxSeqlenQ, + maxSeqlenOriKv, + maxSeqlenCmpKv, + oriTopk, + cmpTopk, + cmpRatio, + oriMaskMode, + cmpMaskMode, + oriWinLeft, + oriWinRight, + layoutQOptional, + layoutKvOptional, + hasOriKv, + hasCmpKv, + socVersion, + aicCoreNum, + aivCoreNum, + isBatchConsistency)); + OP_CHECK(ret == ACL_SUCCESS, + OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, + "XllmKernelSparseFlashMlaMetadata " + "ADD_TO_LAUNCHER_LIST_AICPU failed."), + return nullptr); + return metaData; +} + +} // namespace l0op diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/sparse_flash_mla_metadata.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/sparse_flash_mla_metadata.h new file mode 100644 index 0000000000..f2197b1695 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/sparse_flash_mla_metadata.h @@ -0,0 +1,55 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef L0_SPARSE_FLASH_MLA_METADATA_H +#define L0_SPARSE_FLASH_MLA_METADATA_H + +#include "opdev/op_executor.h" + +namespace l0op { +const aclTensor* XllmKernelSparseFlashMlaMetadata( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensOriKvOptional, + const aclTensor* cuSeqlensCmpKvOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedOriKvOptional, + const aclTensor* sequsedCmpKvOptional, + const aclTensor* cmpResidualKvOptional, + const aclTensor* oriTopkLengthOptional, + const aclTensor* cmpTopkLengthOptional, + int64_t numHeadsQ, + int64_t numHeadsKv, + int64_t headDim, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenOriKv, + int64_t maxSeqlenCmpKv, + int64_t oriTopk, + int64_t cmpTopk, + int64_t cmpRatio, + int64_t oriMaskMode, + int64_t cmpMaskMode, + int64_t oriWinLeft, + int64_t oriWinRight, + const char* layoutQOptional, + const char* layoutKvOptional, + bool hasOriKv, + bool hasCmpKv, + const char* socVersion, + int64_t aicCoreNum, + int64_t aivCoreNum, + bool isBatchConsistency, + const aclTensor* metaData, + aclOpExecutor* executor); +} // namespace l0op + +#endif diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/sparse_flash_mla_metadata_check.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/sparse_flash_mla_metadata_check.h new file mode 100644 index 0000000000..f6280f450a --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/sparse_flash_mla_metadata_check.h @@ -0,0 +1,1464 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file sparse_flash_mla_metadata_check.h + * \brief + */ + +#include +#include + +#include "opdev/data_type_utils.h" +#include "opdev/format_utils.h" +#include "opdev/tensor_view_utils.h" +#include "sparse_flash_mla/op_host/common/log.h" +#include "sparse_flash_mla/op_kernel/sparse_flash_mla_kernel_metadata.h" + +#ifdef __cplusplus +extern "C" { +#endif + +namespace { + +static constexpr const char* SMLA_ACLNN_OP_NAME = + "aclnnXllmKernelSparseFlashMlaMetadata"; + +enum class SparseModeSmla : uint8_t { + DEFAULT_MASK = 0, + ALL_MASK, + LEFT_UP_CAUSAL, + RIGHT_DOWN_CAUSAL, + BAND, + SPARSE_BUTT, +}; + +inline constexpr int64_t SMLA_CMP_RATIO_LOWER_BOUND = 1; +inline constexpr int64_t SMLA_CMP_RATIO_UPPER_BOUND = 128; +inline constexpr int64_t SMLA_NUM_HEADS_Q_LOWER_BOUND = 1; +inline constexpr int64_t SMLA_NUM_HEADS_Q_UPPER_BOUND = 128; + +inline bool IsPowerOfTwoInRangeSmla(int64_t value, + int64_t minValue, + int64_t maxValue) { + return value >= minValue && value <= maxValue && ((value & (value - 1)) == 0); +} + +inline bool IsA5Smla(const char* socVersion) { + return socVersion != nullptr && (strstr(socVersion, "Ascend950") != nullptr); +} + +inline bool IsA6Smla(const char* socVersion) { + return socVersion != nullptr && + (strstr(socVersion, "Ascend960DT") != nullptr || + strstr(socVersion, "Ascend960PR") != nullptr); +} + +inline bool IsCmpRatioSupportSmla(const char* socVersion, + bool hasCmpKv, + int64_t cmpTopk, + int64_t cmpRatio) { + if (IsA5Smla(socVersion) || IsA6Smla(socVersion)) { + return cmpRatio >= SMLA_CMP_RATIO_LOWER_BOUND && + cmpRatio <= SMLA_CMP_RATIO_UPPER_BOUND; + } + return (cmpTopk > 0) ? (cmpRatio == 1 || cmpRatio == 2 || cmpRatio == 4) + : (cmpRatio == 128); +} + +inline bool IsTensorExistSmla(const aclTensor* tensor) { + return (tensor != nullptr) && (tensor->GetViewShape().GetDimNum() > 0) && + (tensor->GetViewShape().GetDim(0) > 0); +} + +aclnnStatus CheckReservedOptionalTensorSmla(const aclTensor* tensor, + const char* tensorName) { + if (!IsTensorExistSmla(tensor)) { + return ACLNN_SUCCESS; + } + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + SMLA_ACLNN_OP_NAME, + tensorName, + std::string(tensorName) + + " is reserved and does not support " + "non-empty tensor"); + return ACLNN_ERR_PARAM_INVALID; +} + +int64_t GetDimNumSmla(const aclTensor* tensor) { + if (tensor == nullptr) { + return -1; + } + return tensor->GetViewShape().GetDimNum(); +} + +aclDataType GetDataTypeSmla(const aclTensor* tensor) { + aclDataType dataType = aclDataType::ACL_DT_UNDEFINED; + if (tensor == nullptr) { + return dataType; + } + aclGetDataType(tensor, &dataType); + return dataType; +} + +inline bool IsTensorSourceSmla(const std::string& source) { + return source != "batch_size"; +} + +inline int64_t GetRawShapeSizeSmla(const std::string& source, + int64_t batchValue) { + if (source.find("cu_seqlens") != std::string::npos) { + return batchValue + 1; + } + return batchValue; +} + +inline std::string GetSourceDescSmla(const std::string& source) { + if (source == "batch_size") { + return "batch_size"; + } + if (source.find("cu_seqlens") != std::string::npos) { + return "the shape size of " + source + " minus 1"; + } + return "the shape size of " + source; +} + +aclnnStatus CheckSingleParamSmla(int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenOriKv, + int64_t maxSeqlenCmpKv, + int64_t numHeadsQ, + int64_t numHeadsKv, + int64_t headDim, + int64_t oriTopk, + int64_t cmpTopk, + int64_t cmpRatio, + int64_t oriMaskMode, + int64_t cmpMaskMode, + int64_t oriWinLeft, + int64_t oriWinRight, + const char* layoutQOptional, + const char* layoutKvOptional, + bool hasOriKv, + bool hasCmpKv, + uint32_t aicCoreNum, + uint32_t aivCoreNum, + const char* socVersion) { + // batch_size >= 0 + if (batchSize < 0) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "batch_size", + std::to_string(batchSize), + "The value of batch_size must be greater than or equal to 0"); + return ACLNN_ERR_PARAM_INVALID; + } + // max_seqlen_q >= 0 + if (maxSeqlenQ < 0) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "max_seqlen_q", + std::to_string(maxSeqlenQ), + "The value of max_seqlen_q must be greater than or equal to 0"); + return ACLNN_ERR_PARAM_INVALID; + } + // max_seqlen_ori_kv >= 0 + if (maxSeqlenOriKv < 0) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "max_seqlen_ori_kv", + std::to_string(maxSeqlenOriKv), + "The value of max_seqlen_ori_kv must be greater than or equal to 0"); + return ACLNN_ERR_PARAM_INVALID; + } + // max_seqlen_cmp_kv >= 0 + if (maxSeqlenCmpKv < 0) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "max_seqlen_cmp_kv", + std::to_string(maxSeqlenCmpKv), + "The value of max_seqlen_cmp_kv must be greater than or equal to 0"); + return ACLNN_ERR_PARAM_INVALID; + } + // num_heads_q [1, 128] + if (numHeadsQ < SMLA_NUM_HEADS_Q_LOWER_BOUND || + numHeadsQ > SMLA_NUM_HEADS_Q_UPPER_BOUND) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "num_heads_q", + std::to_string(numHeadsQ), + "The current value is not within the valid range. " + "The valid range is [" + + std::to_string(SMLA_NUM_HEADS_Q_LOWER_BOUND) + ", " + + std::to_string(SMLA_NUM_HEADS_Q_UPPER_BOUND) + "]"); + return ACLNN_ERR_PARAM_INVALID; + } + // num_heads_kv: 1 + if (numHeadsKv != 1) { + OP_LOGE_FOR_INVALID_VALUE( + SMLA_ACLNN_OP_NAME, "num_heads_kv", std::to_string(numHeadsKv), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + if (numHeadsQ % numHeadsKv != 0) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "num_heads_q, num_heads_kv", + std::to_string(numHeadsQ) + ", " + std::to_string(numHeadsKv), + "The value of num_heads_q must be divisible by " + "that of num_heads_kv"); + return ACLNN_ERR_PARAM_INVALID; + } + int64_t headRatio = numHeadsQ / numHeadsKv; + if (IsA5Smla(socVersion) || IsA6Smla(socVersion)) { + if (headRatio < SMLA_NUM_HEADS_Q_LOWER_BOUND || + headRatio > SMLA_NUM_HEADS_Q_UPPER_BOUND) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "num_heads_q / num_heads_kv", + std::to_string(headRatio), + "The current value is not within the valid range. " + "The valid range is [" + + std::to_string(SMLA_NUM_HEADS_Q_LOWER_BOUND) + ", " + + std::to_string(SMLA_NUM_HEADS_Q_UPPER_BOUND) + "]"); + return ACLNN_ERR_PARAM_INVALID; + } + } else if (!IsPowerOfTwoInRangeSmla(headRatio, + SMLA_NUM_HEADS_Q_LOWER_BOUND, + SMLA_NUM_HEADS_Q_UPPER_BOUND)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "num_heads_q / num_heads_kv", + std::to_string(headRatio), + "The current value is not within the valid range. " + "The valid range is power of two in [" + + std::to_string(SMLA_NUM_HEADS_Q_LOWER_BOUND) + ", " + + std::to_string(SMLA_NUM_HEADS_Q_UPPER_BOUND) + "]"); + return ACLNN_ERR_PARAM_INVALID; + } + // head_dim: 512 + if (headDim != 512) { + OP_LOGE_FOR_INVALID_VALUE( + SMLA_ACLNN_OP_NAME, "head_dim", std::to_string(headDim), "512"); + return ACLNN_ERR_PARAM_INVALID; + } + if (hasOriKv) { + // ori_topk >= 0 + if (oriTopk < 0) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "ori_topk", + std::to_string(oriTopk), + "When has_ori_kv is true, the value of ori_topk must be " + "greater than or equal to 0"); + return ACLNN_ERR_PARAM_INVALID; + } + if (!((IsA5Smla(socVersion) || IsA6Smla(socVersion))) && oriTopk != 0 && + hasCmpKv) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "ori_topk", + std::to_string(oriTopk), + "ori_topk is reserved and " + "the value of ori_topk must be 0 when has_cmp_kv is true"); + return ACLNN_ERR_PARAM_INVALID; + } + if (IsA5Smla(socVersion) || IsA6Smla(socVersion)) { + // ori_mask_mode: 0, 3, or 4 + if (oriMaskMode != static_cast(SparseModeSmla::DEFAULT_MASK) && + oriMaskMode != + static_cast(SparseModeSmla::RIGHT_DOWN_CAUSAL) && + oriMaskMode != static_cast(SparseModeSmla::BAND)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "ori_mask_mode", + std::to_string(oriMaskMode), + "When has_ori_kv is true, the value of ori_mask_mode " + "must be in [0, 3, 4]"); + return ACLNN_ERR_PARAM_INVALID; + } + // A5 treats -1 as unlimited window + if (oriWinLeft < -1 || oriWinRight < -1) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "ori_win_left and ori_win_right", + std::to_string(oriWinLeft) + " and " + std::to_string(oriWinRight), + "When has_ori_kv is true, the value of ori_win_left, " + "ori_win_right must be greater than or equal to -1"); + return ACLNN_ERR_PARAM_INVALID; + } + } else { + if (oriTopk != 0) { + if (oriMaskMode != static_cast(SparseModeSmla::DEFAULT_MASK)) { + OP_LOGE_FOR_INVALID_VALUE(SMLA_ACLNN_OP_NAME, + "ori_mask_mode", + std::to_string(oriMaskMode), + "0"); + return ACLNN_ERR_PARAM_INVALID; + } + if (oriWinLeft < 0 || oriWinRight < 0) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "ori_win_left, ori_win_right", + std::to_string(oriWinLeft) + ", " + std::to_string(oriWinRight), + "When has_ori_kv is true and ori_topk is non-zero (DSpark), " + "ori_win_left and ori_win_right must be non-negative"); + return ACLNN_ERR_PARAM_INVALID; + } + } else { + if (oriMaskMode != static_cast(SparseModeSmla::BAND)) { + OP_LOGE_FOR_INVALID_VALUE(SMLA_ACLNN_OP_NAME, + "ori_mask_mode", + std::to_string(oriMaskMode), + "4"); + return ACLNN_ERR_PARAM_INVALID; + } + if (oriWinLeft != 127 || oriWinRight != 0) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "ori_win_left and ori_win_right", + std::to_string(oriWinLeft) + " and " + + std::to_string(oriWinRight), + "When has_ori_kv is true, the value of ori_win_left " + "must be 127 and the value of ori_win_right must be 0"); + return ACLNN_ERR_PARAM_INVALID; + } + } + } + } + if (hasCmpKv) { + // cmp_topk >= 0 + if (cmpTopk < 0) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cmp_topk", + std::to_string(cmpTopk), + "When has_cmp_kv is true, the value of cmp_topk must be " + "greater than or equal to 0"); + return ACLNN_ERR_PARAM_INVALID; + } + if (!((IsA5Smla(socVersion) || IsA6Smla(socVersion))) && cmpTopk > 8192) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cmp_topk", + std::to_string(cmpTopk), + "When has_cmp_kv is true, the value of cmp_topk must be " + "in [1, 8192]"); + return ACLNN_ERR_PARAM_INVALID; + } + if (IsA5Smla(socVersion) || IsA6Smla(socVersion)) { + // cmp_mask_mode: 0 or 3 + if (cmpMaskMode != static_cast(SparseModeSmla::DEFAULT_MASK) && + cmpMaskMode != + static_cast(SparseModeSmla::RIGHT_DOWN_CAUSAL)) { + OP_LOGE_FOR_INVALID_VALUE(SMLA_ACLNN_OP_NAME, + "cmp_mask_mode", + std::to_string(cmpMaskMode), + "0 or 3"); + return ACLNN_ERR_PARAM_INVALID; + } + } else { + if (cmpMaskMode != + static_cast(SparseModeSmla::RIGHT_DOWN_CAUSAL)) { + OP_LOGE_FOR_INVALID_VALUE(SMLA_ACLNN_OP_NAME, + "cmp_mask_mode", + std::to_string(cmpMaskMode), + "3"); + return ACLNN_ERR_PARAM_INVALID; + } + } + if (!IsCmpRatioSupportSmla(socVersion, hasCmpKv, cmpTopk, cmpRatio)) { + if (IsA5Smla(socVersion) || IsA6Smla(socVersion)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cmp_ratio", + std::to_string(cmpRatio), + "When has_cmp_kv is true, the current value is not " + "within the valid range. The valid range is [" + + std::to_string(SMLA_CMP_RATIO_LOWER_BOUND) + ", " + + std::to_string(SMLA_CMP_RATIO_UPPER_BOUND) + "]"); + } else { + int64_t expectedCmpRatio = (cmpTopk > 0) ? 4 : 128; + if (cmpTopk > 0) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cmp_ratio", + std::to_string(cmpRatio), + "When has_cmp_kv is true and cmp_topk is non-zero" + "(CSA with cmp_sparse_indices), " + "the value of cmp_ratio must be 1, 2 or " + + std::to_string(expectedCmpRatio)); + } else { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cmp_ratio", + std::to_string(cmpRatio), + "When has_cmp_kv is true and cmp_topk is 0" + "(HCA without cmp_sparse_indices), " + "the value of cmp_ratio must be " + + std::to_string(expectedCmpRatio)); + } + } + return ACLNN_ERR_PARAM_INVALID; + } + } + if (layoutQOptional == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + SMLA_ACLNN_OP_NAME, "layout_q", "layout_q cannot be empty"); + return ACLNN_ERR_PARAM_INVALID; + } + if (layoutKvOptional == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + SMLA_ACLNN_OP_NAME, "layout_kv", "layout_kv cannot be empty"); + return ACLNN_ERR_PARAM_INVALID; + } + // layout_q: BSND or TND + if (strcmp(layoutQOptional, "TND") != 0 && + strcmp(layoutQOptional, "BSND") != 0) { + OP_LOGE_FOR_INVALID_VALUE( + SMLA_ACLNN_OP_NAME, "layout_q", layoutQOptional, "TND or BSND"); + return ACLNN_ERR_PARAM_INVALID; + } + // layout_kv: BSND, TND, or PA_BBND + if (strcmp(layoutKvOptional, "BSND") != 0 && + strcmp(layoutKvOptional, "TND") != 0 && + strcmp(layoutKvOptional, "PA_BBND") != 0) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "layout_kv", + layoutKvOptional, + "The value of layout_kv must be in [TND, BSND, PA_BBND]"); + return ACLNN_ERR_PARAM_INVALID; + } + if (strcmp(layoutKvOptional, "PA_BBND") != 0 && + strcmp(layoutQOptional, layoutKvOptional) != 0) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "layout_q, layout_kv", + std::string(layoutQOptional) + ", " + std::string(layoutKvOptional), + "When layout_kv is not PA_BBND, the values of layout_q, layout_kv must " + "be the same"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 layout_q 为 BSND 时,max_seqlen_q 必须大于 0 + if (strcmp(layoutQOptional, "BSND") == 0 && maxSeqlenQ <= 0) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "max_seqlen_q", + std::to_string(maxSeqlenQ), + "When layout_q is BSND, the value of max_seqlen_q " + "must be equal to the size of the second axis of q"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 has_ori_kv 且 layout_kv 为 BSND 时,max_seqlen_ori_kv 必须大于 0 + if (hasOriKv && strcmp(layoutKvOptional, "BSND") == 0 && + maxSeqlenOriKv <= 0) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "max_seqlen_ori_kv", + std::to_string(maxSeqlenOriKv), + "When has_ori_kv is true and layout_kv is BSND, " + "the value of max_seqlen_ori_kv " + "must be equal to the size of the second axis of ori_kv"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 has_cmp_kv 且 layout_kv 为 BSND 时,max_seqlen_cmp_kv 必须大于 0 + if (hasCmpKv && strcmp(layoutKvOptional, "BSND") == 0 && + maxSeqlenCmpKv <= 0) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "max_seqlen_cmp_kv", + std::to_string(maxSeqlenCmpKv), + "When has_cmp_kv is true and layout_kv is BSND, " + "the value of max_seqlen_cmp_kv " + "must be equal to the size of the second axis of cmp_kv"); + return ACLNN_ERR_PARAM_INVALID; + } + // 核数校验 + if (aicCoreNum == 0) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "aic_core_num", + std::to_string(aicCoreNum), + "The value of aic_core_num must be greater than 0"); + return ACLNN_ERR_PARAM_INVALID; + } + if (aicCoreNum > optiling::AIC_CORE_MAX_NUM) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "aic_core_num", + std::to_string(aicCoreNum), + "The current value is not within the valid range. " + "The valid range is [1, " + + std::to_string(optiling::AIC_CORE_MAX_NUM) + "]"); + return ACLNN_ERR_PARAM_INVALID; + } + if (aivCoreNum == 0) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "aiv_core_num", + std::to_string(aivCoreNum), + "The value of aiv_core_num must be greater than 0"); + return ACLNN_ERR_PARAM_INVALID; + } + if (aivCoreNum > optiling::AIV_CORE_MAX_NUM) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "aiv_core_num", + std::to_string(aivCoreNum), + "The current value is not within the valid range. " + "The valid range is [1, " + + std::to_string(optiling::AIV_CORE_MAX_NUM) + "]"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验切g模板核数 + if (numHeadsQ == 128) { + if (aicCoreNum == 1 || aivCoreNum == 1) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "num_heads_q and aic_core_num and aiv_core_num", + std::to_string(numHeadsQ) + " and " + std::to_string(aicCoreNum) + + " and " + std::to_string(aivCoreNum), + "When num_heads_q is 128, the value of aic_core_num, " + "aiv_core_num cannot be 1"); + return ACLNN_ERR_PARAM_INVALID; + } + } + return ACLNN_SUCCESS; +} + +aclnnStatus CheckExistenceSmla(const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensOriKvOptional, + const aclTensor* cuSeqlensCmpKvOptional, + const aclTensor* sequsedOriKvOptional, + const aclTensor* sequsedCmpKvOptional, + const aclTensor* cmpResidualKvOptional, + const aclTensor* oriTopkLengthOptional, + const aclTensor* cmpTopkLengthOptional, + int64_t oriTopk, + int64_t cmpTopk, + int64_t cmpRatio, + int64_t oriMaskMode, + int64_t cmpMaskMode, + bool hasOriKv, + bool hasCmpKv, + const char* layoutQOptional, + const char* layoutKvOptional, + const char* socVersion, + const aclTensor* metadata) { + // cu_seqlens_q 存在性校验 + if (strcmp(layoutQOptional, "TND") == 0) { + if (!IsTensorExistSmla(cuSeqlensQOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cu_seqlens_q", + "When layout_q is TND, cu_seqlens_q cannot be empty"); + return ACLNN_ERR_PARAM_INVALID; + } + } + if (hasOriKv) { + // cu_seqlens_ori_kv 存在性校验 + if (strcmp(layoutKvOptional, "TND") == 0) { + if (!IsTensorExistSmla(cuSeqlensOriKvOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cu_seqlens_ori_kv", + "When has_ori_kv is true and layout_kv is TND, " + "cu_seqlens_ori_kv cannot be empty"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // seqused_ori_kv 存在性校验 + if (IsA5Smla(socVersion) || IsA6Smla(socVersion)) { + if ((oriMaskMode != 0 || oriTopk == 0) && + strcmp(layoutKvOptional, "PA_BBND") == 0) { + if (!IsTensorExistSmla(sequsedOriKvOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "seqused_ori_kv", + "When has_ori_kv is true, ori_mask_mode != 0 or " + "ori_topk == 0, and layout_kv is PA_BBND, " + "seqused_ori_kv cannot be empty"); + return ACLNN_ERR_PARAM_INVALID; + } + } + } else { + if (strcmp(layoutKvOptional, "PA_BBND") == 0) { + if (!IsTensorExistSmla(sequsedOriKvOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "seqused_ori_kv", + "When has_ori_kv is true and layout_kv is PA_BBND, " + "seqused_ori_kv cannot be empty"); + return ACLNN_ERR_PARAM_INVALID; + } + } + } + // ori_topk_length 存在性校验 + if (oriTopk != 0 && + oriMaskMode == static_cast(SparseModeSmla::DEFAULT_MASK)) { + if (!IsTensorExistSmla(oriTopkLengthOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "ori_topk_length", + "When has_ori_kv is true, ori_topk is not 0 and " + "ori_mask_mode is 0, ori_topk_length cannot be empty"); + return ACLNN_ERR_PARAM_INVALID; + } + } + } + if (hasCmpKv) { + // cu_seqlens_cmp_kv 存在性校验 + if (strcmp(layoutKvOptional, "TND") == 0) { + if (!IsTensorExistSmla(cuSeqlensCmpKvOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cu_seqlens_cmp_kv", + "When has_cmp_kv is true and layout_kv is TND, " + "cu_seqlens_cmp_kv cannot be empty"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // seqused_cmp_kv 存在性校验 + if (IsA5Smla(socVersion) || IsA6Smla(socVersion)) { + if ((cmpMaskMode != 0 || cmpTopk == 0) && + strcmp(layoutKvOptional, "PA_BBND") == 0) { + if (!IsTensorExistSmla(sequsedCmpKvOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "seqused_cmp_kv", + "When has_cmp_kv is true, cmp_mask_mode != 0 or " + "cmp_topk == 0, and layout_kv is PA_BBND, " + "seqused_cmp_kv cannot be empty"); + return ACLNN_ERR_PARAM_INVALID; + } + } + } else { + if (strcmp(layoutKvOptional, "PA_BBND") == 0) { + if (!IsTensorExistSmla(sequsedCmpKvOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "seqused_cmp_kv", + "When has_cmp_kv is true and layout_kv is PA_BBND, " + "seqused_cmp_kv cannot be empty"); + return ACLNN_ERR_PARAM_INVALID; + } + } + } + // cmp_residual_kv 存在性校验 + if (cmpRatio != 1 && + cmpMaskMode == + static_cast(SparseModeSmla::RIGHT_DOWN_CAUSAL)) { + if (!IsTensorExistSmla(cmpResidualKvOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cmp_residual_kv", + "When has_cmp_kv is true, cmp_ratio is not 1 and " + "cmp_mask_mode is 3, cmp_residual_kv cannot be empty"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // cmp_topk_length 存在性校验 + if (cmpTopk != 0 && + cmpMaskMode == static_cast(SparseModeSmla::DEFAULT_MASK)) { + if (!IsTensorExistSmla(cmpTopkLengthOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cmp_topk_length", + "When has_cmp_kv is true, cmp_topk is not 0 and " + "cmp_mask_mode is 0, cmp_topk_length cannot be empty"); + return ACLNN_ERR_PARAM_INVALID; + } + } + } + // metadata 存在性校验 + if (!IsTensorExistSmla(metadata)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + SMLA_ACLNN_OP_NAME, "metadata", "metadata cannot be empty"); + return ACLNN_ERR_PARAM_INVALID; + } + return ACLNN_SUCCESS; +} + +int64_t GetQueryBatchSizeSmla(const aclTensor* sequsedQOptional, + const aclTensor* cuSeqlensQOptional, + const char* layoutQOptional, + int64_t batchSize, + std::string* source) { + if (IsTensorExistSmla(sequsedQOptional)) { + *source = "seqused_q"; + return sequsedQOptional->GetViewShape().GetDim(0); + } + if (strcmp(layoutQOptional, "TND") == 0) { + if (IsTensorExistSmla(cuSeqlensQOptional)) { + *source = "cu_seqlens_q"; + return cuSeqlensQOptional->GetViewShape().GetDim(0) - 1; + } + } + *source = "batch_size"; + return batchSize; +} + +int64_t GetOriKvBatchSizeSmla(const aclTensor* sequsedOriKvOptional, + const aclTensor* cuSeqlensOriKvOptional, + const char* layoutKvOptional, + int64_t batchSize, + std::string* source) { + if (IsTensorExistSmla(sequsedOriKvOptional)) { + *source = "seqused_ori_kv"; + return sequsedOriKvOptional->GetViewShape().GetDim(0); + } + if (strcmp(layoutKvOptional, "TND") == 0) { + if (IsTensorExistSmla(cuSeqlensOriKvOptional)) { + *source = "cu_seqlens_ori_kv"; + return cuSeqlensOriKvOptional->GetViewShape().GetDim(0) - 1; + } + } + *source = "batch_size"; + return batchSize; +} + +int64_t GetCmpKvBatchSizeSmla(const aclTensor* sequsedCmpKvOptional, + const aclTensor* cuSeqlensCmpKvOptional, + const char* layoutKvOptional, + int64_t batchSize, + std::string* source) { + if (IsTensorExistSmla(sequsedCmpKvOptional)) { + *source = "seqused_cmp_kv"; + return sequsedCmpKvOptional->GetViewShape().GetDim(0); + } + if (strcmp(layoutKvOptional, "TND") == 0) { + if (IsTensorExistSmla(cuSeqlensCmpKvOptional)) { + *source = "cu_seqlens_cmp_kv"; + return cuSeqlensCmpKvOptional->GetViewShape().GetDim(0) - 1; + } + } + *source = "batch_size"; + return batchSize; +} + +std::string TopkLengthShapeToStringSmla(const aclTensor* topkLengthOptional) { + const auto& shape = topkLengthOptional->GetViewShape(); + std::string result; + for (size_t i = 0; i < shape.GetDimNum(); ++i) { + if (i != 0) { + result += ", "; + } + result += std::to_string(shape.GetDim(i)); + } + return result; +} + +aclnnStatus CheckTopkLengthFirstDimSmla(const aclTensor* topkLengthOptional, + const std::string& topkLengthName, + int64_t queryBatchSize, + const std::string& querySource) { + if (topkLengthOptional->GetViewShape().GetDim(0) == queryBatchSize) { + return ACLNN_SUCCESS; + } + std::string incorrectShape = TopkLengthShapeToStringSmla(topkLengthOptional); + if (IsTensorSourceSmla(querySource)) { + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + topkLengthName, + incorrectShape, + "When layout_q is BSND, the size of the first axis of " + + topkLengthName + " must be equal to " + + GetSourceDescSmla(querySource)); + } else { + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + topkLengthName, + incorrectShape, + "When layout_q is BSND, the size of the first axis of " + + topkLengthName + " must be equal to batch_size"); + } + return ACLNN_ERR_PARAM_INVALID; +} + +struct TopkLengthAxisSmla { + int64_t index; + const char* desc; +}; + +inline constexpr TopkLengthAxisSmla SMLA_TOPK_LENGTH_SECOND_AXIS{1, "second"}; +inline constexpr TopkLengthAxisSmla SMLA_TOPK_LENGTH_THIRD_AXIS{2, "third"}; + +aclnnStatus CheckTopkLengthSingleDimSmla(const aclTensor* topkLengthOptional, + const std::string& topkLengthName, + TopkLengthAxisSmla axis, + int64_t expectedValue, + const std::string& expectedDesc, + const char* layoutQOptional) { + if (topkLengthOptional->GetViewShape().GetDim(axis.index) == expectedValue) { + return ACLNN_SUCCESS; + } + std::string incorrectShape = TopkLengthShapeToStringSmla(topkLengthOptional); + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + topkLengthName, + incorrectShape, + "When layout_q is " + std::string(layoutQOptional) + + ", the size of the " + axis.desc + " axis of " + topkLengthName + + " must be equal to " + expectedDesc); + return ACLNN_ERR_PARAM_INVALID; +} + +aclnnStatus CheckConsistencySmla(const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensOriKvOptional, + const aclTensor* cuSeqlensCmpKvOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedOriKvOptional, + const aclTensor* sequsedCmpKvOptional, + const aclTensor* cmpResidualKvOptional, + const aclTensor* oriTopkLengthOptional, + const aclTensor* cmpTopkLengthOptional, + int64_t batchSize, + const char* layoutQOptional, + const char* layoutKvOptional, + bool hasOriKv, + bool hasCmpKv, + int64_t oriTopk, + int64_t cmpTopk, + int64_t oriMaskMode, + int64_t cmpMaskMode, + int64_t maxSeqlenQ, + int64_t numHeadsKv, + const char* socVersion, + const aclTensor* metadata) { + aclDataType dataType = aclDataType::ACL_DT_UNDEFINED; + int64_t dimNum = -1; + if (!((IsA5Smla(socVersion) || IsA6Smla(socVersion)))) { + if (oriTopk == 0 && + CheckReservedOptionalTensorSmla(oriTopkLengthOptional, + "ori_topk_length") != ACLNN_SUCCESS) { + return ACLNN_ERR_PARAM_INVALID; + } + if (CheckReservedOptionalTensorSmla(cmpTopkLengthOptional, + "cmp_topk_length") != ACLNN_SUCCESS) { + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 cu_seqlens_q + if (IsTensorExistSmla(cuSeqlensQOptional)) { + // 校验 cu_seqlens_q 维度 + dimNum = GetDimNumSmla(cuSeqlensQOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + SMLA_ACLNN_OP_NAME, "cu_seqlens_q", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 cu_seqlens_q 数据类型 + dataType = GetDataTypeSmla(cuSeqlensQOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cu_seqlens_q", + ToString(dataType).GetString(), + "The dtype of cu_seqlens_q must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 seqused_q + if (IsTensorExistSmla(sequsedQOptional)) { + // 校验 seqused_q 维度 + dimNum = GetDimNumSmla(sequsedQOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + SMLA_ACLNN_OP_NAME, "seqused_q", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 seqused_q 数据类型 + dataType = GetDataTypeSmla(sequsedQOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "seqused_q", + ToString(dataType).GetString(), + "The dtype of seqused_q must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // ori_kv部分 + if (hasOriKv) { + // 校验 cu_seqlens_ori_kv + if (IsTensorExistSmla(cuSeqlensOriKvOptional)) { + // 校验 cu_seqlens_ori_kv 维度 + dimNum = GetDimNumSmla(cuSeqlensOriKvOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM(SMLA_ACLNN_OP_NAME, + "cu_seqlens_ori_kv", + std::to_string(dimNum), + "1"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 cu_seqlens_ori_kv 数据类型 + dataType = GetDataTypeSmla(cuSeqlensOriKvOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cu_seqlens_ori_kv", + ToString(dataType).GetString(), + "The dtype of cu_seqlens_ori_kv must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 seqused_ori_kv + if (IsTensorExistSmla(sequsedOriKvOptional)) { + // 校验 seqused_ori_kv 维度 + dimNum = GetDimNumSmla(sequsedOriKvOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + SMLA_ACLNN_OP_NAME, "seqused_ori_kv", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 seqused_ori_kv 数据类型 + dataType = GetDataTypeSmla(sequsedOriKvOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "seqused_ori_kv", + ToString(dataType).GetString(), + "The dtype of seqused_ori_kv must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 ori_topk_length + if (oriTopk != 0 && + oriMaskMode == static_cast(SparseModeSmla::DEFAULT_MASK) && + IsTensorExistSmla(oriTopkLengthOptional)) { + // 校验 ori_topk_length 维度 + dimNum = GetDimNumSmla(oriTopkLengthOptional); + if (strcmp(layoutQOptional, "TND") == 0) { + if (dimNum != 2) { + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "ori_topk_length", + std::to_string(dimNum), + "The shape dim of ori_topk_length must be 2 " + "when layout_q is TND"); + return ACLNN_ERR_PARAM_INVALID; + } + } else if (strcmp(layoutQOptional, "BSND") == 0) { + if (dimNum != 3) { + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "ori_topk_length", + std::to_string(dimNum), + "The shape dim of ori_topk_length must be 3 " + "when layout_q is BSND"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 ori_topk_length 数据类型 + dataType = GetDataTypeSmla(oriTopkLengthOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "ori_topk_length", + ToString(dataType).GetString(), + "The dtype of ori_topk_length must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + } + // cmp_kv部分 + if (hasCmpKv) { + // 校验 cu_seqlens_cmp_kv + if (IsTensorExistSmla(cuSeqlensCmpKvOptional)) { + // 校验 cu_seqlens_cmp_kv 维度 + dimNum = GetDimNumSmla(cuSeqlensCmpKvOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM(SMLA_ACLNN_OP_NAME, + "cu_seqlens_cmp_kv", + std::to_string(dimNum), + "1"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 cu_seqlens_cmp_kv 数据类型 + dataType = GetDataTypeSmla(cuSeqlensCmpKvOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cu_seqlens_cmp_kv", + ToString(dataType).GetString(), + "The dtype of cu_seqlens_cmp_kv must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 seqused_cmp_kv + if (IsTensorExistSmla(sequsedCmpKvOptional)) { + // 校验 seqused_cmp_kv 维度 + dimNum = GetDimNumSmla(sequsedCmpKvOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + SMLA_ACLNN_OP_NAME, "seqused_cmp_kv", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 seqused_cmp_kv 数据类型 + dataType = GetDataTypeSmla(sequsedCmpKvOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "seqused_cmp_kv", + ToString(dataType).GetString(), + "The dtype of seqused_cmp_kv must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 cmp_residual_kv + if (IsTensorExistSmla(cmpResidualKvOptional)) { + // 校验 cmp_residual_kv 维度 + dimNum = GetDimNumSmla(cmpResidualKvOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + SMLA_ACLNN_OP_NAME, "cmp_residual_kv", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 cmp_residual_kv 数据类型 + dataType = GetDataTypeSmla(cmpResidualKvOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cmp_residual_kv", + ToString(dataType).GetString(), + "The dtype of cmp_residual_kv must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 cmp_topk_length + if (cmpTopk != 0 && + cmpMaskMode == static_cast(SparseModeSmla::DEFAULT_MASK) && + IsTensorExistSmla(cmpTopkLengthOptional)) { + // 校验 cmp_topk_length 维度 + dimNum = GetDimNumSmla(cmpTopkLengthOptional); + if (strcmp(layoutQOptional, "TND") == 0) { + if (dimNum != 2) { + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cmp_topk_length", + std::to_string(dimNum), + "The shape dim of cmp_topk_length must be 2 " + "when layout_q is TND"); + return ACLNN_ERR_PARAM_INVALID; + } + } else if (strcmp(layoutQOptional, "BSND") == 0) { + if (dimNum != 3) { + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cmp_topk_length", + std::to_string(dimNum), + "The shape dim of cmp_topk_length must be 3 " + "when layout_q is BSND"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 cmp_topk_length 数据类型 + dataType = GetDataTypeSmla(cmpTopkLengthOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cmp_topk_length", + ToString(dataType).GetString(), + "The dtype of cmp_topk_length must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + } + // 校验 metadata + if (IsTensorExistSmla(metadata)) { + // 校验 metadata 维度 + dimNum = GetDimNumSmla(metadata); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + SMLA_ACLNN_OP_NAME, "metadata", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 metadata 元素数 + if (metadata->GetViewShape().GetDim(0) != + optiling::SMLA_METADATA_TOTAL_SIZE) { + OP_LOGE_FOR_INVALID_SHAPESIZE( + SMLA_ACLNN_OP_NAME, + "metadata", + std::to_string(metadata->GetViewShape().GetDim(0)), + std::to_string(optiling::SMLA_METADATA_TOTAL_SIZE)); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 metadata 数据类型 + dataType = GetDataTypeSmla(metadata); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "metadata", + ToString(dataType).GetString(), + "The dtype of metadata must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 q/kv 维度一致性 + std::string querySource; + int64_t queryBatchSize = GetQueryBatchSizeSmla(sequsedQOptional, + cuSeqlensQOptional, + layoutQOptional, + batchSize, + &querySource); + // 校验TND场景q维度一致性 + if (strcmp(layoutQOptional, "TND") == 0 && + IsTensorExistSmla(sequsedQOptional)) { + int64_t cuSeqlensQBatchSize = + cuSeqlensQOptional->GetViewShape().GetDim(0) - 1; + if (cuSeqlensQBatchSize != queryBatchSize) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cu_seqlens_q and seqused_q", + std::to_string(cuSeqlensQOptional->GetViewShape().GetDim(0)) + + " and " + + std::to_string(sequsedQOptional->GetViewShape().GetDim(0)), + "When layout_q is TND and seqused_q is passed, " + "the shape size of cu_seqlens_q minus 1 must be equal to " + "the shape size of seqused_q"); + return ACLNN_ERR_PARAM_INVALID; + } + } + if (hasOriKv) { + std::string oriKvSource; + int64_t oriKvBatchSize = GetOriKvBatchSizeSmla(sequsedOriKvOptional, + cuSeqlensOriKvOptional, + layoutKvOptional, + batchSize, + &oriKvSource); + // 校验q与ori_kv维度一致性 + if (queryBatchSize != oriKvBatchSize) { + if (IsTensorSourceSmla(querySource) && IsTensorSourceSmla(oriKvSource)) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + SMLA_ACLNN_OP_NAME, + querySource + " and " + oriKvSource, + std::to_string(GetRawShapeSizeSmla(querySource, queryBatchSize)) + + " and " + + std::to_string( + GetRawShapeSizeSmla(oriKvSource, oriKvBatchSize)), + "When has_ori_kv is true, " + GetSourceDescSmla(querySource) + + " must be equal to " + GetSourceDescSmla(oriKvSource)); + } else if (IsTensorSourceSmla(querySource)) { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + querySource, + std::to_string(GetRawShapeSizeSmla(querySource, queryBatchSize)), + "When has_ori_kv is true, " + GetSourceDescSmla(querySource) + + " must be equal to batch_size"); + } else { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + oriKvSource, + std::to_string(GetRawShapeSizeSmla(oriKvSource, oriKvBatchSize)), + "When has_ori_kv is true, " + GetSourceDescSmla(oriKvSource) + + " must be equal to batch_size"); + } + return ACLNN_ERR_PARAM_INVALID; + } + // 校验TND场景ori_kv维度一致性 + if (strcmp(layoutKvOptional, "TND") == 0 && + IsTensorExistSmla(sequsedOriKvOptional)) { + int64_t cuSeqlensOriKvBatchSize = + cuSeqlensOriKvOptional->GetViewShape().GetDim(0) - 1; + if (cuSeqlensOriKvBatchSize != oriKvBatchSize) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cu_seqlens_ori_kv and seqused_ori_kv", + std::to_string(cuSeqlensOriKvOptional->GetViewShape().GetDim(0)) + + " and " + + std::to_string(sequsedOriKvOptional->GetViewShape().GetDim(0)), + "When layout_kv is TND and seqused_ori_kv is passed, " + "the shape size of cu_seqlens_ori_kv minus 1 must be " + "equal to the shape size of seqused_ori_kv"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 ori_topk_length 维度一致性 + if (oriTopk != 0 && + oriMaskMode == static_cast(SparseModeSmla::DEFAULT_MASK) && + IsTensorExistSmla(oriTopkLengthOptional)) { + if (strcmp(layoutQOptional, "BSND") == 0) { + // 校验 ori_topk_length 第一个维度 + aclnnStatus ret = CheckTopkLengthFirstDimSmla(oriTopkLengthOptional, + "ori_topk_length", + queryBatchSize, + querySource); + if (ret != ACLNN_SUCCESS) { + return ret; + } + // 校验 ori_topk_length 第二个维度 + ret = CheckTopkLengthSingleDimSmla(oriTopkLengthOptional, + "ori_topk_length", + SMLA_TOPK_LENGTH_SECOND_AXIS, + maxSeqlenQ, + "max_seqlen_q", + layoutQOptional); + if (ret != ACLNN_SUCCESS) { + return ret; + } + // 校验 ori_topk_length 第三个维度 + ret = CheckTopkLengthSingleDimSmla(oriTopkLengthOptional, + "ori_topk_length", + SMLA_TOPK_LENGTH_THIRD_AXIS, + numHeadsKv, + "num_heads_kv", + layoutQOptional); + if (ret != ACLNN_SUCCESS) { + return ret; + } + } else if (strcmp(layoutQOptional, "TND") == 0) { + // 校验 ori_topk_length 第二个维度 + aclnnStatus ret = + CheckTopkLengthSingleDimSmla(oriTopkLengthOptional, + "ori_topk_length", + SMLA_TOPK_LENGTH_SECOND_AXIS, + numHeadsKv, + "num_heads_kv", + layoutQOptional); + if (ret != ACLNN_SUCCESS) { + return ret; + } + } + } + } + if (hasCmpKv) { + std::string cmpKvSource; + int64_t cmpKvBatchSize = GetCmpKvBatchSizeSmla(sequsedCmpKvOptional, + cuSeqlensCmpKvOptional, + layoutKvOptional, + batchSize, + &cmpKvSource); + // 校验q与cmp_kv维度一致性 + if (queryBatchSize != cmpKvBatchSize) { + if (IsTensorSourceSmla(querySource) && IsTensorSourceSmla(cmpKvSource)) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + SMLA_ACLNN_OP_NAME, + querySource + " and " + cmpKvSource, + std::to_string(GetRawShapeSizeSmla(querySource, queryBatchSize)) + + " and " + + std::to_string( + GetRawShapeSizeSmla(cmpKvSource, cmpKvBatchSize)), + "When has_cmp_kv is true, " + GetSourceDescSmla(querySource) + + " must be equal to " + GetSourceDescSmla(cmpKvSource)); + } else if (IsTensorSourceSmla(querySource)) { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + querySource, + std::to_string(GetRawShapeSizeSmla(querySource, queryBatchSize)), + "When has_cmp_kv is true, " + GetSourceDescSmla(querySource) + + " must be equal to batch_size"); + } else { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + cmpKvSource, + std::to_string(GetRawShapeSizeSmla(cmpKvSource, cmpKvBatchSize)), + "When has_cmp_kv is true, " + GetSourceDescSmla(cmpKvSource) + + " must be equal to batch_size"); + } + return ACLNN_ERR_PARAM_INVALID; + } + // 校验TND场景cmp_kv维度一致性 + if (strcmp(layoutKvOptional, "TND") == 0 && + IsTensorExistSmla(sequsedCmpKvOptional)) { + int64_t cuSeqlensCmpKvBatchSize = + cuSeqlensCmpKvOptional->GetViewShape().GetDim(0) - 1; + if (cuSeqlensCmpKvBatchSize != cmpKvBatchSize) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cu_seqlens_cmp_kv and seqused_cmp_kv", + std::to_string(cuSeqlensCmpKvOptional->GetViewShape().GetDim(0)) + + " and " + + std::to_string(sequsedCmpKvOptional->GetViewShape().GetDim(0)), + "When layout_kv is TND and seqused_cmp_kv is passed, " + "the shape size of cu_seqlens_cmp_kv minus 1 must be " + "equal to the shape size of seqused_cmp_kv"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 cmp_residual_kv 元素数 + if (IsTensorExistSmla(cmpResidualKvOptional)) { + if (cmpResidualKvOptional->GetViewShape().GetDim(0) != queryBatchSize) { + if (IsTensorSourceSmla(querySource)) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cmp_residual_kv and " + querySource, + std::to_string(cmpResidualKvOptional->GetViewShape().GetDim(0)) + + " and " + + std::to_string( + GetRawShapeSizeSmla(querySource, queryBatchSize)), + "The shape size of cmp_residual_kv must be equal to " + + GetSourceDescSmla(querySource)); + } else { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + SMLA_ACLNN_OP_NAME, + "cmp_residual_kv", + std::to_string(cmpResidualKvOptional->GetViewShape().GetDim(0)), + "The shape size of cmp_residual_kv must be equal " + "to batch_size"); + } + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 cmp_topk_length 维度一致性 + if (cmpTopk != 0 && + cmpMaskMode == static_cast(SparseModeSmla::DEFAULT_MASK) && + IsTensorExistSmla(cmpTopkLengthOptional)) { + if (strcmp(layoutQOptional, "BSND") == 0) { + // 校验 cmp_topk_length 第一个维度 + aclnnStatus ret = CheckTopkLengthFirstDimSmla(cmpTopkLengthOptional, + "cmp_topk_length", + queryBatchSize, + querySource); + if (ret != ACLNN_SUCCESS) { + return ret; + } + // 校验 cmp_topk_length 第二个维度 + ret = CheckTopkLengthSingleDimSmla(cmpTopkLengthOptional, + "cmp_topk_length", + SMLA_TOPK_LENGTH_SECOND_AXIS, + maxSeqlenQ, + "max_seqlen_q", + layoutQOptional); + if (ret != ACLNN_SUCCESS) { + return ret; + } + // 校验 cmp_topk_length 第三个维度 + ret = CheckTopkLengthSingleDimSmla(cmpTopkLengthOptional, + "cmp_topk_length", + SMLA_TOPK_LENGTH_THIRD_AXIS, + numHeadsKv, + "num_heads_kv", + layoutQOptional); + if (ret != ACLNN_SUCCESS) { + return ret; + } + } else if (strcmp(layoutQOptional, "TND") == 0) { + // 校验 cmp_topk_length 第二个维度 + aclnnStatus ret = + CheckTopkLengthSingleDimSmla(cmpTopkLengthOptional, + "cmp_topk_length", + SMLA_TOPK_LENGTH_SECOND_AXIS, + numHeadsKv, + "num_heads_kv", + layoutQOptional); + if (ret != ACLNN_SUCCESS) { + return ret; + } + } + } + } + return ACLNN_SUCCESS; +} + +static aclnnStatus ParamsCheck(const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensOriKvOptional, + const aclTensor* cuSeqlensCmpKvOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedOriKvOptional, + const aclTensor* sequsedCmpKvOptional, + const aclTensor* cmpResidualKvOptional, + const aclTensor* oriTopkLengthOptional, + const aclTensor* cmpTopkLengthOptional, + int64_t numHeadsQ, + int64_t numHeadsKv, + int64_t headDim, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenOriKv, + int64_t maxSeqlenCmpKv, + int64_t oriTopk, + int64_t cmpTopk, + int64_t cmpRatio, + int64_t oriMaskMode, + int64_t cmpMaskMode, + int64_t oriWinLeft, + int64_t oriWinRight, + const char* layoutQOptional, + const char* layoutKvOptional, + bool hasOriKv, + bool hasCmpKv, + uint32_t aicCoreNum, + uint32_t aivCoreNum, + const char* socVersion, + const aclTensor* metaData) { + if (CheckSingleParamSmla(batchSize, + maxSeqlenQ, + maxSeqlenOriKv, + maxSeqlenCmpKv, + numHeadsQ, + numHeadsKv, + headDim, + oriTopk, + cmpTopk, + cmpRatio, + oriMaskMode, + cmpMaskMode, + oriWinLeft, + oriWinRight, + layoutQOptional, + layoutKvOptional, + hasOriKv, + hasCmpKv, + aicCoreNum, + aivCoreNum, + socVersion) == ACLNN_SUCCESS && + CheckExistenceSmla(cuSeqlensQOptional, + cuSeqlensOriKvOptional, + cuSeqlensCmpKvOptional, + sequsedOriKvOptional, + sequsedCmpKvOptional, + cmpResidualKvOptional, + oriTopkLengthOptional, + cmpTopkLengthOptional, + oriTopk, + cmpTopk, + cmpRatio, + oriMaskMode, + cmpMaskMode, + hasOriKv, + hasCmpKv, + layoutQOptional, + layoutKvOptional, + socVersion, + metaData) == ACLNN_SUCCESS && + CheckConsistencySmla(cuSeqlensQOptional, + cuSeqlensOriKvOptional, + cuSeqlensCmpKvOptional, + sequsedQOptional, + sequsedOriKvOptional, + sequsedCmpKvOptional, + cmpResidualKvOptional, + oriTopkLengthOptional, + cmpTopkLengthOptional, + batchSize, + layoutQOptional, + layoutKvOptional, + hasOriKv, + hasCmpKv, + oriTopk, + cmpTopk, + oriMaskMode, + cmpMaskMode, + maxSeqlenQ, + numHeadsKv, + socVersion, + metaData) == ACLNN_SUCCESS) { + return ACLNN_SUCCESS; + } else { + return ACLNN_ERR_PARAM_INVALID; + } +} +} // namespace + +#ifdef __cplusplus +} +#endif diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/sparse_flash_mla_metadata_infershape.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/sparse_flash_mla_metadata_infershape.cpp new file mode 100644 index 0000000000..e8d3bbb5aa --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/sparse_flash_mla_metadata_infershape.cpp @@ -0,0 +1,41 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file sparse_flash_mla_metadata_infershape.cpp + * \brief + */ +#include "register/op_impl_registry.h" +#include "sparse_flash_mla/op_kernel/sparse_flash_mla_kernel_metadata.h" + +using namespace ge; + +namespace ops { +static ge::graphStatus InferShapeSparseFlashMlaMetadata( + gert::InferShapeContext* context) { + gert::Shape* oShape = context->GetOutputShape(0); + // output shape (SMLA_METADATA_T, ) + oShape->SetDimNum(1); + oShape->SetDim(0, optiling::SMLA_METADATA_TOTAL_SIZE); + return GRAPH_SUCCESS; +} + +static ge::graphStatus InferDtypeSparseFlashMlaMetadata( + gert::InferDataTypeContext* context) { + context->SetOutputDataType(0, DT_INT32); + return GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(XllmKernelSparseFlashMlaMetadata) + .InferShape(InferShapeSparseFlashMlaMetadata) + .InferDataType(InferDtypeSparseFlashMlaMetadata); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.cpp new file mode 100644 index 0000000000..9a7cb84b45 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.cpp @@ -0,0 +1,1954 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file sparse_flash_mla_metadata_aicpu.cpp + * \brief + */ + +#include "sparse_flash_mla_metadata_aicpu.h" + +#include +#include + +#include "log.h" + +using namespace optiling; + +namespace aicpu::xllm_sparse_mla { +uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::Compute( + CpuKernelContext& ctx) { + bool success = Prepare(ctx); + if (!success) { + return KERNEL_STATUS_PARAM_INVALID; + } + SplitResult splitRes{aicCoreNum_, aivCoreNum_}; + success = BalanceSchedule(splitRes) && GenMetadata(splitRes); + return success ? KERNEL_STATUS_OK : KERNEL_STATUS_PARAM_INVALID; +} + +bool XllmKernelSparseFlashMlaMetadataCpuKernel::Prepare(CpuKernelContext& ctx) { + // input + cuSeqlensQ_ = ctx.Input(static_cast(ParamId::cuSeqlensQ)); + cuSeqlensOriKv_ = ctx.Input(static_cast(ParamId::cuSeqlensOriKv)); + cuSeqlensCmpKv_ = ctx.Input(static_cast(ParamId::cuSeqlensCmpKv)); + sequsedQ_ = ctx.Input(static_cast(ParamId::sequsedQ)); + sequsedOriKv_ = ctx.Input(static_cast(ParamId::sequsedOriKv)); + sequsedCmpKv_ = ctx.Input(static_cast(ParamId::sequsedCmpKv)); + cmpResidualKv_ = ctx.Input(static_cast(ParamId::cmpResidualKv)); + oriTopkLength_ = ctx.Input(static_cast(ParamId::oriTopkLength)); + cmpTopkLength_ = ctx.Input(static_cast(ParamId::cmpTopkLength)); + hasOriTopkLength_ = + (oriTopkLength_ != nullptr && oriTopkLength_->GetData() != nullptr && + oriTopkLength_->NumElements() > 0); + // output + metadata_ = ctx.Output(static_cast(ParamId::metaData)); + + bool requiredAttrs = GetAttrValue(ctx, "num_heads_q", numHeadsQ_) && + GetAttrValue(ctx, "num_heads_kv", numHeadsKv_) && + GetAttrValue(ctx, "head_dim", headDim_); + if (!requiredAttrs) { + return false; + } + + // attributes optional + GetAttrValueOpt(ctx, "soc_version", socVersion_); + GetAttrValueOpt(ctx, "aic_core_num", aicCoreNum_); + GetAttrValueOpt(ctx, "aiv_core_num", aivCoreNum_); + GetAttrValueOpt(ctx, "batch_size", batchSize_); + GetAttrValueOpt(ctx, "max_seqlen_q", maxSeqlenQ_); + GetAttrValueOpt(ctx, "max_seqlen_ori_kv", maxSeqlenOriKv_); + GetAttrValueOpt(ctx, "max_seqlen_cmp_kv", maxSeqlenCmpKv_); + GetAttrValueOpt(ctx, "ori_topk", oriTopK_); + GetAttrValueOpt(ctx, "cmp_topk", cmpTopK_); + GetAttrValueOpt(ctx, "cmp_ratio", cmpRatio_); + GetAttrValueOpt(ctx, "ori_mask_mode", oriMaskMode_); + GetAttrValueOpt(ctx, "cmp_mask_mode", cmpMaskMode_); + GetAttrValueOpt(ctx, "ori_win_left", oriWinLeft_); + GetAttrValueOpt(ctx, "ori_win_right", oriWinRight_); + GetAttrValueOpt(ctx, "layout_q", layoutQ_); + GetAttrValueOpt(ctx, "layout_kv", layoutKv_); + GetAttrValueOpt(ctx, "has_ori_kv", hasOriKv_); + GetAttrValueOpt(ctx, "has_cmp_kv", hasCmpKv_); + GetAttrValueOpt(ctx, "is_batch_consistency", isBatchConsistency_); + return (ParamsCheck() && ParamsInit()); +} + +bool XllmKernelSparseFlashMlaMetadataCpuKernel::ParamsCheck() { + // 校验输出 metadata 是否为空 + if (metadata_ == nullptr) { + KERNEL_LOG_ERROR("Output metadata is nullptr"); + return false; + } else if (metadata_->GetData() == nullptr) { + KERNEL_LOG_ERROR("Output metadata data is nullptr"); + return false; + } + int32_t batchSize = GetQueryBatchSize(); + // 校验 cu_seqlens_q 元素 + if (layoutQ_ == "TND") { + if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { + const int32_t* cuSeqlensQPtr = + static_cast(cuSeqlensQ_->GetData()); + // 校验 cu_seqlens_q 首元素为 0 + if (cuSeqlensQPtr[0] != 0) { + KERNEL_LOG_ERROR( + "The first element of cu_seqlens_q should be 0, but got %d", + cuSeqlensQPtr[0]); + return false; + } + for (int i = 0; i < batchSize + 1; i++) { + // 校验 cu_seqlens_q 元素递增 + if (i > 0 && cuSeqlensQPtr[i - 1] > cuSeqlensQPtr[i]) { + KERNEL_LOG_ERROR( + "The elements in cu_seqlens_q must be in ascending order, " + "but got cu_seqlens_q[%d] = %d, cu_seqlens_q[%d] = %d", + i - 1, + cuSeqlensQPtr[i - 1], + i, + cuSeqlensQPtr[i]); + return false; + } + } + } + } + // 校验 seqused_q 元素 + if (sequsedQ_ != nullptr && sequsedQ_->GetData() != nullptr) { + const int32_t* sequsedQPtr = + static_cast(sequsedQ_->GetData()); + const int32_t* cuSeqlensQPtr = + (layoutQ_ == "TND" && cuSeqlensQ_ != nullptr && + cuSeqlensQ_->GetData() != nullptr) + ? static_cast(cuSeqlensQ_->GetData()) + : nullptr; + for (int i = 0; i < batchSize; i++) { + // 校验 seqused_q 元素非负 + if (sequsedQPtr[i] < 0) { + KERNEL_LOG_ERROR( + "The elements in seqused_q should be >= 0, but got seqused_q[%d] = " + "%d", + i, + sequsedQPtr[i]); + return false; + } + // 校验 seqused_q 元素不大于 max_seqlen_q (BSND) 或 cu_seqlens_q 序列长度 + // (TND) + if (layoutQ_ == "BSND" && sequsedQPtr[i] > maxSeqlenQ_) { + KERNEL_LOG_ERROR( + "The elements in seqused_q should not be greater than max_seqlen_q " + "%d, " + "but got seqused_q[%d] = %d", + maxSeqlenQ_, + i, + sequsedQPtr[i]); + return false; + } + if (cuSeqlensQPtr != nullptr) { + int32_t seqLen = cuSeqlensQPtr[i + 1] - cuSeqlensQPtr[i]; + if (sequsedQPtr[i] > seqLen) { + KERNEL_LOG_ERROR( + "The elements in seqused_q should not be greater than the " + "sequence length " + "from cu_seqlens_q %d, but got seqused_q[%d] = %d", + seqLen, + i, + sequsedQPtr[i]); + return false; + } + } + } + } + if (hasOriKv_) { + // 校验 cu_seqlens_ori_kv 元素 + if (layoutKv_ == "TND") { + if (cuSeqlensOriKv_ != nullptr && cuSeqlensOriKv_->GetData() != nullptr) { + const int32_t* cuSeqlensOriKvPtr = + static_cast(cuSeqlensOriKv_->GetData()); + // 校验 cu_seqlens_ori_kv 首元素为 0 + if (cuSeqlensOriKvPtr[0] != 0) { + KERNEL_LOG_ERROR( + "The first element of cu_seqlens_ori_kv should be 0, but got %d", + cuSeqlensOriKvPtr[0]); + return false; + } + for (int i = 0; i < batchSize + 1; i++) { + // 校验 cu_seqlens_ori_kv 元素递增 + if (i > 0 && cuSeqlensOriKvPtr[i - 1] > cuSeqlensOriKvPtr[i]) { + KERNEL_LOG_ERROR( + "The elements in cu_seqlens_ori_kv must be in ascending order, " + "but got cu_seqlens_ori_kv[%d] = %d, cu_seqlens_ori_kv[%d] = " + "%d", + i - 1, + cuSeqlensOriKvPtr[i - 1], + i, + cuSeqlensOriKvPtr[i]); + return false; + } + } + } + } + // 校验 seqused_ori_kv 元素 + if (sequsedOriKv_ != nullptr && sequsedOriKv_->GetData() != nullptr) { + const int32_t* sequsedOriKvPtr = + static_cast(sequsedOriKv_->GetData()); + const int32_t* cuSeqlensOriKvPtr = + (layoutKv_ == "TND" && cuSeqlensOriKv_ != nullptr && + cuSeqlensOriKv_->GetData() != nullptr) + ? static_cast(cuSeqlensOriKv_->GetData()) + : nullptr; + for (int i = 0; i < batchSize; i++) { + // 校验 seqused_ori_kv 元素非负 + if (sequsedOriKvPtr[i] < 0) { + KERNEL_LOG_ERROR( + "The elements in seqused_ori_kv should be >= 0, but got " + "seqused_ori_kv[%d] = %d", + i, + sequsedOriKvPtr[i]); + return false; + } + // 校验 seqused_ori_kv 元素不大于 max_seqlen_ori_kv (BSND) 或 + // cu_seqlens_ori_kv 序列长度 (TND) + if (layoutKv_ == "BSND" && sequsedOriKvPtr[i] > maxSeqlenOriKv_) { + KERNEL_LOG_ERROR( + "The elements in seqused_ori_kv should not be greater than " + "max_seqlen_ori_kv %d, but got seqused_ori_kv[%d] = %d", + maxSeqlenOriKv_, + i, + sequsedOriKvPtr[i]); + return false; + } + if (cuSeqlensOriKvPtr != nullptr) { + int32_t seqLen = cuSeqlensOriKvPtr[i + 1] - cuSeqlensOriKvPtr[i]; + if (sequsedOriKvPtr[i] > seqLen) { + KERNEL_LOG_ERROR( + "The elements in seqused_ori_kv should not be greater than the " + "sequence " + "length from cu_seqlens_ori_kv %d, but got seqused_ori_kv[%d] " + "= %d", + seqLen, + i, + sequsedOriKvPtr[i]); + return false; + } + } + } + } + // 校验 ori_topk_length 元素 + if (oriTopK_ != 0 && + oriMaskMode_ == static_cast(SparseMode::DEFAULT_MASK) && + oriTopkLength_ != nullptr && oriTopkLength_->GetData() != nullptr) { + // 校验 ori_topk_length 元素数量 + int32_t sumOfQuerySeq = GetSumOfQuerySeq(); + const int32_t* oriTopkLengthPtr = + static_cast(oriTopkLength_->GetData()); + auto oriTopkLengthShape = oriTopkLength_->GetTensorShape(); + int32_t oriTopkLengthSize = layoutQ_ == "TND" + ? oriTopkLengthShape->GetDimSize(0) * + oriTopkLengthShape->GetDimSize(1) + : oriTopkLengthShape->GetDimSize(0) * + oriTopkLengthShape->GetDimSize(1) * + oriTopkLengthShape->GetDimSize(2); + if (oriTopkLengthSize < sumOfQuerySeq) { + KERNEL_LOG_ERROR( + "The size of ori_topk_length %d should not be smaller than " + "the sum of query sequence %d!", + oriTopkLengthSize, + sumOfQuerySeq); + return false; + } + // 校验 ori_topk_length 元素非负 + for (int i = 0; i < oriTopkLengthSize; i++) { + if (oriTopkLengthPtr[i] < 0) { + KERNEL_LOG_ERROR( + "The elements in ori_topk_length should be >= 0, but got " + "ori_topk_length[%d] = %d", + i, + oriTopkLengthPtr[i]); + return false; + } + } + } + } + if (hasCmpKv_) { + if (layoutKv_ == "TND") { + // 校验 cu_seqlens_cmp_kv 元素 + if (cuSeqlensCmpKv_ != nullptr && cuSeqlensCmpKv_->GetData() != nullptr) { + const int32_t* cuSeqlensCmpKvPtr = + static_cast(cuSeqlensCmpKv_->GetData()); + // 校验 cu_seqlens_cmp_kv 首元素为 0 + if (cuSeqlensCmpKvPtr[0] != 0) { + KERNEL_LOG_ERROR( + "The first element of cu_seqlens_cmp_kv should be 0, but got %d", + cuSeqlensCmpKvPtr[0]); + return false; + } + for (int i = 0; i < batchSize + 1; i++) { + // 校验 cu_seqlens_cmp_kv 元素递增 + if (i > 0 && cuSeqlensCmpKvPtr[i - 1] > cuSeqlensCmpKvPtr[i]) { + KERNEL_LOG_ERROR( + "The elements in cu_seqlens_cmp_kv must be in ascending order, " + "but got cu_seqlens_cmp_kv[%d] = %d, cu_seqlens_cmp_kv[%d] = " + "%d", + i - 1, + cuSeqlensCmpKvPtr[i - 1], + i, + cuSeqlensCmpKvPtr[i]); + return false; + } + } + } + } + // 校验 seqused_cmp_kv 元素 + if (sequsedCmpKv_ != nullptr && sequsedCmpKv_->GetData() != nullptr) { + const int32_t* sequsedCmpKvPtr = + static_cast(sequsedCmpKv_->GetData()); + const int32_t* cuSeqlensCmpKvPtr = + (layoutKv_ == "TND" && cuSeqlensCmpKv_ != nullptr && + cuSeqlensCmpKv_->GetData() != nullptr) + ? static_cast(cuSeqlensCmpKv_->GetData()) + : nullptr; + for (int i = 0; i < batchSize; i++) { + // 校验 seqused_cmp_kv 元素非负 + if (sequsedCmpKvPtr[i] < 0) { + KERNEL_LOG_ERROR( + "The elements in seqused_cmp_kv should be >= 0, but got " + "seqused_cmp_kv[%d] = %d", + i, + sequsedCmpKvPtr[i]); + return false; + } + // 校验 seqused_cmp_kv 元素不大于 max_seqlen_cmp_kv (BSND) 或 + // cu_seqlens_cmp_kv 序列长度 (TND) + if (layoutKv_ == "BSND" && sequsedCmpKvPtr[i] > maxSeqlenCmpKv_) { + KERNEL_LOG_ERROR( + "The elements in seqused_cmp_kv should not be greater than " + "max_seqlen_cmp_kv %d, but got seqused_cmp_kv[%d] = %d", + maxSeqlenCmpKv_, + i, + sequsedCmpKvPtr[i]); + return false; + } + if (cuSeqlensCmpKvPtr != nullptr) { + int32_t seqLen = cuSeqlensCmpKvPtr[i + 1] - cuSeqlensCmpKvPtr[i]; + if (sequsedCmpKvPtr[i] > seqLen) { + KERNEL_LOG_ERROR( + "The elements in seqused_cmp_kv should not be greater than the " + "sequence " + "length from cu_seqlens_cmp_kv %d, but got seqused_cmp_kv[%d] " + "= %d", + seqLen, + i, + sequsedCmpKvPtr[i]); + return false; + } + } + } + } + // 校验 cmp_residual_kv 元素 + if (cmpResidualKv_ != nullptr && cmpResidualKv_->GetData() != nullptr) { + const int32_t* cmpResidualKvPtr = + static_cast(cmpResidualKv_->GetData()); + for (int i = 0; i < batchSize; i++) { + if (cmpResidualKvPtr[i] < 0 || cmpResidualKvPtr[i] >= cmpRatio_) { + KERNEL_LOG_ERROR( + "The elements in cmp_residual_kv should be in [0, " + "cmpRatio_(%d)), but got " + "cmp_residual_kv[%d] = %d", + cmpRatio_, + i, + cmpResidualKvPtr[i]); + return false; + } + } + } + // 校验 cmp_topk_length 元素 + if (cmpTopK_ != 0 && + cmpMaskMode_ == static_cast(SparseMode::DEFAULT_MASK) && + cmpTopkLength_ != nullptr && cmpTopkLength_->GetData() != nullptr) { + // 校验 cmp_topk_length 元素数量 + int32_t sumOfQuerySeq = GetSumOfQuerySeq(); + const int32_t* cmpTopkLengthPtr = + static_cast(cmpTopkLength_->GetData()); + auto cmpTopkLengthShape = cmpTopkLength_->GetTensorShape(); + int32_t cmpTopkLengthSize = layoutQ_ == "TND" + ? cmpTopkLengthShape->GetDimSize(0) * + cmpTopkLengthShape->GetDimSize(1) + : cmpTopkLengthShape->GetDimSize(0) * + cmpTopkLengthShape->GetDimSize(1) * + cmpTopkLengthShape->GetDimSize(2); + if (cmpTopkLengthSize < sumOfQuerySeq) { + KERNEL_LOG_ERROR( + "The size of cmp_topk_length %d should not be smaller than " + "the sum of query sequence %d!", + cmpTopkLengthSize, + sumOfQuerySeq); + return false; + } + // 校验 cmp_topk_length 元素非负 + for (int i = 0; i < cmpTopkLengthSize; i++) { + if (cmpTopkLengthPtr[i] < 0) { + KERNEL_LOG_ERROR( + "The elements in cmp_topk_length should be >= 0, but got " + "cmp_topk_length[%d] = %d", + i, + cmpTopkLengthPtr[i]); + return false; + } + } + } + } + return true; +} + +int32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetSumOfQuerySeq() { + int32_t batchSize = GetQueryBatchSize(); + // 如果sequsedQ_ 传了,使用sequsedQ_获取 BsSize + if (sequsedQ_ != nullptr && sequsedQ_->GetData() != nullptr) { + if (sequsedQ_->GetTensorShape() != nullptr) { + const int32_t* seqUsedPtr = + static_cast(sequsedQ_->GetData()); + int32_t queryBsSize = 0; + for (int i = 0; i < batchSize; i++) { + queryBsSize += seqUsedPtr[i]; + } + return queryBsSize; + } + } + // sequsedQ_ 没传,判断 Layout + if (layoutQ_ == "TND") { + // 如果是 TND,尝试使用 cuSeqlensQ_获取 BsSize + if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { + if (cuSeqlensQ_->GetTensorShape() != nullptr) { + const int32_t* s1Ptr = + static_cast(cuSeqlensQ_->GetData()); + return s1Ptr[batchSize]; + } + } + } + // 如果不是 TND,或者 cuSeqlensQ_ 为空,使用shape信息计算 BsSize + return batchSize_ * maxSeqlenQ_; +} + +int32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetQueryBatchSize() { + // 1. 如果sequsedQ_ 传了,使用sequsedQ_获取BatchSize + if (sequsedQ_ != nullptr && sequsedQ_->GetData() != nullptr) { + if (sequsedQ_->GetTensorShape() != nullptr) { + return sequsedQ_->GetTensorShape()->GetDimSize(0); + } + } + // 2. sequsedQ_ 没传,判断 Layout + if (layoutQ_ == "TND") { + // 如果是 TND,尝试使用 cuSeqlensQ_获取BatchSize + if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { + if (cuSeqlensQ_->GetTensorShape() != nullptr) { + return cuSeqlensQ_->GetTensorShape()->GetDimSize(0) - 1; + } + } + } + // 3. 如果不是 TND,或者 cuSeqlensQ_ 为空,使用batchSize_ + return batchSize_; +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcOriMaskMode() { + if (oriMaskMode_ == static_cast(SparseMode::DEFAULT_MASK)) { + oriPreToken_ = INT64_MAX; + oriNextToken_ = INT64_MAX; + oriAttentionMode_ = NO_MASK; + } else if (oriMaskMode_ == + static_cast(SparseMode::RIGHT_DOWN_CAUSAL)) { + oriPreToken_ = INT64_MAX; + oriNextToken_ = 0; + oriAttentionMode_ = HAS_MASK; + } else { // SparseMode = 4 + oriPreToken_ = (oriWinLeft_ > -1) ? oriWinLeft_ : INT64_MAX; + oriNextToken_ = (oriWinRight_ > -1) ? oriWinRight_ : INT64_MAX; + oriAttentionMode_ = HAS_MASK; + } +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcCmpMaskMode() { + if (cmpMaskMode_ == static_cast(SparseMode::DEFAULT_MASK)) { + cmpPreToken_ = INT64_MAX; + cmpNextToken_ = INT64_MAX; + cmpAttentionMode_ = NO_MASK; + } else if (cmpMaskMode_ == + static_cast(SparseMode::RIGHT_DOWN_CAUSAL)) { + cmpPreToken_ = INT64_MAX; + cmpNextToken_ = 0; + cmpAttentionMode_ = HAS_MASK; + } else { // SparseMode = 4 + cmpPreToken_ = (oriWinLeft_ > -1) ? oriWinLeft_ : INT64_MAX; + cmpNextToken_ = (oriWinRight_ > -1) ? oriWinRight_ : INT64_MAX; + cmpAttentionMode_ = HAS_MASK; + } +} + +ValidSocVersion XllmKernelSparseFlashMlaMetadataCpuKernel::ProcessSocVersion() { + const std::string ascend960Dt = "Ascend960DT"; + const std::string ascend960Pr = "Ascend960PR"; + const std::string ascend950 = "Ascend950"; + if (socVersion_.find(ascend960Dt) != std::string::npos || + socVersion_.find(ascend960Pr) != std::string::npos) { + return ValidSocVersion::ASCEND960; + } else if (socVersion_.find(ascend950) != std::string::npos) { + return ValidSocVersion::ASCEND950; + } else { + return ValidSocVersion::ASCEND910; + } +} + +bool XllmKernelSparseFlashMlaMetadataCpuKernel::ParamsInit() { + batchSize_ = GetQueryBatchSize(); + CalcOriMaskMode(); + CalcCmpMaskMode(); + isS1G_ = (layoutQ_ == "BSND" || layoutQ_ == "BSH" || layoutQ_ == "TND"); + if (numHeadsKv_ == 0) { + KERNEL_LOG_ERROR("num_heads_kv should not be 0."); + return false; + } + ValidSocVersion validSocVersion = ProcessSocVersion(); + groupSize_ = numHeadsQ_ / numHeadsKv_; + if (hasOriKv_ && oriTopK_ != 0) { + isSparseOriKv_ = true; + } + if (hasCmpKv_ && cmpTopK_ != 0) { + isSparseCmpKv_ = true; + } + if (isBatchConsistency_) { + supportFd_ = true; + } + if (validSocVersion == ValidSocVersion::ASCEND910) { + if (isSparseOriKv_ && !isSparseCmpKv_) { + mBaseSize_ = groupSize_; + } else { + mBaseSize_ = + isSparseCmpKv_ ? groupSize_ : (256U / groupSize_) * groupSize_; + } + s2BaseSize_ = 512U; + } else if (validSocVersion == ValidSocVersion::ASCEND950 || + validSocVersion == ValidSocVersion::ASCEND960) { + if (groupSize_ > 64U) { + isSplitG_ = true; + aicCoreNum_ /= NUM_2; + } + mBaseSize_ = groupSize_; + s2BaseSize_ = 128U; + } else { + mBaseSize_ = groupSize_; + s2BaseSize_ = 128U; + } + return true; +} + +uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetS1Idx(uint32_t s1Size, + uint32_t s1GIdx) { + uint32_t s1GToken = s1GIdx * mBaseSize_; + uint32_t s1Idx = 0; + if (isS1G_) { + s1Idx = s1GToken / static_cast(groupSize_); + } else { + s1Idx = s1GToken % static_cast(s1Size); + } + return s1Idx; +} + +uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetBsStride( + uint32_t bIdx, + uint32_t s1Idx) { + uint32_t bsStride = 0; + if (layoutQ_ == "TND") { + if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { + const int32_t* s1Ptr = + static_cast(cuSeqlensQ_->GetData()); + bsStride = s1Ptr[bIdx] + s1Idx; + return bsStride; + } + } + bsStride = bIdx * static_cast(maxSeqlenQ_) + s1Idx; + return bsStride; +} + +uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetOriTopkLength( + uint32_t bsStride) { + // 尝试使用 oriTopkLength_ + if (oriTopK_ != 0 && + oriMaskMode_ == static_cast(SparseMode::DEFAULT_MASK) && + oriTopkLength_ != nullptr && oriTopkLength_->GetData() != nullptr) { + const int32_t* oriTopkPtr = + static_cast(oriTopkLength_->GetData()); + // 规划 FA/FD + // 任务时,将有效稀疏长度限制到索引宽度,与内核的计算范围保持一致。 + return std::min(static_cast(oriTopkPtr[bsStride]), + static_cast(oriTopK_)); + } + // 如果不是 DEFAULT_MASK,使用 oriTopK_ + return static_cast(oriTopK_); +} + +uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::ReadOriTopkLengthAtRow( + uint32_t bIdx, + uint32_t s1Idx) const { + if (!hasOriTopkLength_) { + return static_cast(oriTopK_); + } + const int32_t* topkLenPtr = + static_cast(oriTopkLength_->GetData()); + if (layoutQ_ == "TND") { + uint32_t tIdx = s1Idx; + if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { + const int32_t* cuPtr = + static_cast(cuSeqlensQ_->GetData()); + tIdx = static_cast(cuPtr[bIdx]) + s1Idx; + } else { + tIdx = bIdx * static_cast(maxSeqlenQ_) + s1Idx; + } + return static_cast( + topkLenPtr[tIdx * static_cast(numHeadsKv_)]); + } + return static_cast( + topkLenPtr[(static_cast(bIdx) * + static_cast(maxSeqlenQ_) + + s1Idx) * + static_cast(numHeadsKv_)]); +} + +uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetOriTopkLength( + uint32_t s1GIdx, + const BatchCache& batchCache) const { + if (!hasOriTopkLength_) { + return static_cast(oriTopK_); + } + int64_t s1GFirstToken = + static_cast(s1GIdx) * static_cast(mBaseSize_); + int64_t s1GLastToken = + std::min(s1GFirstToken + static_cast(mBaseSize_), + static_cast(batchCache.s1Size) * + static_cast(groupSize_)) - + 1; + int64_t s1First = s1GFirstToken / static_cast(groupSize_); + int64_t s1Last = s1GLastToken / static_cast(groupSize_); + uint32_t maxLen = 0U; + for (int64_t s1Idx = s1First; s1Idx <= s1Last; ++s1Idx) { + maxLen = std::max( + maxLen, + ReadOriTopkLengthAtRow(batchCache.bIdx, static_cast(s1Idx))); + } + return std::min(maxLen, static_cast(oriTopK_)); +} + +uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetCmpTopkLength( + uint32_t bsStride) { + // 尝试使用 cmpTopkLength_ + if (cmpTopK_ != 0 && + cmpMaskMode_ == static_cast(SparseMode::DEFAULT_MASK) && + cmpTopkLength_ != nullptr && cmpTopkLength_->GetData() != nullptr) { + const int32_t* cmpTopkPtr = + static_cast(cmpTopkLength_->GetData()); + // 规划 FA/FD + // 任务时,将有效稀疏长度限制到索引宽度,与内核的计算范围保持一致。 + return std::min(static_cast(cmpTopkPtr[bsStride]), + static_cast(cmpTopK_)); + } + // 如果不是 DEFAULT_MASK,使用 cmpTopK_ + return static_cast(cmpTopK_); +} + +uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetS1SeqSize( + uint32_t bIdx) { + // 1. 如果 sequsedQ_ 传了,直接使用 + if (sequsedQ_ != nullptr && sequsedQ_->GetData() != nullptr) { + const int32_t* seqUsedPtr = + static_cast(sequsedQ_->GetData()); + return static_cast(seqUsedPtr[bIdx]); + } + // 2. sequsedQ_ 没传,判断 Layout + if (layoutQ_ == "TND") { + // 如果是 TND,尝试使用 cuSeqlensQ_ + if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { + const int32_t* s1Ptr = + static_cast(cuSeqlensQ_->GetData()); + return static_cast(s1Ptr[bIdx + 1U] - s1Ptr[bIdx]); + } + } + // 3. 如果不是 TND,或者 cuSeqlensQ_ 为空,使用 maxSeqlenQ_ + return static_cast(maxSeqlenQ_); +} + +uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetOriS2SeqSize( + uint32_t bIdx) { + // 如果 sequsedOriKv_ 传了,直接使用 + if (sequsedOriKv_ != nullptr && sequsedOriKv_->GetData() != nullptr) { + const int32_t* seqUsedPtr = + static_cast(sequsedOriKv_->GetData()); + return static_cast(seqUsedPtr[bIdx]); + } + // sequsedOriKv_ 没传,判断 Layout + if (layoutKv_ == "TND") { + // 如果是 TND,尝试使用 cuSeqlensOriKv_ + if (cuSeqlensOriKv_ != nullptr && cuSeqlensOriKv_->GetData() != nullptr) { + const int32_t* s2Ptr = + static_cast(cuSeqlensOriKv_->GetData()); + return static_cast(s2Ptr[bIdx + 1U] - s2Ptr[bIdx]); + } + } + // 如果是PA场景,或 max_seqlen_ori_kv 没传入,且 ori_kv 为稀疏的,则尝试从 + // topk 中获取 + if ((layoutKv_ == "PA_BBND" || maxSeqlenOriKv_ == 0) && isSparseOriKv_) { + return UINT32_MAX; + } + // 使用 max_seqlen_ori_kv + return static_cast(maxSeqlenOriKv_); +} + +uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetCmpS2SeqSize( + uint32_t bIdx) { + // 如果 sequsedCmpKv_ 传了,直接使用 + if (sequsedCmpKv_ != nullptr && sequsedCmpKv_->GetData() != nullptr) { + const int32_t* seqUsedPtr = + static_cast(sequsedCmpKv_->GetData()); + return static_cast(seqUsedPtr[bIdx]); + } + // sequsedCmpKv_ 没传,判断 Layout + if (layoutKv_ == "TND") { + // 如果是 TND,尝试使用 cuSeqlensCmpKv_ + if (cuSeqlensCmpKv_ != nullptr && cuSeqlensCmpKv_->GetData() != nullptr) { + const int32_t* s2Ptr = + static_cast(cuSeqlensCmpKv_->GetData()); + return static_cast(s2Ptr[bIdx + 1U] - s2Ptr[bIdx]); + } + } + // 如果是PA场景,或 max_seqlen_cmp_kv 没传入,且 cmp_kv + // 为稀疏的,则尝试从topk中获取 + if ((layoutKv_ == "PA_BBND" || maxSeqlenCmpKv_ == 0) && isSparseCmpKv_) { + return UINT32_MAX; + } + // 使用 max_seqlen_cmp_kv + return static_cast(maxSeqlenCmpKv_); +} + +uint64_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetRevertS2Size( + uint32_t bIdx) { + uint32_t cmpS2Size = GetCmpS2SeqSize(bIdx); + if (cmpResidualKv_ != nullptr && cmpResidualKv_->GetData() != nullptr) { + const int32_t* residualPtr = + static_cast(cmpResidualKv_->GetData()); + return static_cast(cmpS2Size) * static_cast(cmpRatio_) + + residualPtr[bIdx]; + } else { + return static_cast(cmpS2Size) * static_cast(cmpRatio_); + } +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcSplitInfo( + SplitContext& splitContext) { + // 计算每个batch的切分,统计是否为空batch,记录最后有效batch(每个batch的每个N2切分是一样的) + SplitInfo& splitInfo = splitContext.splitInfo; + for (uint32_t bIdx = 0; bIdx < batchSize_; bIdx++) { + uint32_t s1Size = GetS1SeqSize(bIdx); + splitInfo.s1GBaseNum[bIdx] = + (static_cast(s1Size) * groupSize_ + (mBaseSize_ - 1U)) / + mBaseSize_; + splitInfo.s1GTailSize[bIdx] = + (static_cast(s1Size) * groupSize_) % mBaseSize_; + if (hasOriKv_) { + uint32_t curOriS2Size = GetOriS2SeqSize(bIdx); + splitInfo.oriS2BaseNum[bIdx] = + (static_cast(curOriS2Size) + s2BaseSize_ - 1U) / + s2BaseSize_; + } + if (hasCmpKv_) { + uint32_t curCmpS2Size = GetCmpS2SeqSize(bIdx); + splitInfo.cmpS2BaseNum[bIdx] = + (static_cast(curCmpS2Size) + s2BaseSize_ - 1U) / + s2BaseSize_; + } + if (splitInfo.s1GBaseNum[bIdx] != 0U && + (splitInfo.oriS2BaseNum[bIdx] != 0U || + splitInfo.cmpS2BaseNum[bIdx] != 0U)) { + splitInfo.isKvSeqAllZero = false; + } + } +} + +int64_t XllmKernelSparseFlashMlaMetadataCpuKernel::CalcOriPreTokenLeftUp( + uint32_t s1Size, + uint32_t s2Size) { + auto mode = static_cast(oriMaskMode_); + if (mode == SparseMode::BAND) { + return oriPreToken_ == INT64_MAX + ? INT64_MAX + : static_cast(s1Size) - static_cast(s2Size) + + oriPreToken_; + } + return oriPreToken_; +} + +int64_t XllmKernelSparseFlashMlaMetadataCpuKernel::CalcOriNextTokenLeftUp( + uint32_t s1Size, + uint32_t s2Size) { + auto mode = static_cast(oriMaskMode_); + switch (mode) { + case SparseMode::DEFAULT_MASK: + case SparseMode::ALL_MASK: + case SparseMode::LEFT_UP_CAUSAL: + return oriNextToken_; + case SparseMode::RIGHT_DOWN_CAUSAL: + return static_cast(s2Size) - static_cast(s1Size); + case SparseMode::BAND: + return oriNextToken_ == INT64_MAX + ? INT64_MAX + : static_cast(s2Size) - static_cast(s1Size) + + oriNextToken_; + default: + return oriNextToken_; + } +} + +int64_t XllmKernelSparseFlashMlaMetadataCpuKernel::CalcCmpPreTokenLeftUp( + uint32_t s1Size, + uint64_t s2Size) { + auto mode = static_cast(cmpMaskMode_); + if (mode == SparseMode::BAND) { + return cmpPreToken_ == INT64_MAX + ? INT64_MAX + : static_cast(s1Size) - static_cast(s2Size) + + cmpPreToken_; + } + return cmpPreToken_; +} + +int64_t XllmKernelSparseFlashMlaMetadataCpuKernel::CalcCmpNextTokenLeftUp( + uint32_t s1Size, + uint64_t s2Size) { + auto mode = static_cast(cmpMaskMode_); + switch (mode) { + case SparseMode::DEFAULT_MASK: + case SparseMode::ALL_MASK: + case SparseMode::LEFT_UP_CAUSAL: + return cmpNextToken_; + case SparseMode::RIGHT_DOWN_CAUSAL: + return static_cast(s2Size) - static_cast(s1Size); + case SparseMode::BAND: + return cmpNextToken_ == INT64_MAX + ? INT64_MAX + : static_cast(s2Size) - static_cast(s1Size) + + cmpNextToken_; + default: + return cmpNextToken_; + } +} + +int64_t XllmKernelSparseFlashMlaMetadataCpuKernel::OriCalcCost( + uint32_t basicM, + uint32_t basicS2) { + uint32_t oriAlignCoefM = 16U; + uint32_t oriAlignCoefS2 = 64U; + uint32_t oriAlignBasicM = (basicM + oriAlignCoefM - 1U) / oriAlignCoefM; + uint32_t oriAlignBasicS2 = (basicS2 + oriAlignCoefS2 - 1U) / oriAlignCoefS2; + return static_cast(COST_WEIGHT_M * oriAlignBasicM + + COST_WEIGHT_S2 * oriAlignBasicS2); +} + +int64_t XllmKernelSparseFlashMlaMetadataCpuKernel::CmpCalcCost( + uint32_t basicM, + uint32_t basicS2) { + uint32_t cmpAlignCoefM = 16U; + uint32_t cmpAlignCoefS2 = 64U; + uint32_t cmpAlignBasicM = (basicM + cmpAlignCoefM - 1U) / cmpAlignCoefM; + uint32_t cmpAlignBasicS2 = (basicS2 + cmpAlignCoefS2 - 1U) / cmpAlignCoefS2; + return static_cast(COST_WEIGHT_M * cmpAlignBasicM + + COST_WEIGHT_S2 * cmpAlignBasicS2); +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcCostTable( + uint32_t s1GTailSize, + uint32_t reductionBlockSize, + uint32_t oriS2TailSize, + uint32_t cmpS2TailSize) { + uint32_t normalS2Size = isBatchConsistency_ && reductionBlockSize > 0U + ? reductionBlockSize + : s2BaseSize_; + // ori 部分 cost + if (hasOriKv_) { + typeCost_[ORI_NORMAL_BLOCK][ORI_NORMAL_BLOCK] = + OriCalcCost(mBaseSize_, normalS2Size); + typeCost_[ORI_TAIL_BLOCK][ORI_NORMAL_BLOCK] = + (s1GTailSize == 0U) ? 0U : OriCalcCost(s1GTailSize, normalS2Size); + typeCost_[ORI_NORMAL_BLOCK][ORI_TAIL_BLOCK] = + (oriS2TailSize == 0U) ? 0U : OriCalcCost(mBaseSize_, oriS2TailSize); + typeCost_[ORI_TAIL_BLOCK][ORI_TAIL_BLOCK] = + (s1GTailSize == 0U || oriS2TailSize == 0U) + ? 0U + : OriCalcCost(s1GTailSize, oriS2TailSize); + } + // cmp 部分 cost + if (hasCmpKv_) { + typeCost_[CMP_NORMAL_BLOCK][CMP_NORMAL_BLOCK] = + CmpCalcCost(mBaseSize_, normalS2Size); + typeCost_[CMP_TAIL_BLOCK][CMP_NORMAL_BLOCK] = + (s1GTailSize == 0U) ? 0U : CmpCalcCost(s1GTailSize, normalS2Size); + typeCost_[CMP_NORMAL_BLOCK][CMP_TAIL_BLOCK] = + (cmpS2TailSize == 0U) ? 0U : CmpCalcCost(mBaseSize_, cmpS2TailSize); + typeCost_[CMP_TAIL_BLOCK][CMP_TAIL_BLOCK] = + (s1GTailSize == 0U || cmpS2TailSize == 0U) + ? 0U + : CmpCalcCost(s1GTailSize, cmpS2TailSize); + } +} + +Range XllmKernelSparseFlashMlaMetadataCpuKernel::CalcS2TokenRange( + uint32_t s1GIdx, + const BatchCache& batchCache, + bool isCmpKv) { + // actual seq == 0 + if (!isCmpKv) { + if (batchCache.s1Size == 0U || batchCache.oriS2Size == 0U) { + return std::make_pair(0, 0); + } + if (isSparseOriKv_ && !hasCmpKv_) { + uint32_t oriTopkSize = GetOriTopkLength(s1GIdx, batchCache); + if (oriTopkSize == 0U) { + return std::make_pair(0, 0); + } + return std::make_pair(0, static_cast(oriTopkSize) - 1); + } + } else { + if (batchCache.s1Size == 0U || batchCache.cmpRevertS2Size == 0U) { + return std::make_pair(0, 0); + } + } + + // no mask + uint32_t hasMask = 1; + int64_t s2Size = isCmpKv ? static_cast(batchCache.cmpRevertS2Size) + : static_cast(batchCache.oriS2Size); + hasMask = isCmpKv ? cmpAttentionMode_ : oriAttentionMode_; + if (!hasMask) { + return std::make_pair(0, s2Size - 1); + } + + // 1. calc index of s2FirstToken, s2LastToken by index of s1GFirstToken, + // s1GLastToken + int64_t s1GFirstToken = + static_cast(s1GIdx) * static_cast(mBaseSize_); + int64_t s1GLastToken = + std::min(s1GFirstToken + static_cast(mBaseSize_), + static_cast(batchCache.s1Size) * + static_cast(groupSize_)) - + 1; + + int64_t s1FirstToken = 0; + int64_t s1LastToken = 0; + if (isS1G_) { + s1FirstToken = s1GFirstToken / static_cast(groupSize_); + s1LastToken = s1GLastToken / static_cast(groupSize_); + } else { + if (s1GFirstToken / batchCache.s1Size == s1GLastToken / batchCache.s1Size) { + // start and end locate in one G + s1FirstToken = s1GFirstToken % static_cast(batchCache.s1Size); + s1LastToken = s1GLastToken % static_cast(batchCache.s1Size); + } else { + // start and end locate in tow or more G, but working same as crossing a + // complete block + s1FirstToken = 0; + s1LastToken = batchCache.s1Size; + } + } + + int64_t s2FirstToken = 0; + int64_t s2LastToken = 0; + if (!isCmpKv) { + s2FirstToken = s1FirstToken - batchCache.oriPreTokenLeftUp; + s2LastToken = batchCache.oriNextTokenLeftUp == INT64_MAX + ? INT64_MAX + : s1LastToken + batchCache.oriNextTokenLeftUp; + } else { + s2FirstToken = s1FirstToken - batchCache.cmpPreTokenLeftUp; + s2LastToken = batchCache.cmpNextTokenLeftUp == INT64_MAX + ? INT64_MAX + : s1LastToken + batchCache.cmpNextTokenLeftUp; + } + return std::make_pair(s2FirstToken, s2LastToken); +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcBatchCache( + uint32_t bIdx, + const SplitContext& splitContext, + BatchCache& batchCache) { + const SplitInfo& splitInfo = splitContext.splitInfo; + + batchCache.bIdx = bIdx; + batchCache.s1Size = GetS1SeqSize(bIdx); + if (hasOriKv_) { + batchCache.oriS2Size = GetOriS2SeqSize(bIdx); + batchCache.oriPreTokenLeftUp = + CalcOriPreTokenLeftUp(batchCache.s1Size, batchCache.oriS2Size); + batchCache.oriNextTokenLeftUp = + CalcOriNextTokenLeftUp(batchCache.s1Size, batchCache.oriS2Size); + } + if (hasCmpKv_) { + batchCache.cmpRevertS2Size = GetRevertS2Size(bIdx); + batchCache.cmpPreTokenLeftUp = + CalcCmpPreTokenLeftUp(batchCache.s1Size, batchCache.cmpRevertS2Size); + batchCache.cmpNextTokenLeftUp = + CalcCmpNextTokenLeftUp(batchCache.s1Size, batchCache.cmpRevertS2Size); + } +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcOriS1GCache( + S1GCache& s1GCache, + const SplitInfo& splitInfo) { + // 处理 ori 部分 block 信息 + if (s1GCache.oriS2Start >= s1GCache.oriS2End) { + // ori 范围无效, 则整个 s1g 行等效为空行 + s1GCache.oriS1GBlock = 0; + s1GCache.oriS1GCost = 0; + s1GCache.oriS1GLastBlockCost = 0; + s1GCache.oriS1GNormalBlockCost = 0; + } else { + // 计算 ori 方向 Block 数量及 Cost + s1GCache.oriS1GBlock = s1GCache.oriS2End - s1GCache.oriS2Start; + // 判断 ori S2 方向是否包含尾块 + uint32_t curOriTailS2Num = (s1GCache.oriS2TailSize != 0U) ? 1U : 0U; + uint32_t curOriNormalS2Num = s1GCache.oriS1GBlock - curOriTailS2Num; + if (s1GCache.s1GIdx == (splitInfo.s1GBaseNum[s1GCache.bIdx] - 1U) && + splitInfo.s1GTailSize[s1GCache.bIdx] != 0U) { + s1GCache.oriS1GCost = + typeCost_[ORI_TAIL_BLOCK][ORI_NORMAL_BLOCK] * curOriNormalS2Num + + typeCost_[ORI_TAIL_BLOCK][ORI_TAIL_BLOCK] * curOriTailS2Num; + s1GCache.oriS1GLastBlockCost = + curOriTailS2Num > 0U ? typeCost_[ORI_TAIL_BLOCK][ORI_TAIL_BLOCK] + : typeCost_[ORI_TAIL_BLOCK][ORI_NORMAL_BLOCK]; + s1GCache.oriS1GNormalBlockCost = + typeCost_[ORI_TAIL_BLOCK][ORI_NORMAL_BLOCK]; + } else { + s1GCache.oriS1GCost = + typeCost_[ORI_NORMAL_BLOCK][ORI_NORMAL_BLOCK] * curOriNormalS2Num + + typeCost_[ORI_NORMAL_BLOCK][ORI_TAIL_BLOCK] * curOriTailS2Num; + s1GCache.oriS1GLastBlockCost = + curOriTailS2Num > 0U ? typeCost_[ORI_NORMAL_BLOCK][ORI_TAIL_BLOCK] + : typeCost_[ORI_NORMAL_BLOCK][ORI_NORMAL_BLOCK]; + s1GCache.oriS1GNormalBlockCost = + typeCost_[ORI_NORMAL_BLOCK][ORI_NORMAL_BLOCK]; + } + } +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcCmpS1GCache( + S1GCache& s1GCache, + const SplitInfo& splitInfo) { + // 处理cmp部分block信息 + if (s1GCache.cmpS2Start >= s1GCache.cmpS2End) { + // Cmp范围无效, Cost保持为 0 + s1GCache.cmpS1GBlock = 0; + s1GCache.cmpS1GCost = 0; + s1GCache.cmpS1GLastBlockCost = 0; + s1GCache.cmpS1GNormalBlockCost = 0; + } else { + // 计算 cmp 方向 Block 数量及 Cost + s1GCache.cmpS1GBlock = s1GCache.cmpS2End - s1GCache.cmpS2Start; + // 判断 Cmp S2 方向是否包含尾块 + uint32_t curCmpTailS2Num = (s1GCache.cmpS2TailSize != 0U) + ? 1U + : 0U; // Updated check using local var + uint32_t curCmpNormalS2Num = s1GCache.cmpS1GBlock - curCmpTailS2Num; + if (s1GCache.s1GIdx == (splitInfo.s1GBaseNum[s1GCache.bIdx] - 1U) && + splitInfo.s1GTailSize[s1GCache.bIdx] != 0U) { + s1GCache.cmpS1GCost = + typeCost_[CMP_TAIL_BLOCK][CMP_NORMAL_BLOCK] * curCmpNormalS2Num + + typeCost_[CMP_TAIL_BLOCK][CMP_TAIL_BLOCK] * curCmpTailS2Num; + s1GCache.cmpS1GLastBlockCost = + curCmpTailS2Num > 0U ? typeCost_[CMP_TAIL_BLOCK][CMP_TAIL_BLOCK] + : typeCost_[CMP_TAIL_BLOCK][CMP_NORMAL_BLOCK]; + s1GCache.cmpS1GNormalBlockCost = + typeCost_[CMP_TAIL_BLOCK][CMP_NORMAL_BLOCK]; + } else { + s1GCache.cmpS1GCost = + typeCost_[CMP_NORMAL_BLOCK][CMP_NORMAL_BLOCK] * curCmpNormalS2Num + + typeCost_[CMP_NORMAL_BLOCK][CMP_TAIL_BLOCK] * curCmpTailS2Num; + s1GCache.cmpS1GLastBlockCost = + curCmpTailS2Num > 0U ? typeCost_[CMP_NORMAL_BLOCK][CMP_TAIL_BLOCK] + : typeCost_[CMP_NORMAL_BLOCK][CMP_NORMAL_BLOCK]; + s1GCache.cmpS1GNormalBlockCost = + typeCost_[CMP_NORMAL_BLOCK][CMP_NORMAL_BLOCK]; + } + } +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcOriBlockRange( + const Range& oriS2TokenRange, + const BatchCache& batchCache, + S1GCache& s1GCache) { + int64_t oriS2FirstToken = oriS2TokenRange.first; + int64_t oriS2LastToken = oriS2TokenRange.second; + s1GCache.oriS2Start = 0; + // ori 部分 s2 起止和 tailSize + if (oriS2FirstToken >= static_cast(batchCache.oriS2Size) || + oriS2LastToken < 0 || oriS2LastToken < oriS2FirstToken) { + s1GCache.oriS2End = 0; + s1GCache.oriS2TailSize = 0; + } else { + oriS2FirstToken = Clip(oriS2FirstToken, + static_cast(0), + static_cast(batchCache.oriS2Size - 1U)); + oriS2LastToken = Clip(oriS2LastToken, + static_cast(0), + static_cast(batchCache.oriS2Size - 1U)); + // oriS2LastToken 与 topk 取最小 + uint32_t s1Idx = GetS1Idx(batchCache.s1Size, s1GCache.s1GIdx); + uint32_t bsStride = GetBsStride(s1GCache.bIdx, s1Idx); + uint32_t oriTopkSize = + isSparseOriKv_ + ? GetOriTopkLength(s1GCache.s1GIdx, batchCache) + : GetOriTopkLength(GetBsStride( + s1GCache.bIdx, GetS1Idx(batchCache.s1Size, s1GCache.s1GIdx))); + s1GCache.actOriS2Size = + isSparseOriKv_ + ? std::min( + static_cast(oriS2LastToken - oriS2FirstToken + 1), + oriTopkSize) + : static_cast(oriS2LastToken - oriS2FirstToken + 1); + s1GCache.oriS2End = s1GCache.actOriS2Size == 0 + ? 0 + : (s1GCache.actOriS2Size - 1U) / s2BaseSize_ + 1U; + s1GCache.oriS2TailSize = s1GCache.actOriS2Size % s2BaseSize_; + } +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcCmpBlockRange( + const Range& cmpRevertS2TokenRange, + const BatchCache& batchCache, + S1GCache& s1GCache) { + int64_t cmpRevertS2FirstToken = cmpRevertS2TokenRange.first; + int64_t cmpRevertS2LastToken = cmpRevertS2TokenRange.second; + s1GCache.cmpS2Start = s1GCache.oriS2End; + // cmp 部分 s2 起止和 tailSize + if (cmpRevertS2FirstToken >= + static_cast(batchCache.cmpRevertS2Size) || + cmpRevertS2LastToken < 0 || + cmpRevertS2LastToken < cmpRevertS2FirstToken) { + s1GCache.cmpS2End = s1GCache.cmpS2Start; + s1GCache.cmpS2TailSize = 0; + } else { + cmpRevertS2FirstToken = + Clip(cmpRevertS2FirstToken, + static_cast(0), + static_cast(batchCache.cmpRevertS2Size - 1U)); + cmpRevertS2LastToken = + Clip(cmpRevertS2LastToken, + static_cast(0), + static_cast(batchCache.cmpRevertS2Size - 1U)); + // 如果压缩后长度为0,则直接返回 + if ((cmpRevertS2LastToken + 1) / cmpRatio_ == 0) { + s1GCache.cmpS2End = s1GCache.cmpS2Start; + s1GCache.cmpS2TailSize = 0; + return; + } + // 获取压缩后的 token 索引 + uint64_t cmpS2FirstToken = + (cmpRevertS2FirstToken + 1) / cmpRatio_ == 0 + ? 0 + : (cmpRevertS2FirstToken + 1) / cmpRatio_ - 1U; + uint64_t cmpS2LastToken = (cmpRevertS2LastToken + 1) / cmpRatio_ - 1U; + // cmpS2LastToken 与 topk 取最小 + uint32_t s1Idx = GetS1Idx(batchCache.s1Size, s1GCache.s1GIdx); + uint32_t bsStride = GetBsStride(s1GCache.bIdx, s1Idx); + uint32_t cmpTopkSize = GetCmpTopkLength(bsStride); + s1GCache.actCmpS2Size = + isSparseCmpKv_ + ? std::min( + static_cast(cmpS2LastToken - cmpS2FirstToken + 1), + cmpTopkSize) + : static_cast(cmpS2LastToken - cmpS2FirstToken + 1); + s1GCache.cmpS2End = s1GCache.actCmpS2Size == 0 + ? s1GCache.cmpS2Start + : s1GCache.cmpS2Start + + (s1GCache.actCmpS2Size - 1U) / s2BaseSize_ + + 1U; + s1GCache.cmpS2TailSize = s1GCache.actCmpS2Size % s2BaseSize_; + } +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::GatherOriAndCmpCache( + S1GCache& s1GCache) { + s1GCache.s2Start = 0; + if (s1GCache.cmpS1GBlock > 0) { + s1GCache.s1GLastBlockCost = s1GCache.cmpS1GLastBlockCost; + s1GCache.s2End = s1GCache.cmpS2End; + } else { + s1GCache.s1GLastBlockCost = s1GCache.oriS1GLastBlockCost; + s1GCache.s2End = s1GCache.oriS2End; + } + s1GCache.s1GBlock = s1GCache.oriS1GBlock + s1GCache.cmpS1GBlock; + s1GCache.s1GCost = s1GCache.oriS1GCost + s1GCache.cmpS1GCost; +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcS1GCache( + uint32_t s1GIdx, + const SplitContext& splitContext, + const BatchCache& batchCache, + S1GCache& s1GCache) { + const SplitInfo& splitInfo = splitContext.splitInfo; + // 如果s1G是空行,则直接返回 + if (splitInfo.s1GBaseNum[batchCache.bIdx] == 0) { + s1GCache.s1GCost = 0; + s1GCache.s1GLastBlockCost = 0; + s1GCache.oriS1GNormalBlockCost = 0; + s1GCache.oriS1GLastBlockCost = 0; + s1GCache.cmpS1GNormalBlockCost = 0; + s1GCache.cmpS1GLastBlockCost = 0; + s1GCache.s1GBlock = 0; + s1GCache.s2Loop = 0; + s1GCache.s2Start = 0; + s1GCache.cmpS2Start = 0; + s1GCache.s2End = 0; + return; + } + s1GCache.bIdx = batchCache.bIdx; + s1GCache.s1GIdx = s1GIdx; + s1GCache.actOriS2Size = 0U; + s1GCache.actCmpS2Size = 0U; + s1GCache.reductionBlockSize = 0U; + // 计算 ori_kv 有效负载起止 + if (hasOriKv_) { + // 计算 ori_kv 的 s2Token 起止 + auto oriS2TokenRange = CalcS2TokenRange(s1GIdx, batchCache, ORI_KV); + // 计算 ori_kv 的 s2Block 起止 + CalcOriBlockRange(oriS2TokenRange, batchCache, s1GCache); + } else { + // ori_kv s2Token 起止初始化为0 + s1GCache.oriS2Start = 0; + s1GCache.oriS2End = s1GCache.oriS2Start; + s1GCache.oriS2TailSize = 0; + } + // 计算 cmp_kv 有效负载起止 + if (hasCmpKv_) { + // 计算 cmp_kv 的 s2Token 起止 + auto cmpRevertS2TokenRange = CalcS2TokenRange(s1GIdx, batchCache, CMP_KV); + // 计算 cmp_kv 的 s2Block 起止 + CalcCmpBlockRange(cmpRevertS2TokenRange, batchCache, s1GCache); + } else { + // cmp_kv s2Token 起止初始化为0 + s1GCache.cmpS2Start = s1GCache.oriS2End; + s1GCache.cmpS2End = s1GCache.cmpS2Start; + s1GCache.cmpS2TailSize = 0; + } + if (isBatchConsistency_) { + // 规约块大小只依赖当前行,ORI、CMP 分别划分规约块。 + uint64_t actTotalS2Size = + static_cast(s1GCache.actOriS2Size) + s1GCache.actCmpS2Size; + if (actTotalS2Size > 0U) { + uint64_t rawReductionBlockSize = + (actTotalS2Size + BATCH_CONSISTENCY_MAX_REDUCTION_PARTS - 1U) / + BATCH_CONSISTENCY_MAX_REDUCTION_PARTS; + s1GCache.reductionBlockSize = + static_cast((rawReductionBlockSize + s2BaseSize_ - 1U) / + s2BaseSize_ * s2BaseSize_); + s1GCache.reductionBlockSize = + std::max(s1GCache.reductionBlockSize, s2BaseSize_); + s1GCache.oriS2End = + s1GCache.actOriS2Size == 0U + ? 0U + : (s1GCache.actOriS2Size - 1U) / s1GCache.reductionBlockSize + 1U; + s1GCache.oriS2TailSize = + s1GCache.actOriS2Size % s1GCache.reductionBlockSize; + s1GCache.cmpS2Start = s1GCache.oriS2End; + s1GCache.cmpS2End = + s1GCache.actCmpS2Size == 0U + ? s1GCache.cmpS2Start + : s1GCache.cmpS2Start + + (s1GCache.actCmpS2Size - 1U) / s1GCache.reductionBlockSize + + 1U; + s1GCache.cmpS2TailSize = + s1GCache.actCmpS2Size % s1GCache.reductionBlockSize; + } + } + // 计算基本块负载 + CalcCostTable(splitInfo.s1GTailSize[s1GCache.bIdx], + s1GCache.reductionBlockSize, + s1GCache.oriS2TailSize, + s1GCache.cmpS2TailSize); + // 计算 ori 和 cmp 部分的 cost 和 block 信息 + CalcOriS1GCache(s1GCache, splitInfo); + CalcCmpS1GCache(s1GCache, splitInfo); + // 汇总 ori 和 cmp 部分的 cost 和 block 信息 + GatherOriAndCmpCache(s1GCache); + s1GCache.s2Loop = static_cast( + (static_cast(s1GCache.actOriS2Size) + s2BaseSize_ - 1U) / + s2BaseSize_ + + (static_cast(s1GCache.actCmpS2Size) + s2BaseSize_ - 1U) / + s2BaseSize_); +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcBatchCost( + uint32_t bIdx, + const SplitContext& splitContext, + CostInfo& costInfo) { + const SplitInfo& splitInfo = splitContext.splitInfo; + + costInfo.bN2CostOfEachBatch[bIdx] = 0; + costInfo.bN2BlockOfEachBatch[bIdx] = 0U; + costInfo.bN2S2LoopOfEachBatch[bIdx] = 0U; + costInfo.bN2LastBlockCostOfEachBatch[bIdx] = 0U; + + if (GetS1SeqSize(bIdx) == 0U) { + return; + } + if (!hasOriKv_ && !hasCmpKv_) { + return; + } else if (!hasOriKv_) { + if (GetCmpS2SeqSize(bIdx) == 0U) { + return; + } + } else if (!hasCmpKv_) { + if (GetOriS2SeqSize(bIdx) == 0U) { + return; + } + } else { + if ((GetOriS2SeqSize(bIdx) == 0U) && GetCmpS2SeqSize(bIdx) == 0U) { + return; + } + } + + BatchCache bCache; + S1GCache s1GCache; + CalcBatchCache(bIdx, splitContext, bCache); + for (uint32_t s1GIdx = 0; s1GIdx < splitInfo.s1GBaseNum[bIdx]; s1GIdx++) { + CalcS1GCache(s1GIdx, splitContext, bCache, s1GCache); + costInfo.bN2CostOfEachBatch[bIdx] += s1GCache.s1GCost; + costInfo.bN2BlockOfEachBatch[bIdx] += s1GCache.s1GBlock; + costInfo.bN2S2LoopOfEachBatch[bIdx] += s1GCache.s2Loop; + // 更新最大S1G行开销 + if (s1GCache.s1GCost > costInfo.maxS1GCost) { + costInfo.maxS1GCost = s1GCache.s1GCost; + } + if (s1GCache.s1GBlock > 0) { + costInfo.bN2LastBlockCostOfEachBatch[bIdx] = s1GCache.s1GLastBlockCost; + } + } +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcCostInfo( + SplitContext& splitContext) { + const SplitInfo& splitInfo = splitContext.splitInfo; + CostInfo& costInfo = splitContext.costInfo; + + if (splitInfo.isKvSeqAllZero) { + costInfo.totalCost = 0; + costInfo.totalBlockNum = 0U; + return; + } + + // 计算 batch + // 的负载并记录,用于按batch分配,需要按行计算起止点,统计块数、负载 + for (uint32_t bIdx = 0; bIdx < batchSize_; bIdx++) { + CalcBatchCost(bIdx, splitContext, costInfo); + costInfo.totalCost += costInfo.bN2CostOfEachBatch[bIdx] * numHeadsKv_; + costInfo.totalBlockNum += costInfo.bN2BlockOfEachBatch[bIdx] * numHeadsKv_; + } +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::UpdateCursor( + const SplitContext& splitContext, + AssignContext& assignContext) { + const SplitInfo& splitInfo = splitContext.splitInfo; + const CostInfo& costInfo = splitContext.costInfo; + + bool UpdateS1G = false; + bool UpdateBatch = false; + + // Update S2 + if (assignContext.curS2Idx >= + assignContext.s1GCache.s2End) { // 边界assignInfo.s2End是取不到的开区间 + assignContext.curS2Idx = 0U; + assignContext.curS1GIdx++; + UpdateS1G = true; + } + + // Update S1G + if (assignContext.curS1GIdx >= splitInfo.s1GBaseNum[assignContext.curBIdx]) { + assignContext.curS1GIdx = 0U; + assignContext.curBN2Idx++; + } + + // Update Batch + if (assignContext.curBN2Idx == + batchSize_ * + numHeadsKv_) { // 所有负载全部分配完,设置最后一个核的右开区间,返回 + assignContext.curS1GIdx = 0U; + assignContext.curS2Idx = 0U; + assignContext.isFinished = true; + return; + } + + if (assignContext.curBN2Idx / numHeadsKv_ != assignContext.curBIdx) { + assignContext.curBIdx = assignContext.curBN2Idx / numHeadsKv_; + assignContext.curS1GIdx = 0U; + UpdateBatch = true; + UpdateS1G = true; + } + + // Update Cache + if (UpdateBatch) { + CalcBatchCache( + assignContext.curBIdx, splitContext, assignContext.batchCache); + assignContext.bN2Cost = costInfo.bN2CostOfEachBatch[assignContext.curBIdx]; + assignContext.bN2Block = + costInfo.bN2BlockOfEachBatch[assignContext.curBIdx]; + assignContext.bN2S2Loop = + costInfo.bN2S2LoopOfEachBatch[assignContext.curBIdx]; + } + if (UpdateS1G) { + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + assignContext.curS2Idx = + supportFd_ ? assignContext.s1GCache.oriS2Start : 0U; + } +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::AssignByBatch( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + const CostInfo& costInfo = splitContext.costInfo; + const SplitInfo& splitInfo = splitContext.splitInfo; + while (assignContext.bN2Cost == 0 || + IsWithinTolerance( + assignContext.coreCache.costLimit, + costInfo.bN2LastBlockCostOfEachBatch[assignContext.curBIdx] / + FA_TOLERANCE_RATIO, + assignContext.coreCache.cost + assignContext.bN2Cost)) { + assignContext.coreCache.cost += assignContext.bN2Cost; + assignContext.coreCache.block += assignContext.bN2Block; + assignContext.coreCache.s2Loop += assignContext.bN2S2Loop; + assignContext.curBN2Idx++; + // to the end + if (assignContext.curBN2Idx == batchSize_ * numHeadsKv_) { + assignContext.curS1GIdx = 0U; + assignContext.curS2Idx = 0U; + assignContext.isFinished = true; + return; + } + + // next batch + if (assignContext.curBN2Idx / numHeadsKv_ != assignContext.curBIdx) { + assignContext.curBIdx = assignContext.curBN2Idx / numHeadsKv_; + CalcBatchCache( + assignContext.curBIdx, splitContext, assignContext.batchCache); + } + + assignContext.bN2Cost = costInfo.bN2CostOfEachBatch[assignContext.curBIdx]; + assignContext.bN2Block = + costInfo.bN2BlockOfEachBatch[assignContext.curBIdx]; + assignContext.bN2S2Loop = + costInfo.bN2S2LoopOfEachBatch[assignContext.curBIdx]; + assignContext.curS1GIdx = 0U; + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + } +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::AssignByRow( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + + while (IsWithinTolerance( + assignContext.coreCache.costLimit, + assignContext.s1GCache.s1GLastBlockCost / FA_TOLERANCE_RATIO, + assignContext.coreCache.cost + assignContext.s1GCache.s1GCost)) { + assignContext.coreCache.cost += assignContext.s1GCache.s1GCost; + assignContext.coreCache.block += assignContext.s1GCache.s1GBlock; + assignContext.coreCache.s2Loop += assignContext.s1GCache.s2Loop; + // 当前batch被分配一行出去,更新剩余负载 + assignContext.bN2Cost = + assignContext.bN2Cost > assignContext.s1GCache.s1GCost + ? assignContext.bN2Cost - assignContext.s1GCache.s1GCost + : 0; + assignContext.bN2Block = + assignContext.bN2Block > assignContext.s1GCache.s1GBlock + ? assignContext.bN2Block - assignContext.s1GCache.s1GBlock + : 0U; + assignContext.bN2S2Loop = + assignContext.bN2S2Loop > assignContext.s1GCache.s2Loop + ? assignContext.bN2S2Loop - assignContext.s1GCache.s2Loop + : 0U; + // 计算新一行的信息 + do { + assignContext.curS1GIdx++; + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + } while (assignContext.s1GCache.s1GBlock == 0); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + } +} + +int64_t XllmKernelSparseFlashMlaMetadataCpuKernel::CalcCurBlockCost( + const AssignContext& assignContext) { + int64_t curCost = 0; + if (assignContext.curS2Idx < assignContext.s1GCache.cmpS2Start) { + curCost = assignContext.s1GCache.oriS1GNormalBlockCost; + if (assignContext.curS2Idx == (assignContext.s1GCache.cmpS2Start - 1U)) { + curCost = assignContext.s1GCache.oriS1GLastBlockCost; + } + } else { + curCost = assignContext.s1GCache.cmpS1GNormalBlockCost; + if (assignContext.curS2Idx == (assignContext.s1GCache.s2End - 1U)) { + curCost = assignContext.s1GCache.cmpS1GLastBlockCost; + } + } + return curCost; +} + +uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::CalcCurBlockS2Loop( + const AssignContext& assignContext) { + if (!isBatchConsistency_) { + return 1U; + } + const S1GCache& s1GCache = assignContext.s1GCache; + uint32_t blockSize = s1GCache.reductionBlockSize; + if (assignContext.curS2Idx < s1GCache.cmpS2Start) { + if (assignContext.curS2Idx + 1U == s1GCache.cmpS2Start && + s1GCache.oriS2TailSize != 0) { + blockSize = static_cast(s1GCache.oriS2TailSize); + } + } else if (assignContext.curS2Idx + 1U == s1GCache.s2End && + s1GCache.cmpS2TailSize != 0) { + blockSize = static_cast(s1GCache.cmpS2TailSize); + } + return (blockSize + s2BaseSize_ - 1U) / s2BaseSize_; +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::AssignByBlock( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished || !supportFd_) { + return; + } + + int64_t curCost = CalcCurBlockCost(assignContext); + uint32_t curS2Loop = CalcCurBlockS2Loop(assignContext); + + // (costLimit - curCostOnCore) * FA_TOLERANCE_RATIO > curCost;至少分配1块 + while (IsWithinTolerance(assignContext.coreCache.costLimit, + curCost / FA_TOLERANCE_RATIO, + assignContext.coreCache.cost + curCost)) { + assignContext.coreCache.cost += curCost; + assignContext.coreCache.block++; + assignContext.coreCache.s2Loop += curS2Loop; + assignContext.curS2Idx++; + // 当前batch被分配一块出去,更新剩余负载 + assignContext.bN2Cost = assignContext.bN2Cost - curCost; + // 当前行被分配一块出去,更新剩余负载 + assignContext.s1GCache.s1GCost = assignContext.s1GCache.s1GCost - curCost; + assignContext.bN2Block--; + assignContext.s1GCache.s1GBlock--; + assignContext.bN2S2Loop = assignContext.bN2S2Loop > curS2Loop + ? assignContext.bN2S2Loop - curS2Loop + : 0U; + assignContext.s1GCache.s2Loop = + assignContext.s1GCache.s2Loop > curS2Loop + ? assignContext.s1GCache.s2Loop - curS2Loop + : 0U; + curCost = CalcCurBlockCost(assignContext); + curS2Loop = CalcCurBlockS2Loop(assignContext); + } +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::ForceAssign( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + + int64_t curCost = CalcCurBlockCost(assignContext); + uint32_t curS2Loop = CalcCurBlockS2Loop(assignContext); + + assignContext.coreCache.cost += curCost; + assignContext.coreCache.block++; + assignContext.coreCache.s2Loop += curS2Loop; + assignContext.curS2Idx++; + // 当前batch被分配一块出去,更新剩余负载 + assignContext.bN2Cost = assignContext.bN2Cost - curCost; + assignContext.bN2Block--; + assignContext.bN2S2Loop = assignContext.bN2S2Loop > curS2Loop + ? assignContext.bN2S2Loop - curS2Loop + : 0U; + // 当前行被分配一块出去,更新剩余负载 + assignContext.s1GCache.s1GCost = assignContext.s1GCache.s1GCost - curCost; + assignContext.s1GCache.s1GBlock--; + assignContext.s1GCache.s2Loop = + assignContext.s1GCache.s2Loop > curS2Loop + ? assignContext.s1GCache.s2Loop - curS2Loop + : 0U; + UpdateCursor(splitContext, assignContext); +} + +bool XllmKernelSparseFlashMlaMetadataCpuKernel::IsNeedRecordFDInfo( + const AssignContext& assignContext, + const SplitResult& splitRes) { + // 切分点大概率不会刚好在行尾,因此滞后处理归约信息的统计,到下一个切分点再判断是否需要归约 + // 核0无需处理 + if (assignContext.curCoreIdx == 0U) { + return false; + } + // 无跨核行,无需处理 + if (assignContext.curKvSplitPart <= 1U) { + return false; + } + // 需要归约的行还未处理完 + if (assignContext.curBN2Idx == + splitRes.bN2End[assignContext.curCoreIdx - 1U] && + assignContext.curS1GIdx == + splitRes.gS1End[assignContext.curCoreIdx - 1U]) { + return false; + } + return true; +} + +bool XllmKernelSparseFlashMlaMetadataCpuKernel::IsFirstReductionBlock( + const AssignContext& assignContext, + const SplitResult& splitRes) { + if (assignContext.curCoreIdx == 0U || + splitRes.s2End[assignContext.curCoreIdx - 1U] == 0U) { + return true; + } + return assignContext.curBN2Idx != + splitRes.bN2End[assignContext.curCoreIdx - 1U] || + assignContext.curS1GIdx != + splitRes.gS1End[assignContext.curCoreIdx - 1U]; +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::RecordFDInfo( + const SplitContext& splitContext, + const AssignContext& assignContext, + SplitResult& result) { + const SplitInfo& splitInfo = splitContext.splitInfo; + // 需要规约的行是上一个核的切分点所在位置 + uint32_t splitBIdx = + result.bN2End[assignContext.curCoreIdx - 1U] / numHeadsKv_; + uint32_t splitS1GIdx = result.gS1End[assignContext.curCoreIdx - 1U]; + uint32_t s1Size = GetS1SeqSize(splitBIdx); + + // 计算归约数据的FD均衡划分信息 + uint32_t curFdS1gSize = + (splitS1GIdx == splitInfo.s1GBaseNum[splitBIdx] - 1U) + ? (static_cast(s1Size) * groupSize_ - + static_cast(splitS1GIdx) * mBaseSize_) + : mBaseSize_; + // 记录 + result.maxS2SplitNum = + std::max(result.maxS2SplitNum, assignContext.curKvSplitPart); + // 若存在头归约,则切分点一定为上一个核结束的位置 + result.fdRes.fdBN2Idx[result.numOfFdHead] = + result.bN2End[assignContext.curCoreIdx - 1U]; + result.fdRes.fdMIdx[result.numOfFdHead] = + result.gS1End[assignContext.curCoreIdx - 1U]; + result.fdRes.fdWorkspaceIdx[result.numOfFdHead] = assignContext.preFdDataNum; + result.fdRes.fdS2SplitNum[result.numOfFdHead] = assignContext.curKvSplitPart; + result.fdRes.fdMSize[result.numOfFdHead] = curFdS1gSize; + result.numOfFdHead++; +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::AssignBlocksToCore( + const SplitContext& splitContext, + AssignContext& assignContext, + SplitResult& result) { + const CostInfo& costInfo = splitContext.costInfo; + result.firstFdDataWorkspaceIdx[assignContext.curCoreIdx] = + assignContext.preFdDataNum + assignContext.curKvSplitPart - 1U; + int64_t avgCost = + assignContext.unassignedCost / (aicCoreNum_ - assignContext.curCoreIdx); + assignContext.coreCache = {}; + if (!supportFd_) { + assignContext.coreCache.costLimit = std::max(avgCost, costInfo.maxS1GCost); + } else { + assignContext.coreCache.costLimit = avgCost; + } + // 1、按整batch分配 + AssignByBatch(splitContext, assignContext); + // 2、按行分配 + AssignByRow(splitContext, assignContext); + // 3、按块分配 + AssignByBlock(splitContext, assignContext); + // 4、强制分配 + if (assignContext.coreCache.block == 0 && supportFd_) { + ForceAssign(splitContext, assignContext); + } + result.bN2End[assignContext.curCoreIdx] = assignContext.curBN2Idx; + result.gS1End[assignContext.curCoreIdx] = assignContext.curS1GIdx; + result.s2End[assignContext.curCoreIdx] = assignContext.curS2Idx; + result.maxCost = std::max(result.maxCost, assignContext.coreCache.cost); + assignContext.unassignedCost -= assignContext.coreCache.cost; + result.maxS2LoopNum = + std::max(assignContext.coreCache.s2Loop, result.maxS2LoopNum); + // 对之前的归约信息进行记录并清理 + if (IsNeedRecordFDInfo(assignContext, result)) { + if (isBatchConsistency_ && remainedBlockNum_ > 0U) { + // curKvSplitPart already reserves one slot for the core that finishes + // this row. + assignContext.curKvSplitPart += remainedBlockNum_ - 1U; + } + RecordFDInfo(splitContext, assignContext, result); + assignContext.preFdDataNum += assignContext.curKvSplitPart; + assignContext.curKvSplitPart = 1U; + remainedBlockNum_ = 0U; + } + // 更新S2切分信息 + if (assignContext.curS2Idx > assignContext.s1GCache.s2Start && + assignContext.curS2Idx <= assignContext.s1GCache.s2End) { + if (isBatchConsistency_) { + if (IsFirstReductionBlock(assignContext, result)) { + assignContext.curKvSplitPart++; + } else { + assignContext.curKvSplitPart += + result.s2End[assignContext.curCoreIdx] - + result.s2End[assignContext.curCoreIdx - 1U]; + } + remainedBlockNum_ = assignContext.s1GCache.s1GBlock; + } else { + assignContext.curKvSplitPart++; + } + } +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcSplitPlan( + int64_t costLimit, + const SplitContext& splitContext, + SplitResult& result) { + const CostInfo& costInfo = splitContext.costInfo; + const SplitInfo& splitInfo = splitContext.splitInfo; + if (aicCoreNum_ == 0U) { + return; + } + result.maxCost = 0U; + result.usedCoreNum = 0U; + + AssignContext assignContext{}; + assignContext.curBIdx = 0U; + assignContext.curS1GIdx = 0U; + assignContext.unassignedCost = costInfo.totalCost; + assignContext.bN2Cost = costInfo.bN2CostOfEachBatch[assignContext.curBIdx]; + assignContext.bN2Block = costInfo.bN2BlockOfEachBatch[assignContext.curBIdx]; + assignContext.bN2S2Loop = + costInfo.bN2S2LoopOfEachBatch[assignContext.curBIdx]; + CalcBatchCache(assignContext.curBIdx, splitContext, assignContext.batchCache); + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + // 负载分配 + for (uint32_t i = 0; i < aicCoreNum_; ++i) { + if (result.maxCost > costLimit) { + return; + } + if (assignContext.isFinished || assignContext.unassignedCost <= 0) { + break; + } + assignContext.curCoreIdx = i; + AssignBlocksToCore(splitContext, assignContext, result); + } + result.usedCoreNum = assignContext.curCoreIdx + 1; +} + +void XllmKernelSparseFlashMlaMetadataCpuKernel::SplitFD(SplitResult& splitRes) { + // 计算FD的总数据量 + uint64_t totalFDLoad = 0; + for (uint32_t i = 0; i < splitRes.numOfFdHead; i++) { + totalFDLoad += splitRes.fdRes.fdS2SplitNum[i] * splitRes.fdRes.fdMSize[i]; + } + // 计算当前最大冗余vec核数 + uint32_t emptyVectorNum = aivCoreNum_ - splitRes.numOfFdHead; + // 计算每个核处理的load + uint64_t averageLoad = (totalFDLoad + aivCoreNum_ - 1U) / + aivCoreNum_; // 向上取整,避免核负载为0 + uint32_t curCoreIndex = 0; + for (uint32_t i = 0; i < splitRes.numOfFdHead; i++) { + // 冗余vec核数为0,此时规约任务无法进行更小的切分,只能1个vec核计算1个规约任务 + if (emptyVectorNum == 0U) { + splitRes.fdRes.fdIdx[curCoreIndex] = i; + splitRes.fdRes.fdMStart[curCoreIndex] = 0U; + splitRes.fdRes.fdMNum[curCoreIndex] = splitRes.fdRes.fdMSize[i]; + curCoreIndex++; + continue; + } + // 计算当前归约任务所用核数,向下取整,避免使用核数超出总核数 + uint32_t curFDVectorNum = splitRes.fdRes.fdS2SplitNum[i] * + splitRes.fdRes.fdMSize[i] / averageLoad; + curFDVectorNum = std::max(1U, curFDVectorNum); + // 计算当前归约任务每个核的行数,向上取整,避免行数为0 + uint32_t curAveMSize = + (splitRes.fdRes.fdMSize[i] + curFDVectorNum - 1U) / curFDVectorNum; + curFDVectorNum = + (splitRes.fdRes.fdMSize[i] + curAveMSize - 1U) / curAveMSize; + // 需要使用的vec核数与当前剩余可用vec核数取最小 + curFDVectorNum = + std::min(curFDVectorNum, emptyVectorNum + 1U); // 1: Fd任务自身带一个核 + // FD负载分配 + for (uint32_t vid = 0; vid < curFDVectorNum; vid++) { + splitRes.fdRes.fdIdx[curCoreIndex] = i; + splitRes.fdRes.fdMStart[curCoreIndex] = vid * curAveMSize; + splitRes.fdRes.fdMNum[curCoreIndex] = + (vid < curFDVectorNum - 1) + ? curAveMSize + : (splitRes.fdRes.fdMSize[i] - vid * curAveMSize); + curCoreIndex++; + } + // 更新冗余vec核数 + emptyVectorNum -= (curFDVectorNum - 1U); // 1: 空余核不包含FD自身的核,要-1 + } + splitRes.fdRes.fdUsedVecNum = curCoreIndex; +} + +bool XllmKernelSparseFlashMlaMetadataCpuKernel::BalanceSchedule( + SplitResult& splitRes) { + SplitContext splitContext(batchSize_); + + // 1、划分基本块,统计信息 + CalcSplitInfo(splitContext); + // 全空case + if (splitContext.splitInfo.isKvSeqAllZero) { + splitRes.usedCoreNum = 1U; + splitRes.bN2End[0] = batchSize_ * numHeadsKv_; + splitRes.gS1End[0] = 0U; + splitRes.s2End[0] = 0U; + return true; + } + CalcCostInfo(splitContext); + + // 2、获取每个核的分配方案 + splitRes.maxCost = INT64_MAX; + splitRes.usedCoreNum = 1U; + + CalcSplitPlan(splitRes.maxCost, splitContext, splitRes); + // 3、存在FD任务,对FD进行负载均衡分配 + if (splitRes.numOfFdHead > 0U) { + SplitFD(splitRes); + } + splitRes.usedCoreNum = std::max(splitRes.usedCoreNum, 1U); // 至少使用1个core + return true; +} + +bool XllmKernelSparseFlashMlaMetadataCpuKernel::GenMetadata( + SplitResult& splitRes) { + optiling::detail::SmlaMetadata* metadataPtr = + static_cast(metadata_->GetData()); + *metadataPtr = {}; + // FA Metadata Generate + if (isSplitG_) { + for (size_t i = 0; i < aicCoreNum_; i++) { + // 单核s2计算轮次最大数量 + metadataPtr->faMetadata[2 * i][FA_S2_MAX_NUM] = splitRes.maxS2LoopNum; + metadataPtr->faMetadata[2 * i + 1][FA_S2_MAX_NUM] = splitRes.maxS2LoopNum; + + if (i >= splitRes.usedCoreNum) { + metadataPtr->faMetadata[2 * i][FA_CORE_ENABLE_INDEX] = + 0; // AIC disenable + metadataPtr->faMetadata[2 * i + 1][FA_CORE_ENABLE_INDEX] = + 0; // AIC disenable + continue; + } + metadataPtr->faMetadata[2 * i][FA_CORE_ENABLE_INDEX] = 1; // AIC enable + metadataPtr->faMetadata[2 * i + 1][FA_CORE_ENABLE_INDEX] = + 1; // AIC enable + // FA START + metadataPtr->faMetadata[2 * i][FA_BN2_START_INDEX] = + i == 0 ? 0 : splitRes.bN2End[i - 1]; + metadataPtr->faMetadata[2 * i][FA_M_START_INDEX] = + i == 0 ? 0 : splitRes.gS1End[i - 1]; + metadataPtr->faMetadata[2 * i][FA_S2_START_INDEX] = + i == 0 ? 0 : splitRes.s2End[i - 1]; + + metadataPtr->faMetadata[2 * i + 1][FA_BN2_START_INDEX] = + i == 0 ? 0 : splitRes.bN2End[i - 1]; + metadataPtr->faMetadata[2 * i + 1][FA_M_START_INDEX] = + i == 0 ? 0 : splitRes.gS1End[i - 1]; + metadataPtr->faMetadata[2 * i + 1][FA_S2_START_INDEX] = + i == 0 ? 0 : splitRes.s2End[i - 1]; + // FA END + metadataPtr->faMetadata[2 * i][FA_BN2_END_INDEX] = splitRes.bN2End[i]; + metadataPtr->faMetadata[2 * i][FA_M_END_INDEX] = splitRes.gS1End[i]; + metadataPtr->faMetadata[2 * i][FA_S2_END_INDEX] = splitRes.s2End[i]; + + metadataPtr->faMetadata[2 * i + 1][FA_BN2_END_INDEX] = splitRes.bN2End[i]; + metadataPtr->faMetadata[2 * i + 1][FA_M_END_INDEX] = splitRes.gS1End[i]; + metadataPtr->faMetadata[2 * i + 1][FA_S2_END_INDEX] = splitRes.s2End[i]; + // firstFdDataWorkspace + metadataPtr->faMetadata[2 * i][FA_FIRST_FD_DATA_WORKSPACE_IDX_INDEX] = + splitRes.firstFdDataWorkspaceIdx[i]; + metadataPtr->faMetadata[2 * i + 1][FA_FIRST_FD_DATA_WORKSPACE_IDX_INDEX] = + splitRes.firstFdDataWorkspaceIdx[i]; + } + } else { + for (size_t i = 0; i < aicCoreNum_; ++i) { + if (i >= splitRes.usedCoreNum) { + metadataPtr->faMetadata[i][FA_CORE_ENABLE_INDEX] = 0; // AIC disenable + continue; + } + metadataPtr->faMetadata[i][FA_CORE_ENABLE_INDEX] = 1; // AIC enable + // FA START + metadataPtr->faMetadata[i][FA_BN2_START_INDEX] = + i == 0 ? 0 : splitRes.bN2End[i - 1]; + metadataPtr->faMetadata[i][FA_M_START_INDEX] = + i == 0 ? 0 : splitRes.gS1End[i - 1]; + metadataPtr->faMetadata[i][FA_S2_START_INDEX] = + i == 0 ? 0 : splitRes.s2End[i - 1]; + // FA END + metadataPtr->faMetadata[i][FA_BN2_END_INDEX] = splitRes.bN2End[i]; + metadataPtr->faMetadata[i][FA_M_END_INDEX] = splitRes.gS1End[i]; + metadataPtr->faMetadata[i][FA_S2_END_INDEX] = splitRes.s2End[i]; + // firstFdDataWorkspace + metadataPtr->faMetadata[i][FA_FIRST_FD_DATA_WORKSPACE_IDX_INDEX] = + splitRes.firstFdDataWorkspaceIdx[i]; + } + } + + // FD Metadata Generate + for (size_t i = 0; i < aivCoreNum_; ++i) { + if (i >= splitRes.fdRes.fdUsedVecNum) { + metadataPtr->fdMetadata[i][FD_CORE_ENABLE_INDEX] = 0; // AIV disenable + continue; + } + metadataPtr->fdMetadata[i][FD_CORE_ENABLE_INDEX] = 1; // AIV enable + uint32_t curFdIdx = splitRes.fdRes.fdIdx[i]; + metadataPtr->fdMetadata[i][FD_BN2_IDX_INDEX] = + splitRes.fdRes.fdBN2Idx[curFdIdx]; + metadataPtr->fdMetadata[i][FD_M_IDX_INDEX] = + splitRes.fdRes.fdMIdx[curFdIdx]; + metadataPtr->fdMetadata[i][FD_WORKSPACE_IDX_INDEX] = + splitRes.fdRes.fdWorkspaceIdx[curFdIdx]; + metadataPtr->fdMetadata[i][FD_WORKSPACE_NUM_INDEX] = + splitRes.fdRes.fdS2SplitNum[curFdIdx]; + metadataPtr->fdMetadata[i][FD_M_START_INDEX] = splitRes.fdRes.fdMStart[i]; + metadataPtr->fdMetadata[i][FD_M_NUM_INDEX] = splitRes.fdRes.fdMNum[i]; + } + return true; +} + +namespace { +static const char* kernelType = "XllmKernelSparseFlashMlaMetadata"; +REGISTER_CPU_KERNEL(kernelType, XllmKernelSparseFlashMlaMetadataCpuKernel); +} // namespace + +}; // namespace aicpu::xllm_sparse_mla diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.h new file mode 100644 index 0000000000..d23c68d778 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.h @@ -0,0 +1,430 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file sparse_flash_mla_metadata_aicpu.h + * \brief + */ + +#ifndef SPARSE_FLASH_MLA_METADATA_AICPU_H +#define SPARSE_FLASH_MLA_METADATA_AICPU_H + +#include +#include +#include + +#include "cpu_context.h" +#include "cpu_kernel.h" +#include "cpu_tensor.h" +#include "quant_lightning_indexer_metadata/op_kernel_aicpu/cpu_context_util.h" +#include "sparse_flash_mla/op_kernel/sparse_flash_mla_kernel_metadata.h" + +namespace aicpu::xllm_sparse_mla { +constexpr int64_t FA_TOLERANCE_RATIO = 2; +constexpr uint32_t COST_WEIGHT_M = 6U; +constexpr uint32_t COST_WEIGHT_S2 = 10U; +constexpr uint32_t BATCH_CONSISTENCY_MAX_REDUCTION_PARTS = 32U; + +constexpr bool ORI_KV = false; +constexpr bool CMP_KV = true; +constexpr uint32_t NO_MASK = 0; +constexpr uint32_t HAS_MASK = 1; +constexpr uint32_t NUM_2 = 2; + +enum BlockType : uint32_t { + ORI_NORMAL_BLOCK = 0, + ORI_TAIL_BLOCK, + CMP_NORMAL_BLOCK, + CMP_TAIL_BLOCK, + BLOCK_MAX_TYPE +}; + +enum class SparseMode : uint8_t { + DEFAULT_MASK = 0, + ALL_MASK, + LEFT_UP_CAUSAL, + RIGHT_DOWN_CAUSAL, + BAND, + SPARSE_BUTT, +}; + +enum class ValidSocVersion { ASCEND910 = 0, ASCEND950, ASCEND960 }; + +template +using Range = std::pair; + +template +using BlockCost = std::array(BLOCK_MAX_TYPE)>, + static_cast(BLOCK_MAX_TYPE)>; + +template +T Clip(T value, T minValue, T maxValue) { + if (value < minValue) { + return minValue; + } + if (value > maxValue) { + return maxValue; + } + return value; +} + +template +inline bool IsWithinTolerance(T limit, T tolerance, T value) { + return limit + tolerance >= value; +} + +// 分核功能模块输出:FD信息,包含需要归约的数据索引及其分核信息 +struct FlashDecodeResult { + uint32_t fdUsedVecNum{0U}; // 归约过程使用的vector数量 + // 1、归约任务的索引信息 + std::vector + fdBN2Idx{}; // 每个归约任务的BN2索引,脚标为归约任务的序号,最大为核数-1 + std::vector + fdMIdx{}; // 每个归约任务的GS1索引,脚标为归约任务的序号 + std::vector + fdWorkspaceIdx{}; // 每个归约任务在workspace中的存放位置 + std::vector + fdS2SplitNum{}; // 每个归约任务的S2核间切分份数,脚标为归约任务的序号 + std::vector fdMSize{}; // 每个归约任务m轴大小,脚标为归约任务的序号 + // 2、FD负载均衡阶段,归约任务的分核(vec)信息 + std::vector + fdIdx{}; // FD负载均衡阶段,每个vector处理的归约任务对应ID + std::vector + fdMStart{}; // FD负载均衡阶段,每个vector处理的归约任务的m轴起点 + std::vector + fdMNum{}; // FD负载均衡阶段,每个vector处理的归约任务的m轴行数 + + FlashDecodeResult(uint32_t aicNum, uint32_t aivNum) + : fdBN2Idx(aicNum), + fdMIdx(aicNum), + fdWorkspaceIdx(aicNum), + fdS2SplitNum(aicNum), + fdMSize(aicNum), + fdIdx(aivNum), + fdMStart(aivNum), + fdMNum(aivNum) {} +}; + +// 分核功能模块输出:FA阶段的核间分核信息 +struct SplitResult { + uint32_t usedCoreNum{0U}; // 使用的核数量 + std::vector bN2End{}; // 每个核处理数据的BN2结束点 + std::vector gS1End{}; // 每个核处理数据的GS1结束点 + std::vector s2End{}; // 每个核处理数据的S2结束点 + std::vector + firstFdDataWorkspaceIdx{}; // 每个核第一份归约任务的存放位置 + int64_t maxCost{0}; // 慢核开销 + uint32_t numOfFdHead{0U}; // 归约任务数量 + uint32_t maxS2SplitNum{0U}; // 单个归约任务最大分核数量 + uint32_t maxS2LoopNum{0U}; // 单个核最大s2计算轮次数量 + FlashDecodeResult fdRes{0U, 0U}; // FD信息 + + SplitResult(uint32_t aicNum, uint32_t aivNum) + : bN2End(aicNum), + gS1End(aicNum), + s2End(aicNum), + firstFdDataWorkspaceIdx(aicNum), + fdRes(aicNum, aivNum) {}; +}; + +// 分核功能模块内部使用:记录切分信息 +struct SplitInfo { + std::vector s1GBaseNum{}; // S1G方向,切了多少个基本块 + std::vector oriS2BaseNum{}; // oriS2方向,切了多少个基本块 + std::vector cmpS2BaseNum{}; // cmpS2方向,切了多少个基本块 + std::vector s1GTailSize{}; // S1G方向,尾块size + std::vector oriS2TailSize{}; // oriS2方向,尾块size + std::vector cmpS2TailSize{}; // cmpS2方向,尾块size + bool isKvSeqAllZero{true}; + + explicit SplitInfo(uint32_t batchSize) + : s1GBaseNum(batchSize), + oriS2BaseNum(batchSize), + cmpS2BaseNum(batchSize), + s1GTailSize(batchSize), + oriS2TailSize(batchSize), + cmpS2TailSize(batchSize) {} +}; + +// 分核功能模块内部使用:记录batch的开销信息 +struct CostInfo { + std::vector bN2CostOfEachBatch{}; // 整个batch的开销 + std::vector bN2BlockOfEachBatch{}; // 整个batch的开销 + std::vector bN2S2LoopOfEachBatch{}; // 整个batch的s2计算轮次数量 + std::vector bN2LastBlockCostOfEachBatch{}; // batch最后一块的开销 + uint32_t totalBlockNum{0U}; + int64_t totalCost{0}; + int64_t maxS1GCost{0}; // 记录所有S1G行中的最大开销 + + explicit CostInfo(uint32_t batchSize) + : bN2CostOfEachBatch(batchSize), + bN2BlockOfEachBatch(batchSize), + bN2S2LoopOfEachBatch(batchSize), + bN2LastBlockCostOfEachBatch(batchSize) {} +}; + +// 分核功能模块内部使用:分核过程中,case基本信息的上下文信息,组合以减少接口传参数量 +struct SplitContext { + SplitInfo splitInfo{0U}; + CostInfo costInfo{0U}; + + explicit SplitContext(uint32_t batchSize) + : splitInfo(batchSize), costInfo(batchSize) {} +}; + +// 分核功能模块内部使用:记录batch相关的临时信息 +struct BatchCache { + uint32_t bIdx{0U}; + uint32_t s1Size{0U}; + uint32_t oriS2Size{0U}; + uint64_t cmpRevertS2Size{0U}; + int64_t oriPreTokenLeftUp{0}; + int64_t oriNextTokenLeftUp{0}; + int64_t cmpPreTokenLeftUp{0}; + int64_t cmpNextTokenLeftUp{0}; + BlockCost typeCost{}; +}; + +// 分核功能模块内部使用:记录当前行(S1G)的临时信息 +struct S1GCache { + uint32_t bIdx{0U}; + uint32_t s1GIdx{0U}; + uint32_t s2Start{0U}; + uint32_t s2End{0U}; + uint32_t oriS2Start{0U}; + uint32_t oriS2End{0U}; + uint32_t cmpS2Start{0U}; // win部分与cmp部分的切分点 + uint32_t cmpS2End{0U}; + int64_t s1GCost{0}; + int64_t s1GLastBlockCost{0}; + uint32_t s1GBlock{0U}; + uint32_t s2Loop{0U}; + uint32_t oriS1GBlock{0U}; + int64_t oriS1GCost{0}; + int64_t oriS1GLastBlockCost{0}; + int64_t oriS1GNormalBlockCost{0}; + uint32_t cmpS1GBlock{0U}; + int64_t cmpS1GCost{0}; + int64_t cmpS1GLastBlockCost{0}; + int64_t cmpS1GNormalBlockCost{0}; + int64_t oriS2TailSize{0}; + int64_t cmpS2TailSize{0}; + uint32_t actOriS2Size{0U}; + uint32_t actCmpS2Size{0U}; + uint32_t reductionBlockSize{0U}; +}; + +// 分核功能模块内部使用:记录分配过程中,当前核的负载信息 +struct CoreCache { + int64_t costLimit{0}; // 负载上限 + int64_t cost{0}; // 已分配负载 + uint32_t block{0U}; // 已分配块数 + uint32_t s2Loop{0U}; // 已分配s2计算轮次数量 +}; + +// 分核功能模块内部使用:记录分配过程中的上下文信息 +struct AssignContext { + uint32_t curBIdx{0U}; + uint32_t curBN2Idx{0U}; + uint32_t curS1GIdx{0U}; + uint32_t curS2Idx{0U}; + uint32_t curCoreIdx{0U}; + int64_t unassignedCost{0}; + uint32_t curKvSplitPart{1U}; + uint32_t preFdDataNum{0U}; + + int64_t bN2Cost{0}; + uint32_t bN2Block{0U}; + uint32_t bN2S2Loop{0U}; + bool isFinished{false}; + BatchCache batchCache{}; + S1GCache s1GCache{}; + CoreCache coreCache{}; +}; + +class XllmKernelSparseFlashMlaMetadataCpuKernel : public CpuKernel { + public: + XllmKernelSparseFlashMlaMetadataCpuKernel() = default; + ~XllmKernelSparseFlashMlaMetadataCpuKernel() = default; + uint32_t Compute(CpuKernelContext& ctx) override; + + private: + bool Prepare(CpuKernelContext& ctx); + int32_t GetQueryBatchSize(); + void CalcOriMaskMode(); + void CalcCmpMaskMode(); + ValidSocVersion ProcessSocVersion(); + bool ParamsCheck(); + int32_t GetSumOfQuerySeq(); + bool ParamsInit(); + bool BalanceSchedule(SplitResult& splitRes); + bool GenMetadata(SplitResult& splitRes); + // util + uint32_t GetS1SeqSize(uint32_t bIdx); + uint32_t GetOriS2SeqSize(uint32_t bIdx); + uint32_t GetCmpS2SeqSize(uint32_t bIdx); + uint64_t GetRevertS2Size(uint32_t bIdx); + uint32_t GetS1Idx(uint32_t s1Size, uint32_t s1GIdx); + uint32_t GetBsStride(uint32_t bIdx, uint32_t s1Idx); + uint32_t GetOriTopkLength(uint32_t bsStride); + uint32_t GetOriTopkLength(uint32_t s1GIdx, + const BatchCache& batchCache) const; + uint32_t ReadOriTopkLengthAtRow(uint32_t bIdx, uint32_t s1Idx) const; + uint32_t GetCmpTopkLength(uint32_t bsStride); + int64_t CalcOriPreTokenLeftUp(uint32_t s1Size, uint32_t s2Size); + int64_t CalcOriNextTokenLeftUp(uint32_t s1Size, uint32_t s2Size); + int64_t CalcCmpPreTokenLeftUp(uint32_t s1Size, uint64_t s2Size); + int64_t CalcCmpNextTokenLeftUp(uint32_t s1Size, uint64_t s2Size); + Range CalcS2TokenRange(uint32_t s1GIdx, + const BatchCache& batchCache, + bool isCmpKv); + int64_t OriCalcCost(uint32_t basicM, uint32_t basicS2); + int64_t CmpCalcCost(uint32_t basicM, uint32_t basicS2); + void CalcCostTable(uint32_t s1GTailSize, + uint32_t reductionBlockSize, + uint32_t oriS2TailSize, + uint32_t cmpS2TailSize); + + // cache calculation + void CalcBatchCache(uint32_t bIdx, + const SplitContext& splitContext, + BatchCache& batchCache); + void CalcOriBlockRange(const Range& oriS2TokenRange, + const BatchCache& batchCache, + S1GCache& s1GCache); + void CalcCmpBlockRange(const Range& cmpS2TokenRange, + const BatchCache& batchCache, + S1GCache& s1GCache); + void CalcOriS1GCache(S1GCache& s1GCache, const SplitInfo& splitInfo); + void CalcCmpS1GCache(S1GCache& s1GCache, const SplitInfo& splitInfo); + void GatherOriAndCmpCache(S1GCache& s1GCache); + void CalcS1GCache(uint32_t s1GIdx, + const SplitContext& splitContext, + const BatchCache& batchCache, + S1GCache& s1GCache); + + // preprocess + void CalcSplitInfo(SplitContext& splitContext); + void CalcBatchCost(uint32_t bIdx, + const SplitContext& splitContext, + CostInfo& costInfo); + void CalcCostInfo(SplitContext& splitContext); + + // assign + void UpdateCursor(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignByBatch(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignByRow(const SplitContext& splitContext, + AssignContext& assignContext); + int64_t CalcCurBlockCost(const AssignContext& assignContext); + uint32_t CalcCurBlockS2Loop(const AssignContext& assignContext); + void AssignByBlock(const SplitContext& splitContext, + AssignContext& assignContext); + void ForceAssign(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignBlocksToCore(const SplitContext& splitContext, + AssignContext& assignContext, + SplitResult& result); + + // FD + bool IsNeedRecordFDInfo(const AssignContext& assignContext, + const SplitResult& splitRes); + bool IsFirstReductionBlock(const AssignContext& assignContext, + const SplitResult& splitRes); + void RecordFDInfo(const SplitContext& splitContext, + const AssignContext& assignContext, + SplitResult& result); + + // main + void SplitFD(SplitResult& splitRes); + void CalcSplitPlan(int64_t costLimit, + const SplitContext& splitContext, + SplitResult& result); + + private: + // input + Tensor* cuSeqlensQ_ = nullptr; + Tensor* cuSeqlensOriKv_ = nullptr; + Tensor* cuSeqlensCmpKv_ = nullptr; + Tensor* sequsedQ_ = nullptr; + Tensor* sequsedOriKv_ = nullptr; + Tensor* sequsedCmpKv_ = nullptr; + Tensor* cmpResidualKv_ = nullptr; + Tensor* oriTopkLength_ = nullptr; + Tensor* cmpTopkLength_ = nullptr; + + // output + Tensor* metadata_ = nullptr; + + // attributes + int32_t batchSize_ = 0; + int32_t maxSeqlenQ_ = 0; + int32_t numHeadsQ_ = 0; + int32_t maxSeqlenOriKv_ = 0; + int32_t maxSeqlenCmpKv_ = 0; + int32_t numHeadsKv_ = 1; + int32_t headDim_ = 0; + int32_t oriTopK_ = 0; + int32_t cmpTopK_ = 0; + int32_t cmpRatio_ = 1; + int32_t oriMaskMode_ = static_cast(SparseMode::BAND); + int32_t cmpMaskMode_ = static_cast(SparseMode::RIGHT_DOWN_CAUSAL); + int64_t oriWinLeft_ = 127; + int64_t oriWinRight_ = 0; + std::string layoutQ_ = "BSND"; + std::string layoutKv_ = "PA_BBND"; + bool hasOriKv_ = true; + bool hasCmpKv_ = true; + uint32_t aicCoreNum_ = optiling::AIC_CORE_MAX_NUM; + uint32_t aivCoreNum_ = optiling::AIV_CORE_MAX_NUM; + bool isBatchConsistency_ = false; + + // attr + std::string socVersion_ = "Ascend950"; + int64_t oriPreToken_ = 0; + int64_t oriNextToken_ = 0; + int64_t cmpPreToken_ = 0; + int64_t cmpNextToken_ = 0; + uint32_t groupSize_ = 0; + uint32_t mBaseSize_ = 0; + uint32_t s2BaseSize_ = 128U; + bool isS1G_ = true; + bool supportFd_ = false; + uint32_t oriAttentionMode_ = HAS_MASK; + uint32_t cmpAttentionMode_ = HAS_MASK; + BlockCost typeCost_ = {}; + bool isSplitG_ = false; + bool isSparseOriKv_ = false; + bool isSparseCmpKv_ = false; + bool hasOriTopkLength_ = false; + uint32_t remainedBlockNum_ = 0U; + + private: + enum class ParamId : uint32_t { + // input + cuSeqlensQ = 0, + cuSeqlensOriKv = 1, + cuSeqlensCmpKv = 2, + sequsedQ = 3, + sequsedOriKv = 4, + sequsedCmpKv = 5, + cmpResidualKv = 6, + oriTopkLength = 7, + cmpTopkLength = 8, + // output + metaData = 0, + }; +}; +} // namespace aicpu::xllm_sparse_mla + +#endif diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.json b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.json new file mode 100644 index 0000000000..e7736eaf11 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.json @@ -0,0 +1,15 @@ +{ + "XllmKernelSparseFlashMlaMetadata":{ + "opInfo":{ + "computeCost":"100", + "engine":"DNN_VM_AICPU", + "flagAsync":"False", + "flagPartial":"False", + "functionName":"RunCpuKernel", + "kernelSo":"libmath_aicpu_kernels.so", + "opKernelLib":"CUSTAICPUKernel", + "userDefined":"True", + "workspaceSize":"100" + } + } +} diff --git a/xllm-kernel/csrc/ascendc/v41_sparse_mla.cmake b/xllm-kernel/csrc/ascendc/v41_sparse_mla.cmake new file mode 100644 index 0000000000..14fa904d11 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/v41_sparse_mla.cmake @@ -0,0 +1,48 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. + +if(NOT "ascend910_93" IN_LIST ASCEND_COMPUTE_UNIT) + return() +endif() + +set(smla "${CMAKE_CURRENT_SOURCE_DIR}/sparse_flash_mla") +set(smla_host "${smla}/op_host") +set(smla_metadata "${CMAKE_CURRENT_SOURCE_DIR}/sparse_flash_mla_metadata") +list(APPEND op_definitions "${smla_host}/sparse_flash_mla_def.cpp") +file(GLOB smla_checkers CONFIGURE_DEPENDS "${smla_host}/checkers/*.cpp") +list(APPEND sparse_attention_tiling + "${smla_host}/sparse_flash_mla_infershape.cpp" + "${smla_host}/sparse_flash_mla_tiling.cpp" + ${smla_checkers} + "${smla_metadata}/op_host/sparse_flash_mla_metadata_infershape.cpp" +) +set(smla_metadata_api + "${smla_metadata}/op_host/op_api/aclnn_sparse_flash_mla_metadata.cpp" + "${smla_metadata}/op_host/op_api/sparse_flash_mla_metadata.cpp" +) +set_property(SOURCE ${smla_metadata_api} APPEND PROPERTY + COMPILE_DEFINITIONS OP_LOG_LIBOPAPI_ONLY) +set_property(SOURCE ${smla_metadata_api} APPEND PROPERTY + INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}" "${ASCEND_CANN_PACKAGE_PATH}/pkg_inc/op_common") +set_property(SOURCE ${smla_checkers} "${smla_host}/sparse_flash_mla_tiling.cpp" + "${smla_host}/sparse_flash_mla_infershape.cpp" APPEND PROPERTY + INCLUDE_DIRECTORIES "${smla_host}" "${ASCEND_CANN_PACKAGE_PATH}/pkg_inc/op_common") +list(APPEND sparse_attention_api + "${ASCEND_AUTOGEN_PATH}/aclnn_xllm_kernel_sparse_flash_mla.cpp" + ${smla_metadata_api} +) +list(APPEND v41_metadata_graph_sources "${smla_metadata}/op_graph/sparse_flash_mla_metadata_proto.cpp") +list(APPEND v41_aicpu_components sparse_flash_mla_metadata) +list(APPEND v41_aicpu_headers + "${smla}/op_kernel/sparse_flash_mla_kernel_metadata.h" + "${smla}/op_kernel/arch35/common/smla_metadata_common.h" +) +macro(v41_sparse_mla_kernel) + npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelSparseFlashMla + KERNEL_DIR sparse_flash_mla/op_kernel KERNEL_FILE xllm_kernel_sparse_flash_mla.cpp) + npu_op_kernel_options(ascendc_kernels XllmKernelSparseFlashMla + OPTIONS --cce-auto-sync=off -Wno-deprecated-declarations -Werror + -mllvm -cce-vf-remove-membar=false -mllvm -cce-aicore-hoist-movemask=false) +endmacro() +install(FILES "${smla_metadata}/op_host/op_api/aclnn_sparse_flash_mla_metadata.h" + DESTINATION "packages/vendors/${vendor}/op_api/include" + RENAME aclnn_xllm_kernel_sparse_flash_mla_metadata.h) From 88ed1482c5eaefaf9eeceee53ce688f9de843d4d Mon Sep 17 00:00:00 2001 From: PixelFlat <329975279+PixelFlat@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:44:16 +0800 Subject: [PATCH 2/6] feat: expose the V4.1 Ascend operators through xllm-kernel. --- xllm-kernel/csrc/npu/hyper_connection.cpp | 154 +++++-- xllm-kernel/csrc/npu/moe.cpp | 49 +++ xllm-kernel/csrc/npu/normalization.cpp | 39 ++ xllm-kernel/csrc/npu/v41_quant_indexer.cpp | 192 +++++++++ xllm-kernel/csrc/npu/v41_sparse_mla.cpp | 199 +++++++++ .../python/xllm_kernel/_ascendc_opp.py | 8 +- .../python/xllm_kernel/_tilelang_config.py | 11 + xllm-kernel/python/xllm_kernel/catalog.py | 2 + .../ops/attention/dsv41/__init__.py | 149 +++++++ .../ops/attention/dsv41/_compile.py | 50 +++ .../ops/attention/dsv41/_tilelang/__init__.py | 1 + .../attention/dsv41/_tilelang/c2_pool_norm.py | 145 +++++++ .../dsv41/_tilelang/index_key_transform.py | 97 +++++ .../ops/attention/dsv41/_triton/__init__.py | 1 + .../dsv41/_triton/packed_projection.py | 57 +++ .../attention/dsv41/_triton/prefill_swa.py | 84 ++++ .../attention/dsv41/_triton/private_swa.py | 138 ++++++ .../ops/attention/dsv41/ascendc.py | 33 ++ .../ops/attention/dsv41/indexer.py | 75 ++++ .../xllm_kernel/ops/attention/dsv41/mla.py | 87 ++++ .../ops/attention/dsv41/tilelang.py | 180 ++++++++ .../xllm_kernel/ops/attention/dsv41/triton.py | 29 ++ .../python/xllm_kernel/ops/engram/__init__.py | 132 ++++++ .../ops/engram/_triton/__init__.py | 1 + .../xllm_kernel/ops/engram/_triton/engram.py | 396 ++++++++++++++++++ .../python/xllm_kernel/ops/engram/triton.py | 36 ++ .../ops/hyper_connection/__init__.py | 29 +- .../ops/hyper_connection/ascendc.py | 14 +- .../ops/kv_cache/_tilelang/__init__.py | 1 + .../kv_cache/_tilelang/v41_swa_rope_cache.py | 73 ++++ .../python/xllm_kernel/ops/moe/__init__.py | 37 +- .../python/xllm_kernel/ops/moe/ascendc.py | 4 + .../xllm_kernel/ops/normalization/__init__.py | 25 ++ .../xllm_kernel/ops/normalization/ascendc.py | 12 + .../_tilelang/v41_partial_rope.py | 80 ++++ .../ops/quantization/_tilelang/__init__.py | 1 + .../_tilelang/v41_index_query_quant.py | 77 ++++ xllm-kernel/setup.py | 17 +- xllm/_npu_runtime.py | 8 +- xllm/core/platform/npu/startup.cpp | 18 +- 40 files changed, 2672 insertions(+), 69 deletions(-) create mode 100644 xllm-kernel/csrc/npu/v41_quant_indexer.cpp create mode 100644 xllm-kernel/csrc/npu/v41_sparse_mla.cpp create mode 100644 xllm-kernel/python/xllm_kernel/_tilelang_config.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/attention/dsv41/__init__.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_compile.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/__init__.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/c2_pool_norm.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/index_key_transform.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/__init__.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/packed_projection.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/prefill_swa.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/private_swa.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/attention/dsv41/ascendc.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/attention/dsv41/indexer.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/attention/dsv41/mla.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/attention/dsv41/tilelang.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/attention/dsv41/triton.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/engram/__init__.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/engram/_triton/__init__.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/engram/_triton/engram.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/engram/triton.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/kv_cache/_tilelang/__init__.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/kv_cache/_tilelang/v41_swa_rope_cache.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/positional_encoding/_tilelang/v41_partial_rope.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/quantization/_tilelang/__init__.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/quantization/_tilelang/v41_index_query_quant.py diff --git a/xllm-kernel/csrc/npu/hyper_connection.cpp b/xllm-kernel/csrc/npu/hyper_connection.cpp index 014586446c..94c11fe043 100644 --- a/xllm-kernel/csrc/npu/hyper_connection.cpp +++ b/xllm-kernel/csrc/npu/hyper_connection.cpp @@ -71,6 +71,47 @@ bool has_hc_pre_va() { void prepare_ascendc_hyper_connection() { hc_apis(); } +std::tuple +fused_hc_pre(const torch::Tensor& x, + const torch::Tensor& hc_fn, + const torch::Tensor& hc_scale, + const torch::Tensor& hc_base, + const std::optional& pre_mix, + int64_t hc_mult, + int64_t hc_sinkhorn_iters, + double norm_eps, + double hc_eps) { + auto output_shape = x.sizes().vec(); + output_shape.erase(output_shape.end() - 2); + auto post_shape = x.sizes().vec(); + post_shape.pop_back(); + auto combination_shape = post_shape; + combination_shape.emplace_back(hc_mult); + auto output = torch::empty(output_shape, x.options()); + const auto mix_options = x.options().dtype(torch::kFloat32); + auto post = torch::empty(post_shape, mix_options); + auto combination = torch::empty(combination_shape, mix_options); + std::optional pre; + if (pre_mix.has_value()) { + pre = torch::empty(post_shape, mix_options); + } + EXEC_NPU_CMD_EXT(aclnnXllmKernelHcPreVa, + x, + hc_fn, + hc_scale, + hc_base, + pre_mix, + hc_mult, + hc_sinkhorn_iters, + hc_eps, + norm_eps, + output, + post, + combination, + pre); + return {output, post, combination, pre.value_or(torch::Tensor{})}; +} + PreOutput hc_pre(const torch::Tensor& x, const torch::Tensor& hc_fn, const torch::Tensor& hc_scale, @@ -98,6 +139,21 @@ PreOutput hc_pre(const torch::Tensor& x, const torch::DeviceGuard guard(x.device()); const auto x_bf16 = x.to(torch::kBFloat16); + if (has_hc_pre_va() && hc_mult == 4 && hc_sinkhorn_iters > 0 && + hc_fn.scalar_type() == torch::kFloat32 && x_bf16.is_contiguous() && + hc_fn.is_contiguous() && hc_scale.is_contiguous() && + hc_base.is_contiguous()) { + auto [output, post, comb, pre] = fused_hc_pre(x_bf16, + hc_fn, + hc_scale, + hc_base, + std::nullopt, + hc_mult, + hc_sinkhorn_iters, + norm_eps, + hc_eps); + return {output.to(x.scalar_type()), post, comb}; + } auto output_shape = x.sizes().vec(); output_shape.erase(output_shape.end() - 2); auto post_shape = x.sizes().vec(); @@ -108,54 +164,56 @@ PreOutput hc_pre(const torch::Tensor& x, const auto fp32_options = x.options().dtype(torch::kFloat32); auto post = torch::empty(post_shape, fp32_options); auto comb = torch::empty(comb_shape, fp32_options); - if (has_hc_pre_va() && hc_mult == 4 && hc_sinkhorn_iters > 0 && - hc_fn.scalar_type() == torch::kFloat32 && x_bf16.is_contiguous() && - hc_fn.is_contiguous() && hc_scale.is_contiguous() && - hc_base.is_contiguous()) { - const std::optional absent; - EXEC_NPU_CMD_EXT(aclnnXllmKernelHcPreVa, - x_bf16, - hc_fn, - hc_scale, - hc_base, - /*pre_mix=*/absent, - hc_mult, - hc_sinkhorn_iters, - hc_eps, - norm_eps, - output, - post, - comb, - /*pre=*/absent); - } else { - auto rms_shape = post_shape; - rms_shape.back() = 1; - auto inv_rms = torch::empty(rms_shape, fp32_options); - const auto input = x_bf16.contiguous(); - EXEC_NPU_CMD_EXT(aclnnXllmKernelHcPreInvRms, input, norm_eps, inv_rms); - - // Match the staged projection's BF16 inputs and FP32 Sinkhorn logits. - const auto mixes = - torch::linear(input.flatten(-2), hc_fn.to(torch::kBFloat16)) - .to(torch::kFloat32); - const auto scale = hc_scale.contiguous(); - const auto base = hc_base.contiguous(); - EXEC_NPU_CMD_EXT(aclnnXllmKernelHcPreSinkhorn, - mixes, - inv_rms, - scale, - base, - input, - hc_mult, - hc_sinkhorn_iters, - hc_eps, - output, - post, - comb); - } + auto rms_shape = post_shape; + rms_shape.back() = 1; + auto inv_rms = torch::empty(rms_shape, fp32_options); + const auto input = x_bf16.contiguous(); + EXEC_NPU_CMD_EXT(aclnnXllmKernelHcPreInvRms, input, norm_eps, inv_rms); + + // Match the staged projection's BF16 inputs and FP32 Sinkhorn logits. + const auto mixes = + torch::linear(input.flatten(-2), hc_fn.to(torch::kBFloat16)) + .to(torch::kFloat32); + const auto scale = hc_scale.contiguous(); + const auto base = hc_base.contiguous(); + EXEC_NPU_CMD_EXT(aclnnXllmKernelHcPreSinkhorn, + mixes, + inv_rms, + scale, + base, + input, + hc_mult, + hc_sinkhorn_iters, + hc_eps, + output, + post, + comb); return {output.to(x.scalar_type()), post, comb}; } +std::tuple +hc_pre_delayed(const torch::Tensor& x, + const torch::Tensor& hc_fn, + const torch::Tensor& hc_scale, + const torch::Tensor& hc_base, + const torch::Tensor& pre_mix, + int64_t hc_mult, + int64_t hc_sinkhorn_iters, + double norm_eps, + double hc_eps) { + const torch::DeviceGuard guard(x.device()); + CHECK(has_hc_pre_va()) << "Delayed HC pre requires HcPreVa on Ascend A3"; + return fused_hc_pre(x, + hc_fn, + hc_scale, + hc_base, + pre_mix, + hc_mult, + hc_sinkhorn_iters, + norm_eps, + hc_eps); +} + torch::Tensor hc_post(const torch::Tensor& x, const torch::Tensor& residual, const torch::Tensor& post, @@ -189,6 +247,11 @@ torch::Tensor hc_post(const torch::Tensor& x, } TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { + m.def("supports_fused_hc_pre() -> bool", TORCH_FN(has_hc_pre_va)); + m.def( + "hc_pre_delayed(Tensor x, Tensor hc_fn, Tensor hc_scale, Tensor hc_base, " + "Tensor pre_mix, int hc_mult, int hc_sinkhorn_iters, float norm_eps, " + "float hc_eps) -> (Tensor, Tensor, Tensor, Tensor)"); m.def("prepare_ascendc_hyper_connection() -> ()", TORCH_FN(prepare_ascendc_hyper_connection)); m.def( @@ -200,6 +263,7 @@ TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { } TORCH_LIBRARY_IMPL(xllm_kernel, PrivateUse1, m) { + m.impl("hc_pre_delayed", TORCH_FN(hc_pre_delayed)); m.impl("hc_pre", TORCH_FN(hc_pre)); m.impl("hc_post", TORCH_FN(hc_post)); } diff --git a/xllm-kernel/csrc/npu/moe.cpp b/xllm-kernel/csrc/npu/moe.cpp index a3966ca8f7..703a9447e9 100644 --- a/xllm-kernel/csrc/npu/moe.cpp +++ b/xllm-kernel/csrc/npu/moe.cpp @@ -51,6 +51,8 @@ AscendcApi select_api(const char* package_name, const char* cann_name) { const auto& moe_apis() { static const std::unordered_map apis = { + {"aclnnXllmKernelDispatchFFNCombine", + select_api("aclnnXllmKernelDispatchFFNCombine", nullptr)}, {"aclnnXllmKernelMoeGatingTopKHash", select_api("aclnnXllmKernelMoeGatingTopKHash", nullptr)}, {"aclnnXllmKernelMoeInitRoutingV3", @@ -79,6 +81,45 @@ void GetApiFunc(const char* name, workspace = api.workspace; } +bool has_dispatch_ffn_combine() { + return available(moe_apis().at("aclnnXllmKernelDispatchFFNCombine")); +} +torch::Tensor dispatch_ffn_combine(const torch::Tensor& x, + const torch::Tensor& weight1, + const torch::Tensor& weight2, + const torch::Tensor& expert_ids, + const torch::Tensor& scale1, + const torch::Tensor& scale2, + const torch::Tensor& probs, + const torch::Tensor& active_mask, + std::string group, + int64_t max_output_size, + double swiglu_limit) { + const torch::DeviceGuard guard(x.device()); + auto output = torch::empty_like(x); + auto counts = torch::empty({weight1.size(0)}, expert_ids.options()); + const torch::TensorList weights1(&weight1, 1); + const torch::TensorList weights2(&weight2, 1); + const torch::TensorList scales1(&scale1, 1); + const torch::TensorList scales2(&scale2, 1); + char* group_name = group.data(); + EXEC_NPU_CMD_EXT(aclnnXllmKernelDispatchFFNCombine, + x, + weights1, + weights2, + expert_ids, + scales1, + scales2, + probs, + active_mask, + group_name, + max_output_size, + swiglu_limit, + output, + counts); + return output; +} + bool prepare_ascendc_moe() { const auto& apis = moe_apis(); CHECK(available(apis.at("aclnnXllmKernelMoeGatingTopKHash"))); @@ -326,6 +367,13 @@ std::tuple dequant_swiglu_quant( } TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { + m.def("has_dispatch_ffn_combine() -> bool", + TORCH_FN(has_dispatch_ffn_combine)); + m.def( + "dispatch_ffn_combine(Tensor x, Tensor weight1, Tensor weight2, Tensor " + "expert_ids, Tensor scale1, Tensor scale2, Tensor probs, Tensor " + "active_mask, str group, int max_output_size, float swiglu_limit) -> " + "Tensor"); m.def("prepare_ascendc_moe() -> bool", TORCH_FN(prepare_ascendc_moe)); m.def( "moe_gating_top_k_hash(Tensor x, int k, Tensor? bias, Tensor? input_ids, " @@ -352,6 +400,7 @@ TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { } TORCH_LIBRARY_IMPL(xllm_kernel, PrivateUse1, m) { + m.impl("dispatch_ffn_combine", TORCH_FN(dispatch_ffn_combine)); m.impl("moe_gating_top_k_hash", TORCH_FN(moe_gating_top_k_hash)); m.impl("moe_init_routing_v3", TORCH_FN(moe_init_routing_v3)); m.impl("moe_grouped_matmul_swiglu_quant", diff --git a/xllm-kernel/csrc/npu/normalization.cpp b/xllm-kernel/csrc/npu/normalization.cpp index 87f72b59e3..c0aec1ce69 100644 --- a/xllm-kernel/csrc/npu/normalization.cpp +++ b/xllm-kernel/csrc/npu/normalization.cpp @@ -75,6 +75,40 @@ torch::Tensor rms_norm_gated(const torch::Tensor& input, } // namespace gated +namespace cast { +const AscendcApi& get_api() { + static const auto api = + find_ascendc_api("aclnnXllmKernelRmsNormCastVa", + "aclnnXllmKernelRmsNormCastVaGetWorkspaceSize"); + return api; +} + +bool available() { + const auto& api = get_api(); + return api.launch && api.workspace; +} + +void GetApiFunc(const char*, const char*, void*& launch, void*& workspace) { + const auto& api = get_api(); + CHECK(available()); + launch = api.launch; + workspace = api.workspace; +} + +std::tuple rms_norm_cast( + const torch::Tensor& input, + const torch::Tensor& weight, + double eps) { + const torch::DeviceGuard guard(input.device()); + auto normed = torch::empty_like(input); + auto router_input = + torch::empty_like(input, input.options().dtype(torch::kFloat32)); + EXEC_NPU_CMD_EXT( + aclnnXllmKernelRmsNormCastVa, input, weight, eps, normed, router_input); + return {normed, router_input}; +} +} // namespace cast + namespace quant { const AscendcApi& get_api() { @@ -141,6 +175,10 @@ void prepare_ascendc_normalization() { } TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { + m.def("supports_rms_norm_cast() -> bool", TORCH_FN(cast::available)); + m.def( + "rms_norm_cast(Tensor input, Tensor weight, float eps) -> (Tensor, " + "Tensor)"); m.def("prepare_ascendc_normalization() -> ()", TORCH_FN(prepare_ascendc_normalization)); m.def( @@ -152,6 +190,7 @@ TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { } TORCH_LIBRARY_IMPL(xllm_kernel, PrivateUse1, m) { + m.impl("rms_norm_cast", TORCH_FN(cast::rms_norm_cast)); m.impl("rms_norm_gated", TORCH_FN(gated::rms_norm_gated)); m.impl("rms_norm_dynamic_quant", TORCH_FN(quant::rms_norm_dynamic_quant)); } diff --git a/xllm-kernel/csrc/npu/v41_quant_indexer.cpp b/xllm-kernel/csrc/npu/v41_quant_indexer.cpp new file mode 100644 index 0000000000..439d4b92de --- /dev/null +++ b/xllm-kernel/csrc/npu/v41_quant_indexer.cpp @@ -0,0 +1,192 @@ +// Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. + +#include +#include + +#include +#include +#include +#include +#include + +#include "csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h" +#include "csrc/npu/ascendc_api.h" +#include "op_plugin/utils/op_api_common_base.h" + +namespace xllm_kernel { +namespace { + +const auto& indexer_apis() { + static const std::array apis = { + std::pair{ + "aclnnXllmKernelQuantLightningIndexerV2Va", + load_ascendc_api( + "aclnnXllmKernelQuantLightningIndexerV2Va", + "aclnnXllmKernelQuantLightningIndexerV2VaGetWorkspaceSize")}, + std::pair{ + "aclnnXllmKernelQuantLightningIndexerV2MetadataVa", + load_ascendc_api("aclnnXllmKernelQuantLightningIndexerV2MetadataVa", + "aclnnXllmKernelQuantLightningIndexerV2MetadataVaGet" + "WorkspaceSize")}, + }; + return apis; +} + +void GetApiFunc(const char* name, + const char* /*workspace_name*/, + void*& launch, + void*& workspace) { + for (const auto& [entry, api] : indexer_apis()) { + if (std::string_view(name) == entry) { + launch = api.launch; + workspace = api.workspace; + return; + } + } + LOG(FATAL) << "Unknown QLI V2 entry point: " << name; +} + +void prepare_ascendc_v41_indexer() { indexer_apis(); } + +constexpr int64_t kInt8QuantMode = 2; +constexpr int64_t kKeyHeads = 1; +constexpr int64_t kNoReturnValue = 0; +constexpr int64_t kRightDownCausal = 3; +constexpr int64_t kCandidateSource = 1; + +torch::Tensor quant_lightning_indexer_v2_metadata( + const torch::Tensor& query_offsets, + const torch::Tensor& committed_lengths, + const std::optional& residual_lengths, + int64_t query_heads, + int64_t head_dim, + int64_t topk, + int64_t max_query_len, + int64_t max_committed_len, + int64_t compression_ratio) { + const torch::DeviceGuard guard(query_offsets.device()); + auto metadata = + query_offsets.new_empty({optiling::QLI_V2_METADATA_TOTAL_SIZE}); + auto empty = query_offsets.new_empty({0}); + const auto& residual = + residual_lengths.has_value() ? *residual_lengths : empty; + const int64_t batch_size = committed_lengths.numel(); + char query_layout[] = "TND"; + char key_layout[] = "PA_BBND"; + char* layout_query = query_layout; + char* layout_key = key_layout; + EXEC_NPU_CMD_EXT(aclnnXllmKernelQuantLightningIndexerV2MetadataVa, + query_offsets, + /*cu_seqlens_k=*/empty, + /*seqused_q=*/empty, + committed_lengths, + residual, + query_heads, + kKeyHeads, + head_dim, + topk, + kInt8QuantMode, + batch_size, + max_query_len, + max_committed_len, + layout_query, + layout_key, + kRightDownCausal, + compression_ratio, + metadata); + return metadata; +} + +std::tuple quant_lightning_indexer_v2( + const torch::Tensor& query, + const torch::Tensor& key, + const torch::Tensor& weights, + const torch::Tensor& query_scale, + const torch::Tensor& key_scale, + const torch::Tensor& query_offsets, + const torch::Tensor& committed_lengths, + const std::optional& residual_lengths, + const torch::Tensor& block_table, + const torch::Tensor& metadata, + const std::optional& candidate_blocks, + int64_t topk, + int64_t max_query_len, + int64_t compression_ratio, + int64_t candidate_mode, + int64_t candidate_count, + int64_t candidate_block_size) { + const torch::DeviceGuard guard(query.device()); + const int64_t rows = query.size(0); + const int64_t key_heads = key.size(2); + auto output_options = query.options().dtype(torch::kInt32); + auto indices = torch::empty({rows, key_heads, topk}, output_options); + auto values = torch::empty({0}, query.options().dtype(torch::kBFloat16)); + auto candidates = + candidate_mode == kCandidateSource + ? torch::empty({rows, key_heads, candidate_count}, output_options) + : torch::empty({0}, output_options); + const std::optional absent; + const int64_t key_page_stride = key.stride(0); + const int64_t scale_page_stride = key_scale.stride(0); + char query_layout[] = "TND"; + char key_layout[] = "PA_BBND"; + char* layout_query = query_layout; + char* layout_key = key_layout; + EXEC_NPU_CMD_EXT(aclnnXllmKernelQuantLightningIndexerV2Va, + query, + key, + weights, + query_scale, + key_scale, + query_offsets, + /*cu_seqlens_k=*/absent, + /*seqused_q=*/absent, + committed_lengths, + residual_lengths, + block_table, + /*output_idx_offset=*/absent, + metadata, + candidate_blocks, + topk, + kInt8QuantMode, + max_query_len, + layout_query, + layout_key, + kRightDownCausal, + compression_ratio, + kNoReturnValue, + candidate_mode, + candidate_count, + candidate_block_size, + key_page_stride, + scale_page_stride, + indices, + values, + candidates); + return {indices, candidates}; +} + +TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { + m.def("prepare_ascendc_v41_indexer() -> ()", &prepare_ascendc_v41_indexer); + m.def( + "quant_lightning_indexer_v2_metadata(Tensor query_offsets, Tensor " + "committed_lengths, " + "Tensor? residual_lengths, int query_heads, int head_dim, int topk, " + "int max_query_len, int max_committed_len, int compression_ratio) -> " + "Tensor"); + m.def( + "quant_lightning_indexer_v2(Tensor query, Tensor key, Tensor weights, " + "Tensor query_scale, Tensor key_scale, Tensor query_offsets, " + "Tensor committed_lengths, Tensor? residual_lengths, Tensor block_table, " + "Tensor metadata, Tensor? candidate_blocks, int topk, int max_query_len, " + "int compression_ratio, int candidate_mode, int candidate_count, " + "int candidate_block_size) -> (Tensor, Tensor)"); +} + +TORCH_LIBRARY_IMPL(xllm_kernel, PrivateUse1, m) { + m.impl("quant_lightning_indexer_v2_metadata", + TORCH_FN(quant_lightning_indexer_v2_metadata)); + m.impl("quant_lightning_indexer_v2", TORCH_FN(quant_lightning_indexer_v2)); +} +} // namespace +} // namespace xllm_kernel diff --git a/xllm-kernel/csrc/npu/v41_sparse_mla.cpp b/xllm-kernel/csrc/npu/v41_sparse_mla.cpp new file mode 100644 index 0000000000..3ec003e335 --- /dev/null +++ b/xllm-kernel/csrc/npu/v41_sparse_mla.cpp @@ -0,0 +1,199 @@ +// Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. + +#include +#include + +#include +#include + +#include "csrc/ascendc/sparse_flash_mla/op_kernel/sparse_flash_mla_kernel_metadata.h" +#include "csrc/npu/ascendc_api.h" +#include "op_plugin/utils/op_api_common_base.h" + +namespace xllm_kernel { +namespace { + +const AscendcApi& mla_api() { + static const auto api = + load_ascendc_api("aclnnXllmKernelSparseFlashMla", + "aclnnXllmKernelSparseFlashMlaGetWorkspaceSize"); + return api; +} + +const AscendcApi& metadata_api() { + static const auto api = + load_ascendc_api("aclnnXllmKernelSparseFlashMlaMetadata", + "aclnnXllmKernelSparseFlashMlaMetadataGetWorkspaceSize"); + return api; +} + +void GetApiFunc(const char* name, + const char* /*workspace_name*/, + void*& launch, + void*& workspace) { + const auto& api = std::string_view(name) == "aclnnXllmKernelSparseFlashMla" + ? mla_api() + : metadata_api(); + launch = api.launch; + workspace = api.workspace; +} + +constexpr int64_t kSwaMaskMode = 4; +constexpr int64_t kNonCausalMaskMode = 0; +constexpr int64_t kNumKvHeads = 1; +constexpr int64_t kCmpCausalMaskMode = 3; +constexpr int64_t kWinRight = 0; +constexpr int64_t kTopkValueMode = 1; +constexpr bool kHasOriKv = true; +constexpr bool kReturnSoftmaxLse = false; + +torch::Tensor sparse_flash_mla_metadata( + const torch::Tensor& cu_seqlens_q, + const torch::Tensor& seqused_kv, + const std::optional& seqused_cmp_kv, + const std::optional& cmp_residual_kv, + int64_t num_heads_q, + int64_t head_dim, + int64_t max_seqlen_q, + int64_t max_seqlen_kv, + int64_t max_seqlen_cmp_kv, + int64_t cmp_topk, + int64_t cmp_ratio, + int64_t window_size, + const std::optional& ori_topk_length, + int64_t ori_topk) { + auto output = cu_seqlens_q.new_empty({optiling::SMLA_METADATA_TOTAL_SIZE}); + auto empty = cu_seqlens_q.new_empty({0}); + const int64_t batch_size = seqused_kv.numel(); + const int64_t win_left = window_size - 1; + const bool has_cmp_kv = cmp_ratio > 0; + const int64_t cmp_mask_mode = has_cmp_kv ? kCmpCausalMaskMode : 0; + char layout_q[] = "TND"; + char layout_kv[] = "PA_BBND"; + const auto cmp_lengths = seqused_cmp_kv.value_or(empty); + const auto residual = cmp_residual_kv.value_or(empty); + const auto ori_lengths = ori_topk_length.value_or(empty); + const int64_t ori_mask_mode = + ori_topk > 0 ? kNonCausalMaskMode : kSwaMaskMode; + EXEC_NPU_CMD_EXT(aclnnXllmKernelSparseFlashMlaMetadata, + cu_seqlens_q, + /*cu_seqlens_ori_kv=*/empty, + /*cu_seqlens_cmp_kv=*/empty, + /*seqused_q=*/empty, + seqused_kv, + cmp_lengths, + residual, + ori_lengths, + /*cmp_topk_length=*/empty, + num_heads_q, + kNumKvHeads, + head_dim, + batch_size, + max_seqlen_q, + max_seqlen_kv, + max_seqlen_cmp_kv, + ori_topk, + cmp_topk, + cmp_ratio, + ori_mask_mode, + cmp_mask_mode, + win_left, + kWinRight, + layout_q, + layout_kv, + kHasOriKv, + has_cmp_kv, + output); + return output; +} + +torch::Tensor sparse_flash_mla( + const torch::Tensor& q, + const torch::Tensor& kv, + const torch::Tensor& block_table, + const torch::Tensor& cu_seqlens_q, + const torch::Tensor& seqused_kv, + const std::optional& cmp_kv, + const std::optional& cmp_block_table, + const std::optional& cmp_indices, + const std::optional& seqused_cmp_kv, + const std::optional& cmp_residual_kv, + const std::optional& sinks, + const torch::Tensor& metadata, + double softmax_scale, + int64_t cmp_ratio, + int64_t window_size, + const std::optional& ori_sparse_indices, + const std::optional& ori_topk_length) { + auto output = torch::empty_like(q); + auto softmax_lse = torch::empty({0}, q.options().dtype(torch::kFloat32)); + const int64_t win_left = window_size - 1; + const bool has_cmp_kv = cmp_ratio > 0; + const int64_t cmp_mask_mode = has_cmp_kv ? kCmpCausalMaskMode : 0; + const std::optional absent; + const int64_t ori_mask_mode = + ori_sparse_indices.has_value() ? kNonCausalMaskMode : kSwaMaskMode; + char layout_q[] = "TND"; + char layout_kv[] = "PA_BBND"; + EXEC_NPU_CMD_EXT(aclnnXllmKernelSparseFlashMla, + q, + kv, + cmp_kv, + ori_sparse_indices, + cmp_indices, + block_table, + cmp_block_table, + cu_seqlens_q, + /*cu_seqlens_ori_kv=*/absent, + /*cu_seqlens_cmp_kv=*/absent, + /*seqused_q=*/absent, + seqused_kv, + seqused_cmp_kv, + cmp_residual_kv, + ori_topk_length, + /*cmp_topk_length=*/absent, + sinks, + metadata, + softmax_scale, + cmp_ratio, + ori_mask_mode, + cmp_mask_mode, + win_left, + kWinRight, + layout_q, + layout_kv, + kTopkValueMode, + kReturnSoftmaxLse, + output, + softmax_lse); + return output; +} + +TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { + m.def("prepare_ascendc_v41_mla() -> ()", []() { + mla_api(); + metadata_api(); + }); + m.def( + "sparse_flash_mla_metadata(Tensor cu_seqlens_q, Tensor seqused_kv, " + "Tensor? seqused_cmp_kv, Tensor? cmp_residual_kv, int num_heads_q, " + "int head_dim, int max_seqlen_q, int max_seqlen_kv, " + "int max_seqlen_cmp_kv, int cmp_topk, int cmp_ratio, int window_size, " + "Tensor? ori_topk_length=None, int ori_topk=0) -> Tensor"); + m.def( + "sparse_flash_mla(Tensor q, Tensor kv, Tensor block_table, " + "Tensor cu_seqlens_q, Tensor seqused_kv, Tensor? cmp_kv, " + "Tensor? cmp_block_table, Tensor? cmp_indices, Tensor? seqused_cmp_kv, " + "Tensor? cmp_residual_kv, Tensor? sinks, Tensor metadata, " + "float softmax_scale, int cmp_ratio, int window_size, " + "Tensor? ori_sparse_indices=None, Tensor? ori_topk_length=None) -> " + "Tensor"); +} + +TORCH_LIBRARY_IMPL(xllm_kernel, PrivateUse1, m) { + m.impl("sparse_flash_mla_metadata", TORCH_FN(sparse_flash_mla_metadata)); + m.impl("sparse_flash_mla", TORCH_FN(sparse_flash_mla)); +} + +} // namespace +} // namespace xllm_kernel diff --git a/xllm-kernel/python/xllm_kernel/_ascendc_opp.py b/xllm-kernel/python/xllm_kernel/_ascendc_opp.py index ebb54154eb..1f7f1739c1 100644 --- a/xllm-kernel/python/xllm_kernel/_ascendc_opp.py +++ b/xllm-kernel/python/xllm_kernel/_ascendc_opp.py @@ -6,6 +6,10 @@ from xllm_kernel import _npu_binding # noqa: F401 -_vendor = str(Path(__file__).resolve().parent / "ascendc_opp" / "xllm_kernel") +_opp = Path(__file__).resolve().parent / "ascendc_opp" +_vendors = [str(_opp / "xllm_kernel")] +_aicpu_vendor = _opp / "xllm_kernel_math" +if _aicpu_vendor.is_dir(): + _vendors.append(str(_aicpu_vendor)) _previous_vendors = os.environ.get("ASCEND_CUSTOM_OPP_PATH", "").split(os.pathsep) -os.environ["ASCEND_CUSTOM_OPP_PATH"] = os.pathsep.join(dict.fromkeys([_vendor, *filter(None, _previous_vendors)])) +os.environ["ASCEND_CUSTOM_OPP_PATH"] = os.pathsep.join(dict.fromkeys([*_vendors, *filter(None, _previous_vendors)])) diff --git a/xllm-kernel/python/xllm_kernel/_tilelang_config.py b/xllm-kernel/python/xllm_kernel/_tilelang_config.py new file mode 100644 index 0000000000..300ec7b8f5 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/_tilelang_config.py @@ -0,0 +1,11 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Shared pass settings for the Ascend TileLang programs.""" + +DEFAULT_ASCEND_PASS_CONFIGS = { + # Use raw pass-config strings to avoid hard dependency on + # tilelang.PassConfigKey export timing/version. + "tl.ascend_auto_sync": True, + "tl.ascend_memory_planning": True, + "tl.ascend_auto_cross_core_sync": True, + "tl.ascend_auto_cv_combine": True, +} diff --git a/xllm-kernel/python/xllm_kernel/catalog.py b/xllm-kernel/python/xllm_kernel/catalog.py index 8da29b04be..c6d40c91dd 100644 --- a/xllm-kernel/python/xllm_kernel/catalog.py +++ b/xllm-kernel/python/xllm_kernel/catalog.py @@ -61,6 +61,7 @@ def get_prepared(self) -> PreparedKernel: "xllm_kernel.ops.gemm", "xllm_kernel.ops.quantization", "xllm_kernel.ops.hyper_connection", + "xllm_kernel.ops.engram", "xllm_kernel.ops.kv_cache", "xllm_kernel.ops.moe", "xllm_kernel.ops.moe.mega", @@ -76,6 +77,7 @@ def get_prepared(self) -> PreparedKernel: "xllm_kernel.ops.attention.rainfusion", "xllm_kernel.ops.attention.dsa.indexer", "xllm_kernel.ops.attention.dsv4", + "xllm_kernel.ops.attention.dsv41", "xllm_kernel.ops.attention.dsa", "xllm_kernel.ops.positional_encoding", ) diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/__init__.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/__init__.py new file mode 100644 index 0000000000..a424eb4b8a --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/__init__.py @@ -0,0 +1,149 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Ascend kernels for DeepSeek V4.1 compressed and sliding-window attention.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from xllm_kernel.catalog import BackendModule, Operation +from xllm_kernel.platform import PlatformEnum +from xllm_kernel.registry import OpContract + +if TYPE_CHECKING: + import torch + + +TILELANG_OPERATIONS = tuple( + Operation( + OpContract(name, 1, mutates, False, name.rstrip("_")), + ( + BackendModule( + module="xllm_kernel.ops.attention.dsv41.tilelang", + platform=PlatformEnum.NPU, + requires=("torch_npu", "tilelang", "triton"), + implementations=(f"npu.tilelang.{name}",), + ), + ), + ) + for name, mutates in ( + ("v41_partial_rope_", ("value",)), + ("v41_swa_rope_cache_", ("value", "cache")), + ("v41_index_key_transform", ()), + ("v41_index_query_quant", ()), + ("v41_c2_pool_norm", ()), + ("v41_c2_decode_pool_norm", ()), + ) +) +(_PARTIAL_ROPE, _SWA_ROPE_CACHE, _INDEX_KEY_TRANSFORM, _INDEX_QUERY_QUANT, _C2_POOL_NORM, _C2_DECODE_POOL_NORM) = ( + TILELANG_OPERATIONS +) + + +def v41_partial_rope_( + value: torch.Tensor, cos: torch.Tensor, signed_sin: torch.Tensor, swap_offsets: torch.Tensor, inverse: bool +) -> None: + """Partial BF16 rotary embedding, token-major rows with head dimension 128 or 512.""" + _PARTIAL_ROPE.get_prepared().function(value, cos, signed_sin, swap_offsets, inverse) + + +def v41_swa_rope_cache_( + value: torch.Tensor, + cos: torch.Tensor, + signed_sin: torch.Tensor, + swap_offsets: torch.Tensor, + slots: torch.Tensor, + cache: torch.Tensor, +) -> None: + """Rotate BF16 KV rows and write each valid slot into the SWA cache.""" + _SWA_ROPE_CACHE.get_prepared().function(value, cos, signed_sin, swap_offsets, slots, cache) + + +def v41_index_key_transform(key: torch.Tensor, weight: torch.Tensor, cos_sin: torch.Tensor, eps: float) -> torch.Tensor: + """Normalize and rotate BF16 index keys with head dimension 128.""" + return _INDEX_KEY_TRANSFORM.get_prepared().function(key, weight, cos_sin, eps) + + +def v41_index_query_quant(query: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """Quantize 32 or 64 BF16 index query heads to INT8 with per-head FP16 scales.""" + return _INDEX_QUERY_QUANT.get_prepared().function(query) + + +def v41_c2_pool_norm(kv: torch.Tensor, scores: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor: + """Pool two C2 members and normalize each 512-element BF16 row.""" + return _C2_POOL_NORM.get_prepared().function(kv, scores, weight, eps) + + +def v41_c2_decode_pool_norm( + kv: torch.Tensor, + scores: torch.Tensor, + state_kv: torch.Tensor, + state_scores: torch.Tensor, + previous_rows: torch.Tensor, + weight: torch.Tensor, + eps: float, +) -> torch.Tensor: + """Pool current and previous C2 members selected by decode row indices.""" + return _C2_DECODE_POOL_NORM.get_prepared().function(kv, scores, state_kv, state_scores, previous_rows, weight, eps) + + +TRITON_OPERATIONS = tuple( + Operation( + OpContract(name, 1, mutates, False, name), + ( + BackendModule( + module="xllm_kernel.ops.attention.dsv41.triton", + platform=PlatformEnum.NPU, + requires=("torch_npu", "triton"), + implementations=(f"npu.triton.{name}",), + ), + ), + ) + for name, mutates in ( + ("v41_private_swa_metadata", ()), + ("v41_pack_private_swa", ("cache",)), + ("v41_split_packed_projection", ()), + ("v41_pack_prefill_swa", ()), + ) +) +(_PRIVATE_SWA_METADATA, _PACK_PRIVATE_SWA, _SPLIT_PACKED_PROJECTION, _PACK_PREFILL_SWA) = TRITON_OPERATIONS +ASCENDC_OPERATIONS = tuple( + Operation( + OpContract(name, 1, (), False, name), + ( + BackendModule( + module="xllm_kernel.ops.attention.dsv41.ascendc", + platform=PlatformEnum.NPU, + requires=("torch_npu",), + implementations=(f"npu.ascendc.{name}",), + ), + ), + ) + for name in ( + "quant_lightning_indexer_v2_metadata", + "quant_lightning_indexer_v2", + "sparse_flash_mla_metadata", + "sparse_flash_mla", + ) +) +(_INDEXER_METADATA, _INDEXER, _SPARSE_FLASH_MLA_METADATA, _SPARSE_FLASH_MLA) = ASCENDC_OPERATIONS +OPERATIONS = TILELANG_OPERATIONS + TRITON_OPERATIONS + ASCENDC_OPERATIONS + + +def private_swa_metadata( + seq_lens: torch.Tensor, table: torch.Tensor, width: int, window: int, block: int +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + return _PRIVATE_SWA_METADATA.get_prepared().function(seq_lens, table, width, window, block) + + +def pack_private_swa(ring: torch.Tensor, kv: torch.Tensor, slots: torch.Tensor, cache: torch.Tensor) -> None: + return _PACK_PRIVATE_SWA.get_prepared().function(ring, kv, slots, cache) + + +def split_packed_projection(packed: torch.Tensor, query_width: int) -> tuple[torch.Tensor, torch.Tensor]: + return _SPLIT_PACKED_PROJECTION.get_prepared().function(packed, query_width) + + +def pack_prefill_swa( + kv: torch.Tensor, ring: torch.Tensor, table: torch.Tensor, descriptors: torch.Tensor +) -> torch.Tensor: + return _PACK_PREFILL_SWA.get_prepared().function(kv, ring, table, descriptors) diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_compile.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_compile.py new file mode 100644 index 0000000000..c37510efdf --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_compile.py @@ -0,0 +1,50 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Prepare V4.1 TileLang launchers in a subprocess at model initialization. + +The worker loads the resulting libraries without importing TileLang's TVM +runtime alongside the CANN compiler used for W8A8 weight loading. +""" + +import fcntl +import shutil +import sys +from pathlib import Path +from typing import Any + +import tilelang +import torch_npu # noqa: F401 # Registers the NPU device for TileLang disk-cache deserialization. +from tilelang.cache import get_cache_dir + +from xllm_kernel.ops.attention.dsv41._tilelang import ( + c2_pool_norm as c2, +) +from xllm_kernel.ops.attention.dsv41._tilelang import ( + index_key_transform as key, +) +from xllm_kernel.ops.kv_cache._tilelang import v41_swa_rope_cache as swa +from xllm_kernel.ops.positional_encoding._tilelang import v41_partial_rope as rope +from xllm_kernel.ops.quantization._tilelang import v41_index_query_quant as query + + +def _compile(directory: Path, cores: int) -> None: + def emit(name: str, program: Any, configs: dict[str, bool]) -> None: + kernel = tilelang.compile(program, pass_configs=configs) + # The Ascend adapter loads a CDLL on both cache hits and misses. + # Its transient compiler output path is unset on a disk-cache hit. + shutil.copyfile(kernel.adapter.lib._name, directory / f"{name}.so") + + # TP/DP workers share TileLang's disk cache. Serialize cache publication. + with (Path(get_cache_dir()) / "xllm-dsv41.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + for dim in (128, 512): + for heads in (1, 8): + emit(f"rope_{dim}_{heads}", rope.build_v41_partial_rope_kernel(dim, heads, cores), rope.PASS_CONFIGS) + emit("swa", swa.build_v41_swa_rope_cache_kernel(512, cores), swa.PASS_CONFIGS) + emit("key", key.build_index_key_transform_kernel(vec_core_num=cores), key.INDEX_TRANSFORM_PASS_CONFIGS) + emit("query", query.build_index_query_quant_kernel(vec_core_num=cores), query.INDEX_QUERY_QUANT_PASS_CONFIGS) + emit("c2", c2.build_c2_pool_norm_kernel(vec_core_num=cores), c2.C2_PASS_CONFIGS) + emit("c2_decode", c2.build_c2_decode_pool_norm_kernel(vec_core_num=cores), c2.C2_PASS_CONFIGS) + + +if __name__ == "__main__": + _compile(Path(sys.argv[1]), int(sys.argv[2])) diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/__init__.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/__init__.py new file mode 100644 index 0000000000..6d6ae28c9e --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/__init__.py @@ -0,0 +1 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/c2_pool_norm.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/c2_pool_norm.py new file mode 100644 index 0000000000..0e96e26c64 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/c2_pool_norm.py @@ -0,0 +1,145 @@ +# Copyright 2026 The xLLM Authors. 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. +# You may obtain a copy of the License at +# +# https://github.com/xLLM-AI/xllm/blob/main/LICENSE +# +# 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. + +"""Fuse ratio-two FP32 gated pooling and the BF16 compressor RMSNorm.""" + +from typing import Any + +import tilelang.language as T + +from xllm_kernel._tilelang_config import DEFAULT_ASCEND_PASS_CONFIGS + +C2_HEAD_DIM = 512 +C2_MAX_GROUPS = 65536 +C2_MAX_STATE_ROWS = 1 << 21 +C2_PASS_CONFIGS = {**DEFAULT_ASCEND_PASS_CONFIGS, "tl.disable_safe_memory_legalize": True} + + +@T.macro +def _pool_norm(left, right, gate_left, gate_right, denom, weight_fp32, rounded, rms, eps): + T.tile.max(denom, gate_left, gate_right) + T.tile.sub(gate_left, gate_left, denom) + T.tile.sub(gate_right, gate_right, denom) + T.tile.exp(gate_left, gate_left) + T.tile.exp(gate_right, gate_right) + T.tile.add(denom, gate_left, gate_right) + T.tile.div(gate_left, gate_left, denom) + T.tile.div(gate_right, gate_right, denom) + T.tile.mul(left, left, gate_left) + T.tile.mul(right, right, gate_right) + T.tile.add(left, left, right) + + # Match the checkpoint's BF16 rounding between pooling and RMSNorm. + T.tile.cast(rounded, left, "CAST_RINT", C2_HEAD_DIM) + T.tile.cast(left, rounded, "CAST_NONE", C2_HEAD_DIM) + T.tile.mul(right, left, left) + T.reduce_sum(right, rms, dim=-1) + T.tile.mul(rms, rms, 1.0 / C2_HEAD_DIM) + T.tile.add(rms, rms, eps) + T.tile.rsqrt(rms, rms) + T.tile.broadcast(denom, rms) + T.tile.mul(left, left, denom) + T.tile.mul(left, left, weight_fp32) + T.tile.cast(rounded, left, "CAST_RINT", C2_HEAD_DIM) + + +def build_c2_pool_norm_kernel(*, vec_core_num: int) -> Any: + dim = C2_HEAD_DIM + max_groups = C2_MAX_GROUPS + vectors_per_block = 2 + + @T.prim_func + def c2_pool_norm( + kv: T.Tensor((max_groups, 2, dim), "float32"), + score: T.Tensor((max_groups, 2, dim), "float32"), + weight: T.Tensor((dim,), "bfloat16"), + output: T.Tensor((max_groups, dim), "bfloat16"), + groups: T.int32, + eps: T.float32, + ): + with T.Kernel(vec_core_num // vectors_per_block, is_npu=True) as (cid, vid): + worker = cid * vectors_per_block + vid + with T.Scope("V"): + left = T.alloc_ub((1, dim), "float32") + right = T.alloc_ub((1, dim), "float32") + gate_left = T.alloc_ub((1, dim), "float32") + gate_right = T.alloc_ub((1, dim), "float32") + denom = T.alloc_ub((1, dim), "float32") + weight_bf16 = T.alloc_ub((1, dim), "bfloat16") + weight_fp32 = T.alloc_ub((1, dim), "float32") + rounded = T.alloc_ub((1, dim), "bfloat16") + rms = T.alloc_ub((1,), "float32") + T.copy(weight[0], weight_bf16[0, :]) + T.tile.cast(weight_fp32, weight_bf16, "CAST_NONE", dim) + for batch in T.serial(T.ceildiv(groups, vec_core_num)): + row = batch * vec_core_num + worker + if row < groups: + T.copy(kv[row, 0, 0], left[0, :]) + T.copy(kv[row, 1, 0], right[0, :]) + T.copy(score[row, 0, 0], gate_left[0, :]) + T.copy(score[row, 1, 0], gate_right[0, :]) + _pool_norm(left, right, gate_left, gate_right, denom, weight_fp32, rounded, rms, eps) + T.copy(rounded[0, :], output[row, 0]) + + return c2_pool_norm + + +def build_c2_decode_pool_norm_kernel(*, vec_core_num: int) -> Any: + dim = C2_HEAD_DIM + max_groups = C2_MAX_GROUPS + max_state_rows = C2_MAX_STATE_ROWS + + @T.prim_func + def c2_decode_pool_norm( + kv: T.Tensor((max_groups, dim), "float32"), + score: T.Tensor((max_groups, dim), "float32"), + state_kv: T.Tensor((max_state_rows, dim), "float32"), + state_score: T.Tensor((max_state_rows, dim), "float32"), + previous_rows: T.Tensor((max_groups,), "int32"), + weight: T.Tensor((dim,), "bfloat16"), + output: T.Tensor((max_groups, dim), "bfloat16"), + groups: T.int32, + eps: T.float32, + ): + with T.Kernel(vec_core_num // 2, is_npu=True) as (cid, vid), T.Scope("V"): + worker = cid * 2 + vid + left = T.alloc_ub((1, dim), "float32") + right = T.alloc_ub((1, dim), "float32") + gate_left = T.alloc_ub((1, dim), "float32") + gate_right = T.alloc_ub((1, dim), "float32") + denom = T.alloc_ub((1, dim), "float32") + weight_bf16 = T.alloc_ub((1, dim), "bfloat16") + weight_fp32 = T.alloc_ub((1, dim), "float32") + rounded = T.alloc_ub((1, dim), "bfloat16") + rms = T.alloc_ub((1,), "float32") + T.copy(weight[0], weight_bf16[0, :]) + T.tile.cast(weight_fp32, weight_bf16, "CAST_NONE", dim) + for batch in T.serial(T.ceildiv(groups, vec_core_num)): + row = batch * vec_core_num + worker + if row < groups: + previous = previous_rows[row] + # Cache rows are nonnegative. A negative value encodes + # the index of a predecessor in this forward as -(i + 1). + if previous < 0: + T.copy(kv[-previous - 1, 0], left[0, :]) + T.copy(score[-previous - 1, 0], gate_left[0, :]) + else: + T.copy(state_kv[previous, 0], left[0, :]) + T.copy(state_score[previous, 0], gate_left[0, :]) + T.copy(kv[row, 0], right[0, :]) + T.copy(score[row, 0], gate_right[0, :]) + _pool_norm(left, right, gate_left, gate_right, denom, weight_fp32, rounded, rms, eps) + T.copy(rounded[0, :], output[row, 0]) + + return c2_decode_pool_norm diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/index_key_transform.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/index_key_transform.py new file mode 100644 index 0000000000..36c33b0fa2 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_tilelang/index_key_transform.py @@ -0,0 +1,97 @@ +# Copyright 2026 The xLLM Authors. 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. +# You may obtain a copy of the License at +# +# https://github.com/xLLM-AI/xllm/blob/main/LICENSE +# +# 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. + +"""Fuse the V4.1 index key RMSNorm and interleaved RoPE.""" + +import tilelang.language as T + +from xllm_kernel._tilelang_config import DEFAULT_ASCEND_PASS_CONFIGS + +INDEX_KEY_DIM = 128 +INDEX_ROPE_DIM = 64 +MAX_INDEX_ROWS = 65536 +INDEX_TRANSFORM_PASS_CONFIGS = {**DEFAULT_ASCEND_PASS_CONFIGS, "tl.disable_safe_memory_legalize": True} + + +def build_index_key_transform_kernel(*, vec_core_num: int): + dim, rope_dim = INDEX_KEY_DIM, INDEX_ROPE_DIM + max_rows = MAX_INDEX_ROWS + vectors_per_block = 2 + + @T.prim_func + def index_key_transform( + key: T.Tensor((max_rows, dim), "bfloat16"), + weight: T.Tensor((dim,), "bfloat16"), + cos_sin: T.Tensor((max_rows, rope_dim), "float32"), + output: T.Tensor((max_rows, dim), "bfloat16"), + num_rows: T.int32, + eps: T.float32, + ): + with T.Kernel(vec_core_num // vectors_per_block, is_npu=True) as (cid, vid): + worker = cid * vectors_per_block + vid + with T.Scope("V"): + key_bf16 = T.alloc_ub((1, dim), "bfloat16") + x = T.alloc_ub((1, dim), "float32") + square = T.alloc_ub((1, dim), "float32") + weight_bf16 = T.alloc_ub((1, dim), "bfloat16") + weight_fp32 = T.alloc_ub((1, dim), "float32") + rms = T.alloc_ub((1,), "float32") + tail_bf16 = T.alloc_ub((1, rope_dim), "bfloat16") + tail = T.alloc_ub((1, rope_dim), "float32") + swapped = T.alloc_ub((1, rope_dim), "float32") + packed_rope = T.alloc_ub((1, rope_dim), "float32") + cos_full = T.alloc_ub((1, rope_dim), "float32") + sin_full = T.alloc_ub((1, rope_dim), "float32") + cos_offsets = T.alloc_ub((1, rope_dim), "uint32") + sin_offsets = T.alloc_ub((1, rope_dim), "uint32") + swap_offsets = T.alloc_ub((1, rope_dim), "uint32") + signs = T.alloc_ub((1, rope_dim), "float32") + + for lane in T.serial(rope_dim): + cos_offsets[0, lane] = T.Cast("uint32", (lane // 2) * 4) + sin_offsets[0, lane] = T.Cast("uint32", (rope_dim // 2 + lane // 2) * 4) + swap_offsets[0, lane] = T.Cast("uint32", (lane // 2 * 2 + 1 - lane % 2) * 4) + signs[0, lane] = 2.0 * T.Cast("float32", lane % 2) - 1.0 + T.copy(weight[0], weight_bf16[0, :]) + T.tile.cast(weight_fp32, weight_bf16, "CAST_NONE", dim) + for batch in T.serial(T.ceildiv(num_rows, vec_core_num)): + row = batch * vec_core_num + worker + if row < num_rows: + T.copy(key[row, 0], key_bf16[0, :]) + T.tile.cast(x, key_bf16, "CAST_NONE", dim) + T.tile.mul(square, x, x) + T.reduce_sum(square, rms, dim=-1) + T.tile.mul(rms, rms, 1.0 / dim) + T.tile.add(rms, rms, eps) + T.tile.rsqrt(rms, rms) + T.tile.broadcast(square, rms) + T.tile.mul(x, x, square) + T.tile.mul(x, x, weight_fp32) + T.tile.cast(key_bf16, x, "CAST_RINT", dim) + + T.copy(key_bf16[0, dim - rope_dim : dim], tail_bf16[0, :]) + T.tile.cast(tail, tail_bf16, "CAST_NONE", rope_dim) + T.copy(cos_sin[row, 0], packed_rope[0, :]) + T.tile.gather(cos_full, packed_rope, cos_offsets, 0) + T.tile.gather(sin_full, packed_rope, sin_offsets, 0) + T.tile.gather(swapped, tail, swap_offsets, 0) + T.tile.mul(tail, tail, cos_full) + T.tile.mul(swapped, swapped, signs) + T.tile.mul(swapped, swapped, sin_full) + T.tile.add(tail, tail, swapped) + T.tile.cast(tail_bf16, tail, "CAST_RINT", rope_dim) + T.copy(tail_bf16[0, :], key_bf16[0, dim - rope_dim : dim]) + T.copy(key_bf16[0, :], output[row, 0]) + + return index_key_transform diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/__init__.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/__init__.py new file mode 100644 index 0000000000..6d6ae28c9e --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/__init__.py @@ -0,0 +1 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/packed_projection.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/packed_projection.py new file mode 100644 index 0000000000..ceee74b1cb --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/packed_projection.py @@ -0,0 +1,57 @@ +# Copyright 2026 The xLLM Authors. 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. +# You may obtain a copy of the License at +# +# https://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. +# ============================================================================== +"""Copy the two feature ranges of a packed projection into contiguous row-major tensors.""" + +import torch +import triton +import triton.language as tl + + +@triton.jit(do_not_specialize=["num_rows"]) +def _split_packed_projection_kernel( + packed, + query, + kv, + num_rows, + QUERY_WIDTH: tl.constexpr, + KV_WIDTH: tl.constexpr, + ROWS: tl.constexpr, + COLS: tl.constexpr, +): + rows = tl.program_id(0) * ROWS + tl.arange(0, ROWS) + cols = tl.program_id(1) * COLS + tl.arange(0, COLS) + active = rows[:, None] < num_rows + width: tl.constexpr = QUERY_WIDTH + KV_WIDTH + offsets = rows[:, None].to(tl.int64) + values = tl.load(packed + offsets * width + cols[None, :], active & (cols[None, :] < width), 0) + tl.store(query + offsets * QUERY_WIDTH + cols[None, :], values, active & (cols[None, :] < QUERY_WIDTH)) + tl.store( + kv + offsets * KV_WIDTH + (cols[None, :] - QUERY_WIDTH), + values, + active & (cols[None, :] >= QUERY_WIDTH) & (cols[None, :] < width), + ) + + +def split_packed_projection(packed: torch.Tensor, query_width: int) -> tuple[torch.Tensor, torch.Tensor]: + num_rows, width = packed.shape + kv_width = width - query_width + if num_rows <= 1: + return packed[:, :query_width], packed[:, query_width:] + query = packed.new_empty((num_rows, query_width)) + kv = packed.new_empty((num_rows, kv_width)) + cols = min(triton.next_power_of_2(width), 2048) + grid = (triton.cdiv(num_rows, 8), triton.cdiv(width, cols)) + _split_packed_projection_kernel[grid](packed, query, kv, num_rows, query_width, kv_width, 8, cols) + return query, kv diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/prefill_swa.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/prefill_swa.py new file mode 100644 index 0000000000..4b1c8a8ae0 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/prefill_swa.py @@ -0,0 +1,84 @@ +# Copyright 2026 The xLLM Authors. 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. +# You may obtain a copy of the License at +# +# https://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. +# ============================================================================== +"""Gather ring history and append current KV rows for V4.1 paged prefill attention.""" + +import torch +import triton +import triton.language as tl + + +@triton.jit +def _pack_prefill_swa_kernel( + kv, + ring, + table, + descriptors, + output, + KV_ROW: tl.constexpr, + KV_COL: tl.constexpr, + TABLE_ROW: tl.constexpr, + TABLE_COL: tl.constexpr, + TABLE_WIDTH: tl.constexpr, + BLOCK: tl.constexpr, + DIM: tl.constexpr, + ROWS: tl.constexpr, +): + page = tl.program_id(0) + desc = descriptors + page * 6 + seq = tl.load(desc) + row = tl.program_id(1) * ROWS + tl.arange(0, ROWS) + relative = tl.load(desc + 1) + row + history_start = tl.load(desc + 2) + past = tl.load(desc + 3) + input_start = tl.load(desc + 4) + length = tl.load(desc + 5) + history = (row < BLOCK) & (relative < past) + current = (row < BLOCK) & (relative >= past) & (relative < length) + position = history_start + relative + column = position // BLOCK % TABLE_WIDTH + physical = tl.load(table + seq * TABLE_ROW + column * TABLE_COL, history, 0) + slot = tl.maximum(physical, 0).to(tl.int64) * BLOCK + position % BLOCK + col = tl.arange(0, DIM) + old = tl.load(ring + slot[:, None] * DIM + col[None, :], history[:, None], 0) + source = (input_start + relative - past).to(tl.int64) + new = tl.load(kv + source[:, None] * KV_ROW + col[None, :] * KV_COL, current[:, None], 0) + target = page.to(tl.int64) * BLOCK + row + tl.store( + output + target[:, None] * DIM + col[None, :], tl.where(history[:, None], old, new), (row < BLOCK)[:, None] + ) + + +def pack_prefill_swa( + kv: torch.Tensor, ring: torch.Tensor, table: torch.Tensor, descriptors: torch.Tensor +) -> torch.Tensor: + pages = descriptors.size(0) + block, dim = ring.size(1), ring.size(-1) + packed = ring.new_empty((pages, block, 1, dim)) + rows = 8 + _pack_prefill_swa_kernel[(pages, triton.cdiv(block, rows))]( + kv, + ring, + table, + descriptors, + packed, + kv.stride(0), + kv.stride(-1), + *table.stride(), + max(1, table.size(1)), + block, + dim, + rows, + ) + return packed diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/private_swa.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/private_swa.py new file mode 100644 index 0000000000..e23a9947e0 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/_triton/private_swa.py @@ -0,0 +1,138 @@ +# Copyright 2026 The xLLM Authors. 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. +# You may obtain a copy of the License at +# +# https://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. +# ============================================================================== +"""Prepare private sliding-window KV pages for a block of queries without updating the committed ring.""" + +import torch +import triton +import triton.language as tl + + +@triton.jit +def _private_swa_metadata_kernel( + seq_lens, + table, + slots, + positions, + lengths, + sequence_lengths, + private_pages, + TABLE_ROWS: tl.constexpr, + TABLE_COLS: tl.constexpr, + COLUMNS: tl.constexpr, + WIDTH: tl.constexpr, + WINDOW: tl.constexpr, + BLOCK: tl.constexpr, + PAGES: tl.constexpr, + TOPK: tl.constexpr, + TILE: tl.constexpr, +): + owner = tl.program_id(0) + query = tl.program_id(1) + lane = tl.arange(0, TILE) + span: tl.constexpr = WINDOW + WIDTH + length = tl.load(seq_lens + owner).to(tl.int64) + prefix = length - WIDTH + if query == 0: + history = prefix - WINDOW + lane + index = tl.maximum(history, 0) + column = (index // BLOCK) % COLUMNS + block = tl.load(table + owner * TABLE_ROWS + column * TABLE_COLS, lane < WINDOW, 0) + slot = tl.maximum(block.to(tl.int64), 0) * BLOCK + index % BLOCK + tl.store(slots + owner * WINDOW + lane, tl.where(history >= 0, slot, -1), lane < WINDOW) + tl.store(private_pages + owner * PAGES + lane, owner * PAGES + lane, lane < PAGES) + tl.store(sequence_lengths + owner, tl.where(length > 0, span, 0)) + start = tl.minimum(tl.maximum(WINDOW - prefix, 0), span) + pos = start + lane + row = owner * WIDTH + query + tl.store(positions + row * TOPK + lane, tl.where((length > 0) & (pos < span), pos, -1), lane < TOPK) + tl.store(lengths + row, span - start) + + +def private_swa_metadata( + seq_lens: torch.Tensor, table: torch.Tensor, width: int, window: int, block: int +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + batch = seq_lens.numel() + pages = triton.cdiv(window + width, block) + topk = triton.cdiv(window + width, 128) * 128 + slots = seq_lens.new_empty((batch, window), dtype=torch.int64) + positions = seq_lens.new_empty((batch * width, 1, topk), dtype=torch.int32) + lengths = positions.new_empty((batch * width, 1)) + seq_lengths = positions.new_empty((batch,)) + private_pages = positions.new_empty((batch, pages)) + _private_swa_metadata_kernel[(batch, width)]( + seq_lens, + table, + slots, + positions, + lengths, + seq_lengths, + private_pages, + *table.stride(), + table.size(1), + width, + window, + block, + pages, + topk, + triton.next_power_of_2(topk), + ) + return slots, positions, lengths, seq_lengths, private_pages + + +@triton.jit +def _private_swa_pack_kernel( + ring, + kv, + slots, + cache, + KV_BATCH: tl.constexpr, + KV_ROW: tl.constexpr, + KV_COL: tl.constexpr, + WINDOW: tl.constexpr, + WIDTH: tl.constexpr, + CAPACITY: tl.constexpr, + DIM: tl.constexpr, + ROWS: tl.constexpr, +): + owner = tl.program_id(0) + row = tl.program_id(1) * ROWS + tl.arange(0, ROWS) + col = tl.arange(0, DIM) + slot = tl.load(slots + owner * WINDOW + row, row < WINDOW, -1) + past = tl.load(ring + tl.maximum(slot, 0)[:, None] * DIM + col[None, :], (slot >= 0)[:, None], 0) + current = tl.load( + kv + owner * KV_BATCH + (row[:, None] - WINDOW) * KV_ROW + col[None, :] * KV_COL, + ((row >= WINDOW) & (row < WINDOW + WIDTH))[:, None], + 0, + ) + value = tl.where((row < WINDOW)[:, None], past, current) + tl.store(cache + (owner * CAPACITY + row[:, None]) * DIM + col[None, :], value, (row < WINDOW + WIDTH)[:, None]) + + +def pack_private_swa(ring: torch.Tensor, kv: torch.Tensor, slots: torch.Tensor, cache: torch.Tensor) -> None: + batch, window = slots.shape + current = kv.view(batch, -1, cache.size(-1)) + width = current.size(1) + _private_swa_pack_kernel[(batch, triton.cdiv(window + width, 8))]( + ring.view(-1, cache.size(-1)), + current, + slots, + cache, + *current.stride(), + window, + width, + cache.size(1), + cache.size(-1), + 8, + ) diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/ascendc.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/ascendc.py new file mode 100644 index 0000000000..d958488128 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/ascendc.py @@ -0,0 +1,33 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Prepare the package-owned Ascend A3 candidate indexer and sparse MLA.""" + +import torch + +from xllm_kernel import _ascendc_opp # noqa: F401 +from xllm_kernel.ops.attention.dsv41 import ASCENDC_OPERATIONS +from xllm_kernel.platform import PlatformEnum +from xllm_kernel.registry import register_kernel + +torch.ops.xllm_kernel.prepare_ascendc_v41_indexer() +torch.ops.xllm_kernel.prepare_ascendc_v41_mla() + +for operation, domain in zip( + ASCENDC_OPERATIONS, + ( + "Device query offsets, committed compressed lengths and optional residual lengths on Ascend A3.", + "Paged INT8 index keys with FP16 scales and optional sparse candidate blocks on Ascend A3.", + "Device lengths for the sliding window and optional compressed KV cache on Ascend A3.", + "BF16 sliding-window attention with optional compressed sparse KV on Ascend A3.", + ), + strict=True, +): + name = operation.contract.operation + register_kernel( + name=operation.implementations[0], + platform=PlatformEnum.NPU, + execution_modes=("aclgraph", "eager"), + input_domain=domain, + solution="ascendc", + binding="aclnn", + contract=operation.contract, + )(getattr(torch.ops.xllm_kernel, name).default) diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/indexer.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/indexer.py new file mode 100644 index 0000000000..a914ba5a32 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/indexer.py @@ -0,0 +1,75 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Paged INT8 QLI V2 with candidate-block selection and reuse on Ascend A3.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from xllm_kernel.ops.attention.dsv41 import _INDEXER, _INDEXER_METADATA + +if TYPE_CHECKING: + import torch + + +def quant_lightning_indexer_v2_metadata( + query_offsets: torch.Tensor, + committed_lengths: torch.Tensor, + residual_lengths: torch.Tensor | None, + query_heads: int, + head_dim: int, + topk: int, + max_query_len: int, + max_committed_len: int, + compression_ratio: int, +) -> torch.Tensor: + return _INDEXER_METADATA.get_prepared().function( + query_offsets, + committed_lengths, + residual_lengths, + query_heads, + head_dim, + topk, + max_query_len, + max_committed_len, + compression_ratio, + ) + + +def quant_lightning_indexer_v2( + query: torch.Tensor, + key: torch.Tensor, + weights: torch.Tensor, + query_scale: torch.Tensor, + key_scale: torch.Tensor, + query_offsets: torch.Tensor, + committed_lengths: torch.Tensor, + residual_lengths: torch.Tensor | None, + block_table: torch.Tensor, + metadata: torch.Tensor, + candidate_blocks: torch.Tensor | None, + topk: int, + max_query_len: int, + compression_ratio: int, + candidate_mode: int, + candidate_count: int, + candidate_block_size: int, +) -> tuple[torch.Tensor, torch.Tensor]: + return _INDEXER.get_prepared().function( + query, + key, + weights, + query_scale, + key_scale, + query_offsets, + committed_lengths, + residual_lengths, + block_table, + metadata, + candidate_blocks, + topk, + max_query_len, + compression_ratio, + candidate_mode, + candidate_count, + candidate_block_size, + ) diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/mla.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/mla.py new file mode 100644 index 0000000000..3da7ce0cf9 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/mla.py @@ -0,0 +1,87 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Paged original and compressed KV attention for DeepSeek V4.1 on Ascend A3.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from xllm_kernel.ops.attention.dsv41 import _SPARSE_FLASH_MLA, _SPARSE_FLASH_MLA_METADATA + +if TYPE_CHECKING: + import torch + + +def sparse_flash_mla_metadata( + cu_seqlens_q: torch.Tensor, + seqused_kv: torch.Tensor, + seqused_cmp_kv: torch.Tensor | None, + cmp_residual_kv: torch.Tensor | None, + num_heads_q: int, + head_dim: int, + max_seqlen_q: int, + max_seqlen_kv: int, + max_seqlen_cmp_kv: int, + cmp_topk: int, + cmp_ratio: int, + window_size: int, + ori_topk_length: torch.Tensor | None = None, + ori_topk: int = 0, +) -> torch.Tensor: + """Generate device tiling from the lengths and optional sparse SWA selection.""" + return _SPARSE_FLASH_MLA_METADATA.get_prepared().function( + cu_seqlens_q, + seqused_kv, + seqused_cmp_kv, + cmp_residual_kv, + num_heads_q, + head_dim, + max_seqlen_q, + max_seqlen_kv, + max_seqlen_cmp_kv, + cmp_topk, + cmp_ratio, + window_size, + ori_topk_length, + ori_topk, + ) + + +def sparse_flash_mla( + q: torch.Tensor, + kv: torch.Tensor, + block_table: torch.Tensor, + cu_seqlens_q: torch.Tensor, + seqused_kv: torch.Tensor, + cmp_kv: torch.Tensor | None, + cmp_block_table: torch.Tensor | None, + cmp_indices: torch.Tensor | None, + seqused_cmp_kv: torch.Tensor | None, + cmp_residual_kv: torch.Tensor | None, + sinks: torch.Tensor | None, + metadata: torch.Tensor, + softmax_scale: float, + cmp_ratio: int, + window_size: int, + ori_sparse_indices: torch.Tensor | None = None, + ori_topk_length: torch.Tensor | None = None, +) -> torch.Tensor: + """Attend over the sliding window and selected compressed KV tokens.""" + return _SPARSE_FLASH_MLA.get_prepared().function( + q, + kv, + block_table, + cu_seqlens_q, + seqused_kv, + cmp_kv, + cmp_block_table, + cmp_indices, + seqused_cmp_kv, + cmp_residual_kv, + sinks, + metadata, + softmax_scale, + cmp_ratio, + window_size, + ori_sparse_indices, + ori_topk_length, + ) diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/tilelang.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/tilelang.py new file mode 100644 index 0000000000..04da49ead4 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/tilelang.py @@ -0,0 +1,180 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Launch the prepared TileLang kernels on the caller's current NPU stream.""" + +import ctypes +import os +import subprocess +import sys +import sysconfig +import tempfile +from functools import cache +from pathlib import Path +from typing import Any + +import torch + +from xllm_kernel.ops.attention.dsv41 import TILELANG_OPERATIONS +from xllm_kernel.platform import PlatformEnum +from xllm_kernel.registry import register_kernel + + +@cache +def prepare_v41_kernels() -> dict[str, Any]: + from xllm_kernel.ops._tilelang import VECTOR_CORES + + # The binary embeds Python. sys.executable can point at the server itself. + python = Path(sysconfig.get_path("scripts")) / f"python{sys.version_info.major}.{sys.version_info.minor}" + package = Path(__file__).resolve().parents[4] + env = os.environ.copy() + env["PYTHONPATH"] = os.pathsep.join(filter(None, (str(package), env.get("PYTHONPATH")))) + # TileLang and the CANN operator compiler used to load W8A8 weights + # can load incompatible TVM libraries. Only load the JIT launchers here. + with tempfile.TemporaryDirectory(prefix="xllm-dsv41-") as directory: + subprocess.run( + [str(python), "-m", "xllm_kernel.ops.attention.dsv41._compile", directory, str(VECTOR_CORES)], + env=env, + check=True, + ) + ptr, integer, real = ctypes.c_void_p, ctypes.c_int32, ctypes.c_float + signatures = { + **{f"rope_{dim}_{heads}": [ptr] * 4 + [integer] * 3 for dim in (128, 512) for heads in (1, 8)}, + "swa": [ptr] * 6 + [integer, integer], + "key": [ptr] * 4 + [integer, real], + "query": [ptr] * 3 + [integer], + "c2": [ptr] * 4 + [integer, real], + "c2_decode": [ptr] * 7 + [integer, real], + } + functions = {} + for name, arguments in signatures.items(): + call = ctypes.CDLL(str(Path(directory) / f"{name}.so")).call + call.argtypes = [*arguments, ptr] + call.restype = None + functions[name] = call + return functions + + +def _require_tensors(device: torch.device, dtype: torch.dtype, *values: torch.Tensor) -> None: + if device.type != "npu" or any(t.device != device or t.dtype != dtype or not t.is_contiguous() for t in values): + raise ValueError(f"expected contiguous {dtype} tensors on the same NPU, got inputs for {device}") + + +def _launch(name: str, tensors: tuple[torch.Tensor, ...], *scalars: int | float) -> None: + stream = torch.npu.current_stream(tensors[0].device).npu_stream + prepare_v41_kernels()[name](*(t.data_ptr() for t in tensors), *scalars, stream) + + +def _check_rope(value: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, offsets: torch.Tensor) -> None: + _require_tensors(value.device, torch.bfloat16, value) + _require_tensors(value.device, torch.float32, cos, sin) + _require_tensors(value.device, torch.int32, offsets) + if value.size(0) > 4096 or cos.shape != (value.size(0), 64) or sin.shape != cos.shape: + raise ValueError("expected at most 4096 rows with 64 rotary coefficients per row") + + +def _partial_rope( + value: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, offsets: torch.Tensor, inverse: bool +) -> None: + if value.ndim not in (2, 3) or value.size(-1) not in (128, 512) or offsets.numel() != 512: + raise ValueError("expected 128- or 512-wide RoPE heads and 512 swap offsets") + heads = value.size(1) if value.ndim == 3 else 1 + if not 1 <= heads <= 128: + raise ValueError("partial RoPE supports 1 to 128 heads") + _check_rope(value, cos, sin, offsets) + if value.size(0): + tile = 1 if heads % 8 else 8 + _launch(f"rope_{value.size(-1)}_{tile}", (value, cos, sin, offsets), value.size(0), heads, int(inverse)) + + +def _swa_rope_cache( + value: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + offsets: torch.Tensor, + slots: torch.Tensor, + cache: torch.Tensor, +) -> None: + if value.ndim != 2 or value.size(1) != 512 or cache.ndim != 2 or cache.size(1) != 512: + raise ValueError("SWA RoPE needs 512-wide KV rows") + if not 0 < cache.size(0) <= 2**21 or slots.numel() != value.size(0) or offsets.numel() < 64: + raise ValueError("invalid SWA cache capacity, slots or swap offsets") + _check_rope(value, cos, sin, offsets) + _require_tensors(value.device, torch.bfloat16, cache) + _require_tensors(value.device, torch.int32, slots) + if value.size(0): + _launch("swa", (value, cos, sin, offsets, slots, cache), value.size(0), cache.size(0)) + + +def _index_key(key: torch.Tensor, weight: torch.Tensor, cos_sin: torch.Tensor, eps: float) -> torch.Tensor: + if key.ndim != 2 or key.size(1) != 128 or key.size(0) > 65536 or weight.numel() != 128: + raise ValueError("index key transform requires up to 65536 rows of width 128") + if cos_sin.shape != (key.size(0), 64): + raise ValueError("expected 64 rotary coefficients per key") + _require_tensors(key.device, torch.bfloat16, key, weight) + _require_tensors(key.device, torch.float32, cos_sin) + out = torch.empty_like(key) + if key.size(0): + _launch("key", (key, weight, cos_sin, out), key.size(0), eps) + return out + + +def _index_query(query: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + if query.ndim != 3 or not 0 < query.size(0) <= 4096 or query.size(1) not in (32, 64) or query.size(2) != 128: + raise ValueError("index query quantization expects [1..4096, 32 or 64, 128]") + _require_tensors(query.device, torch.bfloat16, query) + codes = torch.empty_like(query, dtype=torch.int8) + scales = query.new_empty(query.shape[:2], dtype=torch.float16) + _launch("query", (query, codes, scales), scales.numel()) + return codes, scales + + +def _check_c2(kv: torch.Tensor, scores: torch.Tensor, weight: torch.Tensor) -> None: + if kv.size(0) > 65536 or scores.shape != kv.shape or weight.numel() != 512: + raise ValueError("invalid C2 row count, scores or normalization weight") + _require_tensors(kv.device, torch.float32, kv, scores) + _require_tensors(kv.device, torch.bfloat16, weight) + + +def _c2(kv: torch.Tensor, scores: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor: + if kv.ndim != 3 or kv.shape[1:] != (2, 512): + raise ValueError("C2 prefill requires pairs of 512-wide rows") + _check_c2(kv, scores, weight) + out = weight.new_empty((kv.size(0), 512)) + if kv.size(0): + _launch("c2", (kv, scores, weight, out), kv.size(0), eps) + return out + + +def _c2_decode( + kv: torch.Tensor, + scores: torch.Tensor, + state: torch.Tensor, + state_scores: torch.Tensor, + previous: torch.Tensor, + weight: torch.Tensor, + eps: float, +) -> torch.Tensor: + if kv.ndim != 2 or kv.size(1) != 512 or previous.shape != (kv.size(0),): + raise ValueError("C2 decode requires 512-wide rows and one previous-row index per row") + if state.ndim != 2 or state.size(1) != 512 or not 0 < state.size(0) <= 2**21 or state.shape != state_scores.shape: + raise ValueError("invalid C2 decode state") + _check_c2(kv, scores, weight) + _require_tensors(kv.device, torch.float32, state, state_scores) + _require_tensors(kv.device, torch.int32, previous) + out = weight.new_empty(kv.shape) + if kv.size(0): + _launch("c2_decode", (kv, scores, state, state_scores, previous, weight, out), kv.size(0), eps) + return out + + +for operation, implementation in zip( + TILELANG_OPERATIONS, (_partial_rope, _swa_rope_cache, _index_key, _index_query, _c2, _c2_decode), strict=True +): + register_kernel( + name=operation.implementations[0], + platform=PlatformEnum.NPU, + execution_modes=("eager", "aclgraph"), + input_domain=operation.contract.operation, + solution="tilelang", + binding="python", + contract=operation.contract, + )(implementation) diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/triton.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/triton.py new file mode 100644 index 0000000000..ee35b9a602 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/triton.py @@ -0,0 +1,29 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Register the Ascend Triton entry points for dsv41.""" + +from xllm_kernel.ops.attention.dsv41 import TRITON_OPERATIONS +from xllm_kernel.ops.attention.dsv41._triton.packed_projection import split_packed_projection +from xllm_kernel.ops.attention.dsv41._triton.prefill_swa import pack_prefill_swa +from xllm_kernel.ops.attention.dsv41._triton.private_swa import pack_private_swa, private_swa_metadata +from xllm_kernel.platform import PlatformEnum +from xllm_kernel.registry import register_kernel + +for operation, implementation in zip( + TRITON_OPERATIONS, + ( + private_swa_metadata, + pack_private_swa, + split_packed_projection, + pack_prefill_swa, + ), + strict=True, +): + register_kernel( + name=operation.implementations[0], + platform=PlatformEnum.NPU, + execution_modes=("eager", "aclgraph"), + input_domain=operation.contract.numerical_mode, + solution="triton", + binding="python", + contract=operation.contract, + )(implementation) diff --git a/xllm-kernel/python/xllm_kernel/ops/engram/__init__.py b/xllm-kernel/python/xllm_kernel/ops/engram/__init__.py new file mode 100644 index 0000000000..67d62791b0 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/engram/__init__.py @@ -0,0 +1,132 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Engram embedding kernel contracts.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from xllm_kernel.catalog import BackendModule, Operation +from xllm_kernel.platform import PlatformEnum +from xllm_kernel.registry import OpContract + +if TYPE_CHECKING: + import torch + + +TRITON_OPERATIONS = tuple( + Operation( + OpContract(name, 1, mutates, False, name), + ( + BackendModule( + module="xllm_kernel.ops.engram.triton", + platform=PlatformEnum.NPU, + requires=("torch_npu", "triton"), + implementations=(f"npu.triton.{name}",), + ), + ), + ) + for name, mutates in ( + ("engram_prepare_unit_query_hash", ()), + ("engram_write_unit_query_history", ("cache",)), + ("engram_hash_rows", ()), + ("engram_lookup_int8", ()), + ("engram_gate", ()), + ) +) +(_PREPARE_UNIT_QUERY_HASH, _WRITE_UNIT_QUERY_HISTORY, _HASH_ROWS, _LOOKUP_INT8, _ENGRAM_GATE) = TRITON_OPERATIONS +OPERATIONS = TRITON_OPERATIONS + + +def prepare_unit_query_hash( + ids: torch.Tensor, + positions: torch.Tensor, + dead: torch.Tensor, + slots: torch.Tensor, + blocks: torch.Tensor, + block_size: int, + token_map: torch.Tensor, + ngram: int, +) -> tuple[torch.Tensor, torch.Tensor]: + return _PREPARE_UNIT_QUERY_HASH.get_prepared().function( + ids, positions, dead, slots, blocks, block_size, token_map, ngram + ) + + +def write_unit_query_history(cache: torch.Tensor, compressed: torch.Tensor, slots: torch.Tensor) -> None: + return _WRITE_UNIT_QUERY_HISTORY.get_prepared().function(cache, compressed, slots) + + +def hash_rows( + compressed_ids: torch.Tensor, + positions: torch.Tensor, + requests: torch.Tensor, + starts: torch.Tensor, + history: torch.Tensor | None, + block_table: torch.Tensor | None, + block_size: int, + replay: torch.Tensor | None, + replay_rows: torch.Tensor | None, + multipliers: torch.Tensor, + primes: torch.Tensor, + offsets: torch.Tensor, + pad_id: int, +) -> torch.Tensor: + return _HASH_ROWS.get_prepared().function( + compressed_ids, + positions, + requests, + starts, + history, + block_table, + block_size, + replay, + replay_rows, + multipliers, + primes, + offsets, + pad_id, + ) + + +def lookup_int8( + indices: torch.Tensor, + weight: torch.Tensor, + scale: torch.Tensor, + head_start: int, + local_heads: int, + vocab_start: int, + vocab_end: int, + width: int, + quant_block: int, + *, + mapped_host: bool = False, + e8m0: bool, +) -> torch.Tensor: + return _LOOKUP_INT8.get_prepared().function( + indices, + weight, + scale, + head_start, + local_heads, + vocab_start, + vocab_end, + width, + quant_block, + mapped_host=mapped_host, + e8m0=e8m0, + ) + + +def engram_gate( + residual: torch.Tensor, + gate_hidden: torch.Tensor, + projected: torch.Tensor, + query_weight: torch.Tensor, + key_weight: torch.Tensor, + mask: torch.Tensor, + eps: float, + clamp: float, +) -> torch.Tensor: + return _ENGRAM_GATE.get_prepared().function( + residual, gate_hidden, projected, query_weight, key_weight, mask, eps, clamp + ) diff --git a/xllm-kernel/python/xllm_kernel/ops/engram/_triton/__init__.py b/xllm-kernel/python/xllm_kernel/ops/engram/_triton/__init__.py new file mode 100644 index 0000000000..6d6ae28c9e --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/engram/_triton/__init__.py @@ -0,0 +1 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. diff --git a/xllm-kernel/python/xllm_kernel/ops/engram/_triton/engram.py b/xllm-kernel/python/xllm_kernel/ops/engram/_triton/engram.py new file mode 100644 index 0000000000..c46212d272 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/engram/_triton/engram.py @@ -0,0 +1,396 @@ +# Copyright 2026 The xLLM Authors. 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. +# You may obtain a copy of the License at +# +# https://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. +# ============================================================================== +"""Device hashing and quantized row lookup for DeepSeek-V4.1 Engram.""" + +from __future__ import annotations + +import torch +import triton +import triton.language as tl + + +@triton.jit(do_not_specialize=["tokens", "table_cols", "table_stride"]) +def _prepare_unit_query_hash_kernel( + Ids, + Positions, + Dead, + Slots, + Blocks, + Map, + Compressed, + Starts, + tokens, + table_cols, + table_stride, + col_stride: tl.constexpr, + vocab: tl.constexpr, + block_size: tl.constexpr, + ngram: tl.constexpr, + tile: tl.constexpr, +): + row = tl.program_id(0) * tile + tl.arange(0, tile) + valid = row < tokens + position = tl.load(Positions + row, valid, 0).to(tl.int64) + token = tl.load(Ids + row, valid, 0) + token = tl.minimum(tl.maximum(token, 0), vocab - 1) + compact = tl.load(Map + token, valid, 0) + dead = tl.load(Dead + row, valid, 0).to(tl.int1) + tl.store(Compressed + row, tl.where(dead, -1, compact), valid) + + # Only ngram - 1 earlier tokens can enter this hash. Each link must + # match both the logical position and the physical SWA slot of its predecessor. + start = position + linked = valid + for distance in tl.static_range(1, ngram): + # Ascend can lower a masked contiguous load to a vector transfer. + # Keep its base inside the allocation even at the first token of a graph. + previous_row = tl.minimum(tl.maximum(row - distance, 0), tokens - 1) + table_row = tl.minimum(tl.maximum(row - distance + 1, 0), tokens - 1) + linked = linked & (row >= distance) + previous_pos = tl.load(Positions + previous_row).to(tl.int64) + previous_slot = tl.load(Slots + previous_row).to(tl.int64) + prior = tl.maximum(position - distance, 0) + col = prior // block_size % table_cols + block = tl.load(Blocks + table_row * table_stride + col * col_stride).to(tl.int64) + linked = linked & (previous_pos == position - distance) & (previous_slot >= 0) + linked = linked & (previous_slot == block * block_size + prior % block_size) + start = tl.where(linked, previous_pos, start) + tl.store(Starts + row, start, valid) + + +def prepare_unit_query_hash( + ids: torch.Tensor, + positions: torch.Tensor, + dead: torch.Tensor, + slots: torch.Tensor, + blocks: torch.Tensor, + block_size: int, + token_map: torch.Tensor, + ngram: int, +) -> tuple[torch.Tensor, torch.Tensor]: + tokens = ids.numel() + compressed = torch.empty(tokens, dtype=torch.int32, device=ids.device) + starts = torch.empty(tokens, dtype=positions.dtype, device=ids.device) + _prepare_unit_query_hash_kernel[(triton.cdiv(tokens, 16),)]( + ids.contiguous(), + positions.contiguous(), + dead.contiguous(), + slots.contiguous(), + blocks, + token_map, + compressed, + starts, + tokens, + blocks.size(1), + blocks.stride(0), + blocks.stride(1), + token_map.numel(), + block_size, + ngram, + 16, + ) + return compressed, starts + + +@triton.jit(do_not_specialize=["tokens"]) +def _write_unit_query_history_kernel(Cache, Compressed, Slots, tokens, TILE: tl.constexpr): + row = tl.program_id(0) * TILE + tl.arange(0, TILE) + slot = tl.load(Slots + row, row < tokens, -1).to(tl.int64) + compact = tl.load(Compressed + row, row < tokens, 0) + tl.store(Cache + slot, compact, (row < tokens) & (slot >= 0)) + + +def write_unit_query_history(cache: torch.Tensor, compressed: torch.Tensor, slots: torch.Tensor) -> None: + # Hashing must finish reading the old ring before any program writes current tokens. + tokens = compressed.numel() + _write_unit_query_history_kernel[(triton.cdiv(tokens, 64),)](cache, compressed, slots.contiguous(), tokens, 64) + + +@triton.jit(do_not_specialize=["tokens", "table_rows", "table_cols", "table_row_stride", "table_col_stride"]) +def _hash_kernel( + Comp, + Positions, + Requests, + Starts, + History, + Blocks, + Replay, + ReplayRows, + Multipliers, + Primes, + Offsets, + Out, + tokens, + LAYERS: tl.constexpr, + NGRAM: tl.constexpr, + HEADS: tl.constexpr, + PAD: tl.constexpr, + table_rows, + table_cols, + table_row_stride, + table_col_stride, + BLOCK_SIZE: tl.constexpr, + SLOTS: tl.constexpr, + REPLAY_WIDTH: tl.constexpr, + TOKEN_TILE: tl.constexpr, + HEAD_TILE: tl.constexpr, +) -> None: + row = tl.program_id(0) * TOKEN_TILE + tl.arange(0, TOKEN_TILE) + layer = tl.program_id(1) + valid = row < tokens + position = tl.load(Positions + row, valid, 0) + request = tl.load(Requests + row, valid, 0) + start = tl.load(Starts + row, valid, 0) + rolling = tl.full((TOKEN_TILE,), 0, tl.int64) + blocked = tl.full((TOKEN_TILE,), False, tl.int1) + head = tl.arange(0, HEAD_TILE) + head_cols: tl.constexpr = (NGRAM - 1) * HEADS + if REPLAY_WIDTH: + replay_row = tl.load(ReplayRows + request, valid, 0) > 0 + for shift in tl.static_range(NGRAM): + lookback = position - shift + in_batch = lookback >= start + batch_index = tl.maximum(row - shift, 0) + source = tl.load(Comp + batch_index, valid & in_batch, 0) + if SLOTS: + previous = tl.maximum(lookback, 0) + column = previous // BLOCK_SIZE % table_cols + table_row = tl.minimum(request, table_rows - 1) + block = tl.load(Blocks + table_row * table_row_stride + column * table_col_stride, valid & ~in_batch, 0).to( + tl.int64 + ) + address = tl.minimum(tl.maximum(block * BLOCK_SIZE + previous % BLOCK_SIZE, 0), SLOTS - 1) + cached = tl.load(History + address, valid & ~in_batch, 0) + source = tl.where(in_batch, source, cached) + if REPLAY_WIDTH: + column = tl.minimum(tl.maximum(lookback - start + REPLAY_WIDTH, 0), REPLAY_WIDTH - 1) + override = valid & replay_row & ~in_batch + replay_id = tl.load(Replay + request * REPLAY_WIDTH + column, override, 0) + source = tl.where(override, replay_id, source) + blocked = blocked | (lookback < 0) | (source == -1) + value = tl.where(blocked, PAD, source).to(tl.int64) + weight = tl.load(Multipliers + layer * NGRAM + shift) + rolling = rolling ^ (value * weight) + if shift > 0: + columns = (shift - 1) * HEADS + head + param = layer * head_cols + columns + prime = tl.load(Primes + param, head < HEADS, 1) + offset = tl.load(Offsets + param, head < HEADS, 0) + remainder = rolling[:, None] % prime[None, :] + remainder = tl.where(remainder < 0, remainder + prime[None, :], remainder) + result = remainder + offset[None, :] + output = (row.to(tl.int64) * LAYERS + layer) * head_cols + tl.store(Out + output[:, None] + columns[None, :], result, valid[:, None] & (head[None, :] < HEADS)) + + +def hash_rows( + compressed_ids: torch.Tensor, + positions: torch.Tensor, + requests: torch.Tensor, + starts: torch.Tensor, + history: torch.Tensor | None, + block_table: torch.Tensor | None, + block_size: int, + replay: torch.Tensor | None, + replay_rows: torch.Tensor | None, + multipliers: torch.Tensor, + primes: torch.Tensor, + offsets: torch.Tensor, + pad_id: int, +) -> torch.Tensor: + tokens = compressed_ids.numel() + layers, ngrams, heads = primes.shape + output = torch.empty((tokens, layers, ngrams * heads), dtype=torch.int32, device=positions.device) + use_history = history is not None and block_table is not None + _hash_kernel[(triton.cdiv(tokens, 16), layers)]( + compressed_ids, + positions, + requests, + starts, + history, + block_table, + replay, + replay_rows, + multipliers, + primes, + offsets, + output, + tokens, + layers, + ngrams + 1, + heads, + pad_id, + block_table.shape[0] if use_history else 0, + block_table.shape[1] if use_history else 0, + block_table.stride(0) if use_history else 0, + block_table.stride(1) if use_history else 0, + block_size, + history.numel() if use_history else 0, + replay.size(1) if replay is not None else 0, + 16, + triton.next_power_of_2(heads), + ) + return output + + +@triton.jit +def _lookup_kernel( + Indices, + Weight, + Scale, + Out, + INDEX_STRIDE_TOKEN: tl.constexpr, + INDEX_STRIDE_HEAD: tl.constexpr, + HEAD_START: tl.constexpr, + HEADS: tl.constexpr, + LOCAL_HEADS: tl.constexpr, + START: tl.constexpr, + END: tl.constexpr, + WIDTH: tl.constexpr, + COLUMN_TILE: tl.constexpr, + QUANT_BLOCK: tl.constexpr, + HOST: tl.constexpr, + E8M0: tl.constexpr, +) -> None: + row = tl.program_id(0) + token = row // LOCAL_HEADS + head = HEAD_START + row % LOCAL_HEADS + index = tl.load(Indices + token * INDEX_STRIDE_TOKEN + head * INDEX_STRIDE_HEAD, head < HEADS, -1) + owned = (index >= START) & (index < END) + local = tl.where(owned, index.to(tl.int64) - START, 0) + if HOST: + weight = tl.load(Weight).to(tl.pointer_type(tl.int8)) + if E8M0: + scale = tl.load(Scale).to(tl.pointer_type(tl.uint8)) + else: + scale = tl.load(Scale).to(tl.pointer_type(tl.float32)) + else: + weight = Weight + scale = Scale + col = tl.arange(0, COLUMN_TILE) + valid_col = col < WIDTH + value = tl.load(weight + local * WIDTH + col, owned & valid_col, 0).to(tl.float32) + group = col // QUANT_BLOCK + scale_value = tl.load(scale + local * (WIDTH // QUANT_BLOCK) + group, owned & valid_col, 0) + if E8M0: + bits = scale_value.to(tl.int32) << 23 + bits = tl.where(scale_value == 0, 0x00400000, bits) + scale_value = bits.to(tl.float32, bitcast=True) + tl.store(Out + row * WIDTH + col, (value * scale_value).to(tl.bfloat16), valid_col) + + +def lookup_int8( + indices: torch.Tensor, + weight: torch.Tensor, + scale: torch.Tensor, + head_start: int, + local_heads: int, + vocab_start: int, + vocab_end: int, + width: int, + quant_block: int, + *, + mapped_host: bool = False, + e8m0: bool, +) -> torch.Tensor: + output = torch.empty((indices.size(0), local_heads, width), dtype=torch.bfloat16, device=indices.device) + if output.numel(): + _lookup_kernel[(indices.size(0) * local_heads,)]( + indices, + weight, + scale, + output, + indices.stride(0), + indices.stride(1), + head_start, + indices.size(1), + local_heads, + vocab_start, + vocab_end, + width, + triton.next_power_of_2(width), + quant_block, + mapped_host, + e8m0, + ) + return output + + +@triton.jit +def _engram_gate_kernel( + residual, + gate_hidden, + projected, + query_weight, + key_weight, + mask, + output, + EPS: tl.constexpr, + CLAMP: tl.constexpr, + HEADS: tl.constexpr, + DIM: tl.constexpr, + TILE: tl.constexpr, +): + row = tl.program_id(0) + token = row // HEADS + head = row % HEADS + col = tl.arange(0, TILE) + keep = col < DIM + offset = row * DIM + col + base = token * (HEADS + 1) * DIM + hidden = tl.load(gate_hidden + offset, keep, 0).to(tl.float32) + key = tl.load(projected + base + head * DIM + col, keep, 0).to(tl.float32) + qw = tl.load(query_weight + head * DIM + col, keep, 0).to(tl.float32) + kw = tl.load(key_weight + head * DIM + col, keep, 0).to(tl.float32) + dot = tl.sum(((hidden * qw) * kw) * key, axis=0) + hidden_rms = tl.rsqrt(tl.sum(hidden * hidden, axis=0) / DIM + EPS) + key_rms = tl.rsqrt(tl.sum(key * key, axis=0) / DIM + EPS) + score = ((dot * hidden_rms) * key_rms) * (DIM**-0.5) + magnitude = tl.sqrt(tl.maximum(tl.abs(score), CLAMP)) + gate = tl.sigmoid(tl.where(score < 0, -magnitude, magnitude)) + gate = tl.where(tl.load(mask + token), gate, 0.0) + value = tl.load(projected + base + HEADS * DIM + col, keep, 0).to(tl.float32) + previous = tl.load(residual + offset, keep, 0).to(tl.float32) + tl.store(output + offset, previous + gate * value, keep) + + +def engram_gate( + residual: torch.Tensor, + gate_hidden: torch.Tensor, + projected: torch.Tensor, + query_weight: torch.Tensor, + key_weight: torch.Tensor, + mask: torch.Tensor, + eps: float, + clamp: float, +) -> torch.Tensor: + tokens, heads, dim = residual.shape + output = torch.empty_like(residual) + _engram_gate_kernel[(tokens * heads,)]( + residual, + gate_hidden, + projected, + query_weight, + key_weight, + mask, + output, + eps, + clamp, + heads, + dim, + triton.next_power_of_2(dim), + enable_fp_fusion=False, + ) + return output diff --git a/xllm-kernel/python/xllm_kernel/ops/engram/triton.py b/xllm-kernel/python/xllm_kernel/ops/engram/triton.py new file mode 100644 index 0000000000..94bcb5ff0d --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/engram/triton.py @@ -0,0 +1,36 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Register the Ascend Triton entry points for engram.""" + +from xllm_kernel.platform import PlatformEnum, current_platform +from xllm_kernel.registry import register_kernel + +if current_platform.is_npu(): + from xllm_kernel.ops.engram import TRITON_OPERATIONS + from xllm_kernel.ops.engram._triton.engram import ( + engram_gate, + hash_rows, + lookup_int8, + prepare_unit_query_hash, + write_unit_query_history, + ) + + for operation, implementation in zip( + TRITON_OPERATIONS, + ( + prepare_unit_query_hash, + write_unit_query_history, + hash_rows, + lookup_int8, + engram_gate, + ), + strict=True, + ): + register_kernel( + name=operation.implementations[0], + platform=PlatformEnum.NPU, + execution_modes=("eager", "aclgraph"), + input_domain=operation.contract.numerical_mode, + solution="triton", + binding="python", + contract=operation.contract, + )(implementation) diff --git a/xllm-kernel/python/xllm_kernel/ops/hyper_connection/__init__.py b/xllm-kernel/python/xllm_kernel/ops/hyper_connection/__init__.py index c1cfbc020e..9466ec3388 100644 --- a/xllm-kernel/python/xllm_kernel/ops/hyper_connection/__init__.py +++ b/xllm-kernel/python/xllm_kernel/ops/hyper_connection/__init__.py @@ -13,6 +13,7 @@ import torch HC_PRE_CONTRACT = OpContract("hc_pre", 1, (), False, "hyper_connection_pre") +HC_PRE_DELAYED_CONTRACT = OpContract("hc_pre_delayed", 1, (), False, "hyper_connection_delayed_pre") HC_POST_CONTRACT = OpContract("hc_post", 1, (), False, "hyper_connection_post") OPERATIONS = tuple( @@ -27,9 +28,9 @@ ), ), ) - for contract in (HC_PRE_CONTRACT, HC_POST_CONTRACT) + for contract in (HC_PRE_CONTRACT, HC_POST_CONTRACT, HC_PRE_DELAYED_CONTRACT) ) -HC_PRE_OPERATION, HC_POST_OPERATION = OPERATIONS +HC_PRE_OPERATION, HC_POST_OPERATION, HC_PRE_DELAYED_OPERATION = OPERATIONS def hc_pre( @@ -51,3 +52,27 @@ def hc_pre( def hc_post(x: torch.Tensor, residual: torch.Tensor, post: torch.Tensor, comb: torch.Tensor) -> torch.Tensor: """Combine [B, S, D] output and [B, S, HC, D] residual into fresh storage.""" return HC_POST_OPERATION.get_prepared().function(x, residual, post, comb) + + +def has_hc_pre_delayed() -> bool: + """Report whether the loaded vendor supports delayed HC pre on this SoC.""" + from xllm_kernel.ops.hyper_connection.ascendc import HAS_HC_PRE_DELAYED + + return HAS_HC_PRE_DELAYED + + +def hc_pre_delayed( + x: torch.Tensor, + hc_fn: torch.Tensor, + hc_scale: torch.Tensor, + hc_base: torch.Tensor, + pre_mix: torch.Tensor, + hc_mult: int, + sinkhorn_iters: int, + norm_eps: float, + hc_eps: float, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Apply the previous pre-mix to x and produce the next pre, post and combination weights.""" + return HC_PRE_DELAYED_OPERATION.get_prepared().function( + x, hc_fn, hc_scale, hc_base, pre_mix, hc_mult, sinkhorn_iters, norm_eps, hc_eps + ) diff --git a/xllm-kernel/python/xllm_kernel/ops/hyper_connection/ascendc.py b/xllm-kernel/python/xllm_kernel/ops/hyper_connection/ascendc.py index 6ea132e1b9..7380cbfd44 100644 --- a/xllm-kernel/python/xllm_kernel/ops/hyper_connection/ascendc.py +++ b/xllm-kernel/python/xllm_kernel/ops/hyper_connection/ascendc.py @@ -4,7 +4,7 @@ import torch from xllm_kernel import _ascendc_opp # noqa: F401 -from xllm_kernel.ops.hyper_connection import HC_POST_CONTRACT, HC_PRE_CONTRACT +from xllm_kernel.ops.hyper_connection import HC_POST_CONTRACT, HC_PRE_CONTRACT, HC_PRE_DELAYED_CONTRACT from xllm_kernel.platform import PlatformEnum from xllm_kernel.registry import register_kernel @@ -27,3 +27,15 @@ binding="aclnn", contract=HC_POST_CONTRACT, )(torch.ops.xllm_kernel.hc_post.default) + +HAS_HC_PRE_DELAYED = torch.ops.xllm_kernel.supports_fused_hc_pre() +if HAS_HC_PRE_DELAYED: + register_kernel( + name="npu.ascendc.hc_pre_delayed", + platform=PlatformEnum.NPU, + execution_modes=("eager", "aclgraph"), + input_domain="Ascend A3 BF16 residual with four streams and FP32 pre-mix and gating weights.", + solution="ascendc", + binding="aclnn", + contract=HC_PRE_DELAYED_CONTRACT, + )(torch.ops.xllm_kernel.hc_pre_delayed.default) diff --git a/xllm-kernel/python/xllm_kernel/ops/kv_cache/_tilelang/__init__.py b/xllm-kernel/python/xllm_kernel/ops/kv_cache/_tilelang/__init__.py new file mode 100644 index 0000000000..6d6ae28c9e --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/kv_cache/_tilelang/__init__.py @@ -0,0 +1 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. diff --git a/xllm-kernel/python/xllm_kernel/ops/kv_cache/_tilelang/v41_swa_rope_cache.py b/xllm-kernel/python/xllm_kernel/ops/kv_cache/_tilelang/v41_swa_rope_cache.py new file mode 100644 index 0000000000..37e2493d50 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/kv_cache/_tilelang/v41_swa_rope_cache.py @@ -0,0 +1,73 @@ +# Copyright 2026 The xLLM Authors. 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. +# You may obtain a copy of the License at +# +# https://github.com/xLLM-AI/xllm/blob/main/LICENSE +# +# 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. + +"""Rotate V4.1 KV and store valid rows in the sliding-window cache.""" + +from typing import Any + +import tilelang.language as T + +from xllm_kernel.ops.positional_encoding._tilelang.v41_partial_rope import MAX_TOKENS, ROPE_WIDTH +from xllm_kernel.ops.positional_encoding._tilelang.v41_partial_rope import PASS_CONFIGS as ROPE_PASS_CONFIGS + +MAX_CACHE_ROWS = 1 << 21 +PASS_CONFIGS = { + **ROPE_PASS_CONFIGS, + "tl.ascend_auto_cross_core_sync": False, + "tl.ascend_auto_cv_combine": False, +} + + +def build_v41_swa_rope_cache_kernel(head_dim: int, vec_cores: int) -> Any: + width = ROPE_WIDTH + + @T.prim_func + def v41_swa_rope_cache( + value: T.Tensor((MAX_TOKENS, head_dim), "bfloat16"), + cos: T.Tensor((MAX_TOKENS, width), "float32"), + signed_sin: T.Tensor((MAX_TOKENS, width), "float32"), + swap_offsets: T.Tensor((8, width), "uint32"), + slots: T.Tensor((MAX_TOKENS,), "int32"), + cache: T.Tensor((MAX_CACHE_ROWS, head_dim), "bfloat16"), + tokens: T.int32, + cache_rows: T.int32, + ): + with T.Kernel(vec_cores // 2, is_npu=True) as (cid, vid), T.Scope("V"): + kv = T.alloc_ub((1, head_dim), "bfloat16") + tail = T.alloc_ub((1, width), "bfloat16") + rotated = T.alloc_ub((1, width), "float32") + swapped = T.alloc_ub((1, width), "float32") + coefficients = T.alloc_ub((1, width), "float32") + offsets = T.alloc_ub((1, width), "uint32") + T.copy(swap_offsets[0:1, :], offsets) + for iteration in T.serial(T.ceildiv(tokens, vec_cores)): + row = cid * 2 + vid + iteration * vec_cores + if row < tokens: + T.copy(value[row, :], kv[0, :]) + T.copy(kv[0, head_dim - width :], tail[0, :]) + T.tile.cast(rotated, tail, "CAST_NONE", width) + T.tile.gather(swapped, rotated, offsets, 0) + T.copy(cos[row, :], coefficients[0, :]) + T.tile.mul(rotated, rotated, coefficients) + T.copy(signed_sin[row, :], coefficients[0, :]) + T.tile.mul(swapped, swapped, coefficients) + T.tile.add(rotated, rotated, swapped) + T.tile.cast(tail, rotated, "CAST_RINT", width) + T.copy(tail[0, :], value[row, head_dim - width :]) + slot = slots[row] + if slot >= 0 and slot < cache_rows: + T.copy(tail[0, :], kv[0, head_dim - width :]) + T.copy(kv[0, :], cache[slot, :]) + + return v41_swa_rope_cache diff --git a/xllm-kernel/python/xllm_kernel/ops/moe/__init__.py b/xllm-kernel/python/xllm_kernel/ops/moe/__init__.py index b6613603a4..6cd191c849 100644 --- a/xllm-kernel/python/xllm_kernel/ops/moe/__init__.py +++ b/xllm-kernel/python/xllm_kernel/ops/moe/__init__.py @@ -19,6 +19,8 @@ "moe_grouped_matmul_swiglu_quant", 1, (), False, "moe_grouped_matmul_swiglu_quant" ) +DISPATCH_FFN_COMBINE = OpContract("dispatch_ffn_combine", 1, (), False, "w8a8_ep_dispatch_ffn_combine") + ASCENDC_OPERATIONS = tuple( Operation( contract, @@ -31,9 +33,15 @@ ), ), ) - for contract in (DEQUANT_SWIGLU_QUANT, MOE_GATING_TOP_K_HASH, MOE_INIT_ROUTING_V3, MOE_GROUPED_MATMUL_SWIGLU_QUANT) + for contract in ( + DEQUANT_SWIGLU_QUANT, + MOE_GATING_TOP_K_HASH, + MOE_INIT_ROUTING_V3, + MOE_GROUPED_MATMUL_SWIGLU_QUANT, + DISPATCH_FFN_COMBINE, + ) ) -_DEQUANT_SWIGLU, _HASH_GATE, _ROUTING_V3, _GROUPED_SWIGLU = ASCENDC_OPERATIONS +_DEQUANT_SWIGLU, _HASH_GATE, _ROUTING_V3, _GROUPED_SWIGLU, _DISPATCH_FFN_COMBINE = ASCENDC_OPERATIONS MOE_DISTRIBUTE_OPERATIONS = ("moe_distribute_dispatch_v2", "moe_distribute_combine_v2") TORCH_OPERATIONS, ACLNN_OPERATIONS = ( tuple( @@ -71,6 +79,31 @@ FUSED_MOE_GMM1_OPERATIONS = (MOE_INIT_ROUTING_V3.operation, MOE_GROUPED_MATMUL_SWIGLU_QUANT.operation) +def has_dispatch_ffn_combine() -> bool: + from xllm_kernel.ops.moe.ascendc import HAS_DISPATCH_FFN_COMBINE + + return HAS_DISPATCH_FFN_COMBINE + + +def dispatch_ffn_combine( + x: torch.Tensor, + weight1: torch.Tensor, + weight2: torch.Tensor, + expert_ids: torch.Tensor, + scale1: torch.Tensor, + scale2: torch.Tensor, + probs: torch.Tensor, + active_mask: torch.Tensor, + group: str, + max_output_size: int, + swiglu_limit: float, +) -> torch.Tensor: + """Run fused EP dispatch, W8A8 expert projections, and combine with packed NZ expert weights.""" + return _DISPATCH_FFN_COMBINE.get_prepared().function( + x, weight1, weight2, expert_ids, scale1, scale2, probs, active_mask, group, max_output_size, swiglu_limit + ) + + def has_fused_moe_gmm1() -> bool: """Return whether the startup provider supports both routing V3 and fused GMM1.""" from xllm_kernel.ops.moe.ascendc import HAS_FUSED_MOE_GMM1 diff --git a/xllm-kernel/python/xllm_kernel/ops/moe/ascendc.py b/xllm-kernel/python/xllm_kernel/ops/moe/ascendc.py index a59e485520..5f7a52d1f2 100644 --- a/xllm-kernel/python/xllm_kernel/ops/moe/ascendc.py +++ b/xllm-kernel/python/xllm_kernel/ops/moe/ascendc.py @@ -6,6 +6,7 @@ from xllm_kernel import _ascendc_opp # noqa: F401 from xllm_kernel.ops.moe import ( DEQUANT_SWIGLU_QUANT, + DISPATCH_FFN_COMBINE, MOE_GATING_TOP_K_HASH, MOE_GROUPED_MATMUL_SWIGLU_QUANT, MOE_INIT_ROUTING_V3, @@ -13,6 +14,7 @@ from xllm_kernel.platform import PlatformEnum from xllm_kernel.registry import OpContract, register_kernel +HAS_DISPATCH_FFN_COMBINE = torch.ops.xllm_kernel.has_dispatch_ffn_combine() HAS_FUSED_MOE_GMM1 = torch.ops.xllm_kernel.prepare_ascendc_moe() @@ -31,6 +33,8 @@ def _register(contract: OpContract, input_domain: str) -> None: _register(DEQUANT_SWIGLU_QUANT, "NPU gate/up tensors with quantization scales for the selected SwiGLU mode.") _register(MOE_GATING_TOP_K_HASH, "NPU floating-point logits and optional bias or token-to-expert lookup.") +if HAS_DISPATCH_FFN_COMBINE: + _register(DISPATCH_FFN_COMBINE, "EP source rows, packed W8A8 expert weights, router weights and an active mask.") if HAS_FUSED_MOE_GMM1: _register(MOE_INIT_ROUTING_V3, "NPU token rows and INT32 expert IDs, with a half-open active expert range.") _register(MOE_GROUPED_MATMUL_SWIGLU_QUANT, "NPU W8A8 expert inputs, NZ weights and V3 expert/count pairs.") diff --git a/xllm-kernel/python/xllm_kernel/ops/normalization/__init__.py b/xllm-kernel/python/xllm_kernel/ops/normalization/__init__.py index ccc3a92542..fe8ca1cd3e 100644 --- a/xllm-kernel/python/xllm_kernel/ops/normalization/__init__.py +++ b/xllm-kernel/python/xllm_kernel/ops/normalization/__init__.py @@ -16,6 +16,7 @@ FUSED_ADD_GEMMA_RMS_NORM_CONTRACT = OpContract( "fused_add_gemma_rms_norm", 1, (), False, "fp32_residual_gemma_norm_cast" ) +RMS_NORM_CAST_CONTRACT = OpContract("rms_norm_cast", 1, (), False, "rms_norm_bf16_and_fp32") RMS_NORM_GATED_CONTRACT = OpContract("rms_norm_gated", 1, (), False, "fp32_rms_norm_silu_gate") RMS_NORM_DYNAMIC_QUANT_CONTRACT = OpContract("rms_norm_dynamic_quant", 1, (), False, "rms_norm_per_row_int8_quant") LAYER_NORM_CONTRACT = OpContract("layer_norm", 1, (), False, "fp32_norm_cast") @@ -93,6 +94,18 @@ ) +RMS_NORM_CAST_OPERATION = Operation( + RMS_NORM_CAST_CONTRACT, + ( + BackendModule( + module="xllm_kernel.ops.normalization.ascendc", + platform=PlatformEnum.NPU, + requires=("torch_npu",), + implementations=("npu.ascendc.rms_norm_cast",), + ), + ), +) + RMS_NORM_GATED_OPERATION = Operation( RMS_NORM_GATED_CONTRACT, ( @@ -121,6 +134,7 @@ FUSED_ADD_RMS_NORM_OPERATION, FUSED_ADD_GEMMA_RMS_NORM_OPERATION, RMS_NORM_GATED_OPERATION, + RMS_NORM_CAST_OPERATION, RMS_NORM_DYNAMIC_QUANT_OPERATION, LAYER_NORM_OPERATION, RMS_NORM_OPERATION, @@ -178,6 +192,17 @@ def gemma_rms_norm(value: torch.Tensor, weight: torch.Tensor, eps: float) -> tor return GEMMA_RMS_NORM_OPERATION.get_prepared().function(value, weight, eps) +def has_rms_norm_cast() -> bool: + from xllm_kernel.ops.normalization.ascendc import HAS_RMS_NORM_CAST + + return HAS_RMS_NORM_CAST + + +def rms_norm_cast(input: torch.Tensor, weight: torch.Tensor, eps: float) -> tuple[torch.Tensor, torch.Tensor]: + """Return normalized activations in input precision and FP32 for MoE routing.""" + return RMS_NORM_CAST_OPERATION.get_prepared().function(input, weight, eps) + + def rms_norm_gated(value: torch.Tensor, gate: torch.Tensor, weight: torch.Tensor, eps: float = 1e-6) -> torch.Tensor: """Apply last-dimension RMSNorm and multiply by SiLU of the matching gate.""" return RMS_NORM_GATED_OPERATION.get_prepared().function(value, gate, weight, eps) diff --git a/xllm-kernel/python/xllm_kernel/ops/normalization/ascendc.py b/xllm-kernel/python/xllm_kernel/ops/normalization/ascendc.py index 5d995b90bd..d03bbfc046 100644 --- a/xllm-kernel/python/xllm_kernel/ops/normalization/ascendc.py +++ b/xllm-kernel/python/xllm_kernel/ops/normalization/ascendc.py @@ -6,6 +6,7 @@ from xllm_kernel import _ascendc_opp # noqa: F401 from xllm_kernel.ops.normalization import ( FUSED_ADD_GEMMA_RMS_NORM_CONTRACT, + RMS_NORM_CAST_CONTRACT, RMS_NORM_DYNAMIC_QUANT_CONTRACT, RMS_NORM_GATED_CONTRACT, ) @@ -14,6 +15,17 @@ torch.ops.xllm_kernel.prepare_gamma_add_rms_norm() torch.ops.xllm_kernel.prepare_ascendc_normalization() +HAS_RMS_NORM_CAST = torch.ops.xllm_kernel.supports_rms_norm_cast() +if HAS_RMS_NORM_CAST: + register_kernel( + name="npu.ascendc.rms_norm_cast", + platform=PlatformEnum.NPU, + execution_modes=("eager", "aclgraph"), + input_domain="A2/A3 nonempty FP16 or BF16 rows and a matching 1D norm weight.", + solution="ascendc", + binding="aclnn", + contract=RMS_NORM_CAST_CONTRACT, + )(torch.ops.xllm_kernel.rms_norm_cast.default) register_kernel( name="npu.ascendc.fused_add_gemma_rms_norm", platform=PlatformEnum.NPU, diff --git a/xllm-kernel/python/xllm_kernel/ops/positional_encoding/_tilelang/v41_partial_rope.py b/xllm-kernel/python/xllm_kernel/ops/positional_encoding/_tilelang/v41_partial_rope.py new file mode 100644 index 0000000000..f2506c356e --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/positional_encoding/_tilelang/v41_partial_rope.py @@ -0,0 +1,80 @@ +# Copyright 2026 The xLLM Authors. 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. +# You may obtain a copy of the License at +# +# https://github.com/xLLM-AI/xllm/blob/main/LICENSE +# +# 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. + +"""V4.1 interleaved partial RoPE with FP32 coefficients.""" + +from typing import Any + +import tilelang.language as T + +from xllm_kernel._tilelang_config import DEFAULT_ASCEND_PASS_CONFIGS + +ROPE_WIDTH = 64 +MAX_TOKENS = 4096 +MAX_HEADS = 128 +PASS_CONFIGS = {**DEFAULT_ASCEND_PASS_CONFIGS, "tl.disable_safe_memory_legalize": True} + + +def build_v41_partial_rope_kernel(head_dim: int, tile_heads: int, vec_cores: int) -> Any: + width = ROPE_WIDTH + max_rows = MAX_TOKENS * MAX_HEADS + tile_elements = tile_heads * width + + @T.prim_func + def v41_partial_rope( + value: T.Tensor((max_rows, head_dim), "bfloat16"), + cos: T.Tensor((MAX_TOKENS, width), "float32"), + signed_sin: T.Tensor((MAX_TOKENS, width), "float32"), + swap_offsets: T.Tensor((8, width), "uint32"), + tokens: T.int32, + heads: T.int32, + inverse: T.int32, + ): + with T.Kernel(vec_cores // 2, is_npu=True) as (cid, vid), T.Scope("V"): + elements = T.alloc_ub((tile_heads, width), "bfloat16") + rotated = T.alloc_ub((tile_heads, width), "float32") + swapped = T.alloc_ub((tile_heads, width), "float32") + coefficients = T.alloc_ub((1, width), "float32") + broadcast = T.alloc_ub((tile_heads, width), "float32") + offsets = T.alloc_ub((tile_heads, width), "uint32") + T.copy(swap_offsets[:tile_heads, :], offsets) + tiles = tokens * (heads // tile_heads) + for iteration in T.serial(T.ceildiv(tiles, vec_cores)): + tile = cid * 2 + vid + iteration * vec_cores + if tile < tiles: + first = tile * tile_heads + token = first // heads + T.copy(value[first : first + tile_heads, head_dim - width :], elements) + T.tile.cast(rotated, elements, "CAST_NONE", tile_elements) + T.tile.gather(swapped, rotated, offsets, 0) + T.copy(cos[token : token + 1, :], coefficients) + if tile_heads == 1: + T.tile.mul(rotated, rotated, coefficients) + else: + T.tile.broadcast(broadcast, coefficients) + T.tile.mul(rotated, rotated, broadcast) + T.copy(signed_sin[token : token + 1, :], coefficients) + if inverse != 0: + T.tile.mul(coefficients, coefficients, -1.0) + if tile_heads == 1: + T.tile.mul(swapped, swapped, coefficients) + else: + T.tile.broadcast(broadcast, coefficients) + T.tile.mul(swapped, swapped, broadcast) + # Match the reference's separate FP32 products before BF16 rounding. + T.tile.add(rotated, rotated, swapped) + T.tile.cast(elements, rotated, "CAST_RINT", tile_elements) + T.copy(elements, value[first : first + tile_heads, head_dim - width :]) + + return v41_partial_rope diff --git a/xllm-kernel/python/xllm_kernel/ops/quantization/_tilelang/__init__.py b/xllm-kernel/python/xllm_kernel/ops/quantization/_tilelang/__init__.py new file mode 100644 index 0000000000..6d6ae28c9e --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/quantization/_tilelang/__init__.py @@ -0,0 +1 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. diff --git a/xllm-kernel/python/xllm_kernel/ops/quantization/_tilelang/v41_index_query_quant.py b/xllm-kernel/python/xllm_kernel/ops/quantization/_tilelang/v41_index_query_quant.py new file mode 100644 index 0000000000..235e936df6 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/quantization/_tilelang/v41_index_query_quant.py @@ -0,0 +1,77 @@ +# Copyright 2026 The xLLM Authors. 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. +# You may obtain a copy of the License at +# +# https://github.com/xLLM-AI/xllm/blob/main/LICENSE +# +# 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. + +"""Quantize V4.1 index queries with one FP16 scale per head.""" + +from typing import Any + +import tilelang.language as T + +from xllm_kernel._tilelang_config import DEFAULT_ASCEND_PASS_CONFIGS + +INDEX_QUERY_DIM = 128 +MAX_QUERY_HEADS = 4096 * 64 +INDEX_QUERY_QUANT_PASS_CONFIGS = {**DEFAULT_ASCEND_PASS_CONFIGS, "tl.disable_safe_memory_legalize": True} + + +def build_index_query_quant_kernel(*, vec_core_num: int) -> Any: + dim = INDEX_QUERY_DIM + capacity = MAX_QUERY_HEADS + tile_heads = 16 + size = tile_heads * dim + + @T.prim_func + def index_query_quant( + query: T.Tensor((capacity, dim), "bfloat16"), + codes: T.Tensor((capacity, dim), "int8"), + scales: T.Tensor((capacity,), "float16"), + heads: T.int32, + ) -> None: + with T.Kernel(vec_core_num // 2, is_npu=True) as (cid, vid), T.Scope("V"): + worker = cid * 2 + vid + source = T.alloc_ub((tile_heads, dim), "bfloat16") + values = T.alloc_ub((tile_heads, dim), "float32") + scratch = T.alloc_ub((tile_heads, dim), "float32") + scale = T.alloc_ub((tile_heads,), "float32") + rounded_scale = T.alloc_ub((tile_heads,), "float16") + rounded_codes = T.alloc_ub((tile_heads, dim), "int32") + cast_codes = T.alloc_ub((tile_heads, dim), "float16") + output = T.alloc_ub((tile_heads, dim), "int8") + for batch in T.serial(T.ceildiv(heads // tile_heads, vec_core_num)): + start = (batch * vec_core_num + worker) * tile_heads + if start < heads: + T.copy(query[start, 0], source) + T.tile.cast(values, source, "CAST_NONE", size) + T.tile.abs(scratch, values) + T.reduce_max(scratch, scale, dim=-1) + T.tile.mul(scale, scale, 1.0 / 127.0) + T.tile.max(scale, scale, 2.0**-24) + T.tile.cast(rounded_scale, scale, "CAST_RINT", tile_heads) + T.copy(rounded_scale, scales[start]) + # The indexer consumes FP16 scales. Quantize with the + # rounded value to match the existing Tensor path. + T.tile.cast(scale, rounded_scale, "CAST_NONE", tile_heads) + T.tile.broadcast(scratch, scale, axis=1) + T.tile.div(values, values, scratch) + T.tile.min(values, values, 127.0) + T.tile.max(values, values, -127.0) + T.tile.cast(rounded_codes, values, "CAST_RINT", size) + # A direct INT32-to-FP16 cast on A3 uses DEQSCALE. These + # rounded INT8-range values are exactly representable in FP32. + T.tile.cast(values, rounded_codes, "CAST_NONE", size) + T.tile.cast(cast_codes, values, "CAST_RINT", size) + T.tile.cast(output, cast_codes, "CAST_RINT", size) + T.copy(output, codes[start, 0]) + + return index_query_quant diff --git a/xllm-kernel/setup.py b/xllm-kernel/setup.py index e899aa353f..771e387723 100644 --- a/xllm-kernel/setup.py +++ b/xllm-kernel/setup.py @@ -19,7 +19,7 @@ npu_root = Path(npu_spec.origin).parent ascend_root = Path(os.environ.get("NPU_HOME_PATH") or os.environ["ASCEND_HOME_PATH"]) atb_root = Path(os.environ["ATB_HOME_PATH"]) - ascendc_vendor = Path("xllm_kernel/ascendc_opp/xllm_kernel") + ascendc_opp = Path("xllm_kernel/ascendc_opp") class NpuBuildExtension(BuildExtension): def build_extensions(self) -> None: @@ -86,7 +86,8 @@ def run(self) -> None: with tempfile.TemporaryDirectory(dir=build) as output: subprocess.run(["cmake", "--install", str(build), "--prefix", output], check=True) - vendor = Path(output) / "packages/vendors/xllm_kernel" + vendors = Path(output) / "packages/vendors" + vendor = vendors / "xllm_kernel" headers = vendor / "op_api/include" (headers / "aclnn_xllm_kernel_gamma_add_rms_norm.h").unlink(missing_ok=True) gamma = source / "gamma_add_rms_norm" @@ -113,18 +114,20 @@ def run(self) -> None: header = source / component / "op_host/op_api" / f"aclnn_xllm_kernel_{component}.h" shutil.copy2(header, headers) shutil.copy2(gamma / "CANN_LICENSE.txt", vendor) + for provenance in sorted(source.glob("*/SOURCE.txt")): + shutil.copy2(provenance, vendor / f"{provenance.parent.name}_SOURCE.txt") paths = [Path(self.build_lib)] if self.inplace: paths.append(Path("python")) for package in paths: - destination = package / ascendc_vendor + destination = package / ascendc_opp if destination.exists(): shutil.rmtree(destination) - shutil.copytree(vendor, destination, symlinks=True) + shutil.copytree(vendors, destination, symlinks=True) def get_outputs(self) -> list[str]: - vendor = Path(self.build_lib) / ascendc_vendor - return [*super().get_outputs(), *(str(path) for path in vendor.rglob("*") if path.is_file())] + vendors = Path(self.build_lib) / ascendc_opp + return [*super().get_outputs(), *(str(path) for path in vendors.rglob("*") if path.is_file())] extensions.append( CppExtension( @@ -153,6 +156,8 @@ def get_outputs(self) -> list[str]: "csrc/npu/reshape_paged_cache.cpp", "csrc/npu/sparse_attention.cpp", "csrc/npu/sparse_indexing.cpp", + "csrc/npu/v41_quant_indexer.cpp", + "csrc/npu/v41_sparse_mla.cpp", "csrc/npu/top_k_top_p.cpp", "csrc/npu/sampling_bindings.cpp", ], diff --git a/xllm/_npu_runtime.py b/xllm/_npu_runtime.py index 93b1f34b88..913ae6b27b 100644 --- a/xllm/_npu_runtime.py +++ b/xllm/_npu_runtime.py @@ -41,9 +41,11 @@ def configure_npu_runtime(binary_path: str) -> Path | None: current process; changing LD_LIBRARY_PATH only affects future processes. """ binary = Path(binary_path) - kernel_vendor = binary.absolute().parent.parent / "xllm_kernel/ascendc_opp/xllm_kernel" - if kernel_vendor.is_dir(): - _prepend_env_path("ASCEND_CUSTOM_OPP_PATH", kernel_vendor) + kernel_opp = binary.absolute().parent.parent / "xllm_kernel/ascendc_opp" + for name in ("xllm_kernel_math", "xllm_kernel"): + vendor = kernel_opp / name + if vendor.is_dir(): + _prepend_env_path("ASCEND_CUSTOM_OPP_PATH", vendor) opp_root = binary.resolve().parent / "opp" if not os.path.lexists(opp_root): diff --git a/xllm/core/platform/npu/startup.cpp b/xllm/core/platform/npu/startup.cpp index f2eb229627..a0823c922b 100644 --- a/xllm/core/platform/npu/startup.cpp +++ b/xllm/core/platform/npu/startup.cpp @@ -119,10 +119,9 @@ bool configure_bundled_npu_ops() { ModelConfig::get_instance().model_impl()); // Native and Python operators both need the package registered before ACL // initializes. - const fs::path kernel_vendor = - host.parent_path().parent_path() / "xllm_kernel/ascendc_opp/xllm_kernel"; - const bool has_kernel_vendor = fs::is_directory(kernel_vendor); - if (!has_bundle && !has_kernel_vendor) { + const fs::path kernel_opp = + host.parent_path().parent_path() / "xllm_kernel/ascendc_opp"; + if (!has_bundle && !fs::is_directory(kernel_opp)) { return true; } if (has_bundle && @@ -140,10 +139,13 @@ bool configure_bundled_npu_ops() { if (custom != nullptr) { existing = absl::StrSplit(custom, ':', absl::SkipEmpty()); } - if (has_kernel_vendor && - std::find(existing.begin(), existing.end(), kernel_vendor.string()) == - existing.end()) { - existing.push_back(kernel_vendor.string()); + for (const char* name : {"xllm_kernel", "xllm_kernel_math"}) { + const fs::path vendor = kernel_opp / name; + if (fs::is_directory(vendor) && + std::find(existing.begin(), existing.end(), vendor.string()) == + existing.end()) { + existing.push_back(vendor.string()); + } } const char* opp = std::getenv("ASCEND_OPP_PATH"); const fs::path system_vendors = From 5fde4bf4002dd2c9ba21b32ef3b2d62d5f163201 Mon Sep 17 00:00:00 2001 From: PixelFlat <329975279+PixelFlat@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:44:17 +0800 Subject: [PATCH 3/6] test: cover V4.1 TileLang and fused Ascend operators. --- xllm-kernel/test/npu/conftest.py | 11 ++ .../npu/test_ascendc_normalization_npu.py | 16 ++- .../npu/test_dsv41_sparse_attention_npu.py | 77 +++++++++++++ .../test/npu/test_dsv41_tilelang_npu.py | 103 ++++++++++++++++++ .../test/npu/test_hyper_connection_npu.py | 21 +++- 5 files changed, 225 insertions(+), 3 deletions(-) create mode 100644 xllm-kernel/test/npu/test_dsv41_sparse_attention_npu.py create mode 100644 xllm-kernel/test/npu/test_dsv41_tilelang_npu.py diff --git a/xllm-kernel/test/npu/conftest.py b/xllm-kernel/test/npu/conftest.py index 6e7748371a..dfbb83c6a6 100644 --- a/xllm-kernel/test/npu/conftest.py +++ b/xllm-kernel/test/npu/conftest.py @@ -9,11 +9,17 @@ torch_npu = pytest.importorskip("torch_npu", reason="NPU integration tests require torch_npu") from xllm_kernel import initialize +from xllm_kernel.ops.attention.dsv41 import ASCENDC_OPERATIONS as V41_ASCENDC_OPERATIONS +from xllm_kernel.ops.attention.dsv41 import TILELANG_OPERATIONS as V41_TILELANG_OPERATIONS +from xllm_kernel.ops.attention.dsv41 import TRITON_OPERATIONS as V41_TRITON_OPERATIONS from xllm_kernel.ops.attention.gdn.mega import has_mega_gdn_mtp_decode_varlen from xllm_kernel.ops.attention.mla import has_mla_preprocess_v2 from xllm_kernel.ops.collectives import HCCL_OPERATIONS, has_matmul_reduce_scatter +from xllm_kernel.ops.engram import OPERATIONS as ENGRAM_OPERATIONS from xllm_kernel.ops.gemm import has_grouped_matmul_out +from xllm_kernel.ops.hyper_connection import has_hc_pre_delayed from xllm_kernel.ops.moe import FUSED_MOE_GMM1_OPERATIONS, has_fused_moe_gmm1 +from xllm_kernel.ops.normalization import has_rms_norm_cast @pytest.fixture @@ -26,6 +32,7 @@ def require_fused_moe_gmm1() -> None: def _prepare_kernels() -> None: if "LOCAL_RANK" in os.environ: torch_npu.npu.set_device(int(os.environ["LOCAL_RANK"])) + v41_ascendc = V41_ASCENDC_OPERATIONS if torch_npu.npu.get_device_name().startswith("Ascend910_93") else () initialize( device="npu", operations=( @@ -34,6 +41,7 @@ def _prepare_kernels() -> None: "fused_add_gemma_rms_norm", "gemma_rms_norm", "rms_norm_gated", + *(("rms_norm_cast",) if has_rms_norm_cast() else ()), "inplace_partial_rotary_mul", "apply_rotary_embedding", "apply_qk_rotary", @@ -43,6 +51,8 @@ def _prepare_kernels() -> None: "rms_norm_dynamic_quant", "hc_pre", "hc_post", + *(op.contract.operation for op in (*v41_ascendc, *V41_TRITON_OPERATIONS, *ENGRAM_OPERATIONS)), + *(("hc_pre_delayed",) if has_hc_pre_delayed() else ()), "fused_recurrent_gated_delta_rule", "fused_sigmoid_gating_delta_rule_update", "fused_qkvzba_split_reshape_cat", @@ -83,6 +93,7 @@ def _prepare_kernels() -> None: *( ( "shared_full_indices_out", + *(op.contract.operation for op in V41_TILELANG_OPERATIONS), "sfa_dcp_remap_out", "split_qkv_rmsnorm_mrope", "fused_gdn_gating", diff --git a/xllm-kernel/test/npu/test_ascendc_normalization_npu.py b/xllm-kernel/test/npu/test_ascendc_normalization_npu.py index bf4ed8fe62..f78b5d6007 100644 --- a/xllm-kernel/test/npu/test_ascendc_normalization_npu.py +++ b/xllm-kernel/test/npu/test_ascendc_normalization_npu.py @@ -1,9 +1,9 @@ # Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. -"""Exercise the package-owned LayerNormFwd and RmsNormDynamicQuant kernels.""" +"""Exercise the package-owned normalization kernels.""" import pytest import torch -from xllm_kernel.ops.normalization import rms_norm_dynamic_quant, rms_norm_gated +from xllm_kernel.ops.normalization import has_rms_norm_cast, rms_norm_cast, rms_norm_dynamic_quant, rms_norm_gated _EPS = 1e-6 @@ -76,3 +76,15 @@ def test_normalization_aclgraph_replays_fresh_inputs() -> None: eager_quantized, eager_scale = rms_norm_dynamic_quant(value, weight, _EPS) for actual, expected in ((gated, eager_gated), (quantized, eager_quantized), (scale, eager_scale)): torch.testing.assert_close(actual, expected, atol=0, rtol=0) + + +def test_router_rms_norm_cast_preserves_rounded_bf16_values() -> None: + if not has_rms_norm_cast(): + pytest.skip("RMSNormCast requires an A2/A3 build") + generator = torch.Generator().manual_seed(613) + value = torch.randn(7, 5120, generator=generator).bfloat16() + weight = torch.randn(5120, generator=generator).bfloat16() + normalized, router_input = rms_norm_cast(value.npu(), weight.npu(), _EPS) + expected = value.float() * torch.rsqrt(value.float().square().mean(-1, keepdim=True) + _EPS) + torch.testing.assert_close(normalized.cpu(), (expected * weight.float()).bfloat16(), rtol=0.02, atol=0.02) + torch.testing.assert_close(router_input, normalized.float(), rtol=0, atol=0) diff --git a/xllm-kernel/test/npu/test_dsv41_sparse_attention_npu.py b/xllm-kernel/test/npu/test_dsv41_sparse_attention_npu.py new file mode 100644 index 0000000000..264e35e4d8 --- /dev/null +++ b/xllm-kernel/test/npu/test_dsv41_sparse_attention_npu.py @@ -0,0 +1,77 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Exercise the A3 sparse kernels together with their device-generated metadata.""" + +import pytest +import torch +from xllm_kernel.ops.attention.dsv41.indexer import quant_lightning_indexer_v2, quant_lightning_indexer_v2_metadata +from xllm_kernel.ops.attention.dsv41.mla import sparse_flash_mla, sparse_flash_mla_metadata + +pytestmark = pytest.mark.skipif(not torch.npu.get_device_name().startswith("Ascend910_93"), reason="requires Ascend A3") + + +def test_indexer_uses_supplied_candidate_blocks() -> None: + heads, topk, page_size = 32, 512, 128 + query = torch.ones((1, heads, 128), dtype=torch.int8, device="npu") + # The first half scores higher, yet only the second half is eligible. + keys = torch.ones((8, page_size, 1, 128), dtype=torch.int8) + keys[:4].fill_(2) + weights = torch.ones((1, heads), dtype=torch.float16, device="npu") + key_scale = torch.ones(keys.shape[:-1], dtype=torch.float16, device="npu") + offsets = torch.tensor([0, 1], dtype=torch.int32, device="npu") + lengths = torch.tensor([1024], dtype=torch.int32, device="npu") + table = torch.arange(8, dtype=torch.int32, device="npu").reshape(1, 8) + candidates = torch.arange(64, 128, dtype=torch.int32, device="npu").reshape(1, 1, 64) + metadata = quant_lightning_indexer_v2_metadata(offsets, lengths, None, heads, 128, topk, 1, 1024, 1) + indices, _ = quant_lightning_indexer_v2( + query, + keys.npu(), + weights, + torch.ones_like(weights), + key_scale, + offsets, + lengths, + None, + table, + metadata, + candidates, + topk=topk, + max_query_len=1, + compression_ratio=1, + candidate_mode=2, + candidate_count=64, + candidate_block_size=8, + ) + torch.testing.assert_close(indices.cpu().flatten().sort().values, torch.arange(512, 1024, dtype=torch.int32)) + + +def test_sparse_mla_applies_window_after_page_lookup() -> None: + heads, head_dim, window = 16, 512, 128 + query = torch.zeros((1, heads, head_dim), dtype=torch.bfloat16, device="npu") + kv = torch.full((2, window, 1, head_dim), -300, dtype=torch.bfloat16) + # Logical tokens 0..127 live on page 1. Token 0 must fall out of the window. + kv[1].fill_(1) + kv[1, 0].fill_(1024) + kv[0, 0].fill_(129) + table = torch.tensor([[1, 0]], dtype=torch.int32, device="npu") + offsets = torch.tensor([0, 1], dtype=torch.int32, device="npu") + lengths = torch.tensor([129], dtype=torch.int32, device="npu") + metadata = sparse_flash_mla_metadata(offsets, lengths, None, None, heads, head_dim, 1, 256, 0, 0, 0, window) + result = sparse_flash_mla( + query, + kv.npu(), + table, + offsets, + lengths, + None, + None, + None, + None, + None, + None, + metadata, + softmax_scale=head_dim**-0.5, + cmp_ratio=0, + window_size=window, + ) + # A zero query gives uniform attention over the 127 ones and the final value of 129. + torch.testing.assert_close(result.cpu(), torch.full(query.shape, 2, dtype=query.dtype), rtol=0, atol=0.016) diff --git a/xllm-kernel/test/npu/test_dsv41_tilelang_npu.py b/xllm-kernel/test/npu/test_dsv41_tilelang_npu.py new file mode 100644 index 0000000000..a1200cbf0b --- /dev/null +++ b/xllm-kernel/test/npu/test_dsv41_tilelang_npu.py @@ -0,0 +1,103 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Check the runtime-compiled kernels against independent CPU tensor operations.""" + +import pytest +import torch +from xllm_kernel.ops.attention import dsv41 + + +def _rotate(x, cos, sin): + tail = x[..., -64:].float().unflatten(-1, (32, 2)) + real, imag = tail.unbind(-1) + rotated = torch.stack((real * cos - imag * sin, real * sin + imag * cos), dim=-1).flatten(-2) + return torch.cat((x[..., :-64], rotated.to(x.dtype)), dim=-1) + + +def _rope_inputs(rows): + angles = torch.linspace(-2.8, 3.1, rows * 32).reshape(rows, 32) + cos, sin = angles.cos(), angles.sin() + expanded = cos.repeat_interleave(2, dim=-1) + signed = torch.stack((-sin, sin), dim=-1).flatten(-2) + offsets = ((torch.arange(8 * 64, dtype=torch.int32) ^ 1) * 4).npu() + return cos, sin, (expanded.npu(), signed.npu(), offsets) + + +@pytest.mark.parametrize(("dim", "heads"), [(128, 1), (128, 8), (512, 1), (512, 8)]) +def test_partial_rope_variants(dim, heads): + value = torch.randn((7, heads, dim), generator=torch.Generator().manual_seed(41)).bfloat16() + cos, sin, inputs = _rope_inputs(value.size(0)) + expected = _rotate(value, cos[:, None], -sin[:, None]) + result = value.npu() + dsv41.v41_partial_rope_(result, *inputs, True) + torch.testing.assert_close(result.cpu(), expected, atol=0.016, rtol=0.008) + + +def test_swa_rope_updates_only_valid_cache_rows(): + value = torch.randn((3, 512), generator=torch.Generator().manual_seed(42)).bfloat16() + cos, sin, inputs = _rope_inputs(value.size(0)) + expected = _rotate(value, cos, sin) + cache = torch.full((7, 512), -8, dtype=torch.bfloat16) + result, cache_device = value.npu(), cache.npu() + dsv41.v41_swa_rope_cache_(result, *inputs, torch.tensor([3, -1, 5], dtype=torch.int32).npu(), cache_device) + cache[[3, 5]] = expected[[0, 2]] + torch.testing.assert_close(result.cpu(), expected, atol=0.016, rtol=0.008) + torch.testing.assert_close(cache_device.cpu(), cache, atol=0.016, rtol=0.008) + + +def test_index_key_transform_and_query_quantization(): + rng = torch.Generator().manual_seed(43) + value = torch.randn((13, 128), generator=rng).bfloat16() + weight = torch.randn((128,), generator=rng).bfloat16() + cos, sin, _ = _rope_inputs(value.size(0)) + normalized = (value.float() * value.float().square().mean(-1, keepdim=True).add(1e-6).rsqrt() * weight).bfloat16() + result = dsv41.v41_index_key_transform(value.npu(), weight.npu(), torch.cat((cos, sin), dim=-1).npu(), 1e-6) + torch.testing.assert_close(result.cpu(), _rotate(normalized, cos, sin), atol=0.032, rtol=0.01) + + query = torch.randn((17, 32, 128), generator=rng).bfloat16() + query[0] = 0 + scale = (query.float().abs().amax(dim=-1) / 127).half().clamp_min(2**-24) + expected = (query.float() / scale.float().unsqueeze(-1)).round().clamp(-127, 127).to(torch.int8) + codes, actual_scale = dsv41.v41_index_query_quant(query.npu()) + torch.testing.assert_close(actual_scale.cpu(), scale, atol=0, rtol=0) + torch.testing.assert_close(codes.cpu(), expected, atol=1, rtol=0) + assert not codes[0].cpu().any() + + +def test_c2_decode_uses_cache_and_previous_batch_rows(): + rng = torch.Generator().manual_seed(44) + kv, scores, state, state_scores = [torch.randn((5, 512), generator=rng) for _ in range(4)] + weight = torch.randn((512,), generator=rng).bfloat16() + previous = torch.tensor([2, -1, 4, -2, 0], dtype=torch.int32) + from_batch = previous[:, None] < 0 + batch_indices, state_indices = (-previous - 1).clamp_min(0), previous.clamp_min(0) + left = torch.where(from_batch, kv[batch_indices], state[state_indices]) + left_scores = torch.where(from_batch, scores[batch_indices], state_scores[state_indices]) + members, gates = torch.stack((left, kv), dim=1), torch.stack((left_scores, scores), dim=1) + pooled = (members * gates.softmax(dim=1)).sum(dim=1).bfloat16().float() + expected = (pooled * pooled.square().mean(-1, keepdim=True).add(1e-6).rsqrt() * weight).bfloat16() + prefill = dsv41.v41_c2_pool_norm(members.npu(), gates.npu(), weight.npu(), 1e-6) + decode = dsv41.v41_c2_decode_pool_norm( + kv.npu(), scores.npu(), state.npu(), state_scores.npu(), previous.npu(), weight.npu(), 1e-6 + ) + torch.testing.assert_close(prefill.cpu(), expected, atol=0.032, rtol=0.012) + torch.testing.assert_close(decode.cpu(), prefill.cpu(), atol=0, rtol=0) + + +def test_index_query_replays_with_new_values_on_capture_stream(monkeypatch) -> None: + from xllm_kernel.ops.attention.dsv41.tilelang import prepare_v41_kernels + + prepare_v41_kernels() + # A fresh worker inherits disabled backend autoload and reopens the cached kernels. + prepare_v41_kernels.cache_clear() + monkeypatch.setenv("TORCH_DEVICE_BACKEND_AUTOLOAD", "0") + prepare_v41_kernels() + query = torch.zeros((3, 32, 128), dtype=torch.bfloat16, device="npu") + graph = torch.npu.NPUGraph() + with torch.npu.graph(graph, stream=torch.npu.Stream()): + codes, scales = dsv41.v41_index_query_quant(query) + + for value in (127.0, -254.0): + query.fill_(value) + graph.replay() + assert torch.all(codes.cpu() == (127 if value > 0 else -127)) + assert torch.all(scales.cpu() == abs(value) / 127) diff --git a/xllm-kernel/test/npu/test_hyper_connection_npu.py b/xllm-kernel/test/npu/test_hyper_connection_npu.py index dfb3974870..91ce766ec5 100644 --- a/xllm-kernel/test/npu/test_hyper_connection_npu.py +++ b/xllm-kernel/test/npu/test_hyper_connection_npu.py @@ -3,7 +3,7 @@ import pytest import torch -from xllm_kernel.ops.hyper_connection import hc_post, hc_pre +from xllm_kernel.ops.hyper_connection import has_hc_pre_delayed, hc_post, hc_pre, hc_pre_delayed _HC_MULT = 4 _SINKHORN_ITERS = 6 @@ -124,3 +124,22 @@ def forward() -> tuple[torch.Tensor, ...]: torch.npu.synchronize() for actual, expected in zip(captured, eager, strict=True): torch.testing.assert_close(actual, expected, atol=0, rtol=0) + + +def test_delayed_pre_uses_input_mix_and_returns_next_mix() -> None: + if not has_hc_pre_delayed(): + pytest.skip("Delayed HC pre requires Ascend A3") + rng = torch.Generator().manual_seed(121) + x = torch.randn((5, _HC_MULT, 4096), generator=rng).bfloat16() + weight, scale, base = _parameters(4096, torch.float32, rng) + weight.zero_() + previous = torch.rand((5, _HC_MULT), generator=rng) + expected_output = (x.float() * previous.unsqueeze(-1)).sum(dim=-2).bfloat16() + _, expected_post, expected_comb = _pre_reference(x, weight, scale, base, fused=True) + expected_pre = (base[:_HC_MULT].sigmoid() + _EPS).expand_as(previous) + output, post, comb, pre = hc_pre_delayed( + x.npu(), weight.npu(), scale.npu(), base.npu(), previous.npu(), _HC_MULT, _SINKHORN_ITERS, _EPS, _EPS + ) + torch.testing.assert_close(output.cpu(), expected_output, atol=0.02, rtol=0.012) + for actual, expected in ((post, expected_post), (comb, expected_comb), (pre, expected_pre)): + torch.testing.assert_close(actual.cpu(), expected, atol=0.003, rtol=0.003) From 66ff771cda1c8ef457e2b89b31e0671fa6adb410 Mon Sep 17 00:00:00 2001 From: PixelFlat <329975279+PixelFlat@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:04:32 +0800 Subject: [PATCH 4/6] bugfix: preserve optional attention sink semantics on Ascend. --- xllm-kernel/csrc/npu/v41_sparse_mla.cpp | 9 ++++++++- .../test/npu/test_dsv41_sparse_attention_npu.py | 12 ++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/xllm-kernel/csrc/npu/v41_sparse_mla.cpp b/xllm-kernel/csrc/npu/v41_sparse_mla.cpp index 3ec003e335..bcfa1ba878 100644 --- a/xllm-kernel/csrc/npu/v41_sparse_mla.cpp +++ b/xllm-kernel/csrc/npu/v41_sparse_mla.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include @@ -135,6 +136,12 @@ torch::Tensor sparse_flash_mla( ori_sparse_indices.has_value() ? kNonCausalMaskMode : kSwaMaskMode; char layout_q[] = "TND"; char layout_kv[] = "PA_BBND"; + // A3 requires a per-head sink. A logit of -inf adds zero softmax mass. + auto sink_logits = sinks + ? *sinks + : torch::full({q.size(1)}, + -std::numeric_limits::infinity(), + q.options().dtype(torch::kFloat32)); EXEC_NPU_CMD_EXT(aclnnXllmKernelSparseFlashMla, q, kv, @@ -152,7 +159,7 @@ torch::Tensor sparse_flash_mla( cmp_residual_kv, ori_topk_length, /*cmp_topk_length=*/absent, - sinks, + sink_logits, metadata, softmax_scale, cmp_ratio, diff --git a/xllm-kernel/test/npu/test_dsv41_sparse_attention_npu.py b/xllm-kernel/test/npu/test_dsv41_sparse_attention_npu.py index 264e35e4d8..788422a967 100644 --- a/xllm-kernel/test/npu/test_dsv41_sparse_attention_npu.py +++ b/xllm-kernel/test/npu/test_dsv41_sparse_attention_npu.py @@ -1,6 +1,8 @@ # Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. """Exercise the A3 sparse kernels together with their device-generated metadata.""" +import math + import pytest import torch from xllm_kernel.ops.attention.dsv41.indexer import quant_lightning_indexer_v2, quant_lightning_indexer_v2_metadata @@ -44,7 +46,8 @@ def test_indexer_uses_supplied_candidate_blocks() -> None: torch.testing.assert_close(indices.cpu().flatten().sort().values, torch.arange(512, 1024, dtype=torch.int32)) -def test_sparse_mla_applies_window_after_page_lookup() -> None: +@pytest.mark.parametrize(("sink_logit", "expected"), [(None, 2.0), (math.log(128), 1.0)]) +def test_sparse_mla_applies_window_after_page_lookup(sink_logit: float | None, expected: float) -> None: heads, head_dim, window = 16, 512, 128 query = torch.zeros((1, heads, head_dim), dtype=torch.bfloat16, device="npu") kv = torch.full((2, window, 1, head_dim), -300, dtype=torch.bfloat16) @@ -56,6 +59,7 @@ def test_sparse_mla_applies_window_after_page_lookup() -> None: offsets = torch.tensor([0, 1], dtype=torch.int32, device="npu") lengths = torch.tensor([129], dtype=torch.int32, device="npu") metadata = sparse_flash_mla_metadata(offsets, lengths, None, None, heads, head_dim, 1, 256, 0, 0, 0, window) + sinks = None if sink_logit is None else torch.full((heads,), sink_logit, dtype=torch.float32, device="npu") result = sparse_flash_mla( query, kv.npu(), @@ -67,11 +71,11 @@ def test_sparse_mla_applies_window_after_page_lookup() -> None: None, None, None, - None, + sinks, metadata, softmax_scale=head_dim**-0.5, cmp_ratio=0, window_size=window, ) - # A zero query gives uniform attention over the 127 ones and the final value of 129. - torch.testing.assert_close(result.cpu(), torch.full(query.shape, 2, dtype=query.dtype), rtol=0, atol=0.016) + # Visible values sum to 256. The optional sink doubles the softmax denominator from 128 to 256. + torch.testing.assert_close(result.cpu(), torch.full(query.shape, expected, dtype=query.dtype), rtol=0, atol=0.016) From 86dde8714c3a46a0e317798c0283c8612624fc7f Mon Sep 17 00:00:00 2001 From: PixelFlat <329975279+PixelFlat@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:04:50 +0800 Subject: [PATCH 5/6] perf: add candidate-driven QLI V3 on Ascend A3. --- xllm-kernel/csrc/ascendc/CMakeLists.txt | 28 +- ...lightning_indexer_v2_metadata_va_aicpu.cpp | 8 +- ...t_lightning_indexer_v2_metadata_va_aicpu.h | 4 - .../quant_lightning_indexer_v2_va/SOURCE.txt | 11 +- .../aclnn_quant_lightning_indexer_v2_va.cpp | 101 + .../aclnn_quant_lightning_indexer_v2_va.h | 68 + .../quant_lightning_indexer_v2_va_def.cpp | 61 +- ...ant_lightning_indexer_v2_va_infershape.cpp | 107 +- .../quant_lightning_indexer_v2_va_tiling.cpp | 1113 +++++++- .../quant_lightning_indexer_v2_va_tiling.h | 58 +- ...nt_lightning_indexer_v2_va_common_arch22.h | 110 +- ...nt_lightning_indexer_v2_va_kernel_arch22.h | 505 +++- ...htning_indexer_v2_va_service_cube_arch22.h | 556 +++- ...ning_indexer_v2_va_service_vector_arch22.h | 2239 +++++++++++++++-- .../quant_lightning_indexer_v2_va_vector.h | 119 +- ...htning_indexer_v2_va_template_tiling_key.h | 158 +- ..._kernel_quant_lightning_indexer_v3_va.cpp} | 12 +- ...se_lightning_indexer_metadata_va_proto.cpp | 33 + ...t_sparse_lightning_indexer_metadata_va.cpp | 222 ++ ...ant_sparse_lightning_indexer_metadata_va.h | 58 + ...t_sparse_lightning_indexer_metadata_va.cpp | 130 + ...ant_sparse_lightning_indexer_metadata_va.h | 45 + ...arse_lightning_indexer_metadata_va_check.h | 767 ++++++ ...ghtning_indexer_metadata_va_infershape.cpp | 40 + ...se_lightning_indexer_metadata_va_aicpu.cpp | 1245 +++++++++ ...arse_lightning_indexer_metadata_va_aicpu.h | 365 +++ ...e_lightning_indexer_metadata_va_aicpu.json | 15 + xllm-kernel/csrc/npu/v41_quant_indexer.cpp | 162 +- .../ops/attention/dsv41/__init__.py | 6 +- .../ops/attention/dsv41/ascendc.py | 2 + .../ops/attention/dsv41/indexer.py | 73 +- .../npu/test_dsv41_sparse_attention_npu.py | 83 +- 32 files changed, 7734 insertions(+), 770 deletions(-) create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_va.cpp create mode 100644 xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_va.h rename xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/{xllm_kernel_quant_lightning_indexer_v2_va.cpp => xllm_kernel_quant_lightning_indexer_v3_va.cpp} (88%) create mode 100644 xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_graph/quant_sparse_lightning_indexer_metadata_va_proto.cpp create mode 100644 xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.cpp create mode 100644 xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.h create mode 100644 xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/quant_sparse_lightning_indexer_metadata_va.cpp create mode 100644 xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/quant_sparse_lightning_indexer_metadata_va.h create mode 100644 xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/quant_sparse_lightning_indexer_metadata_va_check.h create mode 100644 xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/quant_sparse_lightning_indexer_metadata_va_infershape.cpp create mode 100644 xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.cpp create mode 100644 xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.h create mode 100644 xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.json diff --git a/xllm-kernel/csrc/ascendc/CMakeLists.txt b/xllm-kernel/csrc/ascendc/CMakeLists.txt index 8635f61dc7..def251c9fc 100644 --- a/xllm-kernel/csrc/ascendc/CMakeLists.txt +++ b/xllm-kernel/csrc/ascendc/CMakeLists.txt @@ -55,25 +55,36 @@ set(qli_metadata "${CMAKE_CURRENT_SOURCE_DIR}/quant_lightning_indexer_metadata") if("ascend910_93" IN_LIST ASCEND_COMPUTE_UNIT) set(qli_v2 "${CMAKE_CURRENT_SOURCE_DIR}/quant_lightning_indexer_v2_va") set(qli_v2_metadata "${CMAKE_CURRENT_SOURCE_DIR}/quant_lightning_indexer_v2_metadata_va") + set(qli_sparse_metadata "${CMAKE_CURRENT_SOURCE_DIR}/quant_sparse_lightning_indexer_metadata_va") list(APPEND op_definitions "${qli_v2}/op_host/quant_lightning_indexer_v2_va_def.cpp") set(qli_v2_api - "${ASCEND_AUTOGEN_PATH}/aclnn_xllm_kernel_quant_lightning_indexer_v2_va.cpp" + "${ASCEND_AUTOGEN_PATH}/aclnn_xllm_kernel_quant_lightning_indexer_v3_va.cpp" + "${qli_v2}/op_host/op_api/aclnn_quant_lightning_indexer_v2_va.cpp" + "${qli_sparse_metadata}/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.cpp" + "${qli_sparse_metadata}/op_host/op_api/quant_sparse_lightning_indexer_metadata_va.cpp" "${qli_v2_metadata}/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.cpp" "${qli_v2_metadata}/op_host/op_api/quant_lightning_indexer_v2_metadata_va.cpp" ) set_property(SOURCE "${qli_v2_metadata}/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.cpp" + "${qli_sparse_metadata}/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.cpp" APPEND PROPERTY INCLUDE_DIRECTORIES "${ASCEND_CANN_PACKAGE_PATH}/pkg_inc/op_common") set_property(SOURCE "${qli_v2_metadata}/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.cpp" + "${qli_sparse_metadata}/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.cpp" APPEND PROPERTY COMPILE_DEFINITIONS OP_LOG_LIBOPAPI_ONLY) set(qli_v2_tiling "${qli_v2}/op_host/quant_lightning_indexer_v2_va_infershape.cpp" "${qli_v2}/op_host/quant_lightning_indexer_v2_va_tiling.cpp" + "${qli_sparse_metadata}/op_host/quant_sparse_lightning_indexer_metadata_va_infershape.cpp" "${qli_v2_metadata}/op_host/quant_lightning_indexer_v2_metadata_va_infershape.cpp" ) list(APPEND v41_metadata_graph_sources + "${qli_sparse_metadata}/op_graph/quant_sparse_lightning_indexer_metadata_va_proto.cpp" "${qli_v2_metadata}/op_graph/quant_lightning_indexer_v2_metadata_va_proto.cpp") - list(APPEND v41_aicpu_components quant_lightning_indexer_v2_metadata_va) + list(APPEND v41_aicpu_components quant_lightning_indexer_v2_metadata_va quant_sparse_lightning_indexer_metadata_va) list(APPEND v41_aicpu_headers "${qli_v2}/op_kernel/quant_lightning_indexer_v2_metadata_va.h") + install(FILES "${qli_sparse_metadata}/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.h" + DESTINATION "packages/vendors/${vendor}/op_api/include" + RENAME aclnn_xllm_kernel_quant_sparse_lightning_indexer_metadata_va.h) install(FILES "${qli_v2_metadata}/op_host/op_api/aclnn_quant_lightning_indexer_v2_metadata_va.h" DESTINATION "packages/vendors/${vendor}/op_api/include" RENAME aclnn_xllm_kernel_quant_lightning_indexer_v2_metadata_va.h) @@ -460,9 +471,9 @@ npu_op_kernel_options(ascendc_kernels XllmKernelQuantLightningIndexer "-I${CMAKE_CURRENT_SOURCE_DIR}" "-I${qli}/op_kernel") if("ascend910_93" IN_LIST ASCEND_COMPUTE_UNIT) v41_sparse_mla_kernel() - npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelQuantLightningIndexerV2Va - KERNEL_DIR quant_lightning_indexer_v2_va/op_kernel KERNEL_FILE xllm_kernel_quant_lightning_indexer_v2_va.cpp) - npu_op_kernel_options(ascendc_kernels XllmKernelQuantLightningIndexerV2Va + npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelQuantLightningIndexerV3Va + KERNEL_DIR quant_lightning_indexer_v2_va/op_kernel KERNEL_FILE xllm_kernel_quant_lightning_indexer_v3_va.cpp) + npu_op_kernel_options(ascendc_kernels XllmKernelQuantLightningIndexerV3Va OPTIONS --cce-auto-sync=off -Wno-deprecated-declarations -Werror -mllvm -cce-vf-remove-membar=false -mllvm -cce-aicore-hoist-movemask=false "-I${qli_v2}/op_kernel") @@ -528,3 +539,10 @@ npu_op_kernel_library(ascendc_kernels SRC_BASE "${CMAKE_CURRENT_SOURCE_DIR}" TIL include("${CMAKE_CURRENT_SOURCE_DIR}/aicpu.cmake") npu_op_package_add(${vendor} LIBRARY cust_opapi cust_op_proto cust_optiling ascendc_kernels) + +if(qli_v2) + # An incremental CANN build may still have the V2 header from before the V3 migration. + install(FILES "${qli_v2}/op_host/op_api/aclnn_quant_lightning_indexer_v2_va.h" + DESTINATION "packages/vendors/${vendor}/op_api/include" + RENAME aclnn_xllm_kernel_quant_lightning_indexer_v2_va.h) +endif() diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.cpp index 085d768cbc..f77fac3ff0 100644 --- a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.cpp +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.cpp @@ -355,10 +355,11 @@ void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcSplitInfo( SplitContext& splitContext) { // 计算每个batch的切分,统计是否为空batch,记录最后有效batch(每个batch的每个N2切分是一样的) SplitInfo& splitInfo = splitContext.splitInfo; + uint32_t maxS2Size = 0; for (uint32_t bIdx = 0; bIdx < static_cast(batchSize_); bIdx++) { uint32_t s1Size = GetS1SeqSize(bIdx); uint32_t s2Size = GetS2SeqSize(bIdx); - maxS2Size_ = std::max(maxS2Size_, s2Size); + maxS2Size = std::max(maxS2Size, s2Size); splitInfo.s1GBaseNum[bIdx] = (static_cast(s1Size) * groupSize_ + (mBaseSize_ - 1U)) / mBaseSize_; @@ -370,6 +371,11 @@ void XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel::CalcSplitInfo( splitInfo.isKvSeqAllZero = false; } } + // Splitting one query across cores also needs a vector TopK merge. Use + // committed (compressed) keys to decide when that cost is worthwhile. + constexpr uint32_t kMinSplitTiles = 5; + supportFd_ = maxS2Size >= static_cast(topk_) && + maxS2Size > kMinSplitTiles * s2BaseSize_; } int64_t diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.h index 809e5edc1e..ac18497a9c 100644 --- a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.h +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_metadata_va/op_kernel_aicpu/quant_lightning_indexer_v2_metadata_va_aicpu.h @@ -295,9 +295,6 @@ class XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel : public CpuKernel { Tensor* metadata_ = nullptr; // attributes std::string socVersion_ = ""; - // FD/LD 归约路径(SplitFD/IsNeedRecordFDInfo 等)与 base v2 - // 对齐保留但未启用: 当前场景不产生 FD 任务,恒为 - // false,相关分支为休眠代码,勿据此误判为缺陷。 bool supportFd_ = false; uint32_t aicCoreNum_ = optiling::AIC_CORE_MAX_NUM; uint32_t aivCoreNum_ = optiling::AIV_CORE_MAX_NUM; @@ -323,7 +320,6 @@ class XllmKernelQuantLightningIndexerV2MetadataVaCpuKernel : public CpuKernel { uint32_t s1BaseSize_ = 4; uint32_t s2BaseSize_ = 128; bool isS1G_ = true; - uint32_t maxS2Size_ = 0; private: enum class ParamId : uint32_t { diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/SOURCE.txt b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/SOURCE.txt index 8e150ec1fa..30d1e3fc10 100644 --- a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/SOURCE.txt +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/SOURCE.txt @@ -1,9 +1,10 @@ -The AscendC QLI V2 and AICPU metadata implementations originate from xllm_ops -revision 8bd2b014c38fec33ecf14dd33e05e8ad792ec5c8, under -xllm_ops/attention/quant_lightning_indexer_v2_va and -xllm_ops/attention/quant_lightning_indexer_v2_metadata_va. Their original +The AscendC QLI V2/V3 and AICPU metadata implementations originate from xllm_ops +revision ef9819ee59a9298955641e1dfaed9e3b68a6d070, under +xllm_ops/attention/quant_lightning_indexer_v2_va, +xllm_ops/attention/quant_lightning_indexer_v2_metadata_va and +xllm_ops/attention/quant_sparse_lightning_indexer_metadata_va. Their original source headers and CANN Open Software License Agreement Version 2.0 apply. The license is included in ../gamma_add_rms_norm/CANN_LICENSE.txt. -xLLM registers the two operators with XllmKernel-prefixed names and packages +xLLM registers the operators with XllmKernel-prefixed names and packages them in the xllm-kernel vendor, using its shared AICPU library. diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_va.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_va.cpp new file mode 100644 index 0000000000..8c5b5b4b9e --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_va.cpp @@ -0,0 +1,101 @@ +/** + * Copyright 2026 The xLLM Authors. All Rights Reserved. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#include "aclnn_quant_lightning_indexer_v2_va.h" + +#include "aclnn_xllm_kernel_quant_lightning_indexer_v3_va.h" + +extern "C" { +aclnnStatus aclnnXllmKernelQuantLightningIndexerV2VaGetWorkspaceSize( + const aclTensor* query, + const aclTensor* key, + const aclTensor* weights, + const aclTensor* queryScale, + const aclTensor* keyScale, + const aclTensor* cuSeqlensQ, + const aclTensor* cuSeqlensK, + const aclTensor* sequsedQ, + const aclTensor* sequsedK, + const aclTensor* cmpResidualK, + const aclTensor* blockTable, + const aclTensor* outputIdxOffset, + const aclTensor* metadata, + const aclTensor* candidateTopkIndex, + int64_t topk, + int64_t quantMode, + int64_t maxSeqlenQ, + char* layoutQ, + char* layoutK, + int64_t maskMode, + int64_t cmpRatio, + int64_t returnValue, + int64_t candidateMode, + int64_t candidateTopkBlocks, + int64_t candidateBlockSize, + int64_t keyStride0, + int64_t keyDequantScaleStride0, + const aclTensor* sparseIndices, + const aclTensor* sparseValues, + const aclTensor* candidateTopkIndexOut, + uint64_t* workspaceSize, + aclOpExecutor** executor) { + return aclnnXllmKernelQuantLightningIndexerV3VaGetWorkspaceSize( + query, + key, + weights, + queryScale, + keyScale, + cuSeqlensQ, + cuSeqlensK, + sequsedQ, + sequsedK, + cmpResidualK, + blockTable, + outputIdxOffset, + metadata, + candidateTopkIndex, + nullptr, + nullptr, + topk, + quantMode, + maxSeqlenQ, + layoutQ, + layoutK, + maskMode, + cmpRatio, + returnValue, + candidateMode, + candidateTopkBlocks, + candidateBlockSize, + keyStride0, + keyDequantScaleStride0, + false, + 1, + 0, + 1, + sparseIndices, + sparseValues, + candidateTopkIndexOut, + nullptr, + workspaceSize, + executor); +} + +aclnnStatus aclnnXllmKernelQuantLightningIndexerV2Va(void* workspace, + uint64_t workspaceSize, + aclOpExecutor* executor, + aclrtStream stream) { + return aclnnXllmKernelQuantLightningIndexerV3Va( + workspace, workspaceSize, executor, stream); +} + +} // extern "C" diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_va.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_va.h new file mode 100644 index 0000000000..c1e3cb03cf --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/op_api/aclnn_quant_lightning_indexer_v2_va.h @@ -0,0 +1,68 @@ +/** + * Copyright 2026 The xLLM Authors. All Rights Reserved. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef ACLNN_QUANT_LIGHTNING_INDEXER_V2_VA_H +#define ACLNN_QUANT_LIGHTNING_INDEXER_V2_VA_H + +#include "aclnn/acl_meta.h" +#include "aclnn/aclnn_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +__attribute__((visibility("default"))) aclnnStatus +aclnnXllmKernelQuantLightningIndexerV2VaGetWorkspaceSize( + const aclTensor* query, + const aclTensor* key, + const aclTensor* weights, + const aclTensor* queryScale, + const aclTensor* keyScale, + const aclTensor* cuSeqlensQ, + const aclTensor* cuSeqlensK, + const aclTensor* sequsedQ, + const aclTensor* sequsedK, + const aclTensor* cmpResidualK, + const aclTensor* blockTable, + const aclTensor* outputIdxOffset, + const aclTensor* metadata, + const aclTensor* candidateTopkIndex, + int64_t topk, + int64_t quantMode, + int64_t maxSeqlenQ, + char* layoutQ, + char* layoutK, + int64_t maskMode, + int64_t cmpRatio, + int64_t returnValue, + int64_t candidateMode, + int64_t candidateTopkBlocks, + int64_t candidateBlockSize, + int64_t keyStride0, + int64_t keyDequantScaleStride0, + const aclTensor* sparseIndices, + const aclTensor* sparseValues, + const aclTensor* candidateTopkIndexOut, + uint64_t* workspaceSize, + aclOpExecutor** executor); + +__attribute__((visibility("default"))) aclnnStatus +aclnnXllmKernelQuantLightningIndexerV2Va(void* workspace, + uint64_t workspaceSize, + aclOpExecutor* executor, + aclrtStream stream); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_def.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_def.cpp index ae4652dfe4..f2313a1c2b 100644 --- a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_def.cpp +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_def.cpp @@ -17,32 +17,34 @@ the full text of the License.  */ #include "register/op_def_registry.h" namespace ops { -class XllmKernelQuantLightningIndexerV2Va : public OpDef { +class XllmKernelQuantLightningIndexerV3Va : public OpDef { public: - explicit XllmKernelQuantLightningIndexerV2Va(const char* name) : OpDef(name) { + explicit XllmKernelQuantLightningIndexerV3Va(const char* name) : OpDef(name) { + // Arch22 supports BF16 for return_value=0/1 and FP32 for + // return_value=2 local candidates. Arch35 overrides this below. this->Input("q") .ParamType(REQUIRED) - .DataType({ge::DT_INT8}) + .DataType({ge::DT_INT8, ge::DT_INT8}) .FormatList({ge::FORMAT_ND}) .AutoContiguous(); this->Input("k") .ParamType(REQUIRED) - .DataType({ge::DT_INT8}) + .DataType({ge::DT_INT8, ge::DT_INT8}) .FormatList({ge::FORMAT_ND}) .IgnoreContiguous(); this->Input("w") .ParamType(REQUIRED) - .DataType({ge::DT_FLOAT16}) + .DataType({ge::DT_FLOAT16, ge::DT_FLOAT16}) .FormatList({ge::FORMAT_ND}) .AutoContiguous(); this->Input("q_descale") .ParamType(REQUIRED) - .DataTypeList({ge::DT_FLOAT16}) + .DataType({ge::DT_FLOAT16, ge::DT_FLOAT16}) .FormatList({ge::FORMAT_ND}) .AutoContiguous(); this->Input("k_descale") .ParamType(REQUIRED) - .DataTypeList({ge::DT_FLOAT16}) + .DataType({ge::DT_FLOAT16, ge::DT_FLOAT16}) .FormatList({ge::FORMAT_ND}) .IgnoreContiguous(); this->Input("cu_seqlens_q") @@ -90,23 +92,45 @@ class XllmKernelQuantLightningIndexerV2Va : public OpDef { .DataTypeList({ge::DT_INT32}) .FormatList({ge::FORMAT_ND}) .AutoContiguous(); + // 每行有效候选块数(DSL QSLI 的 candidate_block_length 语义): + // 与 candidate_topk_index 一起构成"定长容量 + 有效前缀"的稀疏候选描述。 + // 可选:未传时 kernel 保持全量 S2 扫描(现网行为不变)。 + this->Input("candidate_block_length") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + // DCP (Decode Context Parallel, 解码上下文并行): 每请求本次 Q 片段的全局 + // exclusive 上界 C。 Device Tensor, 避免每轮把全局边界同步回 CPU; 非 DCP + // 场景不传。 + this->Input("causal_seqlens_kv_global") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); this->Output("sparse_indices") .ParamType(REQUIRED) .DataTypeList({ge::DT_INT32}) .FormatList({ge::FORMAT_ND}); this->Output("sparse_values") .ParamType(REQUIRED) - .DataTypeList({ge::DT_BF16}) + .DataType({ge::DT_BF16, ge::DT_FLOAT}) .FormatList({ge::FORMAT_ND}); this->Output("candidate_topk_index_out") .ParamType(OPTIONAL) .DataTypeList({ge::DT_INT32}) .FormatList({ge::FORMAT_ND}); + // mode=1(candidate source)的每行有效候选块数(DSL candidate_length 语义: + // min(ceil(可见 key 长度 / candidate_block_size), + // candidate_topk_blocks)), int32、形状 [T1, N2];候选功能关闭时为空 + // Tensor。 + this->Output("candidate_block_length_out") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}); this->Attr("topk").AttrType(REQUIRED).Int( 2048); // 2048: 筛选前2048个作为输出index - this->Attr("quant_mode") - .AttrType(REQUIRED) - .Int(2); // 2: int8 per-token-head (仅支持2) + this->Attr("quant_mode").AttrType(REQUIRED).Int(2); // INT8 per-token-head this->Attr("max_seqlen_q") .AttrType(OPTIONAL) .Int(-1); // -1: 默认值,表示任意可能长度 @@ -120,7 +144,7 @@ class XllmKernelQuantLightningIndexerV2Va : public OpDef { .Int(3); // 3: 默认关闭candidate this->Attr("candidate_topk_blocks") .AttrType(OPTIONAL) - .Int(2048); // 块级topk个数, 支持(0, 2048]内64的倍数 + .Int(2048); // 块级topk个数, 当前仅支持2048 this->Attr("candidate_block_size") .AttrType(OPTIONAL) .Int(8); // 候选块大小(位置数) @@ -131,6 +155,15 @@ class XllmKernelQuantLightningIndexerV2Va : public OpDef { this->Attr("key_dequant_scale_stride0") .AttrType(OPTIONAL) .Int(0); // A11: k_scale 第0维 stride + // ---- DCP (Decode Context Parallel, 解码上下文并行) ---- + this->Attr("enable_dcp") + .AttrType(OPTIONAL) + .Bool(false); // 开启 CP 位置语义 + this->Attr("cp_world").AttrType(OPTIONAL).Int(1); // P: CP 组大小 + this->Attr("cp_rank").AttrType(OPTIONAL).Int(0); // r: 当前 rank + this->Attr("cp_kv_cache_interleave_size") + .AttrType(OPTIONAL) + .Int(1); // S: 每 S 个 token 轮换 rank OpAICoreConfig aicore_config; aicore_config.DynamicCompileStaticFlag(true) .DynamicFormatFlag(true) @@ -139,9 +172,9 @@ class XllmKernelQuantLightningIndexerV2Va : public OpDef { .NeedCheckSupportFlag(false) .PrecisionReduceFlag(true) .ExtendCfgInfo("opFile.value", - "xllm_kernel_quant_lightning_indexer_v2_va"); + "xllm_kernel_quant_lightning_indexer_v3_va"); this->AICore().AddConfig("ascend910_93", aicore_config); } }; -OP_ADD(XllmKernelQuantLightningIndexerV2Va); +OP_ADD(XllmKernelQuantLightningIndexerV3Va); } // namespace ops diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_infershape.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_infershape.cpp index ba04f4378c..314c1eaaaa 100644 --- a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_infershape.cpp +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_infershape.cpp @@ -25,6 +25,7 @@ using namespace ge; namespace ops { constexpr uint32_t QUERY_INDEX = 0; constexpr uint32_t KEY_INDEX = 1; +constexpr uint32_t CU_SEQLENS_Q_INDEX = 5; constexpr uint32_t ATTR_SPARSE_COUNT_INDEX = 0; constexpr uint32_t ATTR_QUERY_LAYOUT_INDEX = 3; constexpr uint32_t ATTR_KV_LAYOUT_INDEX = 4; @@ -32,17 +33,16 @@ constexpr uint32_t ATTR_RETURN_VALUE_INDEX = 7; constexpr uint32_t ATTR_CANDIDATE_MODE_INDEX = 8; constexpr uint32_t ATTR_CANDIDATE_TOPK_BLOCKS_INDEX = 9; constexpr uint32_t CANDIDATE_MODE_SOURCE = 1; -constexpr uint32_t CU_SEQLENS_Q_INDEX = 5; -constexpr uint32_t SPARSE_VALUES_OUTPUT_INDEX = 1; constexpr uint32_t CANDIDATE_TOPK_INDEX_OUTPUT_INDEX = 2; +constexpr uint32_t CANDIDATE_BLOCK_LENGTH_OUTPUT_INDEX = 3; constexpr uint32_t CANDIDATE_TOPK_BLOCKS_FIX = 2048; constexpr uint32_t DIM_NUM_3 = 3; constexpr uint32_t DIM_NUM_4 = 4; -static ge::graphStatus InferShapeXllmKernelQuantLightningIndexerV2Va( +static ge::graphStatus InferShapeXllmKernelQuantLightningIndexerV3Va( gert::InferShapeContext* context) { if (context == nullptr) { - OP_LOGE("XllmKernelQuantLightningIndexerV2Va", "context is nullptr!"); + OP_LOGE("XllmKernelQuantLightningIndexerV3Va", "context is nullptr!"); return ge::GRAPH_FAILED; } const gert::Shape* queryShape = context->GetInputShape(QUERY_INDEX); @@ -68,7 +68,7 @@ static ge::graphStatus InferShapeXllmKernelQuantLightningIndexerV2Va( std::string inputLayoutQueryPtrStr = std::string(inputLayoutQueryPtr); std::string inputLayoutKeyPtrStr = std::string(inputLayoutKeyPtr); if (inputLayoutQueryPtrStr != "TND" && inputLayoutQueryPtrStr != "BSND") { - OP_LOGE_FOR_INVALID_VALUE("XllmKernelQuantLightningIndexerV2Va", + OP_LOGE_FOR_INVALID_VALUE("XllmKernelQuantLightningIndexerV3Va", "layout_q", inputLayoutQueryPtrStr.c_str(), "BSND or TND"); @@ -90,8 +90,7 @@ static ge::graphStatus InferShapeXllmKernelQuantLightningIndexerV2Va( 1, keyHeadNum); // 1:output shape's N Dim, 2: key shape's N Dim sparseIndicesShape->SetDim(2, *sparse_count); // 2:Dim K } - const int32_t* return_value = - attrs->GetAttrPointer(ATTR_RETURN_VALUE_INDEX); + const auto* return_value = attrs->GetInt(ATTR_RETURN_VALUE_INDEX); bool returnValueFlag = (return_value != nullptr) ? (*return_value != 0) : false; if (returnValueFlag) { @@ -101,42 +100,31 @@ static ge::graphStatus InferShapeXllmKernelQuantLightningIndexerV2Va( sparseValuesShape->SetDim(0, 0); } - // candidate_topk_index: 仅 candidate_mode=1(source) 时输出。 - // gate 与 tiling (quant_lightning_indexer_v2_va_tiling.cpp CheckAttrParaInfo) - // 保持一致: BSND 直接放行; TND 需 layout_k=PA_BBND 且 cu_seqlens_q 存在 - // (候选路径下 K 仅支持分页布局)。 + // candidate_topk_index: 仅 candidate_mode=1(source) 时输出, BSND 布局 [B, S1, + // N2, candidate_topk_blocks] gert::Shape* candidateTopkIndexShape = context->GetOutputShape(CANDIDATE_TOPK_INDEX_OUTPUT_INDEX); - OP_CHECK_NULL_WITH_CONTEXT(context, candidateTopkIndexShape); - const int32_t* candidate_mode = - attrs->GetAttrPointer(ATTR_CANDIDATE_MODE_INDEX); + const auto* candidate_mode = attrs->GetInt(ATTR_CANDIDATE_MODE_INDEX); uint32_t candidateMode = (candidate_mode != nullptr) ? static_cast(*candidate_mode) : 3U; + if (candidateTopkIndexShape == nullptr && + candidateMode != CANDIDATE_MODE_SOURCE) { + return ge::GRAPH_SUCCESS; + } + OP_CHECK_NULL_WITH_CONTEXT(context, candidateTopkIndexShape); if (candidateMode == CANDIDATE_MODE_SOURCE) { - bool tndGateOk = false; - if (inputLayoutQueryPtrStr == "TND") { - const gert::Shape* cuSeqlensQShape = - context->GetOptionalInputShape(CU_SEQLENS_Q_INDEX); - tndGateOk = - (inputLayoutKeyPtrStr == "PA_BBND") && (cuSeqlensQShape != nullptr); - } - OP_CHECK_IF((inputLayoutQueryPtrStr != "BSND") && !tndGateOk, - OP_LOGE("XllmKernelQuantLightningIndexerV2Va", - "candidate_mode=1 only supports layout_q=BSND, or " - "layout_q=TND with " - "layout_k=PA_BBND and cu_seqlens_q provided; but got " - "layout_q=%s, layout_k=%s.", - inputLayoutQueryPtrStr.c_str(), - inputLayoutKeyPtrStr.c_str()), - return GRAPH_FAILED); + OP_CHECK_IF( + inputLayoutQueryPtrStr == "TND" && + (inputLayoutKeyPtrStr != "PA_BBND" || + context->GetOptionalInputShape(CU_SEQLENS_Q_INDEX) == nullptr), + OP_LOGE("XllmKernelQuantLightningIndexerV3Va", + "TND candidate source requires paged keys and cu_seqlens_q."), + return GRAPH_FAILED); const int64_t* candidate_topk_blocks = attrs->GetAttrPointer(ATTR_CANDIDATE_TOPK_BLOCKS_INDEX); int64_t candBlocks = (candidate_topk_blocks != nullptr) ? *candidate_topk_blocks : CANDIDATE_TOPK_BLOCKS_FIX; - // TND 语义: 保持 sparseIndices 的 3 维 [T, N2, topk] 形状, 仅末维替换为 - // candidate_topk_blocks; BSND 则为 4 维 [B, S1, N2, candidate_topk_blocks] - // (SetDim 用 GetDimNum()-1, 布局无关)。 *candidateTopkIndexShape = *sparseIndicesShape; candidateTopkIndexShape->SetDim(sparseIndicesShape->GetDimNum() - 1, candBlocks); @@ -145,33 +133,62 @@ static ge::graphStatus InferShapeXllmKernelQuantLightningIndexerV2Va( candidateTopkIndexShape->SetDim(0, 0); } + // candidate_block_length_out: 仅 candidate_mode=1(source) + // 时输出每行有效候选块数, int32 [T1, N2](N2 = kHeadNum);其它模式为空 + // Tensor(rank 1, dim0 = 0)。 + gert::Shape* candidateBlockLenShape = + context->GetOutputShape(CANDIDATE_BLOCK_LENGTH_OUTPUT_INDEX); + if (candidateBlockLenShape == nullptr) { + return ge::GRAPH_SUCCESS; // Legacy callers omit the valid-length output. + } + if (candidateMode == CANDIDATE_MODE_SOURCE) { + // 行数口径与 tiling 的 rows 一致:TND = T1(=q.dim0);BSND = + // B*S1(=q.dim0*q.dim1) + int64_t lenRows = (inputLayoutQueryPtrStr == "TND") + ? queryShape->GetDim(0) + : queryShape->GetDim(0) * queryShape->GetDim(1); + candidateBlockLenShape->SetDimNum(2); + candidateBlockLenShape->SetDim(0, lenRows); + candidateBlockLenShape->SetDim(1, keyHeadNum); + } else { + candidateBlockLenShape->SetDimNum(1); + candidateBlockLenShape->SetDim(0, 0); + } + OP_LOGD(context->GetNodeName(), - "XllmKernelQuantLightningIndexerV2Va InferShape end."); + "XllmKernelQuantLightningIndexerV3Va InferShape end."); return ge::GRAPH_SUCCESS; } -static ge::graphStatus InferDataTypeXllmKernelQuantLightningIndexerV2Va( +static ge::graphStatus InferDataTypeXllmKernelQuantLightningIndexerV3Va( gert::InferDataTypeContext* context) { if (context == nullptr) { - OP_LOGE("XllmKernelQuantLightningIndexerV2Va", + OP_LOGE("XllmKernelQuantLightningIndexerV3Va", "InferDataTypeContext context is nullptr!"); return ge::GRAPH_FAILED; } OP_LOGD(context->GetNodeName(), - "Enter XllmKernelQuantLightningIndexerV2Va InferDataType impl."); + "Enter XllmKernelQuantLightningIndexerV3Va InferDataType impl."); // default index data type is int32 ge::DataType outputType = ge::DT_INT32; context->SetOutputDataType(0, outputType); - // sparse_values (output 1) 为 bfloat16, 与 tiling GetAndCheckInOutDataType - // 的校验一致 - context->SetOutputDataType(SPARSE_VALUES_OUTPUT_INDEX, ge::DT_BF16); - context->SetOutputDataType(CANDIDATE_TOPK_INDEX_OUTPUT_INDEX, outputType); + const auto* attrs = context->GetAttrs(); + OP_CHECK_NULL_WITH_CONTEXT(context, attrs); + const auto* returnValue = attrs->GetInt(ATTR_RETURN_VALUE_INDEX); + context->SetOutputDataType( + 1, + returnValue != nullptr && *returnValue == 2 ? ge::DT_FLOAT : ge::DT_BF16); + for (size_t i = CANDIDATE_TOPK_INDEX_OUTPUT_INDEX; + i < context->GetComputeNodeOutputNum(); + ++i) { + context->SetOutputDataType(i, outputType); + } OP_LOGD(context->GetNodeName(), - "XllmKernelQuantLightningIndexerV2Va InferDataType end."); + "XllmKernelQuantLightningIndexerV3Va InferDataType end."); return GRAPH_SUCCESS; } -IMPL_OP_INFERSHAPE(XllmKernelQuantLightningIndexerV2Va) - .InferShape(InferShapeXllmKernelQuantLightningIndexerV2Va) - .InferDataType(InferDataTypeXllmKernelQuantLightningIndexerV2Va); +IMPL_OP_INFERSHAPE(XllmKernelQuantLightningIndexerV3Va) + .InferShape(InferShapeXllmKernelQuantLightningIndexerV3Va) + .InferDataType(InferDataTypeXllmKernelQuantLightningIndexerV3Va); } // namespace ops diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.cpp index a0be78adef..7307685a79 100644 --- a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.cpp +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.cpp @@ -228,7 +228,7 @@ ge::graphStatus QLIV2VaInfoParser::GetNpuInfo() { socVersion_ = ascendcPlatform.GetSocVersion(); npuArch_ = ascendcPlatform.GetCurNpuArch(); - if (npuArch_ != NpuArch::DAV_2201) { + if ((npuArch_ != NpuArch::DAV_2201) && (npuArch_ != NpuArch::DAV_3510)) { OP_LOGE( opName_, "NpuArch[%d] is not support.", static_cast(npuArch_)); return GRAPH_FAILED; @@ -278,6 +278,15 @@ void QLIV2VaInfoParser::GetOptionalInputParaInfo() { context_->GetOptionalInputTensor(CANDIDATE_TOPK_INDEX_INPUT_INDEX); opParamInfo_.candidateTopkIndex.desc = context_->GetOptionalInputDesc(CANDIDATE_TOPK_INDEX_INPUT_INDEX); + opParamInfo_.candidateBlockLength.tensor = + context_->GetOptionalInputTensor(CANDIDATE_BLOCK_LENGTH_INDEX); + opParamInfo_.candidateBlockLength.desc = + context_->GetOptionalInputDesc(CANDIDATE_BLOCK_LENGTH_INDEX); + // DCP (Decode Context Parallel, 解码上下文并行): 每请求全局 exclusive 上界 C + opParamInfo_.causalSeqLensKvGlobal.tensor = + context_->GetOptionalInputTensor(CAUSAL_SEQLENS_KV_GLOBAL_INDEX); + opParamInfo_.causalSeqLensKvGlobal.desc = + context_->GetOptionalInputDesc(CAUSAL_SEQLENS_KV_GLOBAL_INDEX); } void QLIV2VaInfoParser::GetInputParaInfo() { @@ -340,6 +349,12 @@ ge::graphStatus QLIV2VaInfoParser::GetAttrParaInfo() { attrs->GetAttrPointer(ATTR_KEY_STRIDE0_INDEX); opParamInfo_.keyDequantScaleStride0Attr = attrs->GetAttrPointer(ATTR_KEY_DEQUANT_SCALE_STRIDE0_INDEX); + // ---- DCP (Decode Context Parallel, 解码上下文并行) ---- + opParamInfo_.enableDcp = attrs->GetAttrPointer(ATTR_ENABLE_DCP_INDEX); + opParamInfo_.cpWorld = attrs->GetAttrPointer(ATTR_CP_WORLD_INDEX); + opParamInfo_.cpRank = attrs->GetAttrPointer(ATTR_CP_RANK_INDEX); + opParamInfo_.cpInterleaveSize = + attrs->GetAttrPointer(ATTR_CP_KV_CACHE_INTERLEAVE_SIZE_INDEX); auto keyStrides = context_->GetDynamicInputStride(KEY_INDEX, 0); auto keyDequantScaleStrides = context_->GetDynamicInputStride(KEY_DEQUANT_SCALE_INDEX, 0); @@ -400,30 +415,61 @@ ge::graphStatus QLIV2VaInfoParser::CheckAttrParaInfo() { std::string layout_key(opParamInfo_.layOutKey); std::string layout_query(opParamInfo_.layOutQuery); - OP_CHECK_IF((std::string(opParamInfo_.layOutKey) != "PA_BBND"), - OP_LOGE(opName_, - "input attr layout_key only supported PA_BBND," - "but now layout_key is %s.", - layout_key.c_str()), - return ge::GRAPH_FAILED); + if (npuArch_ == NpuArch::DAV_2201) { + OP_CHECK_IF((std::string(opParamInfo_.layOutKey) != "PA_BBND"), + OP_LOGE(opName_, + "input attr layout_key only supported PA_BBND," + "but now layout_key is %s.", + layout_key.c_str()), + return ge::GRAPH_FAILED); + } else if (npuArch_ == NpuArch::DAV_3510) { + OP_CHECK_IF(((std::string(opParamInfo_.layOutKey) != "PA_BBND") && + (std::string(opParamInfo_.layOutKey) != "BSND") && + (std::string(opParamInfo_.layOutKey) != "TND")), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "layout_k", + std::string(opParamInfo_.layOutKey).c_str(), + "Layout_k only supports PA_BBND, BSND or TND"), + return ge::GRAPH_FAILED); + } - OP_CHECK_IF(!((*opParamInfo_.sparseCount > 0) && - (*opParamInfo_.sparseCount <= SPARSE_LIMIT)), - OP_LOGE(opName_, - "input attr sparse_count must > 0 and <= %d, but now " - "sparse_count is %d", - SPARSE_LIMIT, - *opParamInfo_.sparseCount), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - (*opParamInfo_.cmpRatio <= 0) || (*opParamInfo_.cmpRatio > 128) || - ((*opParamInfo_.cmpRatio & (*opParamInfo_.cmpRatio - 1)) != 0), - OP_LOGE( - opName_, - "input attr cmpRatio must > 0 and <= 128 and should be powers of 2," - " but now cmpRatio is %ld.", - *opParamInfo_.cmpRatio), - return ge::GRAPH_FAILED); + if (npuArch_ == NpuArch::DAV_2201) { + OP_CHECK_IF(!((*opParamInfo_.sparseCount > 0) && + (*opParamInfo_.sparseCount <= SPARSE_LIMIT)), + OP_LOGE(opName_, + "input attr sparse_count must > 0 and <= %d, but now " + "sparse_count is %d", + SPARSE_LIMIT, + *opParamInfo_.sparseCount), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (*opParamInfo_.cmpRatio <= 0) || (*opParamInfo_.cmpRatio > 128) || + ((*opParamInfo_.cmpRatio & (*opParamInfo_.cmpRatio - 1)) != 0), + OP_LOGE( + opName_, + "input attr cmpRatio must > 0 and <= 128 and should be powers of 2," + " but now cmpRatio is %ld.", + *opParamInfo_.cmpRatio), + return ge::GRAPH_FAILED); + } else if (npuArch_ == NpuArch::DAV_3510) { + OP_CHECK_IF( + !((*opParamInfo_.sparseCount > 0) && + (*opParamInfo_.sparseCount <= SPARSE_LIMIT_8K)), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "topk", + std::to_string(*opParamInfo_.sparseCount), + "Sparse_count must > 0 and <= " + std::to_string(SPARSE_LIMIT_8K)), + return ge::GRAPH_FAILED); + OP_CHECK_IF((*opParamInfo_.cmpRatio <= 0) || (*opParamInfo_.cmpRatio > 128), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "cmp_ratio", + std::to_string(*opParamInfo_.cmpRatio), + "Cmp_ratio must > 0 and <= 128"), + return ge::GRAPH_FAILED); + } OP_CHECK_IF(((std::string(opParamInfo_.layOutQuery) != "BSND") && (std::string(opParamInfo_.layOutQuery) != "TND")), @@ -433,6 +479,15 @@ ge::graphStatus QLIV2VaInfoParser::CheckAttrParaInfo() { std::string(opParamInfo_.layOutQuery).c_str(), "Layout_q only supports BSND or TND"), return ge::GRAPH_FAILED); + OP_CHECK_IF(((std::string(opParamInfo_.layOutKey) != "PA_BBND") && + (std::string(opParamInfo_.layOutQuery)) != + (std::string(opParamInfo_.layOutKey))), + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + opName_, + "layout_q and layout_k", + layout_query + " and " + layout_key, + "Outside of PA, layout_q and layout_k must be the same"), + return ge::GRAPH_FAILED); OP_CHECK_IF(!((*opParamInfo_.sparseMode == 0) || (*opParamInfo_.sparseMode == SPARSE_MODE_LOWER)), OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( @@ -441,13 +496,63 @@ ge::graphStatus QLIV2VaInfoParser::CheckAttrParaInfo() { std::to_string(*opParamInfo_.sparseMode).c_str(), "Sparse_mode only supports 0 or 3"), return ge::GRAPH_FAILED); - OP_CHECK_IF(*opParamInfo_.quantMode != 2, - OP_LOGE(opName_, "input attr quant_mode only supported 2."), - return ge::GRAPH_FAILED); + if (npuArch_ == NpuArch::DAV_2201) { + OP_CHECK_IF(*opParamInfo_.quantMode != 2, + OP_LOGE(opName_, "input attr quant_mode only supported 2."), + return ge::GRAPH_FAILED); + } else if (npuArch_ == NpuArch::DAV_3510) { + OP_CHECK_IF((*opParamInfo_.quantMode != QUANT_MODE_FP8) && + (*opParamInfo_.quantMode != QUANT_MODE_INT8) && + (*opParamInfo_.quantMode != QUANT_MODE_MXFP8) && + (*opParamInfo_.quantMode != QUANT_MODE_HIFLOAT8) && + (*opParamInfo_.quantMode != QUANT_MODE_MXFP4), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "sparse_mode", + std::to_string(*opParamInfo_.quantMode).c_str(), + "Quant_mode only supports 1, 2, 3, 4 and 5"), + return ge::GRAPH_FAILED); + } - OP_CHECK_IF(*opParamInfo_.returnValue, - OP_LOGE(opName_, "input attr returnValue only supported False."), - return ge::GRAPH_FAILED); + if (npuArch_ == NpuArch::DAV_2201) { + // return_value: 1 = DCP/普通 score 输出 (BF16, 无效槽 -inf); 2 = A3 + // 本地候选模式 (FP32)。 + OP_CHECK_IF((*opParamInfo_.returnValue != 0) && + (*opParamInfo_.returnValue != 1) && + (*opParamInfo_.returnValue != 2), + OP_LOGE(opName_, + "Arch22 return_value supports 0, 1 (DCP score) or 2 " + "(local candidates)."), + return ge::GRAPH_FAILED); + } else if (npuArch_ == NpuArch::DAV_3510) { + OP_CHECK_IF( + (*opParamInfo_.returnValue < 0) || (*opParamInfo_.returnValue > 2), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + opName_, + "return_value", + std::to_string(*opParamInfo_.returnValue).c_str(), + "Return_value only supports 0, 1 or private local-candidate mode " + "2"), + return ge::GRAPH_FAILED); + if (*opParamInfo_.returnValue == 2) { + OP_CHECK_IF(*opParamInfo_.sparseMode != 0 || + *opParamInfo_.cmpRatio != 1 || + *opParamInfo_.quantMode != QUANT_MODE_FP8 || + opParamInfo_.outputIdxOffset.tensor == nullptr, + OP_LOGE(opName_, + "Local candidates require FP8, mask_mode=0, " + "cmp_ratio=1 and local visible lengths."), + return ge::GRAPH_FAILED); + } + } + if (npuArch_ == NpuArch::DAV_2201 && *opParamInfo_.returnValue == 2) { + OP_CHECK_IF(*opParamInfo_.sparseMode != 0 || *opParamInfo_.cmpRatio != 1 || + opParamInfo_.outputIdxOffset.tensor == nullptr, + OP_LOGE(opName_, + "Local candidates require mask_mode=0, cmp_ratio=1 and " + "local visible lengths."), + return ge::GRAPH_FAILED); + } OP_CHECK_IF((*opParamInfo_.maxSeqlenQ < -1), OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( opName_, @@ -461,6 +566,11 @@ ge::graphStatus QLIV2VaInfoParser::CheckAttrParaInfo() { (opParamInfo_.candidateMode != nullptr) ? static_cast(*opParamInfo_.candidateMode) : CANDIDATE_MODE_OFF; + OP_CHECK_IF( + npuArch_ == NpuArch::DAV_2201 && *opParamInfo_.returnValue == 2 && + candidateMode != CANDIDATE_MODE_OFF, + OP_LOGE(opName_, "Local candidates require candidate_mode=3 (off)."), + return ge::GRAPH_FAILED); OP_CHECK_IF( (candidateMode != CANDIDATE_MODE_SOURCE) && (candidateMode != CANDIDATE_MODE_CONSUMER) && @@ -472,6 +582,12 @@ ge::graphStatus QLIV2VaInfoParser::CheckAttrParaInfo() { "Candidate_mode only supports 1(source), 2(consumer) or 3(off)"), return ge::GRAPH_FAILED); if (candidateMode != CANDIDATE_MODE_OFF) { + // candidate 功能当前仅在 arch22 (910b/910_93) 实现 + OP_CHECK_IF( + npuArch_ == NpuArch::DAV_3510, + OP_LOGE(opName_, + "candidate_mode only supported on ascend910b/ascend910_93."), + return ge::GRAPH_FAILED); // A12: layout_q 支持 BSND 与 TND (TND 需 cu_seqlens_q; layout_k 固定 // PA_BBND — K 仅支持分页布局) OP_CHECK_IF( @@ -529,6 +645,186 @@ ge::graphStatus QLIV2VaInfoParser::CheckAttrParaInfo() { "candidate_mode=2(consumer)"), return ge::GRAPH_FAILED); } + // candidate_block_length(候选块长度,DSL 契约):int32,元素数 = query + // 行数 + // TND → query 0 轴(所有序列拼接的 token 总数);BSND → B × S1。 + // 取值上界(≤ candidate_topk_blocks)由 kernel 侧钳位(host 读不到 device + // 张量数值)。 + if (opParamInfo_.candidateBlockLength.tensor != nullptr) { + OP_CHECK_IF( + opParamInfo_.candidateBlockLength.desc == nullptr || + opParamInfo_.candidateBlockLength.desc->GetDataType() != + ge::DT_INT32, + OP_LOGE(opName_, "candidate_block_length dtype only supports int32."), + return ge::GRAPH_FAILED); + const gert::StorageShape* candLenStorageShape = + context_->GetOptionalInputShape(CANDIDATE_BLOCK_LENGTH_INDEX); + OP_CHECK_IF(candLenStorageShape == nullptr, + OP_LOGE(opName_, "candidate_block_length shape is nullptr."), + return ge::GRAPH_FAILED); + const gert::Shape& candLenShape = candLenStorageShape->GetStorageShape(); + int64_t expectRows = 0; + if (std::string(opParamInfo_.layOutQuery) == "TND") { + expectRows = opParamInfo_.query.shape->GetStorageShape().GetDim(0); + } else { + expectRows = opParamInfo_.query.shape->GetStorageShape().GetDim(0) * + opParamInfo_.query.shape->GetStorageShape().GetDim(1); + } + OP_CHECK_IF(candLenShape.GetShapeSize() != expectRows, + OP_LOGE(opName_, + "candidate_block_length numel (%s) must equal query " + "row count (%s).", + std::to_string(candLenShape.GetShapeSize()).c_str(), + std::to_string(expectRows).c_str()), + return ge::GRAPH_FAILED); + } + // candidate_block_length_out(mode=1 输出,DSL candidate_length + // 语义:每行有效候选块数): + // int32、形状 [行数, N2]。可选:调用方未传时 kernel + // 侧指针为空、跳过写入。 + if (candidateMode == CANDIDATE_MODE_SOURCE) { + const gert::CompileTimeTensorDesc* candLenOutDesc = + context_->GetOutputDesc(CANDIDATE_BLOCK_LENGTH_OUTPUT_INDEX); + if (candLenOutDesc != nullptr) { + OP_CHECK_IF( + candLenOutDesc->GetDataType() != ge::DT_INT32, + OP_LOGE(opName_, + "candidate_block_length_out dtype only supports int32."), + return ge::GRAPH_FAILED); + const gert::StorageShape* candLenOutShape = + context_->GetOutputShape(CANDIDATE_BLOCK_LENGTH_OUTPUT_INDEX); + if (candLenOutShape != nullptr && + candLenOutShape->GetStorageShape().GetShapeSize() > 0) { + int64_t expectRows = 0; + if (std::string(opParamInfo_.layOutQuery) == "TND") { + expectRows = opParamInfo_.query.shape->GetStorageShape().GetDim(0); + } else { + expectRows = opParamInfo_.query.shape->GetStorageShape().GetDim(0) * + opParamInfo_.query.shape->GetStorageShape().GetDim(1); + } + // N2 口径与 infershape 一致:layout_k=TND 取 key.dim1,PA_BBND 取 + // key.dim2 + const int64_t keyHeadNum = + (std::string(opParamInfo_.layOutKey) == "TND") + ? opParamInfo_.key.shape->GetStorageShape().GetDim(1) + : opParamInfo_.key.shape->GetStorageShape().GetDim(2); + const int64_t expectNumel = expectRows * keyHeadNum; + OP_CHECK_IF( + candLenOutShape->GetStorageShape().GetShapeSize() != expectNumel, + OP_LOGE(opName_, + "candidate_block_length_out numel (%s) must equal rows x " + "N2 (%s).", + std::to_string( + candLenOutShape->GetStorageShape().GetShapeSize()) + .c_str(), + std::to_string(expectNumel).c_str()), + return ge::GRAPH_FAILED); + } + } + } + } + + // -------------------DCP (Decode Context Parallel, 解码上下文并行) + // 校验------------------- 关闭时做反向严格校验, 保证既有调用零变化; + // 开启时开放 arch22/arch35 的 TND + PA 路径。 + bool enableDcp = + (opParamInfo_.enableDcp != nullptr) ? *opParamInfo_.enableDcp : false; + int32_t cpWorld = + (opParamInfo_.cpWorld != nullptr) ? *opParamInfo_.cpWorld : 1; + int32_t cpRank = (opParamInfo_.cpRank != nullptr) ? *opParamInfo_.cpRank : 0; + int32_t cpInterleaveSize = (opParamInfo_.cpInterleaveSize != nullptr) + ? *opParamInfo_.cpInterleaveSize + : 1; + if (enableDcp) { + OP_CHECK_IF( + (npuArch_ != NpuArch::DAV_2201) && (npuArch_ != NpuArch::DAV_3510), + OP_LOGE(opName_, + "enable_dcp is only supported on " + "ascend910b/ascend910_93/ascend950, but got " + "NpuArch[%d].", + static_cast(npuArch_)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(std::string(opParamInfo_.layOutQuery) != "TND", + OP_LOGE(opName_, + "enable_dcp requires layout_q=TND, but got %s.", + std::string(opParamInfo_.layOutQuery).c_str()), + return ge::GRAPH_FAILED); + OP_CHECK_IF(std::string(opParamInfo_.layOutKey) != "PA_BBND", + OP_LOGE(opName_, + "enable_dcp requires layout_k=PA_BBND, but got %s.", + std::string(opParamInfo_.layOutKey).c_str()), + return ge::GRAPH_FAILED); + OP_CHECK_IF(*opParamInfo_.cmpRatio != 1, + OP_LOGE(opName_, + "enable_dcp requires cmp_ratio=1, but got %ld.", + *opParamInfo_.cmpRatio), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + candidateMode != CANDIDATE_MODE_OFF, + OP_LOGE( + opName_, + "enable_dcp is mutually exclusive with candidate_mode, but got %u.", + candidateMode), + return ge::GRAPH_FAILED); + OP_CHECK_IF(*opParamInfo_.returnValue != 1, + OP_LOGE(opName_, + "enable_dcp requires return_value=1 (cross-rank global " + "TopK needs scores)."), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.causalSeqLensKvGlobal.tensor == nullptr, + OP_LOGE(opName_, + "causal_seqlens_kv_global is required when enable_dcp=true."), + return ge::GRAPH_FAILED); + OP_CHECK_IF(cpWorld < 1, + OP_LOGE(opName_, "cp_world must >= 1, but got %d.", cpWorld), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (cpRank < 0) || (cpRank >= cpWorld), + OP_LOGE(opName_, + "cp_rank must be in [0, cp_world), but got rank=%d world=%d.", + cpRank, + cpWorld), + return ge::GRAPH_FAILED); + OP_CHECK_IF(cpInterleaveSize < 1, + OP_LOGE(opName_, + "cp_kv_cache_interleave_size must >= 1, but got %d.", + cpInterleaveSize), + return ge::GRAPH_FAILED); + // kernel 用 32 位 period = cp_world * cp_kv_cache_interleave_size + // 做可见长度计算; 限制在 int32 内, 保证 rem / rankOffset 的 int32 + // 转换不溢出 + OP_CHECK_IF( + static_cast(cpWorld) * static_cast(cpInterleaveSize) > + 0x7FFFFFFFLL, + OP_LOGE(opName_, + "cp_world * cp_kv_cache_interleave_size must fit in int32, but " + "got %d * %d.", + cpWorld, + cpInterleaveSize), + return ge::GRAPH_FAILED); + // DCP 下索引保持本地逻辑序号, 由框架统一转全局; 再叠加 output_idx_offset + // 会重复偏移。 + OP_CHECK_IF(opParamInfo_.outputIdxOffset.tensor != nullptr, + OP_LOGE(opName_, + "output_idx_offset must be null when enable_dcp=true."), + return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF( + (cpWorld != 1) || (cpRank != 0) || (cpInterleaveSize != 1), + OP_LOGE( + opName_, + "cp_world/cp_rank/cp_kv_cache_interleave_size must be 1/0/1 when " + "enable_dcp=false, but got %d/%d/%d.", + cpWorld, + cpRank, + cpInterleaveSize), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.causalSeqLensKvGlobal.tensor != nullptr, + OP_LOGE(opName_, + "causal_seqlens_kv_global must be null when enable_dcp=false."), + return ge::GRAPH_FAILED); } return ge::GRAPH_SUCCESS; @@ -573,21 +869,76 @@ ge::graphStatus QLIV2VaInfoParser::GetAndCheckInOutDataType() { QLIV2VaDataTypeToSerialString(inputKeyScaleType_), "The dtype of q_descale and k_descale must be same"), return ge::GRAPH_FAILED); - OP_CHECK_IF( - inputQType_ != ge::DT_INT8, - OP_LOGE(opName_, - "The data types of the input query and key must be int8."), - return ge::GRAPH_FAILED); - OP_CHECK_IF(inputQueryScaleType_ != ge::DT_FLOAT16, - OP_LOGE(opName_, - "The data types of the input query_dequant_scale and " - "key_dequant_scale must be float16."), - return ge::GRAPH_FAILED); + if (npuArch_ == NpuArch::DAV_2201) { + OP_CHECK_IF( + inputQType_ != ge::DT_INT8, + OP_LOGE(opName_, + "The data types of the input query and key must be int8."), + return ge::GRAPH_FAILED); + OP_CHECK_IF(inputQueryScaleType_ != ge::DT_FLOAT16, + OP_LOGE(opName_, + "The data types of the input query_dequant_scale and " + "key_dequant_scale must be float16."), + return ge::GRAPH_FAILED); + } else if (npuArch_ == NpuArch::DAV_3510) { + ge::DataType expectQType = ge::DT_FLOAT8_E4M3FN; + ge::DataType expectScaleType = ge::DT_FLOAT; + if (*opParamInfo_.quantMode == QUANT_MODE_MXFP8) { + expectScaleType = ge::DT_FLOAT8_E8M0; + } else if (*opParamInfo_.quantMode == QUANT_MODE_HIFLOAT8) { + expectQType = ge::DT_HIFLOAT8; + } else if (*opParamInfo_.quantMode == QUANT_MODE_MXFP4) { + expectQType = ge::DT_FLOAT4_E2M1; + expectScaleType = ge::DT_FLOAT8_E8M0; + } else if (*opParamInfo_.quantMode == QUANT_MODE_INT8) { + expectQType = ge::DT_INT8; + expectScaleType = ge::DT_FLOAT16; + } + OP_CHECK_IF(inputQType_ != expectQType, + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( + opName_, + "q and k", + QLIV2VaDataTypeToSerialString(inputQType_) + " and " + + QLIV2VaDataTypeToSerialString(inputKType_), + "The dtype of q and k must match quant_mode"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + inputQueryScaleType_ != expectScaleType, + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( + opName_, + "q_descale and k_descale", + QLIV2VaDataTypeToSerialString(inputQueryScaleType_) + " and " + + QLIV2VaDataTypeToSerialString(inputKeyScaleType_), + "The dtype of q_descale and k_descale must match quant_mode"), + return ge::GRAPH_FAILED); + } - OP_CHECK_IF( - weightsType_ != ge::DT_FLOAT16, - OP_LOGE(opName_, "The data types of the input weights must be float16."), - return ge::GRAPH_FAILED); + if (npuArch_ == NpuArch::DAV_2201) { + OP_CHECK_IF(weightsType_ != ge::DT_FLOAT16, + OP_LOGE(opName_, + "The data types of the input weights must be float16."), + return ge::GRAPH_FAILED); + } else if (npuArch_ == NpuArch::DAV_3510) { + if (inputQType_ == ge::DT_INT8) { + OP_CHECK_IF(weightsType_ != ge::DT_FLOAT16, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "w", + QLIV2VaDataTypeToSerialString(weightsType_).c_str(), + "When the dtype of query is int8, the dtype of w must be " + "float16"), + return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF(weightsType_ != ge::DT_FLOAT, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "w", + QLIV2VaDataTypeToSerialString(weightsType_).c_str(), + "When the dtype of query is not int8, the dtype of w " + "must be float"), + return ge::GRAPH_FAILED); + } + } OP_CHECK_IF(outputType_ != ge::DT_INT32, OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( @@ -596,12 +947,18 @@ ge::graphStatus QLIV2VaInfoParser::GetAndCheckInOutDataType() { QLIV2VaDataTypeToSerialString(outputType_).c_str(), "The dtype of sparse_indices must be int32"), return ge::GRAPH_FAILED); - OP_CHECK_IF(valuesOutType_ != ge::DT_BF16, + const ge::DataType expectedValuesType = + npuArch_ == NpuArch::DAV_2201 && *opParamInfo_.returnValue == 2 + ? ge::DT_FLOAT + : ge::DT_BF16; + OP_CHECK_IF(valuesOutType_ != expectedValuesType, OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( opName_, "sparse_values", QLIV2VaDataTypeToSerialString(valuesOutType_).c_str(), - "The dtype of sparse_values must be bfloat16"), + expectedValuesType == ge::DT_FLOAT + ? "A3 local sparse_values must be float32" + : "The dtype of sparse_values must be bfloat16"), return ge::GRAPH_FAILED); return ge::GRAPH_SUCCESS; @@ -877,6 +1234,34 @@ ge::graphStatus QLIV2VaInfoParser::GetAndCheckOptionalInput() { return ge::GRAPH_FAILED); } } + if (npuArch_ == NpuArch::DAV_3510) { + if (opParamInfo_.outputIdxOffset.tensor != nullptr) { + OP_CHECK_IF( + opParamInfo_.outputIdxOffset.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "output_idx_offset", + QLIV2VaDataTypeToSerialString( + opParamInfo_.sequsedQ.desc->GetDataType()) + .c_str(), + "The dtype of output_idx_offset only supports int32"), + return ge::GRAPH_FAILED); + } + } + if (npuArch_ == NpuArch::DAV_2201 && *opParamInfo_.returnValue == 2) { + if (opParamInfo_.outputIdxOffset.tensor != nullptr) { + OP_CHECK_IF( + opParamInfo_.outputIdxOffset.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "output_idx_offset", + QLIV2VaDataTypeToSerialString( + opParamInfo_.outputIdxOffset.desc->GetDataType()) + .c_str(), + "The dtype of output_idx_offset only supports int32"), + return ge::GRAPH_FAILED); + } + } // metadata 必传 OP_CHECK_IF(opParamInfo_.metadata.tensor == nullptr, OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( @@ -957,6 +1342,48 @@ ge::graphStatus QLIV2VaInfoParser::CheckShapeDim() { std::to_string(expectShapeDim - 1).c_str()), return ge::GRAPH_FAILED); } + if (npuArch_ == NpuArch::DAV_3510 && *opParamInfo_.returnValue != 0) { + uint32_t sparseValuesShapeDim = + opParamInfo_.sparseValues.shape->GetStorageShape().GetDimNum(); + OP_CHECK_IF(sparseValuesShapeDim != expectShapeDim, + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + "sparse_values", + std::to_string(sparseValuesShapeDim).c_str(), + std::to_string(expectShapeDim).c_str()), + return ge::GRAPH_FAILED); + } + if (npuArch_ == NpuArch::DAV_2201 && *opParamInfo_.returnValue == 2) { + // The Arch22 private mode writes one score per index and reads one visible + // length per output row. Validate every dimension before GM access. + uint32_t sparseValuesShapeDim = + opParamInfo_.sparseValues.shape->GetStorageShape().GetDimNum(); + OP_CHECK_IF(sparseValuesShapeDim != expectShapeDim, + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + "sparse_values", + std::to_string(sparseValuesShapeDim).c_str(), + std::to_string(expectShapeDim).c_str()), + return ge::GRAPH_FAILED); + const auto& indexShape = opParamInfo_.attenOut.shape->GetStorageShape(); + const auto& valueShape = opParamInfo_.sparseValues.shape->GetStorageShape(); + const auto& visibleShape = + opParamInfo_.outputIdxOffset.tensor->GetStorageShape(); + for (uint32_t dim = 0; dim < expectShapeDim; dim++) { + OP_CHECK_IF( + valueShape.GetDim(dim) != indexShape.GetDim(dim), + OP_LOGE(opName_, + "Local candidate score shape must match sparse_indices."), + return ge::GRAPH_FAILED); + if (dim + 1 < expectShapeDim) { + OP_CHECK_IF(visibleShape.GetDim(dim) != indexShape.GetDim(dim), + OP_LOGE(opName_, + "Local visible lengths must match sparse_indices " + "row dimensions."), + return ge::GRAPH_FAILED); + } + } + } OP_CHECK_IF( !(weightsShapeDim == expectShapeDim - 1), OP_LOGE_FOR_INVALID_SHAPEDIM(opName_, @@ -1032,15 +1459,29 @@ ge::graphStatus QLIV2VaInfoParser::GetGSize() { } gSize_ = n1Size_ / n2Size_; - // 910b/910_93: 支持 gSize=64/32 (32 参照 v1 quant_lightning_indexer, - // mBaseSize=4*gSize 推导) - OP_CHECK_IF( - (gSize_ != G_SIZE_LIMIT) && (gSize_ != G_SIZE_LIMIT_32), - OP_LOGE(opName_, - "N1 is %u, N2 is %u, N1 divided by N2 must equal 64 or 32.", - n1Size_, - n2Size_), - return ge::GRAPH_FAILED); + if (npuArch_ == NpuArch::DAV_3510) { + OP_CHECK_IF( + gSize_ > G_SIZE_LIMIT, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and k", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog(opParamInfo_.key.shape->GetStorageShape()), + "The value of (the head num of q divided by the head num of k) " + "must <= 64"), + return ge::GRAPH_FAILED); + } else { + // 910b/910_93: 支持 gSize=64/32 (32 参照 v1 quant_lightning_indexer, + // mBaseSize=4*gSize 推导) + OP_CHECK_IF( + (gSize_ != G_SIZE_LIMIT) && (gSize_ != G_SIZE_LIMIT_32_950), + OP_LOGE(opName_, + "N1 is %u, N2 is %u, N1 divided by N2 must equal 64 or 32.", + n1Size_, + n2Size_), + return ge::GRAPH_FAILED); + } return ge::GRAPH_SUCCESS; } @@ -1298,6 +1739,49 @@ ge::graphStatus QLIV2VaInfoParser::ValidateInputShapesMatch() { opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0)) + " respectively, they must be same"), return ge::GRAPH_FAILED); + if (npuArch_ == NpuArch::DAV_3510) { + if (*opParamInfo_.returnValue != 0 && + opParamInfo_.sparseValues.shape != nullptr) { + OP_CHECK_IF( + (opParamInfo_.sparseValues.shape->GetStorageShape().GetDim(0) != + qTsize), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and sparse_values", + ShapeToStringForLog( + opParamInfo_.query.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.sparseValues.shape->GetStorageShape()), + "TND case q and sparse_values dim 0 are " + + std::to_string(qTsize) + ", " + + std::to_string( + opParamInfo_.sparseValues.shape->GetStorageShape() + .GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + } + if (opParamInfo_.outputIdxOffset.tensor != nullptr) { + OP_CHECK_IF( + (opParamInfo_.outputIdxOffset.tensor->GetStorageShape().GetDim(0) != + qTsize), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and output_idx_offset", + ShapeToStringForLog( + opParamInfo_.query.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.outputIdxOffset.tensor->GetStorageShape()), + "TND case q and output_idx_offset dim 0 are " + + std::to_string(qTsize) + " and " + + std::to_string( + opParamInfo_.outputIdxOffset.tensor->GetStorageShape() + .GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + } + } } else { // -----------------------check BatchSize------------------- // bSize_ 来源于query @@ -1502,6 +1986,59 @@ ge::graphStatus QLIV2VaInfoParser::ValidateInputShapesMatch() { std::to_string(bSize_) + ")"), return ge::GRAPH_FAILED); } + // -----------------------check causal_seqlens_kv_global + // (DCP)------------------- + if (opParamInfo_.causalSeqLensKvGlobal.tensor != nullptr) { + OP_CHECK_IF( + (opParamInfo_.causalSeqLensKvGlobal.desc == nullptr) || + (opParamInfo_.causalSeqLensKvGlobal.desc->GetDataType() != + ge::DT_INT32), + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, + "causal_seqlens_kv_global", + "not int32", + "The dtype of causal_seqlens_kv_global only supports int32"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (opParamInfo_.causalSeqLensKvGlobal.tensor->GetShapeSize() != bSize_), + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, + "causal_seqlens_kv_global", + std::to_string( + opParamInfo_.causalSeqLensKvGlobal.tensor->GetShapeSize()), + "The shape size of causal_seqlens_kv_global must be equal to " + "batch_size (" + + std::to_string(bSize_) + ")"), + return ge::GRAPH_FAILED); + } + // -----------------------check sparse_values------------------ + if (npuArch_ == NpuArch::DAV_3510) { + if (*opParamInfo_.returnValue != 0) { + OP_CHECK_IF( + (opParamInfo_.sparseValues.shape->GetStorageShape().GetDim( + outN2Dim) != n2Size_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "k and sparse_values", + ShapeToStringForLog(opParamInfo_.key.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.sparseValues.shape->GetStorageShape()), + "The head num of k and sparse_values must be same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + (opParamInfo_.sparseValues.shape->GetStorageShape().GetDim( + outN2Dim + 1) != *opParamInfo_.sparseCount), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "topk and sparse_values", + std::to_string(*opParamInfo_.sparseCount) + " and " + + ShapeToStringForLog( + opParamInfo_.sparseValues.shape->GetStorageShape()), + "The last dim of sparse_values must be same as topk"), + return ge::GRAPH_FAILED); + } + } // -----------------------check metadata------------------- OP_CHECK_IF( (opParamInfo_.metadata.tensor->GetShapeSize() != METADATA_LIMIT), @@ -1522,58 +2059,212 @@ ge::graphStatus QLIV2VaInfoParser::CheckScaleShape() { opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDimNum(); uint32_t kDequantScaleShapeDim = opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDimNum(); + bool isMxQuantMode = (*opParamInfo_.quantMode == QUANT_MODE_MXFP8) || + (*opParamInfo_.quantMode == QUANT_MODE_MXFP4); - OP_CHECK_IF(qDequantScaleShapeDim != (qShapeDim - 1), - OP_LOGE_FOR_INVALID_SHAPEDIM( - opName_, - "q_descale", - std::to_string(qDequantScaleShapeDim).c_str(), - std::to_string(qShapeDim - 1).c_str()), - return ge::GRAPH_FAILED); - OP_CHECK_IF(kDequantScaleShapeDim != (kShapeDim - 1), - OP_LOGE_FOR_INVALID_SHAPEDIM( - opName_, - "k_descale", - std::to_string(kDequantScaleShapeDim).c_str(), - std::to_string(kShapeDim - 1).c_str()), - return ge::GRAPH_FAILED); - // check q scale - for (uint32_t i = 0; i < (qShapeDim - 1); i++) { - uint32_t dimValueQueryScale = - opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDim(i); - uint32_t dimValueQuery = - opParamInfo_.query.shape->GetStorageShape().GetDim(i); + if (*opParamInfo_.quantMode == QUANT_MODE_HIFLOAT8) { + OP_CHECK_IF( + qDequantScaleShapeDim != 1, + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + opName_, + "q_descale", + std::to_string(qDequantScaleShapeDim).c_str(), + "When quant_mode is 4, the dim num of q_descale should be 1"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + kDequantScaleShapeDim != 1, + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + opName_, + "k_descale", + std::to_string(kDequantScaleShapeDim).c_str(), + "When quant_mode is 4, the dim num of k_descale should be 1"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDim(0) != + 1, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "q_descale", + ToStringRaw( + opParamInfo_.query_dequant_scale.shape->GetStorageShape()) + .c_str(), + "When quant_mode is 4, q_descale's shape[0] should be 1, but now " + "is " + + std::to_string( + opParamInfo_.query_dequant_scale.shape->GetStorageShape() + .GetDim(0))), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDim(0) != 1, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "k_descale", + ToStringRaw(opParamInfo_.key_dequant_scale.shape->GetStorageShape()) + .c_str(), + "When quant_mode is 4, k_descale's shape[0] should be 1, but now " + "is " + + std::to_string( + opParamInfo_.key_dequant_scale.shape->GetStorageShape() + .GetDim(0))), + return ge::GRAPH_FAILED); + } else if (isMxQuantMode) { + OP_CHECK_IF( + headDim_ % MX_SCALE_SHAPE_ALIGN != 0, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, + "q", + ToStringRaw(opParamInfo_.query.shape->GetStorageShape()).c_str(), + "When quant_mode is " + std::to_string(*opParamInfo_.quantMode) + + ", head_dim should be a multiple of " + + std::to_string(MX_SCALE_SHAPE_ALIGN) + ", but now is " + + std::to_string(headDim_)), + return ge::GRAPH_FAILED); OP_CHECK_IF( - dimValueQueryScale != dimValueQuery, + qDequantScaleShapeDim != (qShapeDim + 1), + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + opName_, + "q_descale", + std::to_string(qDequantScaleShapeDim).c_str(), + "When quant_mode is " + std::to_string(*opParamInfo_.quantMode) + + ", the dim num of q_descale should be " + + std::to_string(qShapeDim + 1)), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + kDequantScaleShapeDim != (kShapeDim + 1), + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + opName_, + "k_descale", + std::to_string(qDequantScaleShapeDim).c_str(), + "When quant_mode is " + std::to_string(*opParamInfo_.quantMode) + + ", the dim num of k_descale should be " + + std::to_string(kShapeDim + 1)), + return ge::GRAPH_FAILED); + for (uint32_t i = 0; i < (qShapeDim - 1); i++) { + uint32_t dimValueQueryScale = + opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDim(i); + uint32_t dimValueQuery = + opParamInfo_.query.shape->GetStorageShape().GetDim(i); + OP_CHECK_IF( + dimValueQueryScale != dimValueQuery, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q and q_descale", + ShapeToStringForLog(opParamInfo_.query.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog(opParamInfo_.query_dequant_scale.shape + ->GetStorageShape()), + "Q_descale's shape[" + std::to_string(i) + "] " + + std::to_string(dimValueQueryScale) + " and q's shape[" + + std::to_string(i) + "] " + std::to_string(dimValueQuery) + + " are not same"), + return ge::GRAPH_FAILED); + } + for (uint32_t i = 0; i < (kShapeDim - 1); i++) { + uint32_t dimValueKeyScale = + opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDim(i); + uint32_t dimValueKey = + opParamInfo_.key.shape->GetStorageShape().GetDim(i); + OP_CHECK_IF( + dimValueKeyScale != dimValueKey, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "k and k_descale", + ShapeToStringForLog(opParamInfo_.key.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.key_dequant_scale.shape->GetStorageShape()), + "K_descale's shape[" + std::to_string(i) + "] " + + std::to_string(dimValueKeyScale) + " and k's shape[" + + std::to_string(i) + "] " + std::to_string(dimValueKey) + + " are not the same"), + return ge::GRAPH_FAILED); + } + uint32_t expectScaleD = headDim_ / MX_SCALE_SHAPE_ALIGN; + OP_CHECK_IF( + (opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDim( + qShapeDim - 1) != expectScaleD) || + (opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDim( + qShapeDim) != MX_E8M0_SCALE_PACK_NUM), OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( opName_, - "q_descale and q", + "q_descale", ShapeToStringForLog( - opParamInfo_.query_dequant_scale.shape->GetStorageShape()) + - " and " + - ShapeToStringForLog( - opParamInfo_.query.shape->GetStorageShape()), - "q_descale's shape[" + std::to_string(i) + "] and q's shape[" + - std::to_string(i) + "] are not the same"), + opParamInfo_.query_dequant_scale.shape->GetStorageShape()), + "When quant_mode is " + std::to_string(*opParamInfo_.quantMode) + + ", q_descale's last dims should be [" + + std::to_string(expectScaleD) + ", " + + std::to_string(MX_E8M0_SCALE_PACK_NUM) + "]"), return ge::GRAPH_FAILED); - } - // check k scale - for (uint32_t i = 0; i < (kShapeDim - 1); i++) { - uint32_t dimValueKeyScale = - opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDim(i); - uint32_t dimValueKey = opParamInfo_.key.shape->GetStorageShape().GetDim(i); OP_CHECK_IF( - dimValueKeyScale != dimValueKey, + (opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDim( + kShapeDim - 1) != expectScaleD) || + (opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDim( + kShapeDim) != MX_E8M0_SCALE_PACK_NUM), OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( opName_, - "k_descale and k", + "k_descale", ShapeToStringForLog( - opParamInfo_.key_dequant_scale.shape->GetStorageShape()) + - " and " + - ShapeToStringForLog(opParamInfo_.key.shape->GetStorageShape()), - "k_descale's shape[" + std::to_string(i) + "] and k's shape[" + - std::to_string(i) + "] are not the same"), + opParamInfo_.key_dequant_scale.shape->GetStorageShape()), + "When quant_mode is " + std::to_string(*opParamInfo_.quantMode) + + ", k_descale's last dims should be [" + + std::to_string(expectScaleD) + ", " + + std::to_string(MX_E8M0_SCALE_PACK_NUM) + "]"), return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF(qDequantScaleShapeDim != (qShapeDim - 1), + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + "q_descale", + std::to_string(qDequantScaleShapeDim).c_str(), + std::to_string(qShapeDim - 1).c_str()), + return ge::GRAPH_FAILED); + OP_CHECK_IF(kDequantScaleShapeDim != (kShapeDim - 1), + OP_LOGE_FOR_INVALID_SHAPEDIM( + opName_, + "k_descale", + std::to_string(kDequantScaleShapeDim).c_str(), + std::to_string(kShapeDim - 1).c_str()), + return ge::GRAPH_FAILED); + // check q scale + for (uint32_t i = 0; i < (qShapeDim - 1); i++) { + uint32_t dimValueQueryScale = + opParamInfo_.query_dequant_scale.shape->GetStorageShape().GetDim(i); + uint32_t dimValueQuery = + opParamInfo_.query.shape->GetStorageShape().GetDim(i); + OP_CHECK_IF( + dimValueQueryScale != dimValueQuery, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "q_descale and q", + ShapeToStringForLog( + opParamInfo_.query_dequant_scale.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.query.shape->GetStorageShape()), + "q_descale's shape[" + std::to_string(i) + "] and q's shape[" + + std::to_string(i) + "] are not the same"), + return ge::GRAPH_FAILED); + } + // check k scale + for (uint32_t i = 0; i < (kShapeDim - 1); i++) { + uint32_t dimValueKeyScale = + opParamInfo_.key_dequant_scale.shape->GetStorageShape().GetDim(i); + uint32_t dimValueKey = + opParamInfo_.key.shape->GetStorageShape().GetDim(i); + OP_CHECK_IF( + dimValueKeyScale != dimValueKey, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, + "k_descale and k", + ShapeToStringForLog( + opParamInfo_.key_dequant_scale.shape->GetStorageShape()) + + " and " + + ShapeToStringForLog( + opParamInfo_.key.shape->GetStorageShape()), + "k_descale's shape[" + std::to_string(i) + "] and k's shape[" + + std::to_string(i) + "] are not the same"), + return ge::GRAPH_FAILED); + } } return ge::GRAPH_SUCCESS; @@ -1585,10 +2276,10 @@ ge::graphStatus QLIV2VaInfoParser::CheckScaleShape() { ge::graphStatus QLIV2VaInfoParser::CheckKeyContiguous() const { bool keyNonContiguous = false; bool scaleNonContiguous = false; - // A11 PA_BBND: 0轴允许非连续,从1轴开始检查;非PA_BBND: 从0轴开始检查 - // (arch22 kernel 已按 keyStride0/keyDequantScaleStride0 寻址, 紧凑值兜底) - // PA_BBND: axis 0 allows non-contiguous, check starts from axis 1 - // Non-PA_BBND: check starts from axis 0 + // A5/A11 PA_BBND: 0轴允许非连续,从1轴开始检查;非PA_BBND: 从0轴开始检查 + // (A11 起不限 arch35 — arch22 kernel 已按 keyStride0/keyDequantScaleStride0 + // 寻址, 紧凑值兜底) PA_BBND: axis 0 allows non-contiguous, check starts from + // axis 1 Non-PA_BBND: check starts from axis 0 size_t checkStartIdx = (kLayout_ == QliV2DataLayout::PA_BBND) ? 1 : 0; if (!keyStridesVec_.empty() && opParamInfo_.key.shape != nullptr) { auto& shape = opParamInfo_.key.shape->GetStorageShape(); @@ -1610,15 +2301,36 @@ ge::graphStatus QLIV2VaInfoParser::CheckKeyContiguous() const { } } } - if (!keyDequantScaleStridesVec_.empty() && + bool isMxQuantMode = (*opParamInfo_.quantMode == QUANT_MODE_MXFP8) || + (*opParamInfo_.quantMode == QUANT_MODE_MXFP4); + if ((*opParamInfo_.quantMode != QUANT_MODE_HIFLOAT8) && + !keyDequantScaleStridesVec_.empty() && opParamInfo_.key_dequant_scale.shape != nullptr) { auto& shape = opParamInfo_.key_dequant_scale.shape->GetStorageShape(); std::vector expectedStrides; - if (kLayout_ == QliV2DataLayout::BSND || - kLayout_ == QliV2DataLayout::PA_BBND) { - expectedStrides = {shape.GetDim(1) * shape.GetDim(2), shape.GetDim(2), 1}; - } else if (kLayout_ == QliV2DataLayout::TND) { - expectedStrides = {shape.GetDim(1), 1}; + if (isMxQuantMode) { + if (kLayout_ == QliV2DataLayout::BSND || + kLayout_ == QliV2DataLayout::PA_BBND) { + expectedStrides = {shape.GetDim(1) * shape.GetDim(2) * shape.GetDim(3) * + shape.GetDim(4), + shape.GetDim(2) * shape.GetDim(3) * shape.GetDim(4), + shape.GetDim(3) * shape.GetDim(4), + shape.GetDim(4), + 1}; + } else if (kLayout_ == QliV2DataLayout::TND) { + expectedStrides = {shape.GetDim(1) * shape.GetDim(2) * shape.GetDim(3), + shape.GetDim(2) * shape.GetDim(3), + shape.GetDim(3), + 1}; + } + } else { + if (kLayout_ == QliV2DataLayout::BSND || + kLayout_ == QliV2DataLayout::PA_BBND) { + expectedStrides = { + shape.GetDim(1) * shape.GetDim(2), shape.GetDim(2), 1}; + } else if (kLayout_ == QliV2DataLayout::TND) { + expectedStrides = {shape.GetDim(1), 1}; + } } for (size_t i = checkStartIdx; i < expectedStrides.size(); ++i) { if (i < keyDequantScaleStridesVec_.size() && @@ -1630,14 +2342,27 @@ ge::graphStatus QLIV2VaInfoParser::CheckKeyContiguous() const { } if (kLayout_ == QliV2DataLayout::PA_BBND) { if (!keyStridesVec_.empty()) { - OP_CHECK_IF(keyStridesVec_[0] <= 0, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "k", - "When layout_k is PA_BBND, key stride0 must be positive, " - "but got " + - std::to_string(keyStridesVec_[0])), - return ge::GRAPH_FAILED); + if (*opParamInfo_.quantMode == QUANT_MODE_MXFP4) { + OP_CHECK_IF( + keyStridesVec_[0] <= 0 || keyStridesVec_[0] % MXFP4_PACK_NUM != 0, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "k", + "When quant_mode is 5 and layout_k is PA_BBND, key stride0 " + "must be positive and satisfy " + "2-element FP4 packing alignment, but got " + + std::to_string(keyStridesVec_[0])), + return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF(keyStridesVec_[0] <= 0, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "k", + "When layout_k is PA_BBND, key stride0 must be " + "positive, but got " + + std::to_string(keyStridesVec_[0])), + return ge::GRAPH_FAILED); + } } // A11 校验: 显式属性 stride0 不得小于紧凑值 (0 轴只允许 padding 型非连续) if (opParamInfo_.keyStride0Attr != nullptr && @@ -1670,6 +2395,19 @@ ge::graphStatus QLIV2VaInfoParser::CheckKeyContiguous() const { std::to_string(compactScale0) + ")"), return ge::GRAPH_FAILED); } + if (isMxQuantMode && !keyDequantScaleStridesVec_.empty()) { + OP_CHECK_IF( + keyDequantScaleStridesVec_[0] <= 0 || + keyDequantScaleStridesVec_[0] % MX_E8M0_SCALE_PACK_NUM != 0, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, + "k_descale", + "When quant_mode is 3 or 5 and layout_k is PA_BBND, " + "key_dequant_scale stride0 must be positive " + "and satisfy 2-element E8M0 packing alignment, but got " + + std::to_string(keyDequantScaleStridesVec_[0])), + return ge::GRAPH_FAILED); + } } OP_CHECK_IF( keyNonContiguous || scaleNonContiguous, @@ -1722,11 +2460,29 @@ void QLIV2VaInfoParser::GenerateInfo(QLIV2VaTilingInfo& QLIV2VaInfo) { (opParamInfo_.candidateBlockSize != nullptr) ? static_cast(*opParamInfo_.candidateBlockSize) : CANDIDATE_BLOCK_SIZE_DEFAULT; + // ---- DCP (Decode Context Parallel, 解码上下文并行) ---- + QLIV2VaInfo.dcpEnable = + (opParamInfo_.enableDcp != nullptr) ? *opParamInfo_.enableDcp : false; + QLIV2VaInfo.cpWorld = (opParamInfo_.cpWorld != nullptr) + ? static_cast(*opParamInfo_.cpWorld) + : 1U; + QLIV2VaInfo.cpRank = (opParamInfo_.cpRank != nullptr) + ? static_cast(*opParamInfo_.cpRank) + : 0U; + QLIV2VaInfo.cpInterleaveSize = + (opParamInfo_.cpInterleaveSize != nullptr) + ? static_cast(*opParamInfo_.cpInterleaveSize) + : 1U; QLIV2VaInfo.keyStridesVec = keyStridesVec_; QLIV2VaInfo.keyDequantScaleStridesVec = keyDequantScaleStridesVec_; if (!keyStridesVec_.empty()) { - QLIV2VaInfo.keyStride0 = static_cast(keyStridesVec_[0]); + uint32_t keyStride0 = static_cast(keyStridesVec_[0]); + if (*opParamInfo_.quantMode == QUANT_MODE_MXFP4) { + // FP4 shape stride以逻辑元素计数,kernel侧以打包后的uint8为寻址单位。 + keyStride0 /= MXFP4_PACK_NUM; + } + QLIV2VaInfo.keyStride0 = keyStride0; } else if (opParamInfo_.keyStride0Attr != nullptr && *opParamInfo_.keyStride0Attr > 0) { // A11: aclnn 动态调用下 GetDynamicInputStride 恒空, 由显式属性兜底 (csrc @@ -1743,6 +2499,10 @@ void QLIV2VaInfoParser::GenerateInfo(QLIV2VaTilingInfo& QLIV2VaInfo) { *opParamInfo_.keyDequantScaleStride0Attr > 0) { QLIV2VaInfo.keyDequantScaleStride0 = static_cast(*opParamInfo_.keyDequantScaleStride0Attr); + } else if ((*opParamInfo_.quantMode == QUANT_MODE_MXFP8) || + (*opParamInfo_.quantMode == QUANT_MODE_MXFP4)) { + QLIV2VaInfo.keyDequantScaleStride0 = + static_cast(blockSize_) * (headDim_ / MX_SCALE_GROUP_SIZE); } else { QLIV2VaInfo.keyDequantScaleStride0 = 0; } @@ -1791,13 +2551,13 @@ ge::graphStatus QLIV2VaInfoParser::ParseAndCheck( } // --------------------------TilingPrepare函数定义------------------------------------- -static ge::graphStatus TilingPrepareForXllmKernelQuantLightningIndexerV2Va( +static ge::graphStatus TilingPrepareForXllmKernelQuantLightningIndexerV3Va( gert::TilingParseContext* /* context */) { return ge::GRAPH_SUCCESS; } -// --------------------------XllmKernelQuantLightningIndexerV2VaTiling类成员函数定义----------------------- -ge::graphStatus XllmKernelQuantLightningIndexerV2VaTiling::DoTiling( +// --------------------------XllmKernelQuantLightningIndexerV3VaTiling类成员函数定义----------------------- +ge::graphStatus XllmKernelQuantLightningIndexerV3VaTiling::DoTiling( QLIV2VaTilingInfo* tilingInfo) { // -------------set blockdim----------------- auto ascendcPlatform = @@ -1819,20 +2579,92 @@ ge::graphStatus XllmKernelQuantLightningIndexerV2VaTiling::DoTiling( constexpr uint32_t V1_DECODE_DATA_NUM = 2; // Decode每个核需要存储头和尾部两块数据 constexpr uint32_t S1_BASE_SIZE = 4; // S1轴基本块的大小 - constexpr uint32_t TOPK_MAX_SIZE = 2048; // TopK选取个数 + constexpr uint32_t TOPK_MAX_SIZE = 2048; // TopK选取个数 + constexpr uint32_t TOPK_MAX_SIZE_950 = 8192; // A5 TopK最大选取个数 uint64_t workspaceSize = ascendcPlatform.GetLibApiWorkSpaceSize(); // 主流程需Workspace大小 - uint32_t mm1ResSize = M_BASE_SIZE * S2_BASE_SIZE; - workspaceSize += mm1ResSize * MM1_RES_ELEM_SIZE * DOUBLE_BUFFER * aicNum; - // Decode流程(LD)需要Workspace大小 - // 临时存储Decode中间结果大小: - // 2(头/尾)*8(s1Base)*2(idx/value)*2048(K)*sizeof(int32)*24=6M - workspaceSize += V1_DECODE_DATA_NUM * S1_BASE_SIZE * V1_RES_ELEM_TYPE * - TOPK_MAX_SIZE * V1_RES_ELEM_SIZE * aicNum; - // 临时存储Decode中间参数信息大小: - // 2(头/尾)*8(s1Base)*16(paramNum)*sizeof(int64_t)*24=48k - workspaceSize += V1_DECODE_DATA_NUM * S1_BASE_SIZE * V1_DECODE_PARAM_NUM * - V1_DECODE_PARAM_ELEM_SIZE * aicNum; + if (ascendcPlatform.GetCurNpuArch() == NpuArch::DAV_3510) { + constexpr uint32_t S1_BASE_SIZE_950 = 4; + constexpr uint32_t S2_BASE_SIZE_950 = 128; + workspaceSize += + S1_BASE_SIZE_950 * + ((tilingInfo->s2Size + S2_BASE_SIZE_950 - 1) / S2_BASE_SIZE_950) * + S2_BASE_SIZE_950 * sizeof(uint16_t) * aicNum; + // 临时存储Decode中间结果大小: + // 2(头/尾)*8(s1Base)*2(idx/value)*2048(K)*sizeof(int32)*24=6M + workspaceSize += V1_DECODE_DATA_NUM * S1_BASE_SIZE * V1_RES_ELEM_TYPE * + TOPK_MAX_SIZE_950 * V1_RES_ELEM_SIZE * aicNum; + // 临时存储Decode中间参数信息大小: + // 2(头/尾)*8(s1Base)*16(paramNum)*sizeof(int64_t)*24=48k + workspaceSize += V1_DECODE_DATA_NUM * S1_BASE_SIZE * V1_DECODE_PARAM_NUM * + V1_DECODE_PARAM_ELEM_SIZE * aicNum; + } else { + uint32_t mm1ResSize = M_BASE_SIZE * S2_BASE_SIZE; + workspaceSize += mm1ResSize * MM1_RES_ELEM_SIZE * DOUBLE_BUFFER * aicNum; + // W 区(AIV 写、AIC 读):对应 kernel Init 的 weightWorkspaceGm, + // 每核 BLOCK_CUBE × mBaseSize(=S1_BASE_SIZE×gSize) × 2(双缓冲) × 2B。 + // 此前 host 漏算该区,kernel 的 offset 累计比 host 大 + // 8~16KB/核,尾部候选区会越界。 + { + constexpr uint32_t BLOCK_CUBE = 16; + uint64_t weightMemSize = + static_cast(BLOCK_CUBE) * + (static_cast(S1_BASE_SIZE) * tilingInfo->gSize) * + DOUBLE_BUFFER * sizeof(uint16_t); + workspaceSize += weightMemSize * aicNum; + } + // Decode流程(LD)需要Workspace大小 + // 临时存储Decode中间结果大小: + // 2(头/尾)*8(s1Base)*2(idx/value)*2048(K)*sizeof(int32)*24=6M + workspaceSize += V1_DECODE_DATA_NUM * S1_BASE_SIZE * V1_RES_ELEM_TYPE * + TOPK_MAX_SIZE * V1_RES_ELEM_SIZE * aicNum; + // 临时存储Decode中间参数信息大小: + // 2(头/尾)*8(s1Base)*16(paramNum)*sizeof(int64_t)*24=48k + workspaceSize += V1_DECODE_DATA_NUM * S1_BASE_SIZE * V1_DECODE_PARAM_NUM * + V1_DECODE_PARAM_ELEM_SIZE * aicNum; + // mode=1(candidate source)+ LD:块级 topk + // 分段结果备份区(与上面位置级那项同构, 但每行槽位宽 = 2 × + // candidate_topk_blocks 个 float,是位置级的 2 倍) + if (tilingInfo->candidateMode == CANDIDATE_MODE_SOURCE) { + constexpr uint32_t CAND_TOPK_BLOCKS_MAX = 2048; // 块级 topk 最大块数 + uint64_t candPairWidth = + 2ULL * CAND_TOPK_BLOCKS_MAX; // 每行 value+index 对宽 (float 个数) + workspaceSize += V1_DECODE_DATA_NUM * S1_BASE_SIZE * V1_RES_ELEM_TYPE * + candPairWidth * V1_RES_ELEM_SIZE * aicNum; + } + // D3a: 候选驱动 staging(mode=2 且传入 candidate_block_length 时): + // v4 单 id 计数信号量,槽数不再受 flag id 限制(8 槽流水深度),与 kernel + // Init 一致 + if (tilingInfo->candidateMode == CANDIDATE_MODE_CONSUMER && + tilingInfo->opParamInfo.candidateBlockLength.tensor != nullptr) { + constexpr uint32_t CAND_STAGING_SLOTS = + 8; // v4 ring 深度(CAND_RING_SLOTS) + constexpr uint32_t CAND_STAGING_TOKENS = 512; // tile = 64 块 × 8 token + constexpr uint32_t CAND_HEAD_DIM = 128; + // staging scale 区已删(V1 探针残留:AIC 不消费 staging scale,kscale 由 + // AIV 消费侧乘) + workspaceSize += static_cast(aicNum) * CAND_STAGING_SLOTS * + (CAND_STAGING_TOKENS * CAND_HEAD_DIM); + // D3b: 候选分数区(s1Base 行 × 32 tile × 512 float = 256KB/核;v4 + // 按任务奇偶双缓冲 = 512KB/核) + constexpr uint32_t CAND_SCORE_TILES_MAX = 32; // ceil(2048 块 × 8 / 512) + constexpr uint32_t CAND_SCORE_DOUBLE_BUF = 2; // v4 跨任务延迟消费 + workspaceSize += static_cast(aicNum) * CAND_SCORE_DOUBLE_BUF * + S1_BASE_SIZE * CAND_SCORE_TILES_MAX * 256 * + sizeof(float); + // v22: 候选 kscale 辅助区奇偶周期 2→4(X6 根因:produce 侧单 AIV + // 可越过对侧 drain-read 覆写同 parity aux,score 区无此问题因 AIC 写被 + // READY 链拴住)。 512KB → 1MB/核,与 kernel Init 的 CAND_AUX_SCALE_BYTES + // 保持一致。 + constexpr uint32_t CAND_AUX_SCALE_TILES = 128; // 4 行 × 32 tile + constexpr uint32_t CAND_AUX_SCALE_BYTES_PER_TILE = + 64 * 16 * sizeof(uint16_t); // 2KB + constexpr uint32_t CAND_AUX_SCALE_QUAD_BUF = + 4; // aux 奇偶周期(score 仍为 2) + workspaceSize += static_cast(aicNum) * CAND_AUX_SCALE_QUAD_BUF * + CAND_AUX_SCALE_TILES * CAND_AUX_SCALE_BYTES_PER_TILE; + } + } size_t* workSpaces = context_->GetWorkspaceSizes(1); workSpaces[0] = workspaceSize; @@ -1844,7 +2676,7 @@ ge::graphStatus XllmKernelQuantLightningIndexerV2VaTiling::DoTiling( tilingInfo->opParamInfo.candidateTopkIndex.desc == nullptr || tilingInfo->opParamInfo.candidateTopkIndex.desc->GetDataType() != ge::DT_INT32, - OP_LOGE("XllmKernelQuantLightningIndexerV2Va", + OP_LOGE("XllmKernelQuantLightningIndexerV3Va", "candidate_topk_index dtype only supports int32."), return ge::GRAPH_FAILED); int64_t expectSize = 0; @@ -1863,7 +2695,7 @@ ge::graphStatus XllmKernelQuantLightningIndexerV2VaTiling::DoTiling( tilingInfo->opParamInfo.candidateTopkIndex.tensor->GetShapeSize(); OP_CHECK_IF( actualSize != expectSize, - OP_LOGE("XllmKernelQuantLightningIndexerV2Va", + OP_LOGE("XllmKernelQuantLightningIndexerV3Va", "candidate_topk_index shape size must be %ld, but got %ld.", expectSize, actualSize), @@ -1888,6 +2720,11 @@ ge::graphStatus XllmKernelQuantLightningIndexerV2VaTiling::DoTiling( tilingData_.set_candidateMode(tilingInfo->candidateMode); tilingData_.set_candidateTopkBlocks(tilingInfo->candidateTopkBlocks); tilingData_.set_candidateBlockSize(tilingInfo->candidateBlockSize); + // ---- DCP (Decode Context Parallel, 解码上下文并行) ---- + tilingData_.set_dcpEnable(static_cast(tilingInfo->dcpEnable)); + tilingData_.set_cpWorld(tilingInfo->cpWorld); + tilingData_.set_cpRank(tilingInfo->cpRank); + tilingData_.set_cpInterleaveSize(tilingInfo->cpInterleaveSize); tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), context_->GetRawTilingData()->GetCapacity()); context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize()); @@ -1914,25 +2751,25 @@ ge::graphStatus XllmKernelQuantLightningIndexerV2VaTiling::DoTiling( } // --------------------------Tiling函数定义--------------------------- -ge::graphStatus TilingForXllmKernelQuantLightningIndexerV2Va( +ge::graphStatus TilingForXllmKernelQuantLightningIndexerV3Va( gert::TilingContext* context) { OP_CHECK_IF( context == nullptr, - OP_LOGE("XllmKernelQuantLightningIndexerV2Va", "Tiling context is null."), + OP_LOGE("XllmKernelQuantLightningIndexerV3Va", "Tiling context is null."), return ge::GRAPH_FAILED); QLIV2VaTilingInfo QLIV2VaInfo; QLIV2VaInfoParser QLIV2VaInfoParser(context); if (QLIV2VaInfoParser.ParseAndCheck(QLIV2VaInfo) != ge::GRAPH_SUCCESS) { return ge::GRAPH_FAILED; } - XllmKernelQuantLightningIndexerV2VaTiling QLIV2VaTiling(context); + XllmKernelQuantLightningIndexerV3VaTiling QLIV2VaTiling(context); return QLIV2VaTiling.DoTiling(&QLIV2VaInfo); } // --------------------------Tiling及函数TilingPrepare函数注册-------- -IMPL_OP_OPTILING(XllmKernelQuantLightningIndexerV2Va) - .Tiling(TilingForXllmKernelQuantLightningIndexerV2Va) +IMPL_OP_OPTILING(XllmKernelQuantLightningIndexerV3Va) + .Tiling(TilingForXllmKernelQuantLightningIndexerV3Va) .TilingParse( - TilingPrepareForXllmKernelQuantLightningIndexerV2Va); + TilingPrepareForXllmKernelQuantLightningIndexerV3Va); } // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.h index cbd3a08542..52b04a3abe 100644 --- a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.h +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_tiling.h @@ -55,9 +55,15 @@ constexpr uint32_t BLOCK_TABLE_INDEX = 10; constexpr uint32_t OUTPUT_IDX_OFFSET_INDEX = 11; constexpr uint32_t METADATA_INDEX = 12; constexpr uint32_t CANDIDATE_TOPK_INDEX_INPUT_INDEX = 13; +constexpr uint32_t CANDIDATE_BLOCK_LENGTH_INDEX = + 14; // 每行有效候选块数(DSL candidate_block_length 语义) +constexpr uint32_t CAUSAL_SEQLENS_KV_GLOBAL_INDEX = + 15; // DCP: 每请求全局 exclusive 上界 C constexpr uint32_t SPARSE_INDICES_INDEX = 0; constexpr uint32_t SPARSE_VALUES_INDEX = 1; constexpr uint32_t CANDIDATE_TOPK_INDEX_OUTPUT_INDEX = 2; +constexpr uint32_t CANDIDATE_BLOCK_LENGTH_OUTPUT_INDEX = + 3; // mode=1 每行有效候选块数 (int32 [T1,N2]) // Attributes Index constexpr uint32_t ATTR_TOPK_INDEX = 0; constexpr uint32_t ATTR_QUANT_MODE_INDEX = 1; @@ -73,6 +79,11 @@ constexpr uint32_t ATTR_CANDIDATE_BLOCK_SIZE_INDEX = 10; constexpr uint32_t ATTR_KEY_STRIDE0_INDEX = 11; // A11: key 第0维 stride constexpr uint32_t ATTR_KEY_DEQUANT_SCALE_STRIDE0_INDEX = 12; // A11: k_scale 第0维 stride +// ---- DCP (Decode Context Parallel, 解码上下文并行) ---- +constexpr uint32_t ATTR_ENABLE_DCP_INDEX = 13; +constexpr uint32_t ATTR_CP_WORLD_INDEX = 14; +constexpr uint32_t ATTR_CP_RANK_INDEX = 15; +constexpr uint32_t ATTR_CP_KV_CACHE_INTERLEAVE_SIZE_INDEX = 16; // Dim Index constexpr uint32_t DIM_IDX_ZERO = 0; @@ -86,22 +97,32 @@ constexpr uint32_t DIM_NUM_FOUR = 4; // 入参限制常量 constexpr uint32_t HEAD_DIM_LIMIT = 128; constexpr uint32_t SPARSE_LIMIT = 2048; +constexpr uint32_t SPARSE_LIMIT_8K = 8192; constexpr uint32_t G_SIZE_LIMIT = 64; -constexpr uint32_t G_SIZE_LIMIT_32 = 32; +constexpr uint32_t G_SIZE_LIMIT_32_950 = 32; constexpr uint32_t BLOCK_SIZE_LIMIT = 1024; constexpr uint32_t BLOCK_SIZE_FACTOR = 16; constexpr uint32_t SPARSE_MODE_LOWER = 3; constexpr uint32_t METADATA_LIMIT = 1024; +constexpr int32_t QUANT_MODE_FP8 = 1; constexpr int32_t QUANT_MODE_INT8 = 2; +constexpr int32_t QUANT_MODE_MXFP8 = 3; +constexpr int32_t QUANT_MODE_HIFLOAT8 = 4; +constexpr int32_t QUANT_MODE_MXFP4 = 5; +constexpr uint32_t MX_SCALE_SHAPE_ALIGN = 64; +constexpr uint32_t MX_E8M0_SCALE_PACK_NUM = + 2; // MX的E8M0 scale形状最后一维打包数为2 +constexpr uint32_t MXFP4_PACK_NUM = 2; // 每个uint8承载2个FP4 E2M1逻辑元素 +constexpr uint32_t MX_SCALE_GROUP_SIZE = + 32; // MX量化每32个D维元素对应1个E8M0 scale // ------------------candidate 两级TopK 常量------------------ constexpr uint32_t CANDIDATE_MODE_SOURCE = 1; // is_candidate_source: 输出候选块索引 constexpr uint32_t CANDIDATE_MODE_CONSUMER = 2; // use_candidate: 输入候选块索引, 候选内选topk -constexpr uint32_t CANDIDATE_MODE_OFF = 3; // 关闭candidate功能(默认) -constexpr uint32_t CANDIDATE_TOPK_BLOCKS_FIX = - 2048; // 上限2048, 支持(0, 2048]内64的倍数 +constexpr uint32_t CANDIDATE_MODE_OFF = 3; // 关闭candidate功能(默认) +constexpr uint32_t CANDIDATE_TOPK_BLOCKS_FIX = 2048; // O2决策: 当前仅支持2048 constexpr uint32_t CANDIDATE_BLOCK_SIZE_DEFAULT = 8; constexpr uint32_t CANDIDATE_BLOCK_SIZE_MAX = 64; @@ -127,8 +148,13 @@ TILING_DATA_FIELD_DEF(uint32_t, quantMode) TILING_DATA_FIELD_DEF(uint32_t, candidateMode) TILING_DATA_FIELD_DEF(uint32_t, candidateTopkBlocks) TILING_DATA_FIELD_DEF(uint32_t, candidateBlockSize) +// ---- DCP (Decode Context Parallel, 解码上下文并行) ---- +TILING_DATA_FIELD_DEF(uint32_t, dcpEnable) +TILING_DATA_FIELD_DEF(uint32_t, cpWorld) +TILING_DATA_FIELD_DEF(uint32_t, cpRank) +TILING_DATA_FIELD_DEF(uint32_t, cpInterleaveSize) END_TILING_DATA_DEF -REGISTER_TILING_DATA_CLASS(XllmKernelQuantLightningIndexerV2Va, +REGISTER_TILING_DATA_CLASS(XllmKernelQuantLightningIndexerV3Va, QLIV2VaTilingData) // -----------算子CompileInfo定义------------------- @@ -150,6 +176,12 @@ struct QLIV2VaParaInfo { QliV2TilingOptionalParaInfo outputIdxOffset = {nullptr, nullptr}; QliV2TilingOptionalParaInfo metadata = {nullptr, nullptr}; QliV2TilingOptionalParaInfo candidateTopkIndex = {nullptr, nullptr}; + QliV2TilingOptionalParaInfo candidateBlockLength = { + nullptr, + nullptr}; // 每行有效候选块数 (int32) + QliV2TilingOptionalParaInfo causalSeqLensKvGlobal = { + nullptr, + nullptr}; // DCP: 全局 exclusive 上界 C QliV2TilingRequiredParaInfo attenOut = {nullptr, nullptr}; QliV2TilingRequiredParaInfo sparseValues = {nullptr, nullptr}; @@ -168,6 +200,11 @@ struct QLIV2VaParaInfo { const int32_t* keyStride0Attr = nullptr; // A11: key 第0维 stride 显式属性 const int32_t* keyDequantScaleStride0Attr = nullptr; // A11: k_scale 第0维 stride 显式属性 + // ---- DCP (Decode Context Parallel, 解码上下文并行) ---- + const bool* enableDcp = nullptr; + const int32_t* cpWorld = nullptr; + const int32_t* cpRank = nullptr; + const int32_t* cpInterleaveSize = nullptr; }; // -----------算子Tiling入参信息类--------------- @@ -196,7 +233,7 @@ class QLIV2VaTilingInfo { // Others Flag uint32_t sparseCount = 0; uint32_t cmpRatio = 1; - bool returnValue = false; + uint32_t returnValue = 0; uint32_t keyStride0 = 0; uint32_t keyDequantScaleStride0 = 0; std::vector keyStridesVec; @@ -206,6 +243,11 @@ class QLIV2VaTilingInfo { uint32_t candidateMode = CANDIDATE_MODE_OFF; uint32_t candidateTopkBlocks = CANDIDATE_TOPK_BLOCKS_FIX; uint32_t candidateBlockSize = CANDIDATE_BLOCK_SIZE_DEFAULT; + // ---- DCP (Decode Context Parallel, 解码上下文并行) ---- + bool dcpEnable = false; + uint32_t cpWorld = 1; + uint32_t cpRank = 0; + uint32_t cpInterleaveSize = 1; // DType ge::DataType inputQType = ge::DT_FLOAT16; ge::DataType inputKType = ge::DT_FLOAT16; @@ -296,9 +338,9 @@ class QLIV2VaInfoParser { }; // ---------------算子Tiling类--------------- -class XllmKernelQuantLightningIndexerV2VaTiling { +class XllmKernelQuantLightningIndexerV3VaTiling { public: - explicit XllmKernelQuantLightningIndexerV2VaTiling( + explicit XllmKernelQuantLightningIndexerV3VaTiling( gert::TilingContext* context) : context_(context) {}; ge::graphStatus DoTiling(QLIV2VaTilingInfo* tilingInfo); diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_common_arch22.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_common_arch22.h index 07747cae7c..c9b9a032b4 100644 --- a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_common_arch22.h +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_common_arch22.h @@ -25,6 +25,56 @@ inline constexpr uint32_t CANDIDATE_MODE_CONSUMER = 2; // use_candidate: 输入候选块索引, 候选内选topk inline constexpr uint32_t CANDIDATE_MODE_OFF = 3; // 关闭candidate功能(默认) +// D3b 候选 staging ring(AIV gather ↔ AIC cube 消费)。 +// 910B 的跨核 flag 语义(同 sparse_flash_attention 的 910B 用法):多个 AIV +// 对同一 id 的 set 合并成一次可等待通知;AIC 的一次 set 广播给两个 +// AIV。故每个事件每侧只 set/wait 一次。 +// **flag id 约束**:910B 只有 4 bit(`GetffstMsg` 里 `flagId & 0xf`),且 +// AscendC 保留 +// 11=SYNC_AIC_FLAG、12=SYNC_AIV_FLAG、13=SYNC_AIC_AIV_FLAG、14=SYNC_AIV_ONLY_ALL; +// 本 kernel 已用 0/1/2(syncV1C1/syncV0C1/syncC1V0)。 +// +// v4(对齐 DSL 的软件流水):生产/消费固定错一拍 + **单 id +// 计数信号量**,深度不再受 flag id 数量限制,只受 workspace 限制。槽号 = 全局 +// tile 序号 % CAND_RING_SLOTS。 +inline constexpr uint32_t CAND_RING_SLOTS = 8; // staging 槽数(流水深度) +// AIV→AIC:每写完一个 tile 的半个 staging 槽各 set 一次(合并成 1 +// 个令牌/tile); AIC 每消费一个 tile wait 一次,并在进入任务的 tile 循环前先 +// wait 一次(错一拍)。 +inline constexpr uint32_t CAND_READY_FLAG = 6; +// AIC→AIV:空槽回执。AIC 启动预置 CAND_RING_SLOTS 个令牌,之后每消费 1 tile +// 回补 1 个。 +inline constexpr uint32_t CAND_FREE_FLAG = 8; +// AIC→AIV:W 槽回收。W 按候选任务交替使用 2 个槽(runInfo.loop%2),预置 2 +// 个令牌, AIC 每完成一个候选任务回补 1 个 ⇒ AIV 最多领先 2 个任务,保证不覆盖 +// AIC 正在读的槽。 +inline constexpr uint32_t CAND_WFREE_FLAG = 3; +// B4: 候选任务 W 就绪 —— AIV 先跑一次 ProcessVec0(w×qscale 广播到 vec0Out), +// 再放行 AIC 的候选 cube 循环。id 10(避开 0/1/2、ring 6/8、WFREE +// 3、保留 11..14)。 +inline constexpr uint32_t CAND_WREADY_FLAG = 10; +// B5: AIC 每算完一个 token 的全部候选 tile 就 set 一次;AIV 消费该 token 分数前 +// wait。 A3 user inter-core flag IDs range from 0 to 10. +inline constexpr uint32_t CAND_SCORE_READY_FLAG = 5; +// v4: AIC 主循环结束令牌 —— pending 队列(各任务末尾两个 +// token)在核尾统一排空, 等 AIC 推进/退出后再读,保证 GM 写已落地。 +inline constexpr uint32_t CAND_AIC_DONE_FLAG = 4; +// 候选分数区每任务的槽位数:s1Base 4 行 × 最大 32 tile(512 token) = 128 个 +// 512-float 行。 +// 按任务序号奇偶双缓冲(跨任务延迟消费时,下一任务不会覆盖尚未消费的分数)。 +inline constexpr uint32_t CAND_SCORE_TILES_PER_TASK = 128; +// 候选 tile 粒度:32 个候选块 × 8 token = 256 token(DSL 为 64 块×8=512;910B +// 上按 现有 mm1 骨架与 UB 容量取 256) +inline constexpr uint32_t CAND_TILE_BLOCKS = 64; +inline constexpr uint32_t CAND_TILE_TOKENS = CAND_TILE_BLOCKS * 8; +// 候选 kscale 辅助区(每 tile 32 块 × 16 half = 512 half = 1KB,块内前 8 half +// 有效、后 8 填充): AIV 在 gather 时每 AIV 写本半(256 half = 512B,一次 +// DMA),消费时按 tile 一次 1KB 读回, 取代原先"每 tile 32 次 16B DMA + 32 次 +// block_table 标量读"的逐块读取; +// 与分数区同样按任务奇偶双缓冲,跨任务延迟消费时不会被覆盖。 +inline constexpr uint32_t CAND_AUX_SCALE_HALVES_PER_TILE = + CAND_TILE_BLOCKS * 16U; + // 与tiling的layout保持一致 enum class LI_LAYOUT : uint32_t { BSND = 0, TND = 1, PA_BBND = 2 }; @@ -57,6 +107,8 @@ struct RunInfo { uint32_t actS1Size = 1; uint32_t actS2Size = 1; uint32_t actS2SizeOrig = 1; + uint32_t causalGlobalLen = + 0; // DCP: 当前请求本次 Q 片段的全局 exclusive 上界 C uint32_t actMBaseSize; uint32_t actualSingleProcessSInnerSize; uint32_t actualSingleProcessSInnerSizeAlign; @@ -74,6 +126,11 @@ struct RunInfo { bool isLastS2InnerLoop; bool isValid = false; bool isNeedLD = false; + // B5: 候选驱动任务 —— 正常全量扫的输出写回被抑制(结果由候选分数路径产生) + bool suppressOut = false; + // v4: 本任务是否候选驱动任务(ProcessVec0 据此决定是否等待 W 槽回收令牌 + // WFREE) + bool candTask = false; uint32_t saveWorkSpaceIdx = 0; }; @@ -116,11 +173,19 @@ struct ConstInfo { uint32_t kCacheBlockSize = 0; // PA场景的block size uint32_t maxBlockNumPerBatch = 0; // PA场景的最大单batch block number uint32_t keyStride0 = - 0; // key 第0维真实 stride (0=非PA/旧调用, 紧凑兜底; A11) + 0; // key 第0维真实 stride (0=非PA/旧调用, 紧凑兜底; 对齐 arch35 A11) uint32_t keyDequantScaleStride0 = 0; // k_scale 第0维真实 stride (同上) - LI_LAYOUT outputLayout; // 输出的格式 + static constexpr uint16_t NEG_INF_BFLOAT = + 0xFF80; // BF16 负无穷位型 (排序缓冲 padding 值) + LI_LAYOUT outputLayout; // 输出的格式 bool attenMaskFlag = false; + bool useLocalVisibleLengths = + false; // private return_value=2: FP32 values + causal local prefix uint32_t cmpRatio = 1; // 压缩率 + uint32_t cmpRatioShift = + 0U; // 压缩率的二进制位宽(log2),用右移代替除法,保证长度换算为精确整除 + uint32_t returnValue = + 0; // 是否输出 sparse_values (DCP 跨 rank 合并需要 score) uint32_t actualLenQDims = 0U; // query的actualSeqLength 的维度 uint32_t actualLenDims = 0U; // KV 的actualSeqLength 的维度 @@ -133,6 +198,12 @@ struct ConstInfo { uint32_t candidateTopkBlocks = 2048U; uint32_t candidateBlockSize = 8U; + // DCP (Decode Context Parallel, 解码上下文并行) + bool dcpEnable = false; + uint32_t cpWorld = 1U; // P: CP 组大小 + uint32_t cpRank = 0U; // r: 当前 rank + uint32_t cpInterleaveSize = 1U; // S: 每 S 个 token 轮换 rank + uint32_t s2Start = 0U; uint32_t s2End = 0U; uint32_t bN2Start = 0U; @@ -153,7 +224,16 @@ struct LdSplitCoreInfo { uint32_t workspaceNum = 0U; // 当前AIV核上规约任务的S2切分数量 uint32_t mStart = 0U; uint32_t mNum = 0U; + // mode=1 输出"每行有效候选块数"需要本 batch 的可见长度参数(LD + // 归约侧原本没有这些量) + uint32_t actS1Size = 0U; + uint32_t actS2Size = 0U; + uint32_t actS2SizeOrig = 0U; uint64_t indiceOutCoreOffset = 0U; // 最终输出索引搬出Topk的初始偏移地址 + // mode=1(candidate source,候选块来源)块级输出 candidate_topk_index + // 的初始偏移地址; 结构与 indiceOutCoreOffset 同构,只是每行的宽度从 + // sparseCount(最终 topk 数)换成 candidateTopkBlocks(块级 topk 数) + uint64_t candidateOutCoreOffset = 0U; }; template @@ -175,6 +255,32 @@ template __aicore__ inline T CeilDiv(T num, T rnd) { return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd))); } + +// DCP (Decode Context Parallel, 解码上下文并行): 由全局可见上界 u +// 算本地可见长度。 u = max(C - Q_len + rowIdx + 1, 0), 即该 Q 行全局可见 token +// 的 exclusive 上界。 分片规则: 全局第 t 个 token 属于 rank (t / S) % P, +// 本地序号按时间序排列。 +__aicore__ inline uint32_t CalcDcpVisibleLen(uint32_t u, + uint32_t localS2Len, + uint32_t cpWorld, + uint32_t cpRank, + uint32_t cpInterleaveSize) { + if (u == 0U || cpWorld == 0U || cpInterleaveSize == 0U) { + return 0U; + } + uint64_t period = + static_cast(cpWorld) * static_cast(cpInterleaveSize); + uint64_t fullRounds = (static_cast(u) / period) * cpInterleaveSize; + int64_t rem = + static_cast(static_cast(u) % period) - + static_cast(cpRank) * static_cast(cpInterleaveSize); + uint64_t tail = (rem <= 0) + ? 0U + : static_cast( + Min(rem, static_cast(cpInterleaveSize))); + uint64_t visible = fullRounds + tail; + return static_cast(Min(static_cast(localS2Len), visible)); +} } // namespace QLIV2VaCommon #endif // QUANT_LIGHTNING_INDEXER_V2_VA_COMMON_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_kernel_arch22.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_kernel_arch22.h index 659a123060..ed422506fc 100644 --- a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_kernel_arch22.h +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_kernel_arch22.h @@ -57,6 +57,17 @@ struct TempLoopInfo { uint32_t mBasicSizeTail = 0U; // gS1方向循环的尾基本块大小 uint32_t s2BasicSizeTail = 0U; // S2方向循环的尾基本块大小 uint32_t validS2Len = 0U; + uint32_t causalGlobalLen = 0U; // DCP: 当前 bIdx 的全局 exclusive 上界 C + // ---- candidate driven (mode=2, V1) ---- + uint32_t actS1RowBase = + 0U; // 本 batch 第 0 行在 candidate_block_length/candidate_topk_index + // 中的行号 + uint32_t maxCandLen = + 0U; // 本任务 (bN2,gS1) 内各 token 候选块数的最大值 L_max + uint32_t maxCandTiles = + 0U; // uniform 循环上界 = ceil(L_max × 8 / 256),V1 tile = 32 块 + bool candDriven = + false; // 本任务是否走候选驱动流水(mode=2 且传入长度且非 FD) }; template @@ -77,9 +88,12 @@ class QLIV2VaPreload { __gm__ uint8_t* outputIdxOffset, __gm__ uint8_t* metadata, __gm__ uint8_t* candidateTopkIndex, + __gm__ uint8_t* candidateBlockLength, + __gm__ uint8_t* causalSeqlensKvGlobal, __gm__ uint8_t* sparseIndices, __gm__ uint8_t* sparseValues, __gm__ uint8_t* candidateTopkIndexOut, + __gm__ uint8_t* candidateBlockLengthOut, __gm__ uint8_t* workspace, const QLIV2VaTilingData* __restrict tiling, TPipe* tPipe); @@ -109,6 +123,11 @@ class QLIV2VaPreload { static constexpr uint32_t K_HEAD_NUM = 1; static constexpr uint32_t GM_ALIGN_BYTES = 512; static constexpr uint32_t LI_QUANT_PRELOAD_TASK_CACHE_SIZE = 2; + // V1 候选驱动:一个候选 tile = 32 个候选块 × 8 token = 256 token(设计 §3.2) + static constexpr uint32_t QLIV2Va_CAND_TILE_BLOCKS = + QLIV2VaCommon::CAND_TILE_BLOCKS; + static constexpr uint32_t QLIV2Va_CAND_TILE_TOKENS = + QLIV2VaCommon::CAND_TILE_TOKENS; // for workspace double static constexpr uint32_t WS_DOUBLE = 2; @@ -136,19 +155,39 @@ class QLIV2VaPreload { GlobalTensor weightsGm; GlobalTensor metadataGm; GlobalTensor indiceOutGm; + GlobalTensor valueOutGm; // return_value: BF16 分数输出 + __gm__ uint8_t* sparseValuesPtr = nullptr; // ProcessInvalid 全量清理用 GlobalTensor candidateTopkIndexInGm; GlobalTensor candidateTopkIndexOutGm; + // mode=1(source)每行有效候选块数(DSL candidate_length 语义:min(ceil(V/8), + // candidateTopkBlocks)) + GlobalTensor candidateBlockLengthOutGm; + GlobalTensor candidateBlockLengthGm; // 每行有效候选块数 (可选输入) + // D3a: 候选 K staging(每个 AIC 私有:8 槽 × 512 token × 128B;scale + // 区已删——AIC 不消费 staging scale) + GlobalTensor candStagingKeyGm; + // D3b: 候选分数区(per token × maxTiles × 256 float;B1+B2 + // 冒烟阶段不参与输出) + GlobalTensor candScoreGm; + // v4: 候选 kscale 辅助区(每 tile 1KB 填充布局,任务奇偶双缓冲) + GlobalTensor candAuxScaleGm; GlobalTensor blockTableGm; GlobalTensor outputIdxOffsetGm; // A15: 每行输出索引偏移 GlobalTensor actualSeqLengthsGmQ; GlobalTensor actualSeqLengthsGm; GlobalTensor cmpResidualKGm; + GlobalTensor + causalSeqLensKvGlobalGm; // DCP: 每请求全局 exclusive 上界 C // ================================类成员变量==================================== // aic、aiv核信息 uint32_t tmpBlockIdx = 0U; uint32_t aiCoreIdx = 0U; + bool hasCandidateBlockLength_ = + false; // 主算子是否传入 candidate_block_length(D2/候选驱动前置) + // v4: 候选任务序号(AIC/AIV 两侧同步递增,仅用于 W 双槽交替 loop%2) + uint32_t candTaskSeq_ = 0U; QLIV2VaCommon::ConstInfo constInfo{}; QLIV2VaCommon::LdSplitCoreInfo ldInfo{}; @@ -159,17 +198,21 @@ class QLIV2VaPreload { __aicore__ inline void InitTilingData( const QLIV2VaTilingData* __restrict tilingData); __aicore__ inline void InitBuffers(); - __aicore__ inline void InitActualSeqLen(__gm__ uint8_t* cuSeqlensQ, - __gm__ uint8_t* cuSeqlensK, - __gm__ uint8_t* sequsedQ, - __gm__ uint8_t* sequsedK, - __gm__ uint8_t* cmpResidualK); + __aicore__ inline void InitActualSeqLen( + __gm__ uint8_t* cuSeqlensQ, + __gm__ uint8_t* cuSeqlensK, + __gm__ uint8_t* sequsedQ, + __gm__ uint8_t* sequsedK, + __gm__ uint8_t* cmpResidualK, + __gm__ uint8_t* causalSeqlensKvGlobal); // ================================Split Core================================ __aicore__ inline void SplitCore(); __aicore__ inline uint32_t GetS2BaseBlockNumOnMask(uint32_t s1gIdx, uint32_t actS1Size, uint32_t actS2SizeOrig, + uint32_t causalGlobalLen, uint32_t& validS2Len); + __aicore__ inline uint32_t GetGlobalCausalLen(uint32_t bIdx); __aicore__ inline uint32_t GetTotalBaseBlockNum(); // ================================Process // functions================================ @@ -221,12 +264,18 @@ __aicore__ inline void QLIV2VaPreload::InitTilingData( constInfo.kSeqSize = tilingData->s2Size; constInfo.qSeqSize = tilingData->s1Size; constInfo.attenMaskFlag = (tilingData->sparseMode == 3); + constInfo.useLocalVisibleLengths = (tilingData->returnValue == 2); constInfo.kCacheBlockSize = tilingData->blockSize; constInfo.maxBlockNumPerBatch = tilingData->maxBlockNumPerBatch; constInfo.keyStride0 = tilingData->keyStride0; // A11: key 0轴非连续 constInfo.keyDequantScaleStride0 = tilingData->keyDequantScaleStride0; constInfo.sparseCount = tilingData->sparseCount; constInfo.cmpRatio = tilingData->cmpRatio; + constInfo.cmpRatioShift = 0U; + for (uint32_t ratio = constInfo.cmpRatio; ratio > 1U; ratio >>= 1U) { + ++constInfo.cmpRatioShift; + } + constInfo.returnValue = tilingData->returnValue; constInfo.outputLayout = Q_LAYOUT_T; // 输出和输入形状一致 if constexpr (Q_LAYOUT_T == LI_LAYOUT::TND) { constInfo.isAccumSeqS1 = true; @@ -246,6 +295,12 @@ __aicore__ inline void QLIV2VaPreload::InitTilingData( constInfo.candidateMode = tilingData->candidateMode; constInfo.candidateTopkBlocks = tilingData->candidateTopkBlocks; constInfo.candidateBlockSize = tilingData->candidateBlockSize; + + // DCP (Decode Context Parallel, 解码上下文并行) + constInfo.dcpEnable = (tilingData->dcpEnable != 0U); + constInfo.cpWorld = tilingData->cpWorld; + constInfo.cpRank = tilingData->cpRank; + constInfo.cpInterleaveSize = tilingData->cpInterleaveSize; } template @@ -263,7 +318,8 @@ __aicore__ inline void QLIV2VaPreload::InitActualSeqLen( __gm__ uint8_t* cuSeqlensK, __gm__ uint8_t* sequsedQ, __gm__ uint8_t* sequsedK, - __gm__ uint8_t* cmpResidualK) { + __gm__ uint8_t* cmpResidualK, + __gm__ uint8_t* causalSeqlensKvGlobal) { // Q side: cu_seqlens (TND) or seqused (non-TND) if constexpr (Q_LAYOUT_T == LI_LAYOUT::TND) { if (cuSeqlensQ != nullptr) { @@ -308,6 +364,19 @@ __aicore__ inline void QLIV2VaPreload::InitActualSeqLen( } else { constInfo.cmpResiduaKLenDims = 0; } + // DCP: 全局 exclusive 上界 C (Device Tensor, tiling 已保证 enable_dcp=true + // 时非空) + if (causalSeqlensKvGlobal != nullptr) { + causalSeqLensKvGlobalGm.SetGlobalBuffer( + (__gm__ int32_t*)causalSeqlensKvGlobal, constInfo.batchSize); + } +} + +template +__aicore__ inline uint32_t QLIV2VaPreload::GetGlobalCausalLen( + uint32_t bIdx) { + int32_t causalLen = causalSeqLensKvGlobalGm.GetValue(bIdx); + return (causalLen <= 0) ? 0U : static_cast(causalLen); } template @@ -377,7 +446,8 @@ __aicore__ inline void QLIV2VaPreload::GetS1S2ActualSeqLen( cmpResidualKGm, constInfo.kSeqSize, constInfo.cmpRatio); // 压缩前的actS2Size - actS2Size = actS2SizeOrig / constInfo.cmpRatio; // 真实使用的压缩后S2长度 + actS2Size = + actS2SizeOrig >> constInfo.cmpRatioShift; // 真实使用的压缩后S2长度 } template @@ -385,21 +455,45 @@ __aicore__ inline uint32_t QLIV2VaPreload::GetS2BaseBlockNumOnMask( uint32_t s1gIdx, uint32_t actS1Size, uint32_t actS2SizeOrig, + uint32_t causalGlobalLen, uint32_t& validS2Len) { - if (actS2SizeOrig / constInfo.cmpRatio == 0) { + uint32_t actS2Size = actS2SizeOrig >> constInfo.cmpRatioShift; + if (actS2Size == 0) { validS2Len = 0; return 0; } uint32_t s1Offset = constInfo.s1BaseSize * s1gIdx; - int32_t validS2LenBase = - static_cast(actS2SizeOrig) - - static_cast(actS1Size); // 压缩前的validS2LenBase - validS2Len = (static_cast(s1Offset) + validS2LenBase + - static_cast(constInfo.s1BaseSize)) / - static_cast(constInfo.cmpRatio); - validS2Len = - Min(validS2Len, static_cast(actS2SizeOrig) / constInfo.cmpRatio); - validS2Len = Max(validS2Len, 1); + if (constInfo.dcpEnable) { + // DCP: 行组最后一行的全局 exclusive 上界 u = C - Q_len + lastRowCount。 + // 可见长度随行号单调不减, 因此行组取最后一个实际 Q 行的上界即可覆盖整组。 + uint32_t lastRowCount = Min(s1Offset + constInfo.s1BaseSize, actS1Size); + int64_t signedCausalLimit = static_cast(causalGlobalLen) - + static_cast(actS1Size) + + static_cast(lastRowCount); + uint32_t u = (signedCausalLimit <= 0) + ? 0U + : static_cast(signedCausalLimit); + validS2Len = QLIV2VaCommon::CalcDcpVisibleLen(u, + actS2Size, + constInfo.cpWorld, + constInfo.cpRank, + constInfo.cpInterleaveSize); + validS2Len = Max(validS2Len, 1U); // 保持“至少 1 块”的既有不变量 + return (validS2Len + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize; + } + // causal 可见长度:先用 64 位计算未压缩的 exclusive 上界(避免 int32 + // 溢出与负数截断), 再按压缩率的二进制位宽精确右移,最后 clamp 到压缩后的 S2 + // 长度。 + int64_t causalLimit = static_cast(s1Offset) + + static_cast(actS2SizeOrig) - + static_cast(actS1Size) + + static_cast(constInfo.s1BaseSize); + uint32_t visible = + causalLimit > 0 + ? (static_cast(causalLimit) >> constInfo.cmpRatioShift) + : 0U; + validS2Len = Min(visible, actS2Size); + validS2Len = Max(validS2Len, 1U); return (validS2Len + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize; } @@ -418,8 +512,12 @@ __aicore__ inline uint32_t QLIV2VaPreload::GetTotalBaseBlockNum() { continue; } for (uint32_t s1gIdx = 0; s1gIdx < s1GBaseNum; s1gIdx++) { - s2BaseNum = - GetS2BaseBlockNumOnMask(s1gIdx, actS1Size, actS2SizeOrig, validS2Len); + s2BaseNum = GetS2BaseBlockNumOnMask( + s1gIdx, + actS1Size, + actS2SizeOrig, + constInfo.dcpEnable ? GetGlobalCausalLen(bIdx) : 0U, + validS2Len); totalBlockNum += s2BaseNum * constInfo.kHeadNum; } } @@ -487,6 +585,9 @@ __aicore__ void inline QLIV2VaPreload::SplitCore() { ldInfo.workspaceNum = metadataGm.GetValue(ldWorkspaceNumINDEX); ldInfo.mStart = metadataGm.GetValue(ldMstartIndex); ldInfo.mNum = metadataGm.GetValue(ldMNumIndex); + // mode=1 长度输出:取本 batch 的可见长度参数(与 CalcGS1LoopParams 同源) + GetS1S2ActualSeqLen( + ldInfo.bIdx, ldInfo.actS1Size, ldInfo.actS2Size, ldInfo.actS2SizeOrig); uint64_t actualSeqQPrefixSum = 0; if constexpr (Q_LAYOUT_T == LI_LAYOUT::TND) { actualSeqQPrefixSum = @@ -501,6 +602,14 @@ __aicore__ void inline QLIV2VaPreload::SplitCore() { static_cast(ldInfo.n2Idx) * constInfo.sparseCount + static_cast(ldInfo.mIdx) * constInfo.s1BaseSize * constInfo.kHeadNum * constInfo.sparseCount; + // mode=1: 块级输出 candidate_topk_index + // 的初始偏移地址(与上面同构,行宽换成 candidateTopkBlocks) + ldInfo.candidateOutCoreOffset = + actualSeqQPrefixSum * constInfo.kHeadNum * + constInfo.candidateTopkBlocks + + static_cast(ldInfo.n2Idx) * constInfo.candidateTopkBlocks + + static_cast(ldInfo.mIdx) * constInfo.s1BaseSize * + constInfo.kHeadNum * constInfo.candidateTopkBlocks; } } @@ -552,9 +661,12 @@ __aicore__ inline void QLIV2VaPreload::Init( __gm__ uint8_t* outputIdxOffset, __gm__ uint8_t* metadata, __gm__ uint8_t* candidateTopkIndex, + __gm__ uint8_t* candidateBlockLength, + __gm__ uint8_t* causalSeqlensKvGlobal, __gm__ uint8_t* sparseIndices, __gm__ uint8_t* sparseValues, __gm__ uint8_t* candidateTopkIndexOut, + __gm__ uint8_t* candidateBlockLengthOut, __gm__ uint8_t* workspace, const QLIV2VaTilingData* __restrict tiling, TPipe* tPipe) { @@ -567,7 +679,22 @@ __aicore__ inline void QLIV2VaPreload::Init( } InitTilingData(tiling); - InitActualSeqLen(cuSeqlensQ, cuSeqlensK, sequsedQ, sequsedK, cmpResidualK); + InitActualSeqLen(cuSeqlensQ, + cuSeqlensK, + sequsedQ, + sequsedK, + cmpResidualK, + causalSeqlensKvGlobal); + sparseValuesPtr = + sparseValues; // ProcessInvalid/全量清理路径的 return_value 输出基址 + + // 可选输入:每行有效候选块数。AIC/AIV 都持有同一 GM 指针(D2 + // 两侧各自现算,天然一致)。 + if (candidateBlockLength != nullptr) { + candidateBlockLengthGm.SetGlobalBuffer( + (__gm__ int32_t*)candidateBlockLength); + hasCandidateBlockLength_ = true; + } if (metadata != nullptr) { metadataGm.SetGlobalBuffer((__gm__ uint32_t*)metadata); @@ -603,15 +730,72 @@ __aicore__ inline void QLIV2VaPreload::Init( offset += GetBlockNum() * constInfo.s1BaseSize * WS_DOUBLE * WS_DOUBLE * BASE_TOPK * sizeof(float); + // mode=1(candidate source,候选块来源)+ LD(跨核归约):块级 topk + // 分段结果的备份区。 与 vec1ResGm 同构([核][S2 段][S1 行][value+index + // 对]),只是每行槽位宽从 topk 换成 2 × + // candidateTopkBlocks(块级累加器的对宽)。位置级那条链已验证,块级这条链原缺 + // 溢写与归约,跨核切分后只剩头段结果(块级输出全错)。 + GlobalTensor blockVec1ResGm; + if (constInfo.candidateMode == CANDIDATE_MODE_SOURCE) { + uint64_t singleCoreBlkVec1Res = + static_cast(constInfo.s1BaseSize) * WS_DOUBLE * WS_DOUBLE * + constInfo.candidateTopkBlocks * 2ULL * sizeof(float); + blockVec1ResGm.SetGlobalBuffer((__gm__ float*)(workspace + offset)); + offset += GetBlockNum() * singleCoreBlkVec1Res; + } + GlobalTensor qScaleGm; GlobalTensor kScaleGm; + // D3a: 候选 staging 区(条件申请:仅在传入 candidate_block_length 时占 + // workspace) + if (candidateBlockLength != nullptr) { + constexpr uint64_t CAND_STAGING_KEY_BYTES = + QLIV2VaCommon::CAND_RING_SLOTS * + static_cast(QLIV2Va_CAND_TILE_TOKENS) * + HEAD_DIM; // 8 槽 × 512 token × 128B + candStagingKeyGm.SetGlobalBuffer( + (__gm__ int8_t*)(workspace + offset + + aiCoreIdx * CAND_STAGING_KEY_BYTES)); + offset += static_cast(GetBlockNum()) * CAND_STAGING_KEY_BYTES; + // D3b: 候选分数区(每任务 4 行 × 64 tile × 256 float;按任务奇偶双缓冲 = + // 512KB/核) + constexpr uint64_t CAND_SCORE_BYTES = + 2ULL * QLIV2VaCommon::CAND_SCORE_TILES_PER_TASK * + QLIV2VaCommon::CAND_TILE_TOKENS * sizeof(float); + candScoreGm.SetGlobalBuffer( + (__gm__ float*)(workspace + offset + aiCoreIdx * CAND_SCORE_BYTES)); + offset += static_cast(GetBlockNum()) * CAND_SCORE_BYTES; + // v22: aux 奇偶周期 2→4(X6 根因)。score 区靠 READY 链天然安全(AIC 写 t + // 需双 AIV produce(t),必晚于 AIV0 对 t−2 的 drain-read);aux 只由单个 AIV + // 写、无此约束, 不消费的那个 AIV 会在对侧 drain-read(t−2) 前把 t 的 aux + // 写进同 parity 区(实测 row11 后半区 kscale 被 row13 覆写)。周期 4 + // 后有严格链:AIV0 drain-read(t−4) [entry(t−2)] < AIV0 produce(t−2) < + // AIC(t−2) 完成 < SR(t−2) < AIV1 drain(t) < AIV1 + // produce(t),覆写不可能。区大小 512KB → 1MB/核(aux 是 workspace 末区)。 + constexpr uint64_t CAND_AUX_SCALE_BYTES = + 4ULL * QLIV2VaCommon::CAND_SCORE_TILES_PER_TASK * + QLIV2VaCommon::CAND_AUX_SCALE_HALVES_PER_TILE * sizeof(half); + candAuxScaleGm.SetGlobalBuffer( + (__gm__ half*)(workspace + offset + aiCoreIdx * CAND_AUX_SCALE_BYTES)); + offset += static_cast(GetBlockNum()) * CAND_AUX_SCALE_BYTES; + } if ASCEND_IS_AIV { vectorService.InitParams(constInfo, ldInfo, tiling); indiceOutGm.SetGlobalBuffer((__gm__ int32_t*)sparseIndices); weightsGm.SetGlobalBuffer((__gm__ half*)weights); qScaleGm.SetGlobalBuffer((__gm__ half*)queryScale); kScaleGm.SetGlobalBuffer((__gm__ half*)keyScale); + keyGm.SetGlobalBuffer((__gm__ K_T*)key); // D3a: AIV 候选 gather 需要 K 源 blockTableGm.SetGlobalBuffer((__gm__ int32_t*)blockTable); + GlobalTensor valueOutGm; + GlobalTensor valueOutFp32Gm; + if (constInfo.useLocalVisibleLengths) { + // return_value=2 (A3 本地候选): 原生 FP32 比较值直出 + valueOutFp32Gm.SetGlobalBuffer((__gm__ float*)sparseValues); + } else if (constInfo.returnValue != 0U) { + // return_value=1 (DCP score): BF16 输出 + valueOutGm.SetGlobalBuffer((__gm__ bfloat16_t*)sparseValues); + } if (constInfo.candidateMode == CANDIDATE_MODE_CONSUMER && candidateTopkIndex != nullptr) { candidateTopkIndexInGm.SetGlobalBuffer( @@ -622,20 +806,43 @@ __aicore__ inline void QLIV2VaPreload::Init( candidateTopkIndexOutGm.SetGlobalBuffer( (__gm__ int32_t*)candidateTopkIndexOut); } - if (outputIdxOffset != nullptr) { // A15: 使能 output_idx_offset + if (constInfo.candidateMode == CANDIDATE_MODE_SOURCE && + candidateBlockLengthOut != nullptr) { + candidateBlockLengthOutGm.SetGlobalBuffer( + (__gm__ int32_t*)candidateBlockLengthOut); + } + if (outputIdxOffset != + nullptr) { // A15: 使能 output_idx_offset (参照 arch35) outputIdxOffsetGm.SetGlobalBuffer((__gm__ int32_t*)outputIdxOffset); } // A15: 有效标志须与 tensor 一并传给 vector (InitParams 已先值拷贝 // constInfo, 此处再改标志不生效) bool outputIdxOffsetValid = (outputIdxOffset != nullptr); - vectorService.InitVecInputTensor( - weightsGm, qScaleGm, kScaleGm, indiceOutGm, blockTableGm); + vectorService.InitVecInputTensor(weightsGm, + qScaleGm, + kScaleGm, + indiceOutGm, + blockTableGm, + valueOutGm, + valueOutFp32Gm); vectorService.InitVecCandidateTensor(candidateTopkIndexInGm, candidateTopkIndexOutGm, + candidateBlockLengthOutGm, + (candidateBlockLengthOut != nullptr), outputIdxOffsetGm, outputIdxOffsetValid); + // D3a: 候选 gather 使能 = mode=2 且传入长度张量(V1 探针:cube 暂不消费 + // staging) + vectorService.InitVecCandidateGatherTensor( + keyGm, + candStagingKeyGm, + candidateBlockLengthGm, + candScoreGm, + candAuxScaleGm, + (constInfo.candidateMode == CANDIDATE_MODE_CONSUMER && + hasCandidateBlockLength_)); vectorService.InitVecWorkspaceTensor( - weightWorkspaceGm, mm1ResGm, vec1ResGm); + weightWorkspaceGm, mm1ResGm, vec1ResGm, blockVec1ResGm); } else { matmulService.InitParams(constInfo); queryGm.SetGlobalBuffer((__gm__ Q_T*)query); @@ -645,6 +852,8 @@ __aicore__ inline void QLIV2VaPreload::Init( keyGm.SetGlobalBuffer((__gm__ K_T*)key); matmulService.InitMm1GlobalTensor( blockTableGm, keyGm, queryGm, mm1ResGm, weightWorkspaceGm); + // D3b: 候选 QK 的 K 源与分数区(B1+B2 冒烟阶段仅写不读) + matmulService.InitCandMm1Tensor(candStagingKeyGm, candScoreGm); } InitBuffers(); } @@ -672,19 +881,41 @@ __aicore__ inline void QLIV2VaPreload::CalcS2LoopParams( (gS1LoopIdx + 1 == tempLoopInfo.gS1LoopEnd); uint32_t s2BlockNum; uint32_t validS2Len = 0; + // DCP: 每个 bIdx 的全局 exclusive 上界 C 只读一次, + // 供行组/行级可见长度计算复用 + tempLoopInfo.causalGlobalLen = + constInfo.dcpEnable ? GetGlobalCausalLen(tempLoopInfo.bIdx) : 0U; if (constInfo.attenMaskFlag) { s2BlockNum = GetS2BaseBlockNumOnMask(gS1LoopIdx, tempLoopInfo.actS1Size, tempLoopInfo.actS2SizeOrig, + tempLoopInfo.causalGlobalLen, tempLoopInfo.validS2Len); } else { s2BlockNum = (tempLoopInfo.actS2Size + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize; tempLoopInfo.validS2Len = tempLoopInfo.actS2Size; } + // DCP + LD: metadata 在 A2/A3 与 A5 上都按 DCP 可见长度切 S2, 与 s2BlockNum + // 同源。 仍保留两处兼容: + // (1) 第一个分片的 s2End 可能 <= s2BlockNum, 不能只按 s2End < s2BlockNum + // 判"无需归约"; (2) 最后一个分片 s2End==0 表示开区间, 终点取可见上界 + // s2BlockNum。 + // 若分片起点已越过可见上界 (旧版 metadata / 非 DCP 切分), 回退到本地完整 L + // 的块数, 保证该分片仍会写 workspace partial。 + uint32_t metaS2BlockNum = + (tempLoopInfo.actS2Size + constInfo.s2BaseSize - 1) / + constInfo.s2BaseSize; + bool dcpLdSplit = constInfo.dcpEnable && isEnd && + ((constInfo.s2Start > 0) || (constInfo.s2End != 0)); tempLoopInfo.s2LoopEnd = (isEnd && constInfo.s2End != 0) ? constInfo.s2End : s2BlockNum; - if (constInfo.s2Start > 0 || tempLoopInfo.s2LoopEnd < s2BlockNum) { + if (dcpLdSplit && constInfo.s2End == 0) { + tempLoopInfo.s2LoopEnd = + (constInfo.s2Start >= s2BlockNum) ? metaS2BlockNum : s2BlockNum; + } + if ((constInfo.s2Start > 0) || (tempLoopInfo.s2LoopEnd < s2BlockNum) || + dcpLdSplit) { tempLoopInfo.isNeedLD = true; } else { tempLoopInfo.isNeedLD = false; @@ -693,6 +924,53 @@ __aicore__ inline void QLIV2VaPreload::CalcS2LoopParams( tempLoopInfo.s2BasicSizeTail = (tempLoopInfo.s2BasicSizeTail == 0) ? constInfo.s2BaseSize : tempLoopInfo.s2BasicSizeTail; + + // ---- D2: 每任务候选统计(V1 候选驱动前置)---- + // AIC 与 AIV 都从同一 candidate_block_length 现算,公式相同 ⇒ + // 循环参数天然一致, 不需要 GM 预扫描区/跨核握手(设计文档 D2 的简化实现)。 + // 注意:本步只计算、不改变现有循环行为;D3 才用 maxCandTiles 替换 S2 + // 内层游标。 + tempLoopInfo.maxCandLen = 0U; + tempLoopInfo.maxCandTiles = 0U; + tempLoopInfo.candDriven = false; + if (constInfo.candidateMode == CANDIDATE_MODE_CONSUMER && + hasCandidateBlockLength_) { + uint32_t taskTokens = + tempLoopInfo.actMBaseSize / static_cast(constInfo.gSize); + uint32_t rowBase = + tempLoopInfo.actS1RowBase + tempLoopInfo.gS1Idx * constInfo.s1BaseSize; + uint32_t maxL = 0U; + for (uint32_t t = 0U; t < taskTokens; t++) { + int32_t len = candidateBlockLengthGm.GetValue(rowBase + t); + uint32_t l = (len > 0) ? static_cast(len) : 0U; + maxL = (l > maxL) ? l : maxL; + } + if (maxL > constInfo.candidateTopkBlocks) { + maxL = constInfo.candidateTopkBlocks; + } + tempLoopInfo.maxCandLen = maxL; + // V1 候选 tile = 32 块 = 256 token;上界按任务内最大 L 取 uniform 值。 + tempLoopInfo.maxCandTiles = + (maxL * constInfo.candidateBlockSize + QLIV2Va_CAND_TILE_TOKENS - 1U) / + QLIV2Va_CAND_TILE_TOKENS; + // maxL=0 的任务仍需一次输出初始化(空行 -1),D3 用 maxCandTiles==0 + // 的特殊分支处理。 + tempLoopInfo.candDriven = true; + // v16:候选 × FD —— 候选模式下 s2 轴语义改为"候选 tile 索引" + // (QSLI metadata 按 max(L)×8 的候选 tile + // 数切分)。覆盖上面按全量扫块数算的 s2LoopEnd/isNeedLD:分片任务的循环上界 + // = metadata 给的 s2End(候选 tile 数), 是否分片 = 区间不覆盖整行 tile + // 范围。maxCandTiles 恒为**整行** tile 数(寻址基准)。 + tempLoopInfo.s2LoopEnd = (isEnd && constInfo.s2End != 0) + ? constInfo.s2End + : tempLoopInfo.maxCandTiles; + if (tempLoopInfo.s2LoopEnd > tempLoopInfo.maxCandTiles) { + tempLoopInfo.s2LoopEnd = tempLoopInfo.maxCandTiles; + } + tempLoopInfo.isNeedLD = + (constInfo.s2Start > 0 || + tempLoopInfo.s2LoopEnd < tempLoopInfo.maxCandTiles); + } } template @@ -708,6 +986,18 @@ __aicore__ inline void QLIV2VaPreload::CalcGS1LoopParams( return; } tempLoopInfo.curActSeqLenIsZero = false; + // candidate_block_length / candidate_topk_index 的行号基址: + // TND 用 cu_seqlens_q 前缀,BSND 用 bIdx × qSeqSize(与 candidateOutOffset + // 的布局一致) + if constexpr (Q_LAYOUT_T == LI_LAYOUT::TND) { + tempLoopInfo.actS1RowBase = + (constInfo.actualLenQDims == 0) + ? 0U + : actualSeqLengthsGmQ.GetValue(tempLoopInfo.bIdx); + } else { + tempLoopInfo.actS1RowBase = + tempLoopInfo.bIdx * static_cast(constInfo.qSeqSize); + } tempLoopInfo.mBasicSizeTail = (tempLoopInfo.actS1Size * constInfo.gSize) % constInfo.mBaseSize; tempLoopInfo.mBasicSizeTail = (tempLoopInfo.mBasicSizeTail == 0) @@ -741,6 +1031,8 @@ __aicore__ inline void QLIV2VaPreload::CalcRunInfo( runInfo.bN2Idx = tempLoopInfo.bN2Idx; runInfo.isValid = s2LoopIdx < tempLoopInfo.s2LoopEnd; runInfo.isNeedLD = tempLoopInfo.isNeedLD; + // B5/v4: 候选任务的全量扫输出写回被抑制(结果由 RunCandTask 的分数消费产生) + runInfo.suppressOut = tempLoopInfo.candDriven; if (runInfo.isNeedLD && s2LoopIdx + 1 == tempLoopInfo.s2LoopEnd) { runInfo.saveWorkSpaceIdx = ldInfo.saveWorkSpaceIdx; ldInfo.saveWorkSpaceIdx++; @@ -753,6 +1045,7 @@ __aicore__ inline void QLIV2VaPreload::CalcRunInfo( runInfo.actS1Size = tempLoopInfo.actS1Size; runInfo.actS2Size = tempLoopInfo.actS2Size; runInfo.actS2SizeOrig = tempLoopInfo.actS2SizeOrig; + runInfo.causalGlobalLen = tempLoopInfo.causalGlobalLen; // DCP // 计算实际基本块size runInfo.actMBaseSize = tempLoopInfo.actMBaseSize; runInfo.actualSingleProcessSInnerSize = constInfo.s2BaseSize; @@ -838,8 +1131,12 @@ template __aicore__ inline void QLIV2VaPreload::ProcessInvalid() { if ASCEND_IS_AIV { uint32_t aivCoreNum = GetBlockNum() * 2; // 2 means c:v = 1:2 - uint64_t totalOutputSize = constInfo.batchSize * constInfo.qSeqSize * + // TND s1Size already counts every query row in the batch. + uint64_t totalOutputSize = static_cast(constInfo.qSeqSize) * constInfo.kHeadNum * constInfo.sparseCount; + if constexpr (Q_LAYOUT_T != LI_LAYOUT::TND) { + totalOutputSize *= constInfo.batchSize; + } uint64_t singleCoreSize = QLIV2VaCommon::Align((totalOutputSize + aivCoreNum - 1) / aivCoreNum, GM_ALIGN_BYTES / sizeof(OUT_T)); @@ -850,6 +1147,26 @@ __aicore__ inline void QLIV2VaPreload::ProcessInvalid() { : totalOutputSize - baseSize; GlobalTensor output = indiceOutGm[baseSize]; AscendC::InitGlobalMemory(output, dealSize, constInfo.INVALID_IDX); + // Fill the score output with the sentinel for its return_value dtype. + if (constInfo.useLocalVisibleLengths || constInfo.returnValue != 0U) { + // The second fill reuses UB; finish the index DMA first. + SetWaitFlag(HardEvent::MTE3_V); + if (constInfo.useLocalVisibleLengths) { + GlobalTensor valueOutput; + valueOutput.SetGlobalBuffer((__gm__ uint32_t*)sparseValuesPtr + + baseSize); + AscendC::InitGlobalMemory( + valueOutput, + dealSize, + static_cast(QLIV2VaServiceVec::NEG_INF)); + } else { + GlobalTensor valueOutput; + valueOutput.SetGlobalBuffer((__gm__ uint16_t*)sparseValuesPtr + + baseSize); + AscendC::InitGlobalMemory( + valueOutput, dealSize, constInfo.NEG_INF_BFLOAT); + } + } } } } @@ -873,6 +1190,20 @@ __aicore__ inline void QLIV2VaPreload::ProcessMain() { constInfo.syncC1V0); CrossCoreSetFlag( constInfo.syncC1V0); + // v4: 候选 ring 的初始令牌 —— FREE 预置 RING_SLOTS 个(单 id 计数信号量, + // 一次 set 广播给两个 AIV,每消费 1 tile 回补 1 个);WFREE 预置 2 个(W + // 双槽)。 + if (constInfo.candidateMode == QLIV2VaCommon::CANDIDATE_MODE_CONSUMER && + hasCandidateBlockLength_) { + for (uint32_t s = 0U; s < QLIV2VaCommon::CAND_RING_SLOTS; s++) { + CrossCoreSetFlag( + QLIV2VaCommon::CAND_FREE_FLAG); + } + for (uint32_t s = 0U; s < 2U; s++) { + CrossCoreSetFlag( + QLIV2VaCommon::CAND_WFREE_FLAG); + } + } } QLIV2VaCommon::RunInfo runInfo[LI_QUANT_PRELOAD_TASK_CACHE_SIZE]; @@ -915,6 +1246,112 @@ __aicore__ inline void QLIV2VaPreload::ProcessMain() { gS1LoopIdx < tempLoopInfo.gS1LoopEnd; gS1LoopIdx++) { CalcS2LoopParams(bN2LoopIdx, gS1LoopIdx); + if (tempLoopInfo.candDriven) { + uint32_t taskTokens = + tempLoopInfo.actMBaseSize / static_cast(constInfo.gSize); + // 候选任务共用的 RunInfo:loop 决定 W 槽位,tensorWeightsOffset + // 指向本行块的权重起点 + QLIV2VaCommon::RunInfo candRun{}; + candRun.bIdx = tempLoopInfo.bIdx; + candRun.n2Idx = tempLoopInfo.n2Idx; + candRun.gS1Idx = tempLoopInfo.gS1Idx; + // W 双槽按候选任务序号交替(AIC/AIV 同一序号);不用 + // gloop,避免与全量扫的 runInfo 双缓冲槽 / 延迟 ProcessVec1 + // 排空相互干扰。 + candRun.loop = candTaskSeq_++; + candRun.candTask = true; + candRun.actS1Size = tempLoopInfo.actS1Size; + candRun.actS2Size = tempLoopInfo.actS2Size; + candRun.actS2SizeOrig = tempLoopInfo.actS2SizeOrig; + candRun.actMBaseSize = tempLoopInfo.actMBaseSize; + candRun.actualSingleProcessSInnerSize = QLIV2Va_CAND_TILE_TOKENS; + candRun.actualSingleProcessSInnerSizeAlign = QLIV2Va_CAND_TILE_TOKENS; + candRun.tensorQueryOffset = + static_cast(tempLoopInfo.actS1RowBase) * + constInfo.qHeadNum * constInfo.headDim + + static_cast(gS1LoopIdx) * constInfo.mBaseSize * + constInfo.headDim; + candRun.tensorWeightsOffset = + static_cast(tempLoopInfo.actS1RowBase) * + constInfo.qHeadNum + + static_cast(tempLoopInfo.n2Idx) * constInfo.gSize; + // v16:候选 × FD —— 本任务负责的候选 tile 区间与溢写参数。 + // 地址口径不变式:score/候选索引恒为绝对行级(maxCandTiles 整行), + // 分片只限定本任务计算的 tile 范围 [tileBegin, tileEnd)。 + const uint32_t candTileBegin = static_cast(constInfo.s2Start); + const uint32_t candTileEnd = tempLoopInfo.s2LoopEnd; + const bool candNeedSpill = tempLoopInfo.isNeedLD; + const uint32_t candWsBase = ldInfo.saveWorkSpaceIdx; + if ASCEND_IS_AIV { + // 跳过全量扫前,先排空上一任务延迟的 + // ProcessVec1(否则它的最终输出会丢失)。 延迟槽 = 上一次 + // ProcessBaseBlock 的槽位 = (gloop-1)%2。 + QLIV2VaCommon::RunInfo& pending = + runInfo[(gloop + LI_QUANT_PRELOAD_TASK_CACHE_SIZE - 1) % + LI_QUANT_PRELOAD_TASK_CACHE_SIZE]; + if (pending.isValid) { + CrossCoreWaitFlag(constInfo.syncC1V1); + vectorService.ProcessVec1(pending); + CrossCoreSetFlag(constInfo.syncV1C1); // 反向同步 1 + pending.isValid = false; + } + // B4: 先算一次本任务的 W(w×qscale 广播),AIC 候选 QK 依赖它 + vectorService.ProcessVec0(candRun); + CrossCoreSetFlag( + QLIV2VaCommon::CAND_WREADY_FLAG); + uint32_t rowBase = + tempLoopInfo.actS1RowBase + gS1LoopIdx * constInfo.s1BaseSize; + uint32_t s1RowBase = gS1LoopIdx * constInfo.s1BaseSize; + uint32_t indiceOutOffset = static_cast( + static_cast(rowBase) * constInfo.kHeadNum * + constInfo.sparseCount + + static_cast(tempLoopInfo.n2Idx) * + constInfo.sparseCount); + uint32_t outputIdxOffsetBase = static_cast( + static_cast(rowBase) * constInfo.kHeadNum + + tempLoopInfo.n2Idx); + // v4: gather 与分数消费按 token 交错 —— 先 gather token t 的全部 + // tile, 再消费 token t-2 的分数(退两拍,保证分数写有落地余量); + // 末尾两个 token 入 pending 队列,跨任务/核尾延迟消费 + vectorService.RunCandTask(tempLoopInfo.bIdx, + tempLoopInfo.n2Idx, + rowBase, + taskTokens, + tempLoopInfo.maxCandTiles, + candRun.loop, + s1RowBase, + tempLoopInfo.actS1Size, + tempLoopInfo.actS2Size, + tempLoopInfo.actS2SizeOrig, + indiceOutOffset, + outputIdxOffsetBase, + candTileBegin, + candTileEnd, + candNeedSpill, + candWsBase); + } else { + // B1+B2+B3+B4:等 W 就绪后,按 per-token M=32 从 staging 读 K 算 QK + CrossCoreWaitFlag(QLIV2VaCommon::CAND_WREADY_FLAG); + matmulService.ComputeMm1Candidate(candRun, + taskTokens, + tempLoopInfo.maxCandTiles, + candTileBegin, + candTileEnd); + // v4: 本任务的 W 槽读完后回收(AIV 最多领先 2 + // 个任务,不会覆盖正在读的槽) + CrossCoreSetFlag( + QLIV2VaCommon::CAND_WFREE_FLAG); + } + // v16:分片任务消耗一个 LD 工作区槽位(与全量扫 CalcRunInfo 同款记账, + // 槽位序列须与 metadata 的分片分配顺序一致) + if (candNeedSpill) { + ldInfo.saveWorkSpaceIdx++; + } + // 候选任务跳过全量扫(结果已由候选路径写出/溢写) + constInfo.s2Start = 0; + continue; + } bool isEnd = (bN2LoopIdx + 1 == constInfo.bN2End) && (gS1LoopIdx + 1 == tempLoopInfo.gS1LoopEnd); uint32_t extraLoop = @@ -936,6 +1373,13 @@ __aicore__ inline void QLIV2VaPreload::ProcessMain() { } if ASCEND_IS_AIV { + // v4 核尾排空:候选任务内最后一个 token 的分数消费延迟到这里, + // 先等 AIC 主循环结束令牌(其分数写已推进/落地),再读分数写输出。 + if (constInfo.candidateMode == QLIV2VaCommon::CANDIDATE_MODE_CONSUMER && + hasCandidateBlockLength_) { + CrossCoreWaitFlag(QLIV2VaCommon::CAND_AIC_DONE_FLAG); + vectorService.DrainPendingCandScore(); + } vectorService.FreeEventID(); CrossCoreWaitFlag(constInfo.syncC1V0); CrossCoreWaitFlag(constInfo.syncC1V0); @@ -943,6 +1387,15 @@ __aicore__ inline void QLIV2VaPreload::ProcessMain() { matmulService.FreeEventID(); CrossCoreWaitFlag(constInfo.syncV1C1); CrossCoreWaitFlag(constInfo.syncV1C1); + if (constInfo.candidateMode == QLIV2VaCommon::CANDIDATE_MODE_CONSUMER && + hasCandidateBlockLength_) { + // v17:AIC_DONE 前必须先等 fixpipe 队列清空 —— 核尾排空读最后一个 tile 的 + // 分数,若分数写未落地,AIV 读到的是旧区域数据(FD 单 tile 分片让"最后写" + // 与"排空读"几乎背靠背,实测 tile5 高分 token 被旧区域数据顶替)。 + AscendC::PipeBarrier(); + CrossCoreSetFlag( + QLIV2VaCommon::CAND_AIC_DONE_FLAG); + } } } diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_cube_arch22.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_cube_arch22.h index 6022c93eb1..4535ccfaf1 100644 --- a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_cube_arch22.h +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_cube_arch22.h @@ -51,12 +51,40 @@ class QLIV2VaMatmul { __aicore__ inline void AllocEventID(); __aicore__ inline void FreeEventID(); __aicore__ inline void ComputeMm1(const QLIV2VaCommon::RunInfo& runInfo); + // AIV gathers the candidate keys into the ring. AIC writes scores for the + // per-row TopK. + __aicore__ inline void InitCandMm1Tensor( + const GlobalTensor& stagingKeyGm, + const GlobalTensor& candScoreGm); + __aicore__ inline void ComputeMm1Candidate( + const QLIV2VaCommon::RunInfo& runInfo, + uint32_t taskTokens, + uint32_t maxTiles, + uint32_t tileBegin, + uint32_t tileEnd); static constexpr IsResetLoad3dConfig LOAD3DV2_CONFIG = { true, true}; // isSetFMatrix isSetPadding; static constexpr uint64_t DOUBLE_BUF_NUM = 2; static constexpr uint64_t L0AB_BUF_NUM = 4; + // K 每 2 对只装一次:K 槽在 0/1 之间轮转,第二对 QK 后归还;S 仍使用全部 4 个 + // L0B 槽, 只在每个 WS 内跳过当前仍被 K 占用的槽。 + static constexpr uint64_t K_L0B_SLOT_NUM = 2; + static constexpr uint64_t S_L0B_SLOT_NUM = L0AB_BUF_NUM; + + // 优化:Q 与 W 的 L0A 常驻槽共用一个 M→MTE1 守卫 id(PIN_MTE1_EVENT), + // 每个行块只在首尾各 wait/set 一次 —— 内层循环的 M→MTE1 + // 等待条数与基线完全相同(每对 3 条), 从而避开"新增 M→MTE1 + // 等待即挂死"的硬件限制(见 README §15.3)。 L0A 布局:槽0 = 本行块 4 个 s1 + // 行的 W(每行 2KB,共 8KB);槽1 空闲;槽2/3 = 两个 M 块的 Q(各 16KB)。 + static constexpr uint64_t Q_SLOT_BASE = 2; + static constexpr uint64_t W_SLOT_HALF_BASE = + 0; // W 区在 L0A 的 half 元素起点 + static constexpr uint64_t W_ROW_STRIDE_HALF = + 1024; // 每行 W 占 1024 个 half(=2KB) + static constexpr uint32_t PIN_MTE1_EVENT = + EVENT_ID7; // Q+W 常驻区共用守卫(ids 7) static constexpr uint32_t KEY_MTE1_MTE2_EVENT = EVENT_ID2; static constexpr uint32_t QW_MTE1_MTE2_EVENT = @@ -65,6 +93,16 @@ class QLIV2VaMatmul { static constexpr uint32_t M_FIX_EVENT = EVENT_ID0; static constexpr uint32_t FIX_M_EVENT = EVENT_ID2; static constexpr uint32_t FIX_MTE1_EVENT = EVENT_ID4; + // S(L1 上的中间结果)双缓冲 → 3 块 + 消费滞后 2 对:让"S 就绪"(FIX_MTE1) + // 等待落在 两对之前置位的旗标上(被更深的流水吸收)。旗标 id 用 + // 4/5/6(FIX→MTE1 方向 id 6 空闲; 事件 id 按流水方向隔离,与 M_MTE1 + // 方向的同号 id 不冲突)。 注意:缓冲槽与旗标 id 都必须用**全局对号**(成员 + // sL1BufIdx_,跨 行块/s2 内循环 连续), 用本 call + // 内的局部游标会与写侧的全局游标错位 —— 见 scripts/prof_output/naie273qli/ + // model_s_pipeline.py(协议离线模型:局部游标版会出 "Wait 无可用 Set" + // 的挂死形状)。 + static constexpr uint64_t S_L1_BUF_NUM = 3; + static constexpr uint64_t S_L1_BUF_LAG = S_L1_BUF_NUM - 1; static constexpr uint64_t S8_BLOCK_CUBE = 32; @@ -92,15 +130,21 @@ class QLIV2VaMatmul { private: __aicore__ inline void WeightDmaCopy(uint64_t s1gL1RealSize, const QLIV2VaCommon::RunInfo& runInfo); - __aicore__ inline void LoadKeyToL0b(uint64_t s2L0RealSize); + __aicore__ inline void LoadKeyToL0b(uint64_t s2L0RealSize, uint64_t kSlot); __aicore__ inline void LoadQueryToL0a(uint64_t s1gL1Offset, uint64_t s1gL1RealSize, - uint64_t s1gL0RealSize); + uint64_t s1gL0RealSize, + uint64_t qSlot); __aicore__ inline void QueryNd2Nz(uint64_t s1gL1RealSize, const QLIV2VaCommon::RunInfo& runInfo); __aicore__ inline void KeyNd2NzForPA(uint64_t s2L1RealSize, uint64_t s2GmOffset, - const QLIV2VaCommon::RunInfo& runInfo); + const QLIV2VaCommon::RunInfo& runInfo, + uint64_t dstSlot); + // D3b: 候选 staging(ND [512][128B])→ L1,nValue = 本次 L0B 块 token 数 + __aicore__ inline void KeyFromStaging(uint64_t s2L0RealSize, + uint64_t srcByteBase); + __aicore__ inline void KeyNd2Nz(uint64_t s2L1RealSize, const MmInfo& mmInfo, const QLIV2VaCommon::RunInfo& runInfo); @@ -108,22 +152,30 @@ class QLIV2VaMatmul { uint64_t s2L0RealSize); __aicore__ inline void LoadSToL0b(uint64_t s1gL1RealSize, uint64_t s2L0RealSize, - uint64_t sL1BufIdx, - int64_t mStartPt); - __aicore__ inline void LoadWeightToL0a(uint64_t s1gL1Offset); + uint64_t sL1SlotIdx, + int64_t mStartPt, + uint64_t sSlot); + __aicore__ inline void LoadWeightToL0a(uint64_t l1ElemOffset, + uint64_t l0aHalfOffset); + __aicore__ inline void LoadAllWeightRowsToL0a(); __aicore__ inline void ComputeWs(uint64_t s1gL0RealSize, uint64_t s2L0RealSize, - int64_t s1gOffset); + int64_t s1gOffset, + uint64_t wRowIdx, + uint64_t sSlot); __aicore__ inline void FixpResToGm(uint64_t s1L0RealCount, uint64_t s2L0RealSize, uint64_t s1GmOffset, uint64_t s2GmOffset, const QLIV2VaCommon::RunInfo& runInfo); __aicore__ inline void ComputeQk(uint64_t s1gL0RealSize, - uint64_t s2L0RealSize); + uint64_t s2L0RealSize, + uint64_t qSlot, + uint64_t kSlot); + // sL1SlotIdx:已取模的 S 缓冲槽号(0..S_L1_BUF_NUM-1),不是运行计数器 __aicore__ inline void ProcessWs(uint64_t s1gL0RealSize, uint64_t s1gL1Offset, - uint64_t sL1BufIdx, + uint64_t sL1SlotIdx, const MmInfo& mmInfo, const QLIV2VaCommon::RunInfo& runInfo); __aicore__ inline void ProcessQk(uint64_t s1gL0RealSize, @@ -143,6 +195,22 @@ class QLIV2VaMatmul { GlobalTensor queryGm_; GlobalTensor weightGm_; GlobalTensor mm1ResGm_; + // D3b: 候选驱动(K staging / 候选分数区 / 当前 tile 的基址与 W 行偏移) + GlobalTensor candStagingKeyGm_; + GlobalTensor candScoreGm_; + bool candMode_ = false; // 仅当前 ComputeMm1 调用生效(候选分支开关) + uint64_t candKBase_ = 0; // 当前候选 tile 的 staging 字节基址 + uint64_t candOutBase_ = 0; // 当前 (token,tile) 的候选分数 float 基址 + uint64_t weightRowOffset_ = + 0; // 当前 token 在 vec0OutGm 中的 half 行偏移(非候选路径恒 0) + // v4: 候选 tile 消费序号(每消费一个 tile 自增一次,槽号 = seq % + // CAND_RING_SLOTS) + uint32_t candConsTileSeq_ = 0U; + // v20: 候选 mm1 的 K L0B 槽轮转序号。上游 K 槽重构后 kSlot = s2L0LoopId % + // 2,而候选 mm1 的 s2L0LoopId 恒 0 → 单槽串行(LoadKeyToL0b 须等上一 tile 的 + // MMAD 完成)。 候选路径恢复预合并版的 4 槽轮转(L0AB_BUF_NUM),装载与 MMAD + // 跨 tile 重叠。 + uint32_t candL0bSeq_ = 0U; TBuf bufQL1_; LocalTensor queryL1_; @@ -164,8 +232,10 @@ class QLIV2VaMatmul { uint64_t keyL1BufIdx_ = 0; uint64_t qwL1Mte2BufIdx_ = 0; uint64_t sL1BufIdx_ = 0; - uint64_t l0BufIdx_ = 0; uint64_t l0cBufIdx_ = 0; + uint64_t sL0BufIdx_ = 0; // S 的 L0B 4 槽环游标 + bool kPairFilledNext_ = false; // (旧 kp3 对填充,保留兼容) + bool kPrefetched_ = false; // 本组 K 已在上一组预取到 L1 ConstInfo constInfo_; }; @@ -193,7 +263,7 @@ __aicore__ inline void QLIV2VaMatmul::InitBuffers(TPipe* pipe) { weightL1_ = bufWeightL1_.Get(); pipe->InitBuffer( bufSL1_, - DOUBLE_BUF_NUM * S2_BASIC_BLOCK_L0 * S1G_BASIC_BLOCK_L0 * sizeof(half)); + S_L1_BUF_NUM * S2_BASIC_BLOCK_L0 * S1G_BASIC_BLOCK_L0 * sizeof(half)); sL1_ = bufSL1_.Get(); pipe->InitBuffer(bufL0A_, 64 * 1024); @@ -223,20 +293,31 @@ template __aicore__ inline void QLIV2VaMatmul::ProcessWs( uint64_t s1gL0RealSize, uint64_t s1gL1Offset, - uint64_t sL1BufIdx, + uint64_t sL1SlotIdx, const MmInfo& mmInfo, const QLIV2VaCommon::RunInfo& runInfo) { - WaitFlag(FIX_M_EVENT + l0cBufIdx_ % DOUBLE_BUF_NUM); + WaitFlag(FIX_M_EVENT + (l0cBufIdx_ & (DOUBLE_BUF_NUM - 1))); + // S 用全部 4 个 L0B 槽,但必须跳过本迭代 ProcessQk 占用/正在装载的 K 槽。 + // 对 s1g=0 的 WS,下一组 K 已在同迭代装好并要占住两对;对 s1g=1 的 WS,本组 K + // 也要 到本次 QK 结束才释放。若 S 落进该槽,S 装载会等 QK 的 MMAD,WS + // 被整体推到 QK 之后。 + const uint64_t avoidSlot = (mmInfo.s2L0LoopId + 1) % K_L0B_SLOT_NUM; + // W 行号按块递增,除法只在循环外做一次(原来每块一次 DIV)。 + uint64_t wRowIdx = static_cast( + s1gL1Offset / static_cast(constInfo_.gSize)); for (int64_t s1gOffset = 0; s1gOffset < s1gL0RealSize; s1gOffset += constInfo_.gSize) { - WaitFlag(M_MTE1_EVENT + l0BufIdx_ % L0AB_BUF_NUM); - LoadSToL0b(s1gL0RealSize, mmInfo.s2L0RealSize, sL1BufIdx, s1gOffset); - LoadWeightToL0a(s1gOffset + s1gL1Offset); - - ComputeWs(s1gL0RealSize, mmInfo.s2L0RealSize, s1gOffset); - - SetFlag(M_MTE1_EVENT + l0BufIdx_ % L0AB_BUF_NUM); - l0BufIdx_++; + uint64_t sSlot = sL0BufIdx_ % S_L0B_SLOT_NUM; + if (sSlot == avoidSlot) { + sSlot = (sSlot + 1) % S_L0B_SLOT_NUM; + } + WaitFlag(M_MTE1_EVENT + sSlot); + LoadSToL0b( + s1gL0RealSize, mmInfo.s2L0RealSize, sL1SlotIdx, s1gOffset, sSlot); + ComputeWs(s1gL0RealSize, mmInfo.s2L0RealSize, s1gOffset, wRowIdx, sSlot); + ++wRowIdx; + SetFlag(M_MTE1_EVENT + sSlot); + sL0BufIdx_ = sSlot + 1; } FixpResToGm(s1gL0RealSize / constInfo_.gSize, @@ -244,7 +325,7 @@ __aicore__ inline void QLIV2VaMatmul::ProcessWs( s1gL1Offset / constInfo_.gSize, mmInfo.s2L0LoopId * S2_BASIC_BLOCK_L0, runInfo); - SetFlag(FIX_M_EVENT + l0cBufIdx_ % DOUBLE_BUF_NUM); + SetFlag(FIX_M_EVENT + (l0cBufIdx_ & (DOUBLE_BUF_NUM - 1))); l0cBufIdx_++; } @@ -255,38 +336,103 @@ __aicore__ inline void QLIV2VaMatmul::ProcessQk( uint64_t s1L0LoopCnt, const MmInfo& mmInfo, const QLIV2VaCommon::RunInfo& runInfo) { + // K 填充滚动预取:每组的 K 在上一组就填到另一块 L1 槽;当前组只等上一组已发的 + // 填充完成,不再等本组填充。本组 K 的 L0B 装载释放后,再为下一组发填充(与 QK + // 重叠)。 + uint64_t curKIdx = keyL1BufIdx_ & (DOUBLE_BUF_NUM - 1); + uint64_t myGmOffsetK = 0; + bool prefetchNextK = false; if (mmInfo.s1gL0LoopId == 0) { - WaitFlag(KEY_MTE1_MTE2_EVENT + - keyL1BufIdx_ % DOUBLE_BUF_NUM); if constexpr (K_LAYOUT_T == LI_LAYOUT::PA_BBND) { - KeyNd2NzForPA(mmInfo.s2L0RealSize, - runInfo.s2Idx * constInfo_.s2BaseSize + mmInfo.s2GmOffset, - runInfo); + if (candMode_) { + // D3b: 候选 tile 的 K 已在 staging(ND 连续),按 s2L0 子块偏移直接 + // nd2nz 搬入 L1 (握手与预合并版逐字一致:前置等 K L1 + // 槽复用窗口,后置通知+等 L0B 装载就绪; + // 合并上游 K 预取重构时曾丢这两对旗标,case C 候选路径 aicore 挂死 + // 507014) + WaitFlag(KEY_MTE1_MTE2_EVENT + curKIdx); + KeyFromStaging(mmInfo.s2L0RealSize, + candKBase_ + static_cast(mmInfo.s2GmOffset) * + constInfo_.headDim); + SetFlag(MTE2_MTE1_EVENT); + WaitFlag(MTE2_MTE1_EVENT); + } else { + myGmOffsetK = runInfo.s2Idx * constInfo_.s2BaseSize + mmInfo.s2GmOffset; + if (!kPrefetched_) { + WaitFlag(KEY_MTE1_MTE2_EVENT + curKIdx); + KeyNd2NzForPA(mmInfo.s2L0RealSize, myGmOffsetK, runInfo, curKIdx); + SetFlag(MTE2_MTE1_EVENT + curKIdx); + } + kPrefetched_ = false; + WaitFlag(MTE2_MTE1_EVENT + curKIdx); + const uint64_t s2Tail = + runInfo.s2Idx * constInfo_.s2BaseSize + + static_cast(runInfo.actualSingleProcessSInnerSize); + prefetchNextK = mmInfo.s2L0RealSize == S2_BASIC_BLOCK_L0 && + ((myGmOffsetK % constInfo_.kCacheBlockSize) + + 2 * S2_BASIC_BLOCK_L0 <= + constInfo_.kCacheBlockSize) && + (myGmOffsetK + 2 * S2_BASIC_BLOCK_L0 <= s2Tail); + } } else { + WaitFlag(KEY_MTE1_MTE2_EVENT + curKIdx); KeyNd2Nz(mmInfo.s2L0RealSize, mmInfo, runInfo); + SetFlag(MTE2_MTE1_EVENT); + WaitFlag(MTE2_MTE1_EVENT); } - - SetFlag(MTE2_MTE1_EVENT); - WaitFlag(MTE2_MTE1_EVENT); } - WaitFlag(M_MTE1_EVENT + l0BufIdx_ % L0AB_BUF_NUM); - LoadQueryToL0a(s1gL1Offset, runInfo.actMBaseSize, s1gL0RealSize); - LoadKeyToL0b(mmInfo.s2L0RealSize); - - if (mmInfo.s1gL0LoopId + 1 >= s1L0LoopCnt) { - SetFlag(KEY_MTE1_MTE2_EVENT + - keyL1BufIdx_ % DOUBLE_BUF_NUM); + // 常驻区(Q + W):Q/W 只取决于查询行、与键无关 ⇒ + // 真正的装载只需按**行块**做一次 (L1 + // 源缓冲同样是每行块填一次:isFirstS2InnerLoop,见 kernel_arch22.h:609); + // 但**握手仍保持"每基块一次"**(与已验证版逐字一致,旗标配平不变),只是后续基块跳过装载体。 + const uint64_t qSlot = Q_SLOT_BASE + mmInfo.s1gL0LoopId; + if (mmInfo.s2L0LoopId == 0) { + if (mmInfo.s1gL0LoopId == 0) { + WaitFlag( + PIN_MTE1_EVENT); // 每基块一次(保持与原协议同构) + if (runInfo.isFirstS2InnerLoop) { + LoadAllWeightRowsToL0a(); // 仅行块首块真装 + } + } + if (runInfo.isFirstS2InnerLoop) { + LoadQueryToL0a(s1gL1Offset, runInfo.actMBaseSize, s1gL0RealSize, qSlot); + } + } + // K 槽:非候选按 s2 组号在 0/1 之间轮转(两对 QK 共用,第二对 QK 后归还); + // 候选 per-token mm1 的 s2L0LoopId 恒 0,用 4 槽轮转保持装载/MMAD 跨 tile + // 重叠(v20)。 + const uint64_t kSlot = + candMode_ ? (static_cast(candL0bSeq_++) % L0AB_BUF_NUM) + : (mmInfo.s2L0LoopId % K_L0B_SLOT_NUM); + if (mmInfo.s1gL0LoopId == 0) { + WaitFlag(M_MTE1_EVENT + kSlot); + LoadKeyToL0b(mmInfo.s2L0RealSize, kSlot); + // 当前 K 的 L1 只被这一次 L0B 装载消费,装完即可释放;随后为下一组发填充。 + SetFlag(KEY_MTE1_MTE2_EVENT + curKIdx); keyL1BufIdx_++; + if constexpr (K_LAYOUT_T == LI_LAYOUT::PA_BBND) { + if (prefetchNextK) { + const uint64_t nextKIdx = keyL1BufIdx_ & (DOUBLE_BUF_NUM - 1); + WaitFlag(KEY_MTE1_MTE2_EVENT + nextKIdx); + KeyNd2NzForPA(S2_BASIC_BLOCK_L0, + myGmOffsetK + S2_BASIC_BLOCK_L0, + runInfo, + nextKIdx); + SetFlag(MTE2_MTE1_EVENT + nextKIdx); + kPrefetched_ = true; + } + } } - WaitFlag(FIX_M_EVENT + l0cBufIdx_ % DOUBLE_BUF_NUM); - ComputeQk(s1gL0RealSize, mmInfo.s2L0RealSize); - SetFlag(M_MTE1_EVENT + l0BufIdx_ % L0AB_BUF_NUM); + WaitFlag(FIX_M_EVENT + (l0cBufIdx_ & (DOUBLE_BUF_NUM - 1))); + ComputeQk(s1gL0RealSize, mmInfo.s2L0RealSize, qSlot, kSlot); + if (mmInfo.s1gL0LoopId + 1 >= s1L0LoopCnt) { + SetFlag(M_MTE1_EVENT + kSlot); + } FixpSToL1(s1gL0RealSize, mmInfo.s2L0RealSize); - SetFlag(FIX_M_EVENT + l0cBufIdx_ % DOUBLE_BUF_NUM); - l0BufIdx_++; + SetFlag(FIX_M_EVENT + (l0cBufIdx_ & (DOUBLE_BUF_NUM - 1))); l0cBufIdx_++; } @@ -297,8 +443,17 @@ __aicore__ inline void QLIV2VaMatmul::CalcMmInfo( uint64_t s1L0LoopCnt, const MmInfo& lastMmInfo, const QLIV2VaCommon::RunInfo& runInfo) { - mmInfo.s2L0LoopId = loopIdx / s1L0LoopCnt; - mmInfo.s1gL0LoopId = loopIdx % s1L0LoopCnt; + // s1L0LoopCnt 实际只有 1 或 2(基块最多 256 行):用移位/掩码替代 DIV/REM。 + if (s1L0LoopCnt == 2) { + mmInfo.s2L0LoopId = loopIdx >> 1; + mmInfo.s1gL0LoopId = loopIdx & 1; + } else if (s1L0LoopCnt == 1) { + mmInfo.s2L0LoopId = loopIdx; + mmInfo.s1gL0LoopId = 0; + } else { + mmInfo.s2L0LoopId = loopIdx / s1L0LoopCnt; + mmInfo.s1gL0LoopId = loopIdx % s1L0LoopCnt; + } if (mmInfo.s1gL0LoopId == 0) { mmInfo.s2GmOffset = mmInfo.s2L0LoopId * S2_BASIC_BLOCK_L0; @@ -317,7 +472,7 @@ __aicore__ inline void QLIV2VaMatmul::ComputeMm1( const QLIV2VaCommon::RunInfo& runInfo) { if (runInfo.isFirstS2InnerLoop) { WaitFlag(QW_MTE1_MTE2_EVENT + - qwL1Mte2BufIdx_ % DOUBLE_BUF_NUM); + (qwL1Mte2BufIdx_ & (DOUBLE_BUF_NUM - 1))); QueryNd2Nz(runInfo.actMBaseSize, runInfo); // 256 * 128 // L1BasicBlock WeightDmaCopy(runInfo.actMBaseSize, runInfo); } @@ -338,55 +493,91 @@ __aicore__ inline void QLIV2VaMatmul::ComputeMm1( mmInfo[(loopIdx + 1) & 1], runInfo); - ProcessQk(s1gL0RealSize[mmInfo[loopIdx & 1].s1gL0LoopId % s1L0LoopCnt], - s1gL1Offset[mmInfo[loopIdx & 1].s1gL0LoopId % s1L0LoopCnt], - s1L0LoopCnt, - mmInfo[loopIdx & 1], - runInfo); - - SetFlag(FIX_MTE1_EVENT + sL1BufIdx_ % DOUBLE_BUF_NUM); - sL1BufIdx_++; - loopIdx++; + // 3 块 S 流水:生产超前消费 S_L1_BUF_LAG(=2) 对,让 "S 就绪"(FIX_MTE1) + // 等待落在两对之前的旗标上。 + // * 缓冲槽与旗标 id 一律用**全局对号** gIdx = globalBase + 本 call + // 内的对号;globalBase 取成员 + // sL1BufIdx_(每生产一对 +1、跨 行块/s2 内循环 + // 连续),使写侧与读侧看到同一个槽、同一个 id。 若读侧改用本 call + // 内的局部游标,call 边界处会与写侧错位(Wait 等一个尚未置位的 id ⇒ + // 挂死), 这正是 2026-10-15 那版 507014 的来源,见 + // scripts/prof_output/naie273qli/model_s_pipeline.py。 + // * 消费所需的对信息取自快照环 ringInfo[本 call 内对号 % + // S_L1_BUF_NUM](生产时写入):mmInfo 只有 + // 2 个槽,消费第 i 对时其槽可能已被第 i+1 + // 对覆盖,不能靠重算取得(会读到错的上一次对信息)。 + // * 旗标计数与基线一致:每对 1 次 set(生产)+ 1 次 wait(消费)。 + const int64_t totalLoop = s2L0LoopCnt * s1L0LoopCnt; + const int64_t earlyCnt = totalLoop < static_cast(S_L1_BUF_LAG) + ? totalLoop + : static_cast(S_L1_BUF_LAG); + const uint64_t globalBase = sL1BufIdx_; // 本 call 首对的全局对号 + MmInfo ringInfo[S_L1_BUF_NUM]; + int64_t consumeIdx = 0; // 本 call 内下一个待消费的对号(= 已消费对数) + + for (int64_t w = 0; w < earlyCnt; ++w) { // 预热:只生产、不消费 + CalcMmInfo(mmInfo[loopIdx & 1], + loopIdx, + s1L0LoopCnt, + mmInfo[(loopIdx + 1) & 1], + runInfo); + ringInfo[loopIdx % S_L1_BUF_NUM] = mmInfo[loopIdx & 1]; + ProcessQk(s1gL0RealSize[mmInfo[loopIdx & 1].s1gL0LoopId], + s1gL1Offset[mmInfo[loopIdx & 1].s1gL0LoopId], + s1L0LoopCnt, + mmInfo[loopIdx & 1], + runInfo); + SetFlag(FIX_MTE1_EVENT + sL1BufIdx_ % S_L1_BUF_NUM); + sL1BufIdx_++; + loopIdx++; + } - while (loopIdx < s2L0LoopCnt * s1L0LoopCnt) { + while (loopIdx < totalLoop) { CalcMmInfo(mmInfo[loopIdx & 1], loopIdx, s1L0LoopCnt, mmInfo[(loopIdx + 1) & 1], runInfo); + ringInfo[loopIdx % S_L1_BUF_NUM] = mmInfo[loopIdx & 1]; - ProcessQk(s1gL0RealSize[mmInfo[loopIdx & 1].s1gL0LoopId % s1L0LoopCnt], - s1gL1Offset[mmInfo[loopIdx & 1].s1gL0LoopId % s1L0LoopCnt], + ProcessQk(s1gL0RealSize[mmInfo[loopIdx & 1].s1gL0LoopId], + s1gL1Offset[mmInfo[loopIdx & 1].s1gL0LoopId], s1L0LoopCnt, mmInfo[loopIdx & 1], runInfo); - SetFlag(FIX_MTE1_EVENT + sL1BufIdx_ % DOUBLE_BUF_NUM); + SetFlag(FIX_MTE1_EVENT + sL1BufIdx_ % S_L1_BUF_NUM); sL1BufIdx_++; - WaitFlag(FIX_MTE1_EVENT + sL1BufIdx_ % DOUBLE_BUF_NUM); - - ProcessWs( - s1gL0RealSize[mmInfo[(loopIdx + 1) & 1].s1gL0LoopId % s1L0LoopCnt], - s1gL1Offset[mmInfo[(loopIdx + 1) & 1].s1gL0LoopId % s1L0LoopCnt], - sL1BufIdx_, - mmInfo[(loopIdx + 1) & 1], - runInfo); + const uint64_t gIdx = globalBase + static_cast(consumeIdx); + WaitFlag(FIX_MTE1_EVENT + gIdx % S_L1_BUF_NUM); + ProcessWs(s1gL0RealSize[ringInfo[consumeIdx % S_L1_BUF_NUM].s1gL0LoopId], + s1gL1Offset[ringInfo[consumeIdx % S_L1_BUF_NUM].s1gL0LoopId], + gIdx % S_L1_BUF_NUM, + ringInfo[consumeIdx % S_L1_BUF_NUM], + runInfo); + consumeIdx++; loopIdx++; } - WaitFlag(FIX_MTE1_EVENT + - (sL1BufIdx_ + 1) % DOUBLE_BUF_NUM); + for (int64_t t = 0; t < earlyCnt; ++t) { // 尾部排空:把预热未消费的 S 消费完 + const uint64_t gIdx = globalBase + static_cast(consumeIdx); + WaitFlag(FIX_MTE1_EVENT + gIdx % S_L1_BUF_NUM); + ProcessWs(s1gL0RealSize[ringInfo[consumeIdx % S_L1_BUF_NUM].s1gL0LoopId], + s1gL1Offset[ringInfo[consumeIdx % S_L1_BUF_NUM].s1gL0LoopId], + gIdx % S_L1_BUF_NUM, + ringInfo[consumeIdx % S_L1_BUF_NUM], + runInfo); + consumeIdx++; + } - ProcessWs(s1gL0RealSize[mmInfo[(loopIdx + 1) & 1].s1gL0LoopId % s1L0LoopCnt], - s1gL1Offset[mmInfo[(loopIdx + 1) & 1].s1gL0LoopId % s1L0LoopCnt], - sL1BufIdx_ - 1, - mmInfo[(loopIdx + 1) & 1], - runInfo); + // 常驻区(Q+W)释放:此刻本行块所有读 Q/W 的 MMAD 均已发完(M 流水保序), + // 事件触发后下一个行块可覆盖这两个区;与行块首的 1 次 wait 一一对应。 + SetFlag(PIN_MTE1_EVENT); if (runInfo.isLastS2InnerLoop) { SetFlag(QW_MTE1_MTE2_EVENT + - qwL1Mte2BufIdx_ % DOUBLE_BUF_NUM); + (qwL1Mte2BufIdx_ & (DOUBLE_BUF_NUM - 1))); qwL1Mte2BufIdx_++; } } @@ -396,7 +587,8 @@ template __aicore__ inline void QLIV2VaMatmul::KeyNd2NzForPA( uint64_t s2L1RealSize, uint64_t s2GmOffset, - const QLIV2VaCommon::RunInfo& runInfo) { + const QLIV2VaCommon::RunInfo& runInfo, + uint64_t dstSlot) { uint64_t s2L1Offset = 0; // A11: key 0 轴非连续寻址 — 块基址 = 表值 x keyStride0 (host 下发的真实 // stride)。 keyStride0 == 0 (旧调用/非 PA 紧凑) 时兜底原紧凑公式, 现网行为 @@ -428,8 +620,7 @@ __aicore__ inline void QLIV2VaMatmul::KeyNd2NzForPA( nd2nzPara.dstNzNStride = 1; nd2nzPara.srcNdMatrixStride = 0; nd2nzPara.dstNzMatrixStride = 0; - DataCopy(keyL1_[(keyL1BufIdx_ % DOUBLE_BUF_NUM) * KEY_BUFFER_OFFSET + - s2L1Offset * S8_BLOCK_CUBE], + DataCopy(keyL1_[dstSlot * KEY_BUFFER_OFFSET + s2L1Offset * S8_BLOCK_CUBE], keyGm_[keyGmOffset], nd2nzPara); @@ -437,6 +628,105 @@ __aicore__ inline void QLIV2VaMatmul::KeyNd2NzForPA( } } +template +__aicore__ inline void QLIV2VaMatmul::KeyFromStaging( + uint64_t s2L0RealSize, + uint64_t srcByteBase) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = s2L0RealSize; // token 行数(128) + nd2nzPara.dValue = constInfo_.headDim; + nd2nzPara.srcDValue = constInfo_.headDim; + nd2nzPara.dstNzC0Stride = CeilAlign(s2L0RealSize, (uint64_t)BLOCK_CUBE); + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(keyL1_[(keyL1BufIdx_ % DOUBLE_BUF_NUM) * KEY_BUFFER_OFFSET], + candStagingKeyGm_[srcByteBase], + nd2nzPara); +} + +template +__aicore__ inline void QLIV2VaMatmul::InitCandMm1Tensor( + const GlobalTensor& stagingKeyGm, + const GlobalTensor& candScoreGm) { + candStagingKeyGm_ = stagingKeyGm; + candScoreGm_ = candScoreGm; +} + +// v4(对齐 DSL 软件流水):逐 token 跑现成的 ComputeMm1 骨架 —— M=32(该 token +// 的 32 头), N=256(一个候选 tile)。Q 按 token 重新装载(tile0),W 按 token +// 行偏移读取; K 从 staging 读(KeyFromStaging);输出写候选分数区。 +// **消费错一拍**:进入任务先领一个 READY 令牌(丢弃),此后每个 tile 消费前再 +// wait 一个, 最后一个 tile 等 AIV 任务末的 drain 令牌 ⇒ 每个 tile 的写→读间隔 +// ≥ 一个 tile 的 gather 时间(与 DSL "先发 tile k、再算 tile k-1" 同构,规避 +// 910B GM 写后立即读不可见)。 +template +__aicore__ inline void QLIV2VaMatmul::ComputeMm1Candidate( + const QLIV2VaCommon::RunInfo& runInfo, + uint32_t taskTokens, + uint32_t maxTiles, + uint32_t tileBegin, + uint32_t tileEnd) { + if (tileEnd <= tileBegin || taskTokens == 0U) { + return; + } + constexpr uint32_t CAND_TILE_TOKENS = + QLIV2VaCommon::CAND_TILE_TOKENS; // 64 块 × 8 token = 512 + const uint64_t tokenQueryStride = static_cast(constInfo_.gSize) * + static_cast(constInfo_.headDim); + candMode_ = true; + QLIV2VaCommon::RunInfo candInfo = runInfo; + candInfo.actMBaseSize = static_cast(constInfo_.gSize); // M = 32 头 + candInfo.actualSingleProcessSInnerSize = CAND_TILE_TOKENS; // N = 512 + candInfo.actualSingleProcessSInnerSizeAlign = CAND_TILE_TOKENS; + // v16:候选 × FD —— 本任务只算 tile 区间 [tileBegin, tileEnd)(分片); + // 地址口径不变式:分数写地址恒为绝对行级 (t×maxTiles + absTile)×512,maxTiles + // 为整行 tile 数。 + const uint32_t sliceTiles = tileEnd - tileBegin; + const uint32_t tileCount = taskTokens * sliceTiles; + // 错一拍:先领一个令牌(tile0 的 READY),之后每消费一个 tile 前再 wait + // 一个令牌 + AscendC::CrossCoreWaitFlag(QLIV2VaCommon::CAND_READY_FLAG); + for (uint32_t k = 0U; k < tileCount; k++) { + AscendC::CrossCoreWaitFlag(QLIV2VaCommon::CAND_READY_FLAG); + const uint32_t t = k / sliceTiles; + const uint32_t relTile = k % sliceTiles; + const uint32_t absTile = tileBegin + relTile; + candInfo.tensorQueryOffset = + runInfo.tensorQueryOffset + static_cast(t) * tokenQueryStride; + candInfo.isFirstS2InnerLoop = (relTile == 0U); + candInfo.isLastS2InnerLoop = (relTile + 1U == sliceTiles); + // vec0Out 每 token 行 = 32 头 × 16 lane = 512 half + weightRowOffset_ = static_cast(t) * BLOCK_CUBE * constInfo_.gSize; + const uint32_t slot = candConsTileSeq_ % QLIV2VaCommon::CAND_RING_SLOTS; + ++candConsTileSeq_; + candKBase_ = static_cast(slot) * CAND_TILE_TOKENS * + static_cast(constInfo_.headDim); + // 分数区按任务序号奇偶双缓冲(runInfo.loop = 候选任务序号): + // AIV 跨任务延迟消费上一任务最后一个 token 的分数时,本任务的写不会覆盖它。 + const uint64_t scoreSlotBase = static_cast(runInfo.loop & 1U) * + QLIV2VaCommon::CAND_SCORE_TILES_PER_TASK * + CAND_TILE_TOKENS; + candOutBase_ = + scoreSlotBase + + (static_cast(t) * maxTiles + absTile) * CAND_TILE_TOKENS; + ComputeMm1(candInfo); + // 消费完成:一次 set 广播给两个 AIV,各放一个空槽令牌 + AscendC::CrossCoreSetFlag(QLIV2VaCommon::CAND_FREE_FLAG); + // 本 token 的分片内全部候选 tile 已算完 → 放行 AIV 消费该 token 的分数 + // (AIV 侧对任务最后一个 token 另有 ≥3 + // 个任务的延迟消费队列,不依赖此处时序) + if (relTile + 1U == sliceTiles) { + AscendC::CrossCoreSetFlag(QLIV2VaCommon::CAND_SCORE_READY_FLAG); + } + } + candMode_ = false; + weightRowOffset_ = 0U; +} + template __aicore__ inline void QLIV2VaMatmul::KeyNd2Nz( uint64_t s2L1RealSize, @@ -458,7 +748,7 @@ __aicore__ inline void QLIV2VaMatmul::KeyNd2Nz( nd2nzPara.dstNzMatrixStride = 0; // 默认一块buf最多放两份 DataCopy( - keyL1_[(keyL1BufIdx_ % DOUBLE_BUF_NUM) * KEY_BUFFER_OFFSET], + keyL1_[((keyL1BufIdx_ & (DOUBLE_BUF_NUM - 1))) * KEY_BUFFER_OFFSET], keyGm_[runInfo.tensorKeyOffset + mmInfo.s2GmOffset * constInfo_.headDim], nd2nzPara); } @@ -473,9 +763,11 @@ __aicore__ inline void QLIV2VaMatmul::WeightDmaCopy( copyInParams.blockLen = s1gL1RealSize; copyInParams.srcStride = 0; copyInParams.dstStride = 0; - DataCopy(weightL1_[(qwL1Mte2BufIdx_ % DOUBLE_BUF_NUM) * WEIGHT_BUFFER_OFFSET], + DataCopy(weightL1_[((qwL1Mte2BufIdx_ & (DOUBLE_BUF_NUM - 1))) * + WEIGHT_BUFFER_OFFSET], weightGm_[runInfo.loop % DOUBLE_BUF_NUM * BLOCK_CUBE * - constInfo_.mBaseSize], + constInfo_.mBaseSize + + weightRowOffset_], copyInParams); } @@ -495,7 +787,8 @@ __aicore__ inline void QLIV2VaMatmul::QueryNd2Nz( nd2nzPara.srcNdMatrixStride = 0; nd2nzPara.dstNzMatrixStride = 0; // 默认一块buf最多放两份 - DataCopy(queryL1_[(qwL1Mte2BufIdx_ % DOUBLE_BUF_NUM) * QUERY_BUFFER_OFFSET], + DataCopy(queryL1_[((qwL1Mte2BufIdx_ & (DOUBLE_BUF_NUM - 1))) * + QUERY_BUFFER_OFFSET], queryGm_[runInfo.tensorQueryOffset], nd2nzPara); } @@ -505,7 +798,8 @@ template __aicore__ inline void QLIV2VaMatmul::LoadQueryToL0a( uint64_t s1gL1Offset, uint64_t s1gL1RealSize, - uint64_t s1gL0RealSize) { + uint64_t s1gL0RealSize, + uint64_t qSlot) { LoadData3DParamsV2 loadData3DParams; // SetFmatrixParams loadData3DParams.l1H = CeilDiv(s1gL1RealSize, BLOCK_CUBE); // Hin=M1=8 @@ -535,8 +829,9 @@ __aicore__ inline void QLIV2VaMatmul::LoadQueryToL0a( loadData3DParams.fMatrixCtrl = 0; LoadData( - l0a_[(l0BufIdx_ % L0AB_BUF_NUM) * L0AB_BUFFER_OFFSET_S8_16K], - queryL1_[(qwL1Mte2BufIdx_ % DOUBLE_BUF_NUM) * QUERY_BUFFER_OFFSET], + l0a_[qSlot * L0AB_BUFFER_OFFSET_S8_16K], + queryL1_[((qwL1Mte2BufIdx_ & (DOUBLE_BUF_NUM - 1))) * + QUERY_BUFFER_OFFSET], loadData3DParams); } @@ -545,8 +840,9 @@ template __aicore__ inline void QLIV2VaMatmul::LoadSToL0b( uint64_t s1gL1RealSize, uint64_t s2L0RealSize, - uint64_t sL1BufIdx, - int64_t mStartPt) { + uint64_t sL1SlotIdx, + int64_t mStartPt, + uint64_t sSlot) { LoadData3DParamsV2 loadData3DParams; // SetFmatrixParams loadData3DParams.l1H = S1G_BASIC_BLOCK_L0 / BLOCK_CUBE; // Hin=M1=8 @@ -576,33 +872,44 @@ __aicore__ inline void QLIV2VaMatmul::LoadSToL0b( loadData3DParams.mStartPt = mStartPt; LoadData( - l0b_.template ReinterpretCast()[(l0BufIdx_ % L0AB_BUF_NUM) * + l0b_.template ReinterpretCast()[sSlot * L0AB_BUFFER_OFFSET_FP16_16K], - sL1_[(sL1BufIdx % DOUBLE_BUF_NUM) * SL1_BUFFER_OFFSET], + sL1_[(sL1SlotIdx % S_L1_BUF_NUM) * SL1_BUFFER_OFFSET], loadData3DParams); } // s1,g,1(16), 2,64,16 template __aicore__ inline void QLIV2VaMatmul::LoadWeightToL0a( - uint64_t s1gL1Offset) { + uint64_t l1ElemOffset, + uint64_t l0aHalfOffset) { LoadData2DParams loadData2DParams; loadData2DParams.startIndex = 0; loadData2DParams.repeatTimes = CeilDiv(constInfo_.gSize, BLOCK_CUBE); loadData2DParams.srcStride = 1; loadData2DParams.dstGap = 0; loadData2DParams.ifTranspose = true; - LoadData(l0a_.template ReinterpretCast()[(l0BufIdx_ % L0AB_BUF_NUM) * - L0AB_BUFFER_OFFSET_FP16_16K], - weightL1_[(qwL1Mte2BufIdx_ % DOUBLE_BUF_NUM) * WEIGHT_BUFFER_OFFSET + - s1gL1Offset * BLOCK_CUBE], + LoadData(l0a_.template ReinterpretCast()[l0aHalfOffset], + weightL1_[((qwL1Mte2BufIdx_ & (DOUBLE_BUF_NUM - 1))) * + WEIGHT_BUFFER_OFFSET + + l1ElemOffset], loadData2DParams); } +// 行块开头一次性装载本行块 4 个 s1 行的 W 到 L0A 常驻槽(每行 2KB,共 8KB) +template +__aicore__ inline void QLIV2VaMatmul::LoadAllWeightRowsToL0a() { + for (uint64_t j = 0; j < (S1G_BASIC_BLOCK_L0 * 2 / constInfo_.gSize); j++) { + LoadWeightToL0a(j * constInfo_.gSize * BLOCK_CUBE, + W_SLOT_HALF_BASE + j * W_ROW_STRIDE_HALF); + } +} + // s2, d -> 128,128 template __aicore__ inline void QLIV2VaMatmul::LoadKeyToL0b( - uint64_t s2L0RealSize) { + uint64_t s2L0RealSize, + uint64_t kSlot) { LoadData2DParams loadData2DParams; loadData2DParams.startIndex = 0; loadData2DParams.repeatTimes = CeilDiv(s2L0RealSize, BLOCK_CUBE) * @@ -610,8 +917,8 @@ __aicore__ inline void QLIV2VaMatmul::LoadKeyToL0b( loadData2DParams.srcStride = 1; loadData2DParams.dstGap = 0; loadData2DParams.ifTranspose = false; - LoadData(l0b_[(l0BufIdx_ % L0AB_BUF_NUM) * L0AB_BUFFER_OFFSET_S8_16K], - keyL1_[(keyL1BufIdx_ % DOUBLE_BUF_NUM) * KEY_BUFFER_OFFSET], + LoadData(l0b_[kSlot * L0AB_BUFFER_OFFSET_S8_16K], + keyL1_[((keyL1BufIdx_ & (DOUBLE_BUF_NUM - 1))) * KEY_BUFFER_OFFSET], loadData2DParams); } @@ -620,7 +927,9 @@ template __aicore__ inline void QLIV2VaMatmul::ComputeWs( uint64_t s1gL0RealSize, uint64_t s2L0RealSize, - int64_t s1gOffset) { + int64_t s1gOffset, + uint64_t wRowIdx, + uint64_t sSlot) { SetFlag(MTE1_M_EVENT); WaitFlag(MTE1_M_EVENT); MmadParams mmadParams; @@ -629,12 +938,12 @@ __aicore__ inline void QLIV2VaMatmul::ComputeWs( mmadParams.k = constInfo_.gSize; mmadParams.cmatrixInitVal = true; mmadParams.cmatrixSource = false; - Mmad(cL0_.template ReinterpretCast()[(l0cBufIdx_ % DOUBLE_BUF_NUM) * - L0C_BUFFER_OFFSET + - s1gOffset * S2_BASIC_BLOCK_L0], - l0a_.template ReinterpretCast()[(l0BufIdx_ % L0AB_BUF_NUM) * - L0AB_BUFFER_OFFSET_FP16_16K], - l0b_.template ReinterpretCast()[(l0BufIdx_ % L0AB_BUF_NUM) * + Mmad(cL0_.template ReinterpretCast< + float>()[((l0cBufIdx_ & (DOUBLE_BUF_NUM - 1))) * L0C_BUFFER_OFFSET + + s1gOffset * S2_BASIC_BLOCK_L0], + l0a_.template ReinterpretCast()[W_SLOT_HALF_BASE + + wRowIdx * W_ROW_STRIDE_HALF], + l0b_.template ReinterpretCast()[sSlot * L0AB_BUFFER_OFFSET_FP16_16K], mmadParams); } @@ -642,7 +951,9 @@ __aicore__ inline void QLIV2VaMatmul::ComputeWs( template __aicore__ inline void QLIV2VaMatmul::ComputeQk( uint64_t s1gL0RealSize, - uint64_t s2L0RealSize) { + uint64_t s2L0RealSize, + uint64_t qSlot, + uint64_t kSlot) { SetFlag(MTE1_M_EVENT); WaitFlag(MTE1_M_EVENT); @@ -652,9 +963,9 @@ __aicore__ inline void QLIV2VaMatmul::ComputeQk( mmadParams.k = constInfo_.headDim; mmadParams.cmatrixInitVal = true; mmadParams.cmatrixSource = false; - Mmad(cL0_[(l0cBufIdx_ % DOUBLE_BUF_NUM) * L0C_BUFFER_OFFSET], - l0a_[(l0BufIdx_ % L0AB_BUF_NUM) * L0AB_BUFFER_OFFSET_S8_16K], - l0b_[(l0BufIdx_ % L0AB_BUF_NUM) * L0AB_BUFFER_OFFSET_S8_16K], + Mmad(cL0_[((l0cBufIdx_ & (DOUBLE_BUF_NUM - 1))) * L0C_BUFFER_OFFSET], + l0a_[qSlot * L0AB_BUFFER_OFFSET_S8_16K], + l0b_[kSlot * L0AB_BUFFER_OFFSET_S8_16K], mmadParams); if ((mmadParams.m / 16) * (mmadParams.n / 16) < 10) { PipeBarrier(); @@ -677,8 +988,8 @@ __aicore__ inline void QLIV2VaMatmul::FixpSToL1( params.channelSplit = 0; params.nz2ndEn = 0; SetFixpipePreQuantFlag(0x3a800000); - DataCopy(sL1_[(sL1BufIdx_ % DOUBLE_BUF_NUM) * SL1_BUFFER_OFFSET], - cL0_[(l0cBufIdx_ % DOUBLE_BUF_NUM) * L0C_BUFFER_OFFSET], + DataCopy(sL1_[(sL1BufIdx_ % S_L1_BUF_NUM) * SL1_BUFFER_OFFSET], + cL0_[((l0cBufIdx_ & (DOUBLE_BUF_NUM - 1))) * L0C_BUFFER_OFFSET], params); } @@ -705,13 +1016,22 @@ __aicore__ inline void QLIV2VaMatmul::FixpResToGm( s1L0RealCount, CeilDiv(constInfo_.gSize, BLOCK_CUBE) * S2_BASIC_BLOCK_L0 / BLOCK_CUBE, 2048); - AscendC::DataCopy( - mm1ResGm_[(runInfo.loop % 2) * constInfo_.mBaseSize / constInfo_.gSize * - constInfo_.s2BaseSize + - s1GmOffset * intriParams.dstStride + s2GmOffset], - cL0_.template ReinterpretCast()[(l0cBufIdx_ % DOUBLE_BUF_NUM) * - L0C_BUFFER_OFFSET], - intriParams); + if (candMode_) { + // D3b: 候选分数区 —— 每个 (token, tile) 一行 256 float,由调用方给出基址 + AscendC::DataCopy( + candScoreGm_[candOutBase_ + s2GmOffset], + cL0_.template ReinterpretCast< + float>()[((l0cBufIdx_ & (DOUBLE_BUF_NUM - 1))) * L0C_BUFFER_OFFSET], + intriParams); + } else { + AscendC::DataCopy( + mm1ResGm_[((runInfo.loop & 1)) * constInfo_.mBaseSize / + constInfo_.gSize * constInfo_.s2BaseSize + + s1GmOffset * intriParams.dstStride + s2GmOffset], + cL0_.template ReinterpretCast< + float>()[((l0cBufIdx_ & (DOUBLE_BUF_NUM - 1))) * L0C_BUFFER_OFFSET], + intriParams); + } } template @@ -728,6 +1048,8 @@ __aicore__ inline void QLIV2VaMatmul::AllocEventID() { SetFlag(M_MTE1_EVENT + 2); SetFlag(M_MTE1_EVENT + 3); + SetFlag(PIN_MTE1_EVENT); // Q+W 常驻区守卫播种 + SetFlag(FIX_M_EVENT + 0); SetFlag(FIX_M_EVENT + 1); } @@ -746,6 +1068,8 @@ __aicore__ inline void QLIV2VaMatmul::FreeEventID() { WaitFlag(M_MTE1_EVENT + 2); WaitFlag(M_MTE1_EVENT + 3); + WaitFlag(PIN_MTE1_EVENT); // 与播种一一对应的回收 + WaitFlag(FIX_M_EVENT + 0); WaitFlag(FIX_M_EVENT + 1); } diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_vector_arch22.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_vector_arch22.h index 7db88dc204..2f62f4d25f 100644 --- a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_vector_arch22.h +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_service_vector_arch22.h @@ -52,20 +52,65 @@ class QLIV2VaVector { const struct QLIV2VaCommon::LdSplitCoreInfo& ldInfo, const QLIV2VaTilingData* __restrict tilingData); __aicore__ inline void ProcessLD(); + // mode=1 + LD:块级 topk + // 分段结果的归并与输出(与位置级归并链完全同构,宽度换成块级口径) + __aicore__ inline void ReduceBlockTopkRow(uint32_t rowInBlock); __aicore__ inline void InitVecWorkspaceTensor( GlobalTensor vec0OutGm, GlobalTensor mm1ResGm, - GlobalTensor vec1ResGm); + GlobalTensor vec1ResGm, + GlobalTensor blockVec1ResGm); __aicore__ inline void InitVecCandidateTensor( GlobalTensor candidateTopkIndexInGm, GlobalTensor candidateTopkIndexOutGm, + GlobalTensor candidateBlockLengthOutGm, + bool candidateBlockLengthOutValid, GlobalTensor outputIdxOffsetGm, bool outputIdxOffsetValid); + // D3a: 候选 gather —— 每个 AIV 搬 16 个候选块(8 token × 128B)到 UB,再写 GM + // staging ring。 V1 阶段 cube 尚未消费(探针模式),仅验证地址/吞吐;D3b 接入 + // ring 握手。 + __aicore__ inline void InitVecCandidateGatherTensor( + GlobalTensor keyGm, + GlobalTensor stagingKeyGm, + GlobalTensor candLenGm, + GlobalTensor candScoreGm, + GlobalTensor candAuxScaleGm, + bool enabled); + // v4 候选任务驱动(对齐 DSL 软件流水):按 token 交错执行 —— + // 先 gather token t 的全部候选 tile(生产),再消费 token t-1 + // 的分数(消费滞后一拍); + // taskSeq 决定分数区奇偶槽;任务内最后一个 token 的消费延迟到下一任务(或核尾 + // ConsumePendingCandScore),保证每次分数读之前 AIC 已继续推进过(GM + // 写已落地)。 + __aicore__ inline void RunCandTask(uint32_t bIdx, + uint32_t n2Idx, + uint32_t rowBase, + uint32_t taskTokens, + uint32_t maxTiles, + uint32_t taskSeq, + uint32_t s1RowBase, + uint32_t actS1Size, + uint32_t actS2Size, + uint32_t actS2SizeOrig, + uint32_t indiceOutOffset, + uint32_t outputIdxOffsetBase, + uint32_t tileBegin, + uint32_t tileEnd, + bool needSpill, + uint32_t wsBase); + // 消费队首的一条 pending 记录(队列满时由 RunCandTask 调用) + __aicore__ inline void ConsumePendingCandScore(); + // 核尾排空:消费队列中所有 pending 记录 + // (调用前须等 AIC 主循环结束令牌;由 kernel 在 ProcessMain 末尾触发) + __aicore__ inline void DrainPendingCandScore(); __aicore__ inline void InitVecInputTensor(GlobalTensor weightsGm, GlobalTensor qScaleGm, GlobalTensor kScaleGm, GlobalTensor indiceOutGm, - GlobalTensor blockTableGm); + GlobalTensor blockTableGm, + GlobalTensor valueOutGm, + GlobalTensor valueOutFp32Gm); __aicore__ inline void CleanInvalidOutput(int64_t invalidS1offset); __aicore__ inline int32_t AlignS2(int32_t cuS2Len); __aicore__ inline void AllocEventID(); @@ -75,14 +120,72 @@ class QLIV2VaVector { protected: GlobalTensor mm1ResGm; GlobalTensor vec1ResGm; + // mode=1 + LD:块级 topk 分段结果备份区(布局与 vec1ResGm 相同,行槽位宽 = 2 + // × candidateTopkBlocks) + GlobalTensor blockVec1ResGm_; GlobalTensor weightsGm; GlobalTensor qScaleGm; GlobalTensor kScaleGm; GlobalTensor vec0OutGm; GlobalTensor indiceOutGm; + GlobalTensor valueOutGm; // return_value=1 (DCP score): BF16 输出 + GlobalTensor + valueOutFp32Gm; // return_value=2 (A3 local candidates): FP32 输出 GlobalTensor candidateTopkIndexInGm; GlobalTensor candidateTopkIndexOutGm; + // mode=1(source)每行有效候选块数输出(int32 [T1, N2],DSL candidate_length + // = 块数) + GlobalTensor candidateBlockLengthOutGm_; + bool candLenOutValid_ = + false; // mode=1 且调用方传了 candidate_block_length_out 时为真 GlobalTensor blockTableGm; + // D3a 候选 gather:K 源、GM staging(K/scale)与使能标志 + GlobalTensor keyGmCand_; + GlobalTensor candStagingKeyGm_; + GlobalTensor candLenGm_; // B5: 每行有效候选块数 + GlobalTensor + candScoreGm_; // B5: AIC 写出的候选分数(每 (token,tile) 256 float) + GlobalTensor candAuxScaleGm_; // v4: 每 tile 32 块 × 16 half 的 + // kscale(任务奇偶双缓冲) + bool candGatherEnabled_ = false; + // v4: 候选 tile 生产序号(每个 tile 自增一次,槽号 = seq % CAND_RING_SLOTS; + // 与 AIC 侧消费序号按同一顺序推进,独立计数即可对齐) + uint32_t candProdTileSeq_ = 0U; + bool candMaskConstReady_ = + false; // 每核一次的位置模式表(块内偏移 0..7)已构建 + // v4: 跨任务延迟消费的"任务末尾 token"记录队列(深度 8,正常保留 ≤7 条)。 + // 每任务压 2 条(最后两个 token)⇒ 队首约延迟 3 个任务再消费,对 1-tile + // 任务也保证 ≥3 个后续 tile 的 AIC 计算量,覆盖 GM 写落地延迟;核尾由 + // DrainPendingCandScore 排空。 + static constexpr uint32_t CAND_PENDING_SCORE_SLOTS = 8; + struct PendingCandScore { + bool valid = false; + uint32_t bIdx = 0; + uint32_t rowBase = 0; + uint32_t s1RowBase = 0; + uint32_t n2Idx = 0; + uint32_t tokenIdx = 0; + uint32_t maxTiles = 0; + uint32_t actS1Size = 0; + uint32_t actS2Size = 0; + uint32_t actS2SizeOrig = 0; + uint32_t indiceOutOffset = 0; + uint32_t outputIdxOffsetBase = 0; + uint64_t scoreSlotBase = 0; + // v16:候选 × FD —— 分片任务的 tile 区间与溢写参数(延迟消费末尾 token + // 时同样溢写) + uint32_t tileBegin = 0; + uint32_t tileEnd = 0; + uint32_t wsBase = 0; + bool needSpill = false; + uint32_t taskSeq = + 0U; // 所属候选任务序号:分数区 parity 周期 2,任务 t 的写会覆写 t-2 + // 的同 parity 区,故任务 t 开跑前必须消费掉 ≤t-2 的 pending + // 记录(2026-11-10 B5 decode 混合 L 145 丢 token 根因) + }; + PendingCandScore pendingScore_[CAND_PENDING_SCORE_SLOTS]; + uint32_t pendingHead_ = 0U; + uint32_t pendingCount_ = 0U; // =================================常量区================================= private: @@ -110,6 +213,68 @@ class QLIV2VaVector { const QLIV2VaCommon::RunInfo& info, int32_t cuS1Idx, int32_t innerS1Idx); + // mode=1: 每行有效候选块数 = min(ceil(V / candidateBlockSize), + // candidateTopkBlocks), V 为该行 mask 调整后的可见 key 长度(与 + // ConsumeCandScoreToken / ProcessVec1 同一公式) + __aicore__ inline int32_t CalcCandBlockLen(int32_t actS1Size, + int32_t actS2Size, + int32_t actS2SizeOrig, + int32_t rowInBatch) const; + // mode=1: 把长度写到 candidate_block_length_out(lenOffset = 行号 × N2 + n2) + __aicore__ inline void WriteCandBlockLen(uint64_t lenOffset, int32_t len); + // mode=1 + LD:把本行块级累积器溢写到 GM,供跨核归约侧(ProcessLD)读取 + __aicore__ inline void SpillBlockTopkToGm(const QLIV2VaCommon::RunInfo& info, + int32_t blockRowIdx, + int32_t innerS1Idx); + // v4 候选驱动:单 token 的 gather / 分数消费(由 RunCandTask 按 token + // 交错调用) + __aicore__ inline void GatherTokenCandidates(uint32_t bIdx, + uint32_t n2Idx, + uint32_t rowBase, + uint32_t tokenIdx, + uint32_t maxTiles, + uint64_t auxSlotBase, + uint32_t tileBegin, + uint32_t tileEnd); + __aicore__ inline void ConsumeCandScoreToken(uint32_t bIdx, + uint32_t rowBase, + uint32_t s1RowBase, + uint32_t n2Idx, + uint32_t tokenIdx, + uint32_t maxTiles, + uint32_t actS1Size, + uint32_t actS2Size, + uint32_t actS2SizeOrig, + uint32_t indiceOutOffset, + uint32_t outputIdxOffsetBase, + uint64_t scoreSlotBase, + uint64_t auxSlotBase, + uint32_t tileBegin, + uint32_t tileEnd, + bool needSpill, + uint32_t wsBase); + // 记录任务最后一个 token(压入 pending 队列) + __aicore__ inline void RecordPendingCandScore(uint32_t bIdx, + uint32_t rowBase, + uint32_t s1RowBase, + uint32_t n2Idx, + uint32_t tokenIdx, + uint32_t maxTiles, + uint32_t actS1Size, + uint32_t actS2Size, + uint32_t actS2SizeOrig, + uint32_t indiceOutOffset, + uint32_t outputIdxOffsetBase, + uint64_t scoreSlotBase, + uint32_t tileBegin, + uint32_t tileEnd, + bool needSpill, + uint32_t wsBase, + uint32_t taskSeq); + // v16:候选 × FD —— 把本行(分片)的 token 级累积器溢写到 LD + // 工作区(布局与全量扫 ProcessVec1 溢写一致:[wsBase × s1Base + + // 块内相对行][value+index 对],供 ProcessLD 归并) + __aicore__ inline void SpillCandTokenTopk(uint32_t wsBase, uint32_t tokenIdx); // candidate 新增向量 op 的 64 元素分块封装 (本版本 Level-2 count > 64 的 vmax // 等指令会触发 aicore 异常) __aicore__ inline void VecMaxPair(const LocalTensor& dst, @@ -152,6 +317,8 @@ class QLIV2VaVector { TBuf sortOutBuf_; TBuf indexBuf_; TBuf tmpBuf_; + TBuf + valueOutBuf_; // return_value=1: FP32 score extraction (8KB) // tmp buff for LD TBuf<> ldToBeMrgBuf_; @@ -163,9 +330,11 @@ class QLIV2VaVector { TBuf blockSortOutBuf_; // mode=1: 块级 topk 累加器 [CeilDiv(s1BaseSize,2), // 2048, 2] - TBuf - candBuf_; // mode=2: 排序后的候选块索引 [2048, 2] (value+idx) + TBuf candBuf_; // mode=2: gather merge scratch or legacy + // sorted candidate pairs TBuf candConstBuf_; // mode=1/2: negHuge 常量 [2048] + TBuf + candGatherScaleBuf_; // D3a: gather 的 scale 暂存 (16 块 × 8 token × 2B) LocalTensor globalTopkIndice_; LocalTensor globalTopkUb_; @@ -179,6 +348,10 @@ class QLIV2VaVector { false; // A15: offset 是否传入 (经 InitVecCandidateTensor 传递) int32_t blockId_ = -1; + // P3: topk 自适应宽度 — 累加器/抽取/LD 归并按 sparseCount 收缩 (64 对齐), + // 动态 topk (topk<2048) 时消除固定 2048 宽度的无效排序合并与搬运 + uint32_t topkWidth_ = BASE_TOPK; // Align(sparseCount, 64) + uint32_t topkPairWidth_ = 4096; // 2 * topkWidth_ (value+index 对) // para for vector int32_t groupInner_ = 0; int32_t globalTopkNum_ = 0; @@ -274,9 +447,14 @@ __aicore__ inline void QLIV2VaVector::InitBuffers(TPipe* pipe) { pipe->InitBuffer(outQueue_, 1, BASE_TOPK * sizeof(float)); // 8 KB pipe->InitBuffer(indexBuf_, s2BaseSize_ * sizeof(int32_t)); // 8 KB pipe->InitBuffer(tmpBuf_, 64 * 1024); // 64KB + // P3: 累加器按 topk 宽度分配 (topk<2048 时省 UB; 2048 时与原一致) pipe->InitBuffer(sortOutBuf_, - CeilDiv(s1BaseSize_, 2) * BASE_TOPK_VALUE_IDX_SIZE * - sizeof(float)); // 32KB + CeilDiv(s1BaseSize_, 2) * topkPairWidth_ * sizeof(float)); + // Extract FP32 scores; reuse the output queue for BF16 after the index DMA. + // A separate BF16 buffer would add 4KB to the candidate-mode UB budget. + if (constInfo_.returnValue == 1U) { + pipe->InitBuffer(valueOutBuf_, BASE_TOPK * sizeof(float)); // 8 KB + } globalTopkIndice_ = indexBuf_.Get(); globalTopkUb_ = sortOutBuf_.Get(); @@ -292,6 +470,13 @@ __aicore__ inline void QLIV2VaVector::InitBuffers(TPipe* pipe) { globalBlockTopkUb_ = blockSortOutBuf_.Get(); InitSortOutBuf(globalBlockTopkUb_, CeilDiv(s1BaseSize_, 2) * BASE_TOPK_VALUE_IDX_SIZE); + } else if (candGatherEnabled_) { + // MrgSort writes both input lists as (score, index) pairs, including + // entries beyond TopK. + pipe->InitBuffer( + candBuf_, + (topkWidth_ + QLIV2VaCommon::CAND_TILE_TOKENS) * 2 * sizeof(float)); + pipe->InitBuffer(candGatherScaleBuf_, 512); } else if (constInfo_.candidateMode == CANDIDATE_MODE_CONSUMER) { // R6 修复: candBuf 按行分区 (每 AIV 处理 CeilDiv(s1BaseSize,2)=2 行, 行间 // tile0 重排序 会互相覆盖) — 2 行 x 2048 对 x 8B = 32KB; mode=2 UB 预算 @@ -310,19 +495,33 @@ __aicore__ inline void QLIV2VaVector::InitBuffers(TPipe* pipe) { // step1. 初始化一个有序索引 0 - s2BaseSize_ ArithProgression(globalTopkIndice_, 0, 1, s2BaseSize_); // step2. globalTopkUb_ [CeilDiv(s1BaseSize_, 2), BASE_TOPK, 2] -inf,-1 - InitSortOutBuf(globalTopkUb_, - CeilDiv(s1BaseSize_, 2) * BASE_TOPK_VALUE_IDX_SIZE); + InitSortOutBuf(globalTopkUb_, CeilDiv(s1BaseSize_, 2) * topkPairWidth_); } template __aicore__ inline void QLIV2VaVector::InitLDBuffers(TPipe* pipe) { pipe->Reset(); - pipe->InitBuffer(ldToBeMrgBuf_, - BASE_TOPK_VALUE_IDX_SIZE * mrgListNum_ * sizeof(float)); - pipe->InitBuffer(ldTmpBuf_, - BASE_TOPK_VALUE_IDX_SIZE * mrgListNum_ * sizeof(float)); - pipe->InitBuffer(ldOutValueBuf_, BASE_TOPK * sizeof(float)); - pipe->InitBuffer(ldOutIdxBuf_, BASE_TOPK * sizeof(int32_t)); + // P3: LD 归并缓冲按 topk 实际宽度收缩 (mrgListNum_ 列表 × 每列表 value+idx + // 对) mode=1(candidate + // source,候选块来源)下同一组缓冲在位置级归并之后还要复用给块级归并: + // 块级每行对宽 = 2 × + // candidateTopkBlocks,故按两者较大值分配,不再单开一组块级缓冲 (UB 预算 + // 192KB:位置级 16KB×2 + 块级 64KB×2 若各开一组会吃掉 160KB,复用后只占 + // 128KB)。 + uint32_t mrgPairWidth = topkPairWidth_; + uint32_t mrgOutWidth = topkWidth_; + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + uint32_t candPairWidth = 2U * constInfo_.candidateTopkBlocks; + mrgPairWidth = + (candPairWidth > mrgPairWidth) ? candPairWidth : mrgPairWidth; + mrgOutWidth = (constInfo_.candidateTopkBlocks > mrgOutWidth) + ? constInfo_.candidateTopkBlocks + : mrgOutWidth; + } + pipe->InitBuffer(ldToBeMrgBuf_, mrgPairWidth * mrgListNum_ * sizeof(float)); + pipe->InitBuffer(ldTmpBuf_, mrgPairWidth * mrgListNum_ * sizeof(float)); + pipe->InitBuffer(ldOutValueBuf_, mrgOutWidth * sizeof(float)); + pipe->InitBuffer(ldOutIdxBuf_, mrgOutWidth * sizeof(int32_t)); } template @@ -344,6 +543,11 @@ __aicore__ inline void QLIV2VaVector::InitParams( kCacheBlockSize_ = constInfo.kCacheBlockSize; maxBlockNumPerBatch_ = constInfo.maxBlockNumPerBatch; blockId_ = GetBlockIdx(); + // P3: 按 sparseCount 计算实际 topk 工作宽度 (对齐 64; MergeSort/ExtractIndex + // 元素粒度需求) + topkWidth_ = QLIV2VaCommon::Align( + static_cast(constInfo.sparseCount), static_cast(64)); + topkPairWidth_ = 2 * topkWidth_; } template @@ -352,11 +556,15 @@ __aicore__ inline void QLIV2VaVector::InitVecInputTensor( GlobalTensor qScaleGm, GlobalTensor kScaleGm, GlobalTensor indiceOutGm, - GlobalTensor blockTableGm) { + GlobalTensor blockTableGm, + GlobalTensor valueOutGm, + GlobalTensor valueOutFp32Gm) { this->weightsGm = weightsGm; this->qScaleGm = qScaleGm; this->kScaleGm = kScaleGm; this->indiceOutGm = indiceOutGm; + this->valueOutGm = valueOutGm; + this->valueOutFp32Gm = valueOutFp32Gm; this->blockTableGm = blockTableGm; } @@ -364,20 +572,26 @@ template __aicore__ inline void QLIV2VaVector::InitVecWorkspaceTensor( GlobalTensor vec0OutGm, GlobalTensor mm1ResGm, - GlobalTensor vec1ResGm) { + GlobalTensor vec1ResGm, + GlobalTensor blockVec1ResGm) { this->mm1ResGm = mm1ResGm; this->vec1ResGm = vec1ResGm; this->vec0OutGm = vec0OutGm; + this->blockVec1ResGm_ = blockVec1ResGm; } template __aicore__ inline void QLIV2VaVector::InitVecCandidateTensor( GlobalTensor candidateTopkIndexInGm, GlobalTensor candidateTopkIndexOutGm, + GlobalTensor candidateBlockLengthOutGm, + bool candidateBlockLengthOutValid, GlobalTensor outputIdxOffsetGm, bool outputIdxOffsetValid) { this->candidateTopkIndexInGm = candidateTopkIndexInGm; this->candidateTopkIndexOutGm = candidateTopkIndexOutGm; + this->candidateBlockLengthOutGm_ = candidateBlockLengthOutGm; + this->candLenOutValid_ = candidateBlockLengthOutValid; this->outputIdxOffsetGm_ = outputIdxOffsetGm; // A15 this->isOutputIdxOffsetValid_ = outputIdxOffsetValid; } @@ -400,7 +614,37 @@ __aicore__ inline void QLIV2VaVector::CleanInvalidOutput( valueULocal = outQueue_.DeQue(); QLIV2VaServiceVec::CopyOut( indiceOutGm[invalidS1offset], idxULocal1, constInfo_.sparseCount); + if (constInfo_.useLocalVisibleLengths) { + // Reuse the output queue only after the index copy has finished. + SetWaitFlag(HardEvent::MTE3_V); + Duplicate(valueULocal.template ReinterpretCast(), + QLIV2VaServiceVec::NEG_INF, + constInfo_.sparseCount); + SetWaitFlag(HardEvent::V_MTE3); + QLIV2VaServiceVec::CopyOut( + valueOutFp32Gm[invalidS1offset], valueULocal, constInfo_.sparseCount); + SetWaitFlag(HardEvent::MTE3_V); + } else if (constInfo_.returnValue != 0U) { + // The same queue can hold BF16 sentinels after the index DMA completes. + SetWaitFlag(HardEvent::MTE3_V); + LocalTensor valU16 = + valueULocal.template ReinterpretCast(); + Duplicate(valU16, + static_cast(QLIV2VaCommon::ConstInfo::NEG_INF_BFLOAT), + static_cast(constInfo_.sparseCount)); + SetWaitFlag(HardEvent::V_MTE3); + QLIV2VaServiceVec::CopyOut(valueOutGm[invalidS1offset], + valU16.template ReinterpretCast(), + static_cast(constInfo_.sparseCount)); + SetWaitFlag(HardEvent::MTE3_V); + } outQueue_.FreeTensor(valueULocal); + // mode=1: candidate_block_length 同步填 0(空行/无效行),行偏移 = sparse + // 偏移 / sparseCount + if (candLenOutValid_) { + WriteCandBlockLen( + static_cast(invalidS1offset) / constInfo_.sparseCount, 0); + } // mode=1: candidate_topk_index 同步填 -1 (行偏移 = sparse 偏移 / sparseCount // * candidateTopkBlocks) if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { @@ -421,15 +665,28 @@ __aicore__ inline void QLIV2VaVector::CleanInvalidOutput( } } -// 64 元素分块封装: 规避 Level-2 大 count 的 vmax/vmin/vabs 等指令异常 +// Level-0 vector repeats avoid large Level-2 counts and per-repeat dispatch +// overhead. template __aicore__ inline void QLIV2VaVector::VecMaxPair( const LocalTensor& dst, const LocalTensor& src0, const LocalTensor& src1, int32_t n) { - for (int32_t off = 0; off < n; off += 64) { - Max(dst[off], src0[off], src1[off], 64); + { + int32_t off = 0; + while (off < n) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(n - off, mask, repeatTimes); + Max(dst[off], + src0[off], + src1[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); } @@ -440,8 +697,20 @@ __aicore__ inline void QLIV2VaVector::VecMinPair( const LocalTensor& src0, const LocalTensor& src1, int32_t n) { - for (int32_t off = 0; off < n; off += 64) { - Min(dst[off], src0[off], src1[off], 64); + { + int32_t off = 0; + while (off < n) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(n - off, mask, repeatTimes); + Min(dst[off], + src0[off], + src1[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); } @@ -451,8 +720,19 @@ __aicore__ inline void QLIV2VaVector::VecAbs( const LocalTensor& dst, const LocalTensor& src, int32_t n) { - for (int32_t off = 0; off < n; off += 64) { - Abs(dst[off], src[off], 64); + { + int32_t off = 0; + while (off < n) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(n - off, mask, repeatTimes); + Abs(dst[off], + src[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); } @@ -463,8 +743,20 @@ __aicore__ inline void QLIV2VaVector::VecMinsScalar( const LocalTensor& src, float v, int32_t n) { - for (int32_t off = 0; off < n; off += 64) { - Mins(dst[off], src[off], v, 64); + { + int32_t off = 0; + while (off < n) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(n - off, mask, repeatTimes); + Mins(dst[off], + src[off], + v, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); } @@ -475,8 +767,20 @@ __aicore__ inline void QLIV2VaVector::VecMaxsScalar( const LocalTensor& src, float v, int32_t n) { - for (int32_t off = 0; off < n; off += 64) { - Maxs(dst[off], src[off], v, 64); + { + int32_t off = 0; + while (off < n) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(n - off, mask, repeatTimes); + Maxs(dst[off], + src[off], + v, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); } @@ -487,8 +791,20 @@ __aicore__ inline void QLIV2VaVector::VecSubPair( const LocalTensor& src0, const LocalTensor& src1, int32_t n) { - for (int32_t off = 0; off < n; off += 64) { - Sub(dst[off], src0[off], src1[off], 64); + { + int32_t off = 0; + while (off < n) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(n - off, mask, repeatTimes); + Sub(dst[off], + src0[off], + src1[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); } @@ -499,8 +815,20 @@ __aicore__ inline void QLIV2VaVector::VecAddsScalar( const LocalTensor& src, float v, int32_t n) { - for (int32_t off = 0; off < n; off += 64) { - Adds(dst[off], src[off], v, 64); + { + int32_t off = 0; + while (off < n) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(n - off, mask, repeatTimes); + Adds(dst[off], + src[off], + v, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); } @@ -511,8 +839,20 @@ __aicore__ inline void QLIV2VaVector::VecMulPair( const LocalTensor& src0, const LocalTensor& src1, int32_t n) { - for (int32_t off = 0; off < n; off += 64) { - Mul(dst[off], src0[off], src1[off], 64); + { + int32_t off = 0; + while (off < n) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(n - off, mask, repeatTimes); + Mul(dst[off], + src0[off], + src1[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); } @@ -597,29 +937,34 @@ __aicore__ inline void QLIV2VaVector::BuildCandidateMask( CountGE(candPairs2, candBlocks, static_cast(tileBlockBase)); int32_t hi = CountGE( candPairs2, candBlocks, static_cast(tileBlockBase + tileBlkNum)); - LocalTensor blkIdxF = tmp[4096]; // [tileBlkNum] - LocalTensor acc = tmp[4352]; // [tileBlkNum] - LocalTensor diff = tmp[4608]; // [tileBlkNum] - Cast(blkIdxF, globalTopkIndice_, RoundMode::CAST_NONE, tileBlkNum); - PipeBarrier(); - Adds(blkIdxF, blkIdxF, static_cast(tileBlockBase), tileBlkNum); - PipeBarrier(); - Duplicate(acc.ReinterpretCast(), - QLIV2VaServiceVec::POS_INF_F32, - tileBlkNum); - PipeBarrier(); // 降序排序下: 值 >= base+tileBlkNum 占 [0, hi), 落在 tile 内的候选占 [hi, - // lo), < base (含 -1 pad) 占 [lo, ...) + // lo), < base (含 -1 pad) 占 [lo, ...) 注:原来这里先用 Cast+Adds 造 tile + // 块号向量、再逐候选 |块号-候选| 取 min(每候选 3 条向量指令), + // 现改为下面的块级命中位图,块号向量与整条距离链删除。 + // 块级命中位图:先用一次 Duplicate 全置 1(候选外),再把落在本 tile + // 内的候选块号 (排序后落在 [hi, lo) 区间,块号必在 [tileBlockBase, + // tileBlockBase+tileBlkNum))标量置 0。 替代原来"逐候选 + // Adds→VecAbs→VecMinPair"的距离链:那里每个候选要 3 条向量指令 + 3 次流水 + // drain, 本 shape 每 tile 约 32 个候选 → 约 96 次 drain;改为 1 次 Duplicate + // + N 次标量写 + 1 次 S_V 围栏。 (v220 的 ReduceMin 是整张量归约到 1 + // 个最小值,不能做"每 8 个候选取 min",故不走 2D 归约路线。) 用 float 存 + // 0.0f/1.0f(不能存 int32 的 0/1 再 ReinterpretCast —— 1 会变成 1.4e-45 的 + // denormal) + LocalTensor blkHit = + tmp[8192]; // [tileBlkNum]:0.0f=候选内, 1.0f=候选外 + Duplicate(blkHit, 1.0f, tileBlkNum); + PipeBarrier(); + // 标量写不受 PipeBarrier 围栏(设计文档 P2 铁律),必须显式 V→S / S→V + SetWaitFlag(HardEvent::V_S); for (int32_t j = hi; j < lo; j++) { - float v = candPairs2.GetValue(2 * j); - Adds(diff, blkIdxF, -v, tileBlkNum); - PipeBarrier(); - VecAbs(diff, diff, tileBlkNum); - VecMinPair(acc, acc, diff, tileBlkNum); + int32_t candBlk = static_cast(candPairs2.GetValue(2 * j)); + blkHit.SetValue(candBlk - tileBlockBase, 0.0f); } - // 距离 0 → 候选块; Brcb 展开到位置级; 距离 clamp 到 1 得 isOut (0/1) + SetWaitFlag(HardEvent::S_V); + // 位图展开到位置级(每块 candidate_block_size 个位置),语义与原来的"距离 + // clamp 到 1"一致 LocalTensor posDist = tmp[12288]; // candInt 已释放, 可复用 - Brcb(posDist, acc, tileBlkNum / 8, {1, 8}); + Brcb(posDist, blkHit, tileBlkNum / 8, {1, 8}); PipeBarrier(); VecMinsScalar(posDist, posDist, 1.0f, s2BaseSize_); PipeBarrier(); @@ -670,9 +1015,9 @@ __aicore__ inline void QLIV2VaVector::ProcessCandBlockTopk( // 管道读存在确定性竞态 // (实测 innerS1Idx=1 行的填充被 SortAll 抢跑覆盖); 禁止 s32->f32 Cast (v220 // 无此组合)。 改为纯 int32 向量算术: idx' = idx - (idx+1)*isPad, isPad = - // clamp(idx - thr, 0, 1), thr = base + realBlockNum - 1; 所有指令 - // count=blockNumPad (64 对齐), 按 64 分块避免 mask 寄存器限制。 scratch 用 - // mode=1 独占区 [14336,15360) (mode=2 的 isOutI32 已随 R11 leak 改造删除), + // clamp(idx - thr, 0, 1), thr = base + realBlockNum - 1; 所有指令覆盖 + // blockNumPad (64 对齐), 用 Level-0 repeatTimes 批量下发。 scratch 用 mode=1 + // 独占区 [14336,15360) (mode=2 的 isOutI32 已随 R11 leak 改造删除), // 避开主路径 tmpSortBuf [4096,12288), 消除跨迭代残留读的隐患) LocalTensor idxScr = tmp[14336].template ReinterpretCast(); // 等差源 @@ -688,28 +1033,100 @@ __aicore__ inline void QLIV2VaVector::ProcessCandBlockTopk( idxScr, static_cast(tileBlockBase), 1, blockNumPad); Duplicate(thrI, tileBlockBase + realBlockNum - 1, blockNumPad); PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Sub(offI[off], idxScr[off], thrI[off], 64); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Sub(offI[off], + idxScr[off], + thrI[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Maxs(offI[off], offI[off], 0, 64); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Maxs(offI[off], + offI[off], + 0, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Mins(offI[off], offI[off], 1, 64); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Mins(offI[off], + offI[off], + 1, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Adds(tI[off], idxScr[off], 1, 64); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Adds(tI[off], + idxScr[off], + 1, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Mul(tI[off], tI[off], offI[off], 64); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Mul(tI[off], + tI[off], + offI[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Sub(blkIdx[off], idxScr[off], tI[off], 64); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Sub(blkIdx[off], + idxScr[off], + tI[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); // pad 块 score 归一为 -inf 位型: 覆盖 [realBlockNum, blockNumPad), 含 stale @@ -726,27 +1143,81 @@ __aicore__ inline void QLIV2VaVector::ProcessCandBlockTopk( tmp[15616] .template ReinterpretCast(); // (score-NINF)*(-isPad) LocalTensor scoreI = blkScore.template ReinterpretCast(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Duplicate(pRaw[off], -1, 64); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Duplicate(pRaw[off], -1, mask, repeatTimes, 1, B32_VEC_REPEAT_STRIDE); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Mul(pRaw[off], pRaw[off], offI[off], 64); // -isPad + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Mul(pRaw[off], + pRaw[off], + offI[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); // -isPad + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Adds(pNeg[off], - scoreI[off], - 8388608, - 64); // score - NINF_bits (NINF=0xFF800000=-8388608) + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Adds(pNeg[off], + scoreI[off], + 8388608, + mask, + repeatTimes, + QLIV2VaServiceVec:: + B32RepeatParams()); // score - NINF_bits + // (NINF=0xFF800000=-8388608) + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Mul(pNeg[off], pNeg[off], pRaw[off], 64); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Mul(pNeg[off], + pNeg[off], + pRaw[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Add(scoreI[off], scoreI[off], pNeg[off], 64); // pad 块 -> -inf 位型 + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Add(scoreI[off], + scoreI[off], + pNeg[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); // pad 块 -> -inf 位型 + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); } @@ -764,57 +1235,186 @@ __aicore__ inline void QLIV2VaVector::ProcessCandBlockTopk( LocalTensor pB = offI; LocalTensor pFlag = tI; LocalTensor scoreI = blkScore.template ReinterpretCast(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - // idxScr 为全局块号, pin 也必须用全局 id (tileBlockBase + pinLocal) 比较 - Adds(pRaw[off], - idxScr[off], - -(tileBlockBase + pinLocal), - 64); // 0 于 pin 块 + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + // idxScr 为全局块号, pin 也必须用全局 id (tileBlockBase + pinLocal) + // 比较 + Adds(pRaw[off], + idxScr[off], + -(tileBlockBase + pinLocal), + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); // 0 于 pin 块 + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); Duplicate(pNeg, 0, blockNumPad); PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Sub(pNeg[off], pNeg[off], pRaw[off], 64); // -(idx-pinLocal) + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Sub(pNeg[off], + pNeg[off], + pRaw[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); // -(idx-pinLocal) + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Maxs(pA[off], pRaw[off], 0, 64); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Maxs(pA[off], + pRaw[off], + 0, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Mins(pA[off], pA[off], 1, 64); // 1 若 idx > pin + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Mins(pA[off], + pA[off], + 1, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); // 1 若 idx > pin + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Maxs(pB[off], pNeg[off], 0, 64); + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Maxs(pB[off], + pNeg[off], + 0, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Mins(pB[off], pB[off], 1, 64); // 1 若 idx < pin + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Mins(pB[off], + pB[off], + 1, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); // 1 若 idx < pin + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Add(pFlag[off], pA[off], pB[off], 64); // isNotPin (0/1, 互斥) + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Add(pFlag[off], + pA[off], + pB[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); // isNotPin (0/1, + // 互斥) + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Adds(pFlag[off], pFlag[off], -1, 64); // -1 于 pin, 0 其余 + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Adds(pFlag[off], + pFlag[off], + -1, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); // -1 于 pin, 0 其余 + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Adds(pRaw[off], - scoreI[off], - -2139095040, - 64); // score - 0x7F800000 (复用 pRaw) + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Adds(pRaw[off], + scoreI[off], + -2139095040, + mask, + repeatTimes, + QLIV2VaServiceVec::B32RepeatParams()); // score - 0x7F800000 (复用 + // pRaw) + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Mul(pRaw[off], pRaw[off], pFlag[off], 64); // (score-PINF)*flag + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Mul(pRaw[off], + pRaw[off], + pFlag[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); // (score-PINF)*flag + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); - for (int32_t off = 0; off < blockNumPad; off += 64) { - Add(scoreI[off], scoreI[off], pRaw[off], 64); // pin -> +inf 位型 + { + int32_t off = 0; + while (off < blockNumPad) { + uint64_t mask = 0; + uint8_t repeatTimes = 0; + QLIV2VaServiceVec::VecRepeatPlan(blockNumPad - off, mask, repeatTimes); + Add(scoreI[off], + scoreI[off], + pRaw[off], + mask, + repeatTimes, + QLIV2VaServiceVec::B32BinaryRepeatParams()); // pin -> +inf 位型 + off += static_cast(repeatTimes) * B32_VEC_ELM_NUM; + } } PipeBarrier(); } @@ -862,20 +1462,113 @@ __aicore__ inline void QLIV2VaVector::CopyOutCandTopkIndex( candIdxULocal.template ReinterpretCast(), constInfo_.candidateTopkBlocks); outQueue_.FreeTensor(candIdxULocal); + // mode=1: 同步写该行的有效候选块数(行偏移 = 块级偏移 / + // candidateTopkBlocks,即 (行, n2) 布局) + const uint64_t candLenRow = + info.candidateOutOffset / + static_cast(constInfo_.candidateTopkBlocks) + + static_cast(cuS1Idx) * constInfo_.kHeadNum; + WriteCandBlockLen(candLenRow, + CalcCandBlockLen(static_cast(info.actS1Size), + static_cast(info.actS2Size), + static_cast(info.actS2SizeOrig), + cuS1Idx)); +} + +template +__aicore__ inline int32_t QLIV2VaVector::CalcCandBlockLen( + int32_t actS1Size, + int32_t actS2Size, + int32_t actS2SizeOrig, + int32_t rowInBatch) const { + // 可见 key 长度:mask_mode=3(causal)按右下对齐,其余模式取整段 key 长度 + int32_t visible = actS2Size; + if (constInfo_.attenMaskFlag) { + visible = (actS2SizeOrig - actS1Size + rowInBatch + 1) / + static_cast(constInfo_.cmpRatio); + } + if (visible <= 0) { + return 0; // 空行 / 全无效行:候选块数 0(DSL store_empty_candidate_lengths + // 同语义) + } + if (visible > actS2Size) { + visible = actS2Size; // 与 seqused_k 取小(cmp_residual 造成的越界保护) + } + int32_t blkSize = static_cast(constInfo_.candidateBlockSize); + if (blkSize <= 0) { + blkSize = 8; + } + int32_t len = (visible + blkSize - 1) / blkSize; // ceil + const int32_t cap = static_cast(constInfo_.candidateTopkBlocks); + return (len > cap) ? cap : len; +} + +template +__aicore__ inline void QLIV2VaVector::WriteCandBlockLen( + uint64_t lenOffset, + int32_t len) { + if (!candLenOutValid_) { + return; // 调用方未提供该输出 + } + // 走 DMA(UB → GM)而不是 GM 标量 SetValue:标量写在本架构上未见落地(实测全 + // 0), 且 DMA 与其它输出共用同一条 MTE3 通路,时序语义与 CopyOut 一致。 + LocalTensor lenUb = outQueue_.AllocTensor(); + Duplicate(lenUb, len, B32_VEC_ELM_NUM); + PipeBarrier(); + outQueue_.EnQue(lenUb); + lenUb = outQueue_.DeQue(); + QLIV2VaServiceVec::CopyOut(candidateBlockLengthOutGm_[lenOffset], lenUb, 1); + outQueue_.FreeTensor(lenUb); +} + +// mode=1 + LD:块级 topk 累积器溢写到 GM(与位置级 globalTopkUb_ → vec1ResGm +// 完全对称)。 GM 布局 [核][S2 段][S1 行][value+index 对],行槽位宽 = 2 × +// candidateTopkBlocks; 段内行号用 **gS1 块内相对行号** blockRowIdx,与 +// ProcessLD 侧 ldInfo_.mStart + j 同一坐标。 +template +__aicore__ inline void QLIV2VaVector::SpillBlockTopkToGm( + const QLIV2VaCommon::RunInfo& info, + int32_t blockRowIdx, + int32_t innerS1Idx) { + uint32_t candPairWidth = 2U * constInfo_.candidateTopkBlocks; + uint64_t blockWsOffset = static_cast(info.saveWorkSpaceIdx) * + s1BaseSize_ * candPairWidth + + static_cast(blockRowIdx) * candPairWidth; + AscendC::DataCopyExtParams blockWsParams; + blockWsParams.blockLen = candPairWidth * sizeof(float); + blockWsParams.srcStride = 0; + blockWsParams.dstStride = 0; + blockWsParams.blockCount = 1; + SetWaitFlag(HardEvent::V_MTE3); + AscendC::DataCopyPad( + blockVec1ResGm_[blockWsOffset], + globalBlockTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], + blockWsParams); + SetWaitFlag(HardEvent::MTE3_V); + // 溢写后复位本行块级累积器(下一 S2 段/下一行重新累积),与位置级同语义 + InitSortOutBuf(globalBlockTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], + BASE_TOPK_VALUE_IDX_SIZE); + PipeBarrier(); } template __aicore__ inline void QLIV2VaVector::ProcessVec0( const QLIV2VaCommon::RunInfo& info) { + // v4: 候选任务先领 W 槽回收令牌 —— 两个 AIV 都 wait,保持计数守恒 + // (AIC 每完成一个候选任务回补 1 个;预置 2 个 ⇒ AIV 最多领先 2 个任务, + // 写入的槽是 AIC 已读完的槽,不会覆盖正在读的 W) + if (info.candTask) { + AscendC::CrossCoreWaitFlag(QLIV2VaCommon::CAND_WFREE_FLAG); + } // 只需要一个v核做 - if (blockId_ % 2 != 0) { + if ((blockId_ & 1) != 0) { return; } int32_t cuBaseS1Idx = info.gS1Idx * s1BaseSize_; // 计算输出w基地址偏移 偶数循环 -> 0 + aic_offset 奇数循环 -> 4*64 + // aic_offset int64_t vec0OutGmOffset = - (info.loop % 2) * ((s1BaseSize_ * gSize_ * BLOCK_CUBE)); + ((info.loop & 1)) * ((s1BaseSize_ * gSize_ * BLOCK_CUBE)); // 计算输入weight的地址偏移,qScale的地址偏移与weight相同 int64_t weightGmOffset = info.tensorWeightsOffset + cuBaseS1Idx * qHeadNum_; // 当前需要计算的S1行数,处理尾块场景 @@ -920,6 +1613,793 @@ __aicore__ inline void QLIV2VaVector::ProcessVec0( outQueue_.FreeTensor(resUb); } +template +__aicore__ inline void QLIV2VaVector::InitVecCandidateGatherTensor( + GlobalTensor keyGm, + GlobalTensor stagingKeyGm, + GlobalTensor candLenGm, + GlobalTensor candScoreGm, + GlobalTensor candAuxScaleGm, + bool enabled) { + this->keyGmCand_ = keyGm; + this->candStagingKeyGm_ = stagingKeyGm; + this->candLenGm_ = candLenGm; + this->candScoreGm_ = candScoreGm; + this->candAuxScaleGm_ = candAuxScaleGm; + this->candGatherEnabled_ = enabled; +} + +// v4 候选任务驱动(对齐 DSL 软件流水):按 token 交错执行 —— +// 先 gather token t 的全部候选 tile(生产),再消费 token t-1 +// 的分数(消费滞后一拍)。 +// 任务内**最后一个 token** 不在此任务内消费:记入 pendingScore_,延迟到下一任务 +// gather 了 1~2 个 token 之后(或核尾 ConsumePendingCandScore)再读 —— +// 这样最后一次分数读之前, AIC 一定已经推进过至少一个 tile 的计算(规避 910B 上 +// GM"写后立即读"不可见的时序问题)。 taskSeq +// 决定分数区奇偶槽,跨任务消费上一任务分数时不会被本任务的写覆盖。 +template +__aicore__ inline void QLIV2VaVector::RunCandTask( + uint32_t bIdx, + uint32_t n2Idx, + uint32_t rowBase, + uint32_t taskTokens, + uint32_t maxTiles, + uint32_t taskSeq, + uint32_t s1RowBase, + uint32_t actS1Size, + uint32_t actS2Size, + uint32_t actS2SizeOrig, + uint32_t indiceOutOffset, + uint32_t outputIdxOffsetBase, + uint32_t tileBegin, + uint32_t tileEnd, + bool needSpill, + uint32_t wsBase) { + if (!candGatherEnabled_ || taskTokens == 0U) { + return; + } + // v19:分数区 parity 双缓冲只隔一个任务 —— 任务 t 的 AIC 写会覆写任务 t-2 同 + // parity 区的 分数(pending 记录若拖到核尾 drain 才读,读到的已是 t-2 之后同 + // parity 任务的分数: B5 decode 混合 L 实测 row5 分片被同核第 3 + // 个任务覆写、145 token 错排,确定性复现)。 任务 t 开跑前强制消费所有 + // taskSeq ≤ t-2 的队首记录;t-1 的记录保留(消费间距仍 ≥1 个 任务的 + // gather+计算时间,GM 落地余量不小于原 2-token 滞后路径)。每任务入队 ≤ + // taskTokens (≤4)条,队列深度恒 ≤ 8,原有"队列满 7 + // 消费队首"逻辑自然退化不触发。 + while (pendingCount_ > 0U) { + const PendingCandScore& front = pendingScore_[pendingHead_]; + if (!front.valid || front.taskSeq + 2U > taskSeq) { + break; + } + ConsumePendingCandScore(); + } + const uint64_t scoreSlotBase = static_cast(taskSeq & 1U) * + QLIV2VaCommon::CAND_SCORE_TILES_PER_TASK * + QLIV2VaCommon::CAND_TILE_TOKENS; + // v22:aux 区独立奇偶周期 4(X6 修复,见 kernel Init 注)——score + // 仍按任务奇偶双缓冲, aux 按 taskSeq&3 取 4 周期,覆写链在周期 4 下被 + // AIC(t−2) 完成点严格隔断。 + const uint64_t auxSlotBase = static_cast(taskSeq & 3U) * + QLIV2VaCommon::CAND_SCORE_TILES_PER_TASK * + QLIV2VaCommon::CAND_TILE_TOKENS; + if (maxTiles == 0U) { + // 空候选任务:不产生 ring 流量与分数信号(AIC 侧同样提前返回),只做整行 -1 + // 输出。 pending 队列不在此处消费(延迟策略由队列统一管理,核尾排空)。 + for (uint32_t t = 0U; t < taskTokens; t++) { + ConsumeCandScoreToken(bIdx, + rowBase, + s1RowBase, + n2Idx, + t, + maxTiles, + actS1Size, + actS2Size, + actS2SizeOrig, + indiceOutOffset, + outputIdxOffsetBase, + scoreSlotBase, + auxSlotBase, + tileBegin, + tileEnd, + needSpill, + wsBase); + } + return; + } + // 任务内 token 交错:gather token t 后消费 token t-lagTokens(自适应滞后)。 + // 滞后的原因:AIC 在算完 token 的**最后一个 tile** 后立刻发 SCORE_READY, + // 滞后一拍时该 tile 的分数写还没有落地余量(随机数据下会读到 0/旧值); + // 滞后拍数须保证读 token t-lag 时 AIC 已继续推进过足够多的 tile。 + // v16:FD 分片的 sliceTiles 可小至 2~3(非分片为整行 + // 32)——固定退两拍的落地余量 从 ~64 tile 缩到 ~4 tile(16 + // 倍),随机数据上偶发读到未落地分数(实测 ~5% 概率 单行掉 5~19 个元素)。按 + // 16 tile 的余量自适应:lagTokens = ceil(16 / sliceTiles), 下限 + // 2(保持非分片语义);sliceTiles ≤ 8 时整任务 token 全部走 + // pending(滞后于任务)。 + const uint32_t sliceTiles = tileEnd - tileBegin; + const uint32_t lagTokens = + (sliceTiles >= 16U) ? 2U : ((16U + sliceTiles - 1U) / sliceTiles); + for (uint32_t t = 0U; t < taskTokens; t++) { + GatherTokenCandidates( + bIdx, n2Idx, rowBase, t, maxTiles, auxSlotBase, tileBegin, tileEnd); + if (t >= lagTokens) { + ConsumeCandScoreToken(bIdx, + rowBase, + s1RowBase, + n2Idx, + t - lagTokens, + maxTiles, + actS1Size, + actS2Size, + actS2SizeOrig, + indiceOutOffset, + outputIdxOffsetBase, + scoreSlotBase, + auxSlotBase, + tileBegin, + tileEnd, + needSpill, + wsBase); + } + } + // drain:AIC 每任务 wait 的令牌数 = tile 数 + 1,最后一个 tile 也能错拍消费 + AscendC::CrossCoreSetFlag(QLIV2VaCommon::CAND_READY_FLAG); + // 末尾 lagTokens 个 token 入队;队列满(>7 条)时消费队首(更早任务的那条) + const uint32_t pendBegin = + (taskTokens > lagTokens) ? (taskTokens - lagTokens) : 0U; + for (uint32_t t = pendBegin; t < taskTokens; t++) { + RecordPendingCandScore(bIdx, + rowBase, + s1RowBase, + n2Idx, + t, + maxTiles, + actS1Size, + actS2Size, + actS2SizeOrig, + indiceOutOffset, + outputIdxOffsetBase, + scoreSlotBase, + tileBegin, + tileEnd, + needSpill, + wsBase, + taskSeq); + } + while (pendingCount_ > CAND_PENDING_SCORE_SLOTS - 1U) { + ConsumePendingCandScore(); + } +} + +template +__aicore__ inline void QLIV2VaVector::RecordPendingCandScore( + uint32_t bIdx, + uint32_t rowBase, + uint32_t s1RowBase, + uint32_t n2Idx, + uint32_t tokenIdx, + uint32_t maxTiles, + uint32_t actS1Size, + uint32_t actS2Size, + uint32_t actS2SizeOrig, + uint32_t indiceOutOffset, + uint32_t outputIdxOffsetBase, + uint64_t scoreSlotBase, + uint32_t tileBegin, + uint32_t tileEnd, + bool needSpill, + uint32_t wsBase, + uint32_t taskSeq) { + const uint32_t slot = + (pendingHead_ + pendingCount_) % CAND_PENDING_SCORE_SLOTS; + PendingCandScore& rec = pendingScore_[slot]; + rec.valid = true; + rec.bIdx = bIdx; + rec.rowBase = rowBase; + rec.s1RowBase = s1RowBase; + rec.n2Idx = n2Idx; + rec.tokenIdx = tokenIdx; + rec.maxTiles = maxTiles; + rec.actS1Size = actS1Size; + rec.actS2Size = actS2Size; + rec.actS2SizeOrig = actS2SizeOrig; + rec.indiceOutOffset = indiceOutOffset; + rec.outputIdxOffsetBase = outputIdxOffsetBase; + rec.scoreSlotBase = scoreSlotBase; + rec.tileBegin = tileBegin; + rec.tileEnd = tileEnd; + rec.needSpill = needSpill; + rec.taskSeq = taskSeq; + rec.wsBase = wsBase; + ++pendingCount_; +} + +template +__aicore__ inline void QLIV2VaVector::ConsumePendingCandScore() { + if (pendingCount_ == 0U) { + return; + } + PendingCandScore& rec = pendingScore_[pendingHead_]; + if (rec.valid) { + rec.valid = false; + const uint64_t auxSlotBase = static_cast(rec.taskSeq & 3U) * + QLIV2VaCommon::CAND_SCORE_TILES_PER_TASK * + QLIV2VaCommon::CAND_TILE_TOKENS; + ConsumeCandScoreToken(rec.bIdx, + rec.rowBase, + rec.s1RowBase, + rec.n2Idx, + rec.tokenIdx, + rec.maxTiles, + rec.actS1Size, + rec.actS2Size, + rec.actS2SizeOrig, + rec.indiceOutOffset, + rec.outputIdxOffsetBase, + rec.scoreSlotBase, + auxSlotBase, + rec.tileBegin, + rec.tileEnd, + rec.needSpill, + rec.wsBase); + } + pendingHead_ = (pendingHead_ + 1U) % CAND_PENDING_SCORE_SLOTS; + --pendingCount_; +} + +template +__aicore__ inline void QLIV2VaVector::DrainPendingCandScore() { + while (pendingCount_ > 0U) { + ConsumePendingCandScore(); + } +} + +// 单 token gather:每个 AIV 搬本候选 tile 的一半(16 个候选块),块内 8 token × +// 128B 连续读。 候选块号来自 candidate_topk_index +// 原始顺序(与后续位置映射同一份表); 超出有效前缀(c<0)的槽位不搬,内容由 +// vector 掩码丢弃。 +template +__aicore__ inline void QLIV2VaVector::GatherTokenCandidates( + uint32_t bIdx, + uint32_t n2Idx, + uint32_t rowBase, + uint32_t tokenIdx, + uint32_t maxTiles, + uint64_t auxSlotBase, + uint32_t tileBegin, + uint32_t tileEnd) { + // v16:tile 区间 [tileBegin, tileEnd)(FD + // 分片);候选索引/辅助区地址恒为绝对行级(maxTiles 整行) + if (!candGatherEnabled_ || tileEnd <= tileBegin) { + return; + } + using K_T = typename QLIV2VaT::keyType; + constexpr uint32_t CAND_BLOCKS_PER_TILE = + QLIV2VaCommon::CAND_TILE_BLOCKS; // 64 块 = 512 token + constexpr uint32_t CAND_BLOCKS_PER_AIV = + CAND_BLOCKS_PER_TILE / 2U; // 本 AIV 半区 32 块 + // tile 512 时本 AIV 半区 32 块 × 1KB = 32KB,超过 inQueue 单缓冲(随 shape + // 变化不可控), 故按 16 块一个 chunk 分块搬运:kUb/scaleUb 复用,UB 预算与 + // 256-tile 完全一致。 + constexpr uint32_t CAND_BLOCKS_PER_CHUNK = 16U; + constexpr uint32_t CAND_TOKENS_PER_TILE = QLIV2VaCommon::CAND_TILE_TOKENS; + constexpr uint32_t CAND_BLOCK_BYTES = 8U * 128U; // 8 token × D=128(int8) + const uint32_t aivHalf = static_cast(blockId_ % 2); + const uint32_t halfBlkBase = aivHalf * CAND_BLOCKS_PER_AIV; + const uint32_t pageBlkNum = static_cast(kCacheBlockSize_) / 8U; + if (pageBlkNum == 0U) { + return; + } + // 与 Cube KeyNd2NzForPA 同一套地址口径:块基址 = 页表值 × stride(0 时兜底紧凑 + // stride) + const uint64_t blkStride = (constInfo_.keyStride0 != 0) + ? static_cast(constInfo_.keyStride0) + : static_cast(kCacheBlockSize_) * + static_cast(kHeadNum_) * + 128ULL; + const uint64_t scaleStride = + (constInfo_.keyDequantScaleStride0 != 0) + ? static_cast(constInfo_.keyDequantScaleStride0) + : static_cast(kCacheBlockSize_); + const uint64_t tableBase = + static_cast(bIdx) * static_cast(maxBlockNumPerBatch_); + LocalTensor scaleUb = candGatherScaleBuf_.Get(); + const uint32_t row = rowBase + tokenIdx; + const uint32_t rowBlocks = + static_cast(Max(candLenGm_.GetValue(row), 0)); + const uint64_t rowOff = + (static_cast(row) * static_cast(kHeadNum_) + n2Idx) * + constInfo_.candidateTopkBlocks; + for (uint32_t tile = tileBegin; tile < tileEnd; tile++) { + LocalTensor kUb = inQueue_.AllocTensor(); + // v4 ring:槽号 = 全局生产序号 % RING_SLOTS;两个 chunk 共用一个槽,FREE 每 + // tile 等一次 + const uint32_t ringSlot = candProdTileSeq_ % QLIV2VaCommon::CAND_RING_SLOTS; + ++candProdTileSeq_; + const uint64_t slotKeyBase = + static_cast(ringSlot) * CAND_TOKENS_PER_TILE * 128ULL + + static_cast(aivHalf) * + (CAND_BLOCKS_PER_AIV * CAND_BLOCK_BYTES); + // v4: kscale 辅助区(本 AIV 半区 32 块 × 16 half = 1KB,分两 chunk 各 + // 512B) v22: aux 区按 auxSlotBase(taskSeq & 3 的 4 周期)寻址,不再与 + // score 同 parity + const uint64_t auxTileBase = + 2ULL * + (auxSlotBase + static_cast(tokenIdx * maxTiles + tile) * + QLIV2VaCommon::CAND_TILE_TOKENS) + + static_cast(aivHalf) * (CAND_BLOCKS_PER_AIV * 16ULL); + AscendC::CrossCoreWaitFlag(QLIV2VaCommon::CAND_FREE_FLAG); + for (uint32_t chunk = 0U; + chunk < CAND_BLOCKS_PER_AIV / CAND_BLOCKS_PER_CHUNK; + chunk++) { + const uint32_t blkBase = chunk * CAND_BLOCKS_PER_CHUNK; + const uint32_t firstBlock = + tile * CAND_BLOCKS_PER_TILE + halfBlkBase + blkBase; + const uint32_t validBlocks = + rowBlocks > firstBlock + ? Min(rowBlocks - firstBlock, CAND_BLOCKS_PER_CHUNK) + : 0U; + if (validBlocks < CAND_BLOCKS_PER_CHUNK) { + AscendC::Duplicate(scaleUb[validBlocks * 16], + static_cast(0.0f), + (CAND_BLOCKS_PER_CHUNK - validBlocks) * 16); + } + for (uint32_t i = 0U; i < validBlocks; i++) { + int32_t c = candidateTopkIndexInGm.GetValue(rowOff + firstBlock + i); + if (c < 0) { + // v17: 无效槽的 aux 必须显式写 0 —— 陈旧位型可能是 + // NaN,下游"score=raw×scale" 会得 + // NaN(NaN×0=NaN、惩罚压不住、归并时把高分局挤掉,slot 头实测 + // (nan,-1))。 必须 V 管道清零 + V_MTE3 栅栏:标量 SetValue 的写对 + // MTE3 的 staging DMA 不可见(曾因此偶发搬进陈旧 NaN),Duplicate 走 + // V 管道受栅栏约束。 + AscendC::Duplicate(scaleUb[i * 16], static_cast(0.0f), 16); + continue; + } + uint64_t page = static_cast(c) / pageBlkNum; + uint64_t within = static_cast(c) % pageBlkNum; + int32_t phys = blockTableGm.GetValue(tableBase + page); + uint64_t kOff = + static_cast(phys) * blkStride + within * 8ULL * 128ULL; + uint64_t sOff = + static_cast(phys) * scaleStride + within * 8ULL; + AscendC::DataCopyPadExtParams kPad{false, 0, 0, 0}; + AscendC::DataCopyExtParams kParams; + kParams.blockCount = 1; + kParams.blockLen = CAND_BLOCK_BYTES * sizeof(K_T); + kParams.srcStride = 0; + kParams.dstStride = 0; + kParams.rsv = 0; + AscendC::DataCopyPad( + kUb[i * CAND_BLOCK_BYTES], keyGmCand_[kOff], kParams, kPad); + AscendC::DataCopyPadExtParams sPad{false, 0, 0, 0}; + AscendC::DataCopyExtParams sParams; + sParams.blockCount = 1; + sParams.blockLen = 8 * sizeof(half); + sParams.srcStride = 0; + sParams.dstStride = 0; + sParams.rsv = 0; + // UB 目的地址按 32B 对齐:每块 scale 占 32B(16B 实数据 + 16B 填充) + AscendC::DataCopyPad(scaleUb[i * 16], kScaleGm[sOff], sParams, sPad); + } + SetWaitFlag(HardEvent::MTE2_MTE3); + SetWaitFlag( + HardEvent::V_MTE3); // v17: 覆盖无效槽的 V 管道清零写 + AscendC::DataCopyExtParams outParams; + outParams.blockCount = 1; + outParams.blockLen = CAND_BLOCKS_PER_CHUNK * CAND_BLOCK_BYTES; // 16KB + outParams.srcStride = 0; + outParams.dstStride = 0; + outParams.rsv = 0; + AscendC::DataCopyPad( + candStagingKeyGm_[slotKeyBase + + static_cast(blkBase) * CAND_BLOCK_BYTES], + kUb, + outParams); + AscendC::DataCopyExtParams auxParams; + auxParams.blockCount = 1; + auxParams.blockLen = + CAND_BLOCKS_PER_CHUNK * 32U; // 16 块 × 32B(16B 实数据 + 16B 填充) + auxParams.srcStride = 0; + auxParams.dstStride = 0; + auxParams.rsv = 0; + AscendC::DataCopyPad( + candAuxScaleGm_[auxTileBase + static_cast(blkBase) * 16ULL], + scaleUb, + auxParams); + // 本 chunk 的 staging/辅助区写已下发(MTE3 同管有序);kUb/scaleUb 下 + // chunk 复用前 必须分别等 MTE2 与 V 管道读完 —— 原缺 MTE3_V:下一 chunk + // 的无效槽清零 Duplicate (V 管道)会在本 chunk 的 aux MTE3 还在读 + // scaleUb 时把它清成 0,整块 tile (下一 chunk 全真实 gather、无 V + // 写)永不踩,末 tile(下一 chunk 全无效 = 16 个 Duplicate)必踩 —— aux + // 区落定 0,score=raw×0=0,8 个有效 token 被归并丢弃 (L=321 类确定性 + // 508/512 的根因)。 + SetWaitFlag(HardEvent::MTE3_MTE2); + SetWaitFlag(HardEvent::MTE3_V); + } + // 本 AIV 的一半(两个 chunk)已写完 → 通知 AIC(两个 AIV 的 set 合并成 1 + // 个令牌/tile) + AscendC::CrossCoreSetFlag(QLIV2VaCommon::CAND_READY_FLAG); + inQueue_.FreeTensor(kUb); + } +} + +// v16:候选 × FD —— 本行(分片)token 级累积器溢写到 LD 工作区。 +// 候选任务的行号 tokenIdx 本来就是 gS1 块内相对行号,与 ProcessLD 的 mStart+j +// 同坐标; 握手与全量扫溢写同款(V_MTE3 等累加器就绪、MTE3_V +// 等落盘、复位供下一行复用)。 +template +__aicore__ inline void QLIV2VaVector::SpillCandTokenTopk( + uint32_t wsBase, + uint32_t tokenIdx) { + const uint32_t inner = tokenIdx / 2U; + const uint64_t wsOffset = + static_cast(wsBase) * s1BaseSize_ * topkPairWidth_ + + static_cast(tokenIdx) * topkPairWidth_; + AscendC::DataCopyExtParams spillParams; + spillParams.blockCount = 1; + spillParams.blockLen = topkPairWidth_ * sizeof(float); + spillParams.srcStride = 0; + spillParams.dstStride = 0; + spillParams.rsv = 0; + SetWaitFlag(HardEvent::V_MTE3); + AscendC::DataCopyPad( + vec1ResGm[wsOffset], globalTopkUb_[inner * topkPairWidth_], spillParams); + SetWaitFlag(HardEvent::MTE3_V); + InitSortOutBuf(globalTopkUb_[inner * topkPairWidth_], topkPairWidth_); + PipeBarrier(); +} + +// 单 token 分数消费:掩码 A(列表序号 < L)/ 掩码 B(逻辑 token = c×8 + +// 块内偏移 < cuRealAcSeq)。 无效位置分数置 -inf、索引 -1;有效位置直接写逻辑 +// token 号(TopK 之后无需再映射)。 空行/零候选行走 CleanInvalidOutput(全 +// -1)。 +template +__aicore__ inline void QLIV2VaVector::ConsumeCandScoreToken( + uint32_t bIdx, + uint32_t rowBase, + uint32_t s1RowBase, + uint32_t n2Idx, + uint32_t tokenIdx, + uint32_t maxTiles, + uint32_t actS1Size, + uint32_t actS2Size, + uint32_t actS2SizeOrig, + uint32_t indiceOutOffset, + uint32_t outputIdxOffsetBase, + uint64_t scoreSlotBase, + uint64_t auxSlotBase, + uint32_t tileBegin, + uint32_t tileEnd, + bool needSpill, + uint32_t wsBase) { + constexpr uint32_t CAND_TILE_TOKENS = QLIV2VaCommon::CAND_TILE_TOKENS; + constexpr uint32_t CAND_BLOCKS_PER_TILE = QLIV2VaCommon::CAND_TILE_BLOCKS; + constexpr uint32_t BLOCK_TOKENS = 8U; + const int32_t candBlocks = + static_cast(constInfo_.candidateTopkBlocks); + const uint32_t aivParity = static_cast(blockId_ % 2); + LocalTensor sortBuff = tmpBuf_.Get(); + LocalTensor sortTmp = candBuf_.Get(); + + // AIC 每 token set 一次;两个 AIV 各 wait 一次(广播语义)。未分到的 token + // 也要 wait, 保持计数守恒。分片为空(tileEnd<=tileBegin,含 maxTiles==0 + // 的空任务)时 AIC 不产生任何 token(ComputeMm1Candidate + // 提前返回),这里也不能 wait,否则死锁。 + if (tileEnd > tileBegin) { + AscendC::CrossCoreWaitFlag(QLIV2VaCommon::CAND_SCORE_READY_FLAG); + } + if ((tokenIdx % 2U) != aivParity) { + return; + } + const uint32_t row = rowBase + tokenIdx; + int32_t L = candLenGm_.GetValue(row); + L = (L < 0) ? 0 : ((L > candBlocks) ? candBlocks : L); + int32_t V = static_cast(actS2Size); + if (constInfo_.attenMaskFlag) { + V = (static_cast(actS2SizeOrig) - static_cast(actS1Size) + + static_cast(s1RowBase + tokenIdx) + 1) / + static_cast(constInfo_.cmpRatio); + } + const uint64_t outRow = + static_cast(indiceOutOffset) + + static_cast(tokenIdx) * constInfo_.sparseCount; + // An empty shard must not leave a GM-to-UB copy pending on the sort buffer. + const uint32_t rowTileEnd = + Min(tileEnd, CeilDiv(static_cast(L), CAND_BLOCKS_PER_TILE)); + if (V <= 0 || tileBegin >= rowTileEnd) { + // v16:FD 分片下最终输出由归约侧(ProcessLD)写——空行/无效行也要溢写"空 + // partial" (累加器此处恰为 InitSortOutBuf 的 -inf/-1 + // 初态),不能直写最终输出。 + if (needSpill) { + SpillCandTokenTopk(wsBase, tokenIdx); + } else { + CleanInvalidOutput(static_cast(outRow)); + } + return; + } + const uint32_t inner = tokenIdx / 2U; + // 位置模式(每核一次):块内偏移 j=[0..7] 重复 256 次;把"8×块号"广播到 8 + // 个位置后 加上该模式即得每位置的逻辑 token 号。暂存区一律用 TBuf + // 的**直接类型视图** (tmpBuf_.Get()[idx]):对切片张量做 ReinterpretCast + // 不保留基址偏移, 会把掩码/kscale/索引写到错误位置(本轮实测)。 + LocalTensor posPatternF = + tmpBuf_.Get()[4096]; // [512] 块内偏移 0..7 重复 + LocalTensor oneF = + tmpBuf_.Get()[14848]; // [512] 全 1.0(Select 常量) + LocalTensor zeroF = tmpBuf_.Get()[15360]; // [512] 全 0.0 + // v12: 硬件比较 mask 缓冲(uint8 ×512 ×2 = 512B ×2) + LocalTensor maskA = tmpBuf_.Get()[45312U]; + LocalTensor maskB = tmpBuf_.Get()[45824U]; + if (!candMaskConstReady_) { + for (uint32_t p = 0U; p < CAND_TILE_TOKENS; p++) { + posPatternF.SetValue(p, static_cast(static_cast(p % 8U))); + } + SetWaitFlag(HardEvent::S_V); + Duplicate(oneF, 1.0f, CAND_TILE_TOKENS); + Duplicate(zeroF, 0.0f, CAND_TILE_TOKENS); + PipeBarrier(); + candMaskConstReady_ = true; + } + // 每 tile 的向量暂存(逻辑 token 号 → 掩码 / 排序索引)。UB 分区(float + // 偏移): + // [0,1024) 排序区:score 512 @0 + idx 512 @512(idxTokI 即 int32[512]) + // [4096,4608) 位置模式 0..7 ×64;[4608,8704) 掩码/scale 暂存(见下) + LocalTensor idxTokF = + tmpBuf_.Get()[4608]; // [512] 逻辑 token 号 + LocalTensor validF = tmpBuf_.Get()[5120]; // [512] 位置有效 0/1 + LocalTensor penF = + tmpBuf_.Get()[5632]; // [512] 1-valid(无效罚分权重) + LocalTensor scaleF = + tmpBuf_.Get()[6144]; // [512] 去填充后的 kscale + LocalTensor scalePad = + tmpBuf_.Get()[2 * 6656]; // 2KB:64 块 × 16 half(含填充) + LocalTensor scalePadF = + tmpBuf_.Get()[7680]; // [1024] 填充 kscale 的 fp32 视图 + // v9: score/kscale 双缓冲预取(奇数 tile 用 Ping 槽)——DMA 提前一拍下发, + // 与上一 tile 的 SortAll/MergeSort 重叠,消费侧 MTE2_V 等待≈0 + LocalTensor scorePing = + tmpBuf_.Get()[8704]; // [1024] score 512 + idx 512 + LocalTensor scalePadPing = tmpBuf_.Get()[2 * 9728]; // 2KB + LocalTensor scalePadFPing = tmpBuf_.Get()[10240]; // [1024] + LocalTensor idxTokI = + tmpBuf_.Get()[CAND_TILE_TOKENS]; // 排序索引区(逻辑 token) + InitSortOutBuf(globalTopkUb_[inner * topkPairWidth_], topkPairWidth_); + PipeBarrier(); + const uint64_t candRowOff = + (static_cast(row) * static_cast(kHeadNum_) + n2Idx) * + constInfo_.candidateTopkBlocks; + // DMA 参数(score 2KB / kscale 2KB,整 token 复用) + AscendC::DataCopyPadExtParams padParams{false, 0, 0, 0}; + AscendC::DataCopyExtParams copyParams; + copyParams.blockCount = 1; + copyParams.blockLen = CAND_TILE_TOKENS * sizeof(float); + copyParams.srcStride = 0; + copyParams.dstStride = 0; + copyParams.rsv = 0; + AscendC::DataCopyPadExtParams sPad{false, 0, 0, 0}; + AscendC::DataCopyExtParams sParams; + sParams.blockCount = 1; + sParams.blockLen = + QLIV2VaCommon::CAND_AUX_SCALE_HALVES_PER_TILE * sizeof(half); // 2KB + sParams.srcStride = 0; + sParams.dstStride = 0; + sParams.rsv = 0; + const uint64_t scoreBase0 = + scoreSlotBase + + static_cast(tokenIdx * maxTiles) * CAND_TILE_TOKENS; + // v22: aux 区独立 4 周期寻址(与 score 的 2 周期脱钩,覆写链见 kernel Init + // 注) + const uint64_t auxBase0 = + auxSlotBase + + static_cast(tokenIdx * maxTiles) * CAND_TILE_TOKENS; + // tile 0 预取:sortBuff 的上个读者是上一 token 的 SortAll/MergeSort(V_MTE2 + // 覆盖全部先前排队的 V 读) v16:分片的首 tile = tileBegin(不一定是 + // 0)——预取必须读 tileBegin 的分数/辅助区, 且落进与 tileBegin + // 奇偶一致的缓冲槽;否则首 tile 消费的是上一任务残留(错分/漏分)。 + const uint64_t scoreFirst = + scoreBase0 + static_cast(tileBegin) * CAND_TILE_TOKENS; + const uint64_t auxFirst = + auxBase0 + static_cast(tileBegin) * CAND_TILE_TOKENS; + LocalTensor firstScore = (tileBegin & 1U) ? scorePing : sortBuff; + LocalTensor firstPad = (tileBegin & 1U) ? scalePadPing : scalePad; + SetWaitFlag(HardEvent::V_MTE2); + AscendC::DataCopyPad( + firstScore, candScoreGm_[scoreFirst], copyParams, padParams); + AscendC::DataCopyPad( + firstPad, candAuxScaleGm_[2ULL * auxFirst], sParams, sPad); + for (uint32_t tile = tileBegin; tile < rowTileEnd; tile++) { + const uint64_t scoreBase = + scoreBase0 + static_cast(tile) * CAND_TILE_TOKENS; + // v9: 奇数 tile 用 Ping 槽(score+idx 一体,SortAll 的索引区在 +512) + LocalTensor curScore = (tile & 1U) ? scorePing : sortBuff; + LocalTensor curPad = (tile & 1U) ? scalePadPing : scalePad; + LocalTensor curPadF = (tile & 1U) ? scalePadFPing : scalePadF; + SetWaitFlag( + HardEvent::MTE2_V); // 本 tile 的 DMA(上轮预取)→ 向量,等待≈0 + // 填充 1024 half → fp32 视图(每块 16 个,前 8 个有效) + AscendC::Cast(curPadF, + curPad, + RoundMode::CAST_NONE, + QLIV2VaCommon::CAND_AUX_SCALE_HALVES_PER_TILE); + PipeBarrier(); + // v10: 无效候选槽位的 staging 是陈旧数据,原始分可能是 NaN 位型;NaN×scale + // 仍传播 NaN (排序网络比较恒 false 会沉底,但 ReduceMax 会中毒)。先上界 + // clamp(minNum 语义 下 NaN → 1e30,有限值不变;无效分随后被 1e30 罚到 0 + // 以下)。 + Mins(curScore, curScore, 1.0e30f, CAND_TILE_TOKENS); + PipeBarrier(); + // 每 tile 32 个候选块:块内 8 个位置 = 32B,天然满足向量操作的对齐要求。 + // 同一次循环里做两件事(都不用 Brcb / Gather): + // 1) 逻辑 token 号 = 8×块号 + j(无效块得 -8+j < 0); + // 2) kscale 去填充:从 fp32 视图按 64B 步长取每块前 8 个。 + uint64_t blkMask[2] = {0xFFULL, 0ULL}; // bit 模式:低 8 位 ⇒ 8 个 float + for (uint32_t b = 0U; b < CAND_BLOCKS_PER_TILE; b++) { + const uint32_t ci = tile * CAND_BLOCKS_PER_TILE + b; + int32_t c = -1; + if (static_cast(ci) < L) { + c = candidateTopkIndexInGm.GetValue(candRowOff + ci); + } + const float seed = + (c >= 0) ? static_cast(c * static_cast(BLOCK_TOKENS)) + : -8.0f; + AscendC::Adds(idxTokF[b * 8U], + posPatternF[b * 8U], + seed, + blkMask, + static_cast(1), + QLIV2VaServiceVec::B32RepeatParams()); + AscendC::Adds(scaleF[b * 8U], + curPadF[b * 16U], + 0.0f, + blkMask, + static_cast(1), + QLIV2VaServiceVec::B32RepeatParams()); + } + PipeBarrier(); + // v12: valid = (tok >= 0) && (tok <= V-1):两次硬件标量比较 + 两次 + // Select(0/1 浮点) + AscendC::Compares(maskA, idxTokF, 0.0f, CMPMODE::GE, CAND_TILE_TOKENS); + PipeBarrier(); + AscendC::Compares(maskB, + idxTokF, + static_cast(V), + CMPMODE::LT, + CAND_TILE_TOKENS); // LT(V) 等价 LE(V-1)(V 是整数) + PipeBarrier(); + AscendC::Select(validF, + maskA, + oneF, + zeroF, + SELMODE::VSEL_TENSOR_TENSOR_MODE, + CAND_TILE_TOKENS); + PipeBarrier(); + AscendC::Select(validF, + maskB, + validF, + zeroF, + SELMODE::VSEL_TENSOR_TENSOR_MODE, + CAND_TILE_TOKENS); + PipeBarrier(); + Muls(penF, validF, -1.0f, CAND_TILE_TOKENS); + PipeBarrier(); + Adds(penF, penF, 1.0f, CAND_TILE_TOKENS); // penF = 1 - valid + PipeBarrier(); + // 排序索引:有效位置 = 逻辑 token 号,无效位置 = -1(不足 topk 时按 -1 + // 填充输出) + Mul(idxTokF, idxTokF, validF, CAND_TILE_TOKENS); + PipeBarrier(); + Sub(idxTokF, idxTokF, penF, CAND_TILE_TOKENS); + PipeBarrier(); + // v9: 索引直接落到本 tile 缓冲的 idx 半区(与 score 相邻,SortAll 约定 + // layout) + { + LocalTensor idxSlot = + tmpBuf_.Get()[((tile & 1U) ? 8704U : 0U) + CAND_TILE_TOKENS]; + AscendC::Cast(idxSlot, idxTokF, RoundMode::CAST_RINT, CAND_TILE_TOKENS); + } + PipeBarrier(); + // 分数 = 原始分数 × kscale - 1e30 × (1 - valid) + // (无效槽的 scale 已在上游生产侧写 0,见 GatherTokenCandidates 的 v17 注) + Mul(curScore, curScore, scaleF, CAND_TILE_TOKENS); + PipeBarrier(); + // v17:缩放后必须再 clamp 一次 —— 无效位置的 raw 先被 NaN-clamp 到 + // 1e30,若乘上 未 gather 的陈旧 kscale(≤65504)可达 6.5e34,1e31 + // 惩罚压不住,会以 idx=-1 占位挤进 top-512(仅在"末 tile + // 含无效候选块"的形状暴露,且随陈旧数据概率出现)。 + Mins(curScore, curScore, 1.0e30f, CAND_TILE_TOKENS); + PipeBarrier(); + Muls(penF, + penF, + 1.0e31f, + CAND_TILE_TOKENS); // ≥ clamp 上界 × kscale 上界,保证无效分 < 0 + PipeBarrier(); + Sub(curScore, curScore, penF, CAND_TILE_TOKENS); + PipeBarrier(); + // v9: 预取 tile+1(奇偶换槽)。其缓冲的上读者是 tile-1 的 + // SortAll(顺序核已退休),等待≈0 v16: 预取上界用分片区间 tileEnd(越过 + // tileEnd 的分数属于别的分片/旧任务,读了也不用) + if (tile + 1U < rowTileEnd) { + SetWaitFlag(HardEvent::V_MTE2); + const uint64_t nextBase = scoreBase + CAND_TILE_TOKENS; + LocalTensor nextScore = ((tile + 1U) & 1U) ? scorePing : sortBuff; + LocalTensor nextPad = ((tile + 1U) & 1U) ? scalePadPing : scalePad; + AscendC::DataCopyPad( + nextScore, candScoreGm_[nextBase], copyParams, padParams); + AscendC::DataCopyPad( + nextPad, + candAuxScaleGm_[2ULL * (auxBase0 + static_cast(tile + 1U) * + CAND_TILE_TOKENS)], + sParams, + sPad); + } + // Keep tied tiles so their indices follow the same merge order. + LocalTensor maxSlot = + tmpBuf_.Get()[11264]; // ReduceMax 输出 + 临时 + AscendC::ReduceMax(maxSlot, + curScore, + maxSlot[32], + static_cast(CAND_TILE_TOKENS), + false); + PipeBarrier(); + SetWaitFlag(HardEvent::V_S); + const float tileMax = maxSlot.GetValue(0); + const float curTail = + globalTopkUb_.GetValue(inner * topkPairWidth_ + 2 * (topkWidth_ - 1)); + SetWaitFlag(HardEvent::S_V); + // Source block order does not bound later scores under the consumer's query + // and weights. + if (tileMax < curTail) { + continue; + } + QLIV2VaServiceVec::SortAll(curScore, sortTmp, CAND_TILE_TOKENS); + PipeBarrier(); + QLIV2VaServiceVec::MergeSort(globalTopkUb_[inner * topkPairWidth_], + topkWidth_, + curScore, + CAND_TILE_TOKENS, + sortTmp); + PipeBarrier(); + } + // v16:FD 分片 —— 本行只完成了候选 tile 的一个分片,溢写 partial TopK 到 LD + // 工作区 (布局与全量扫 ProcessVec1 + // 溢写一致:[分片槽][块内相对行][value+index 对]), + // 最终输出由归约侧(ProcessLD)归并各分片后写出。 + if (needSpill) { + SpillCandTokenTopk(wsBase, tokenIdx); + return; + } + LocalTensor idxULocal = outQueue_.AllocTensor(); + QLIV2VaServiceVec::ExtractIndex(idxULocal, + globalTopkUb_[inner * topkPairWidth_] + .template ReinterpretCast(), + topkWidth_); + PipeBarrier(); + // output_idx_offset:把 topk 索引整体平移到逻辑 key 空间(基线语义) + if (isOutputIdxOffsetValid_) { + int32_t rowOff = outputIdxOffsetGm_.GetValue( + outputIdxOffsetBase + static_cast(tokenIdx) * kHeadNum_); + if (rowOff != 0) { + LocalTensor idxI32 = + idxULocal.template ReinterpretCast(); + for (int32_t off = 0; off < constInfo_.sparseCount; off += 64) { + Adds(idxI32[off], idxI32[off], rowOff, 64); + } + PipeBarrier(); + } + } + outQueue_.EnQue(idxULocal); + idxULocal = outQueue_.DeQue(); + QLIV2VaServiceVec::CopyOut(indiceOutGm[outRow], + idxULocal.template ReinterpretCast(), + constInfo_.sparseCount); + outQueue_.FreeTensor(idxULocal); + InitSortOutBuf(globalTopkUb_[inner * topkPairWidth_], topkPairWidth_); + PipeBarrier(); +} + template __aicore__ inline int32_t QLIV2VaVector::AlignS2(int32_t cuS2Len) { // 限制:当前cuS2Len最大为2048,暂不考虑更长 @@ -942,7 +2422,7 @@ __aicore__ inline void QLIV2VaVector::ProcessVec1( // 计算基本块基地址偏移 偶数循环 -> 0 + aic_offset 奇数循环 -> 4*2048 + // aic_offset - int64_t mmGmOffset = (info.loop % 2) * (s1BaseSize_ * s2BaseSize_); + int64_t mmGmOffset = ((info.loop & 1)) * (s1BaseSize_ * s2BaseSize_); // cuS1BeginIdxPerAiv: 每个AIV的S1起始偏移 int32_t cuS1BeginIdxPerAiv = cuBaseS1Idx; @@ -951,15 +2431,14 @@ __aicore__ inline void QLIV2VaVector::ProcessVec1( : s1BaseSize_; // cuS1ProcNumPerAiv: 每个AIv的S1计算量 int32_t cuS1ProcNumPerAiv = - blockId_ % 2 == 0 ? CeilDiv(cuS1ProcNum, 2) : (cuS1ProcNum / 2); - cuS1BeginIdxPerAiv += (blockId_ % 2) * CeilDiv(cuS1ProcNum, 2); + (blockId_ & 1) == 0 ? CeilDiv(cuS1ProcNum, 2) : (cuS1ProcNum / 2); + cuS1BeginIdxPerAiv += ((blockId_ & 1)) * CeilDiv(cuS1ProcNum, 2); // 基本块基地址偏移奇数核加一个S1地址偏移 - mmGmOffset += (blockId_ % 2) * CeilDiv(cuS1ProcNum, 2) * s2BaseSize_; + mmGmOffset += ((blockId_ & 1)) * CeilDiv(cuS1ProcNum, 2) * s2BaseSize_; // 非首个基本块, M(S1)轴发生切换需要初始化 if (info.loop != 0 && info.s2Idx == 0) { // globalTopkUb_ value,index=-inf,-1 - InitSortOutBuf(globalTopkUb_, - CeilDiv(s1BaseSize_, 2) * BASE_TOPK_VALUE_IDX_SIZE); + InitSortOutBuf(globalTopkUb_, CeilDiv(s1BaseSize_, 2) * topkPairWidth_); blockS2StartIdx_ = 0; if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { InitSortOutBuf(globalBlockTopkUb_, @@ -979,22 +2458,48 @@ __aicore__ inline void QLIV2VaVector::ProcessVec1( // LD输出S1方向偏移,保证2个Vector输出的内容连续 uint32_t ldS1Offset = - (blockId_ % 2 == 0) ? s1BaseSize_ / 2 - cuS1ProcNumPerAiv : 0; + ((blockId_ & 1) == 0) ? s1BaseSize_ / 2 - cuS1ProcNumPerAiv : 0; for (int innerS1Idx = 0; innerS1Idx < cuS1ProcNumPerAiv; innerS1Idx++) { - if (constInfo_.attenMaskFlag) { + if (constInfo_.dcpEnable && constInfo_.attenMaskFlag) { + // DCP (Decode Context Parallel, 解码上下文并行): mask_mode=3 时每行现算 + // u = C - Q_len + rowIdx + 1, 再用闭式公式求本 rank 可见长度。 + int64_t signedCausalLimit = + static_cast(info.causalGlobalLen) - + static_cast(info.actS1Size) + + static_cast(cuS1BeginIdxPerAiv + innerS1Idx) + 1; + uint32_t u = (signedCausalLimit <= 0) + ? 0U + : static_cast(signedCausalLimit); + cuRealAcSeq = static_cast( + QLIV2VaCommon::CalcDcpVisibleLen(u, + info.actS2Size, + constInfo_.cpWorld, + constInfo_.cpRank, + constInfo_.cpInterleaveSize)); + } else if (constInfo_.attenMaskFlag) { cuRealAcSeqCount += 1; cuRealAcSeq = (cuRealAcSeqCount + cuRealAcSeqIni) / static_cast(constInfo_.cmpRatio); } + int32_t cuS1Idx = cuS1BeginIdxPerAiv + innerS1Idx; + if (constInfo_.useLocalVisibleLengths) { + // Interleaved owner-local IDs remain ordered. Causality is a + // local PREFIX and must limit scores before sorting candidates. + int32_t visible = outputIdxOffsetGm_.GetValue( + info.outputIdxOffsetCoreOffset + cuS1Idx * kHeadNum_); + cuRealAcSeq = Max(0, Min(visible, static_cast(info.actS2Size))); + } int32_t cuS2Len = cuBaseS2Idx + s2BaseSize_ >= cuRealAcSeq ? cuRealAcSeq - cuBaseS2Idx : s2BaseSize_; - int32_t cuS1Idx = cuS1BeginIdxPerAiv + innerS1Idx; - // 当前vec1ResGm对应S1的位置 - uint64_t wsOffset = - static_cast(info.saveWorkSpaceIdx) * s1BaseSize_ * - BASE_TOPK_VALUE_IDX_SIZE + - static_cast(cuS1Idx - cuBaseS1Idx) * BASE_TOPK_VALUE_IDX_SIZE; + // Each LD workspace slot contains s1BaseSize_ rows of the current S1 block. + // ProcessLD reads block-relative rows, while output/mask offsets use + // cuS1Idx. + + int32_t blockRowIdx = cuS1Idx - cuBaseS1Idx; + uint64_t wsOffset = static_cast(info.saveWorkSpaceIdx) * + s1BaseSize_ * topkPairWidth_ + + static_cast(blockRowIdx) * topkPairWidth_; if (cuRealAcSeq > 0 && cuS2Len > 0) { int32_t cuS2LenVecAlign = AlignS2(cuS2Len); LocalTensor mmInUb = inQueue_.AllocTensor(); @@ -1071,47 +2576,86 @@ __aicore__ inline void QLIV2VaVector::ProcessVec1( LocalTensor tmpSortBuf = sortBuff[2 * cuS2LenVecAlign]; QLIV2VaServiceVec::SortAll(sortBuff, tmpSortBuf, cuS2LenVecAlign); PipeBarrier(); - // 主路径累加器归并: 与候选路径 (:689) 一致, 改用纯 V 回拷的 - // MergeSortVecCopy。 旧 MergeSort 尾部 UB->UB DataCopy 若落 MTE 管道, - // 其后的 PipeBarrier 不构成 fence, 跨 tile/跨行对 globalTopkUb_ - // 的下一次 MrgSort 读存在调度敏感竞态 (tile1 读到 tile0 stale 数据, - // 累加器出现 -inf 位型+垃圾)。MergeSortVecCopy 回拷全程 V 管道, 受 - // PipeBarrier 约束。 - QLIV2VaServiceVec::MergeSortVecCopy( - globalTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], - BASE_TOPK, - sortBuff, - cuS2LenVecAlign, - tmpSortBuf); + if (constInfo_.useLocalVisibleLengths) { + QLIV2VaServiceVec::MergeSortVecCopy( + globalTopkUb_[innerS1Idx * topkPairWidth_], + topkWidth_, + sortBuff, + cuS2LenVecAlign, + tmpSortBuf, + true); + } else { + QLIV2VaServiceVec::MergeSort(globalTopkUb_[innerS1Idx * topkPairWidth_], + topkWidth_, + sortBuff, + cuS2LenVecAlign, + tmpSortBuf); + } + PipeBarrier(); bool isS2End = cuBaseS2Idx + s2BaseSize_ >= cuRealAcSeq; bool needCopyOutGm = blockS2StartIdx_ == 0 && isS2End; // 中间结果保存 - if (needCopyOutGm && !info.isNeedLD) { + if (needCopyOutGm && !info.isNeedLD && !info.suppressOut) { LocalTensor idxULocal = outQueue_.AllocTensor(); - ExtractIndex(idxULocal, - globalTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE] - .template ReinterpretCast(), - BASE_TOPK); + LocalTensor valueLocal = tmpBuf_.Get(); + if (constInfo_.useLocalVisibleLengths) { + // Extract the same FP32 values used by native Sort/MrgSort. + // tmpBuf_ is no longer used by this row's merge. + Extract(valueLocal, + idxULocal, + globalTopkUb_[innerS1Idx * topkPairWidth_], + (topkWidth_ / 32)); + } else { + ExtractIndex(idxULocal, + globalTopkUb_[innerS1Idx * topkPairWidth_] + .template ReinterpretCast(), + topkWidth_); + } + PipeBarrier(); - // A15: output_idx_offset — 输出拷 GM 前逐元素加行偏移 - // (IndicesAddOffset; 零偏移零开销; GM 标量读无 V_S 竞态; int32 整数域 + // return_value: 同一排序缓冲里抽取偶数 lane 的分数 (无效槽 padding 即 + // -inf) + LocalTensor valueUb; + if (constInfo_.returnValue != 0U && + !constInfo_.useLocalVisibleLengths) { + valueUb = valueOutBuf_.Get(); + ExtractValue(valueUb.template ReinterpretCast(), + globalTopkUb_[innerS1Idx * topkPairWidth_] + .template ReinterpretCast(), + topkWidth_); + } + // A15: output_idx_offset — 输出拷 GM 前逐元素加行偏移 (对齐 arch35 + // IndicesAddOffset; 零偏移零开销; GM 标量读无 V_S 竞态; int32 整数域 // Adds 位精确, -1 槽 +0 不变。 candidate_topk_index 不加 (相对块号契约, // §11.6)) - if (isOutputIdxOffsetValid_) { + if (isOutputIdxOffsetValid_ && !constInfo_.useLocalVisibleLengths) { int32_t rowOff = outputIdxOffsetGm_.GetValue( info.outputIdxOffsetCoreOffset + cuS1Idx * kHeadNum_); if (rowOff != 0) { + // A16: offset 只作用于有效 index, [validNum, sparseCount) 的 + // padding 保持 -1。 validNum = 本行真实候选数 = min(topk, + // 可见长度); 不能用扫描 -1 反推, 因为加偏移后 -1 + // 已不可辨。只写有效前缀, 尾部自然保持 Extract 时的 -1, 避免从非 + // 32B 对齐地址做 Duplicate (会触发 aicore 异常)。 + int32_t validNum = Min(static_cast(constInfo_.sparseCount), + Max(cuRealAcSeq, 0)); LocalTensor idxI32 = idxULocal.template ReinterpretCast(); - for (int32_t off = 0; off < constInfo_.sparseCount; off += 64) { + int32_t off = 0; + for (; off + 64 <= validNum; off += 64) { Adds(idxI32[off], idxI32[off], rowOff, 64); } - PipeBarrier(); + if (off < validNum) { + Adds(idxI32[off], idxI32[off], rowOff, validNum - off); + } + if (validNum > 0) { + PipeBarrier(); + } } } - InitSortOutBuf(globalTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], - BASE_TOPK_VALUE_IDX_SIZE); + InitSortOutBuf(globalTopkUb_[innerS1Idx * topkPairWidth_], + topkPairWidth_); outQueue_.EnQue(idxULocal); idxULocal = outQueue_.DeQue(); QLIV2VaServiceVec::CopyOut( @@ -1119,6 +2663,36 @@ __aicore__ inline void QLIV2VaVector::ProcessVec1( cuS1Idx * constInfo_.sparseCount], idxULocal.template ReinterpretCast(), constInfo_.sparseCount); + if (constInfo_.useLocalVisibleLengths) { + SetWaitFlag(HardEvent::V_MTE3); + QLIV2VaServiceVec::CopyOut( + valueOutFp32Gm[info.indiceOutOffset + + cuS1Idx * constInfo_.sparseCount], + valueLocal, + constInfo_.sparseCount); + // Next row's sort reuses tmpBuf_. + SetWaitFlag(HardEvent::MTE3_V); + } + // Reuse the index queue only after its DMA completes. The FP32 + // source remains in valueOutBuf_, so Cast has disjoint buffers. + if (constInfo_.returnValue != 0U && + !constInfo_.useLocalVisibleLengths) { + SetWaitFlag(HardEvent::MTE3_V); + LocalTensor valueBf16 = + idxULocal.template ReinterpretCast(); + Cast(valueBf16, + valueUb, + RoundMode::CAST_ROUND, + static_cast(constInfo_.sparseCount)); + PipeBarrier(); + SetWaitFlag(HardEvent::V_MTE3); + QLIV2VaServiceVec::CopyOut( + valueOutGm[info.indiceOutOffset + + cuS1Idx * constInfo_.sparseCount], + valueBf16, + static_cast(constInfo_.sparseCount)); + SetWaitFlag(HardEvent::MTE3_V); + } outQueue_.FreeTensor(idxULocal); // mode=1: 块级 topk 直出 candidate_topk_index if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { @@ -1129,33 +2703,42 @@ __aicore__ inline void QLIV2VaVector::ProcessVec1( if (info.isNeedLD && info.isLastS2InnerLoop) { // 当前核存在归约任务 且是最后处理的一段 AscendC::DataCopyExtParams copyWsParams; - copyWsParams.blockLen = BASE_TOPK_VALUE_IDX_SIZE * sizeof(float); + copyWsParams.blockLen = + topkPairWidth_ * sizeof(float); // P3: 按实际 topk 宽度 copyWsParams.srcStride = 0; copyWsParams.dstStride = 0; copyWsParams.blockCount = 1; SetWaitFlag(HardEvent::V_MTE3); - AscendC::DataCopyPad( - vec1ResGm[wsOffset], - globalTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], - copyWsParams); + AscendC::DataCopyPad(vec1ResGm[wsOffset], + globalTopkUb_[innerS1Idx * topkPairWidth_], + copyWsParams); SetWaitFlag(HardEvent::MTE3_V); - InitSortOutBuf(globalTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], - BASE_TOPK_VALUE_IDX_SIZE); + InitSortOutBuf(globalTopkUb_[innerS1Idx * topkPairWidth_], + topkPairWidth_); PipeBarrier(); + // mode=1:块级累积器也必须同样溢写。原实现只在非 LD 分支里直出 + // candidate_topk_index,跨核切分(LD)后块级累积器没有溢写也没有归约, + // 归约侧拿到的是空/旧数据,块级输出整行错误(实测 0/24)。 + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + SpillBlockTopkToGm(info, blockRowIdx, innerS1Idx); + } } } else if (cuRealAcSeq <= 0) { // 无效长度处理 if (info.isNeedLD && info.isLastS2InnerLoop) { PipeBarrier(); - InitSortOutBuf(globalTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], - BASE_TOPK_VALUE_IDX_SIZE); + InitSortOutBuf(globalTopkUb_[innerS1Idx * topkPairWidth_], + topkPairWidth_); SetWaitFlag(HardEvent::V_MTE3); - QLIV2VaServiceVec::CopyOut( - vec1ResGm[wsOffset], - globalTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], - BASE_TOPK_VALUE_IDX_SIZE); + QLIV2VaServiceVec::CopyOut(vec1ResGm[wsOffset], + globalTopkUb_[innerS1Idx * topkPairWidth_], + topkPairWidth_); SetWaitFlag(HardEvent::MTE3_V); - } else { + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + SpillBlockTopkToGm( + info, blockRowIdx, innerS1Idx); // 与位置级成对溢写 + } + } else if (!info.suppressOut) { CleanInvalidOutput(info.indiceOutOffset + cuS1Idx * constInfo_.sparseCount); } @@ -1164,14 +2747,17 @@ __aicore__ inline void QLIV2VaVector::ProcessVec1( if (info.isNeedLD && info.isLastS2InnerLoop) { // 当前核存在归约任务 且是最后处理的一段 SetWaitFlag(HardEvent::V_MTE3); - QLIV2VaServiceVec::CopyOut( - vec1ResGm[wsOffset], - globalTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], - BASE_TOPK_VALUE_IDX_SIZE); + QLIV2VaServiceVec::CopyOut(vec1ResGm[wsOffset], + globalTopkUb_[innerS1Idx * topkPairWidth_], + topkPairWidth_); SetWaitFlag(HardEvent::MTE3_V); - InitSortOutBuf(globalTopkUb_[innerS1Idx * BASE_TOPK_VALUE_IDX_SIZE], - BASE_TOPK_VALUE_IDX_SIZE); + InitSortOutBuf(globalTopkUb_[innerS1Idx * topkPairWidth_], + topkPairWidth_); PipeBarrier(); + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + SpillBlockTopkToGm( + info, blockRowIdx, innerS1Idx); // 与位置级成对溢写 + } } } } @@ -1184,9 +2770,9 @@ __aicore__ inline void QLIV2VaVector::ProcessVec1( // blockS2StartIdx_ == 0 控制S2从开始的核去做冗余清理 if (invalidS1Num > 0 && isS1LoopEnd && blockS2StartIdx_ == 0) { int32_t s1NumPerAiv = - blockId_ % 2 == 0 ? CeilDiv(invalidS1Num, 2) : (invalidS1Num / 2); + (blockId_ & 1) == 0 ? CeilDiv(invalidS1Num, 2) : (invalidS1Num / 2); int32_t s1OffsetPerAiv = - info.actS1Size + (blockId_ % 2) * CeilDiv(invalidS1Num, 2); + info.actS1Size + ((blockId_ & 1)) * CeilDiv(invalidS1Num, 2); for (int innerS1Idx = 0; innerS1Idx < s1NumPerAiv; innerS1Idx++) { CleanInvalidOutput(info.indiceOutOffset + (s1OffsetPerAiv + innerS1Idx) * @@ -1198,8 +2784,8 @@ __aicore__ inline void QLIV2VaVector::ProcessVec1( if (invalidS1Num2 > 0 && isS1LoopEnd && blockS2StartIdx_ == 0 && constInfo_.attenMaskFlag) { int32_t s1NumPerAiv = - blockId_ % 2 == 0 ? CeilDiv(invalidS1Num2, 2) : (invalidS1Num2 / 2); - int32_t s1OffsetPerAiv = (blockId_ % 2) * CeilDiv(invalidS1Num2, 2); + (blockId_ & 1) == 0 ? CeilDiv(invalidS1Num2, 2) : (invalidS1Num2 / 2); + int32_t s1OffsetPerAiv = ((blockId_ & 1)) * CeilDiv(invalidS1Num2, 2); for (int innerS1Idx = 0; innerS1Idx < s1NumPerAiv; innerS1Idx++) { CleanInvalidOutput( (info.bN2Idx * constInfo_.qSeqSize + s1OffsetPerAiv + innerS1Idx) * @@ -1214,6 +2800,147 @@ __aicore__ inline void QLIV2VaVector::ProcessVec1( } } +// mode=1 + LD:块级 topk 的分段归并。 +// 与位置级(ProcessLD)的 MrgSort 链完全同构,只有三个口径不同: +// ① 元素宽度:每段 candidateTopkBlocks 对(value+index),即 +// 2×candidateTopkBlocks 个 float; ② 槽位步长:块级 GM 区每行 slot = +// 2×candidateTopkBlocks 个 float; ③ 输出宽度:candidateTopkIndexOutGm 每行 +// candidateTopkBlocks 个块号。 +// 归并缓冲与位置级**共用**(InitLDBuffers +// 已按两者较大宽度分配),故必须在位置级 Extract/CopyOut 之后再执行(本函数在 +// ProcessLD 每行的位置级输出之后调用)。 +template +__aicore__ inline void QLIV2VaVector::ReduceBlockTopkRow( + uint32_t rowInBlock) { + uint32_t candBlocks = constInfo_.candidateTopkBlocks; + uint32_t candPairWidth = 2U * candBlocks; + LocalTensor curCand = ldToBeMrgBuf_.Get(); + LocalTensor tmpCand = ldTmpBuf_.Get(); + LocalTensor outIdxCand = ldOutIdxBuf_.Get(); + + AscendC::DataCopyPadExtParams candPadParams{true, 0, 0, 0}; + AscendC::DataCopyExtParams candParams; + candParams.blockLen = candPairWidth * sizeof(float); + candParams.srcStride = 0; + candParams.dstStride = 0; + candParams.blockCount = 1; + + uint32_t ldProWorkspaceNum = ldInfo_.workspaceNum; + uint32_t ldProcessLen = 4; // 4: 4 段归约任务做一次 MrgSort + uint32_t ldProcessNum = (ldProWorkspaceNum - 1) / (ldProcessLen - 1); + uint32_t ldTailLen = + ldProWorkspaceNum - (ldProcessNum * (ldProcessLen - 1) + 1); // 尾段数 + + // 本行在 GM 中的起点:与写侧 SpillBlockTopkToGm 同一公式 + // (workspaceIdx × s1Base × pairW + 段内相对行号 × pairW) + uint64_t rowBase = static_cast(ldInfo_.workspaceIdx) * s1BaseSize_ * + candPairWidth + + static_cast(rowInBlock) * candPairWidth; + uint64_t segGap = + static_cast(s1BaseSize_) * candPairWidth; // 相邻 S2 段起点间隔 + + SetWaitFlag(HardEvent::V_MTE2); + AscendC::DataCopyPad( + curCand, blockVec1ResGm_[rowBase], candParams, candPadParams); + uint32_t nextOffset = candPairWidth; + SetWaitFlag(HardEvent::MTE2_V); + + AscendC::MrgSort4Info prm; + prm.elementLengths[0] = candBlocks; + prm.elementLengths[1] = candBlocks; + prm.elementLengths[2] = candBlocks; + prm.elementLengths[3] = candBlocks; + prm.ifExhaustedSuspension = true; + prm.validBit = 0b1111; + prm.repeatTimes = 1; + + for (uint32_t i = 0; i < ldProcessNum; i++) { + uint64_t segBase = + rowBase + static_cast(i * (ldProcessLen - 1) + 1) * segGap; + SetWaitFlag(HardEvent::V_MTE2); + for (uint32_t k = 0; k < ldProcessLen - 1U; k++) { + AscendC::DataCopyPad(curCand[nextOffset + k * candPairWidth], + blockVec1ResGm_[segBase + k * segGap], + candParams, + candPadParams); + } + SetWaitFlag(HardEvent::MTE2_V); + AscendC::MrgSortSrcList srcList; + srcList.src1 = curCand[0]; + srcList.src2 = curCand[candPairWidth]; + srcList.src3 = curCand[2 * candPairWidth]; + srcList.src4 = curCand[3 * candPairWidth]; + MrgSort(tmpCand, srcList, prm); + PipeBarrier(); + // 回拷走纯 V(bit-exact):DataCopy 走 MTE,PipeBarrier 不构成 + // fence, 多段归并下一轮 MrgSort 会读到 stale 累加器(输出 -1 + // 空槽/丢项,非确定)。 + QLIV2VaServiceVec::VecCopyExact(curCand, tmpCand, candPairWidth); + PipeBarrier(); + } + + if (ldTailLen != 0) { + uint64_t tailBase = + rowBase + + static_cast(ldProcessNum * (ldProcessLen - 1) + 1) * segGap; + AscendC::DataCopyExtParams tailParams = candParams; + tailParams.blockCount = ldTailLen; + // srcStride 单位是**字节**,填"段间空隙"(段起点间隔 − + // 一段长度),与位置级同一修法 + tailParams.srcStride = + (s1BaseSize_ * candPairWidth - candPairWidth) * sizeof(float); + SetWaitFlag(HardEvent::V_MTE2); + AscendC::DataCopyPad(curCand[nextOffset], + blockVec1ResGm_[tailBase], + tailParams, + candPadParams); + SetWaitFlag(HardEvent::MTE2_V); + AscendC::MrgSort4Info tailPrm; + tailPrm.elementLengths[0] = candBlocks; + tailPrm.elementLengths[1] = candBlocks; + tailPrm.elementLengths[2] = candBlocks; + tailPrm.elementLengths[3] = candBlocks; + tailPrm.ifExhaustedSuspension = true; + tailPrm.validBit = + (ldTailLen == 1) ? 0b0011 : ((ldTailLen == 2) ? 0b0111 : 0b1111); + tailPrm.repeatTimes = 1; + AscendC::MrgSortSrcList srcList; + srcList.src1 = curCand[0]; + srcList.src2 = curCand[candPairWidth]; + srcList.src3 = curCand[2 * candPairWidth]; + srcList.src4 = curCand[3 * candPairWidth]; + MrgSort(tmpCand, srcList, tailPrm); + PipeBarrier(); + QLIV2VaServiceVec::VecCopyExact(curCand, tmpCand, candPairWidth); + PipeBarrier(); + } + + // 抽出块号并写到 candidate_topk_index(行偏移 = 行内相对行号 × kHeadNum × + // candBlocks) + ExtractIndex( + outIdxCand, curCand.template ReinterpretCast(), candBlocks); + SetWaitFlag(HardEvent::V_MTE3); + uint64_t outOffset = + ldInfo_.candidateOutCoreOffset + + static_cast(rowInBlock) * constInfo_.kHeadNum * candBlocks; + QLIV2VaServiceVec::CopyOut(candidateTopkIndexOutGm[outOffset], + outIdxCand.template ReinterpretCast(), + static_cast(candBlocks)); + // mode=1: LD 归约核是该行块级输出的唯一写者,长度也在这里写 + int32_t globalRow = + static_cast(ldInfo_.mIdx * s1BaseSize_ + rowInBlock); + const uint64_t candLenRow = + ldInfo_.candidateOutCoreOffset / static_cast(candBlocks) + + static_cast(rowInBlock) * constInfo_.kHeadNum; + WriteCandBlockLen( + candLenRow, + CalcCandBlockLen(static_cast(ldInfo_.actS1Size), + static_cast(ldInfo_.actS2Size), + static_cast(ldInfo_.actS2SizeOrig), + globalRow)); + SetWaitFlag(HardEvent::MTE3_V); +} + template __aicore__ inline void QLIV2VaVector::ProcessLD() { LocalTensor curValueIdxUb = ldToBeMrgBuf_.Get(); @@ -1230,9 +2957,18 @@ __aicore__ inline void QLIV2VaVector::ProcessLD() { AscendC::DataCopyPadExtParams indexValuePadParams{true, 0, 0, 0}; AscendC::DataCopyExtParams indexValueParams; - indexValueParams.blockLen = - BASE_TOPK_VALUE_IDX_SIZE * sizeof(int32_t); // bytes - indexValueParams.srcStride = 3 * BASE_TOPK_VALUE_IDX_SIZE * sizeof(int32_t); + // P3: 每列表搬运/间距按实际 topk 对宽 (vec1ResGm 内相邻列表间距 = 3 对宽) + indexValueParams.blockLen = topkPairWidth_ * sizeof(int32_t); // bytes + // P10: 分段槽按核分布 (核 i 的区起点 = i*s1Base 槽)。 + // P11 更正:`DataCopyExtParams.srcStride` + // 的单位是**字节**、语义是"块与块之间的空隙" (不是起点间距、更不是 32B + // 块数)—— 原写法 `s1Base*pairW*4/32` 只跳 512B 而不是一个槽位, + // 段与段几乎重叠,正是 507015 的根因。归并(3 + // 段)走的是逐段拷贝、blockCount=1 时该字段被忽略; + // 只有尾段(blockCount=ldTailLen)真正用它,故在尾段分支里按 (s1Base×pairW − + // pairW)×4B 赋值。 + indexValueParams.srcStride = 0; + indexValueParams.dstStride = 0; uint32_t ldProWorkspaceNum = ldInfo_.workspaceNum; @@ -1247,13 +2983,13 @@ __aicore__ inline void QLIV2VaVector::ProcessLD() { indexValueParams.blockCount = 1; uint64_t wsOffsetIni = static_cast(ldInfo_.workspaceIdx) * s1BaseSize_ * - BASE_TOPK_VALUE_IDX_SIZE + - static_cast(ldInfo_.mStart + j) * BASE_TOPK_VALUE_IDX_SIZE; + topkPairWidth_ + + static_cast(ldInfo_.mStart + j) * topkPairWidth_; AscendC::DataCopyPad(curValueIdxUb, vec1ResGm[wsOffsetIni], indexValueParams, indexValuePadParams); - uint64_t valueOffset = BASE_TOPK_VALUE_IDX_SIZE; + uint64_t valueOffset = topkPairWidth_; SetWaitFlag(HardEvent::MTE2_V); // 处理等于4的部分 @@ -1261,23 +2997,28 @@ __aicore__ inline void QLIV2VaVector::ProcessLD() { // LD处理偏移 uint64_t wsOffset = static_cast(ldInfo_.workspaceIdx) * s1BaseSize_ * - BASE_TOPK_VALUE_IDX_SIZE + - static_cast(ldInfo_.mStart + j) * BASE_TOPK_VALUE_IDX_SIZE + + topkPairWidth_ + static_cast(i * (ldProcessLen - 1) + 1) * s1BaseSize_ * - BASE_TOPK_VALUE_IDX_SIZE; - indexValueParams.blockCount = ldProcessLen - 1; // 拷贝4块进行merge + topkPairWidth_ + + static_cast(ldInfo_.mStart + j) * topkPairWidth_; + indexValueParams.blockCount = 1; // P10: 逐段拷贝 (见上) SetWaitFlag(HardEvent::V_MTE2); - AscendC::DataCopyPad(curValueIdxUb[valueOffset], - vec1ResGm[wsOffset], - indexValueParams, - indexValuePadParams); - // merge参数 + // P10: 绕开 srcStride 语义不确定性 — 3 个分段槽逐个显式拷贝 + for (uint32_t k = 0; k < ldProcessLen - 1U; k++) { + uint64_t segSlot = + wsOffset + static_cast(k) * s1BaseSize_ * topkPairWidth_; + AscendC::DataCopyPad(curValueIdxUb[valueOffset + k * topkPairWidth_], + vec1ResGm[segSlot], + indexValueParams, + indexValuePadParams); + } + // merge参数 (P3: elementLengths 按实际 topk 宽度) AscendC::MrgSort4Info params; - params.elementLengths[0] = BASE_TOPK; - params.elementLengths[1] = BASE_TOPK; - params.elementLengths[2] = BASE_TOPK; - params.elementLengths[3] = BASE_TOPK; + params.elementLengths[0] = topkWidth_; + params.elementLengths[1] = topkWidth_; + params.elementLengths[2] = topkWidth_; + params.elementLengths[3] = topkWidth_; params.ifExhaustedSuspension = true; params.validBit = 0b1111; params.repeatTimes = 1; @@ -1285,13 +3026,15 @@ __aicore__ inline void QLIV2VaVector::ProcessLD() { SetWaitFlag(HardEvent::MTE2_V); AscendC::MrgSortSrcList srcList; srcList.src1 = curValueIdxUb[0]; - srcList.src2 = curValueIdxUb[BASE_TOPK_VALUE_IDX_SIZE]; - srcList.src3 = curValueIdxUb[2 * BASE_TOPK_VALUE_IDX_SIZE]; - srcList.src4 = curValueIdxUb[3 * BASE_TOPK_VALUE_IDX_SIZE]; + srcList.src2 = curValueIdxUb[topkPairWidth_]; + srcList.src3 = curValueIdxUb[2 * topkPairWidth_]; + srcList.src4 = curValueIdxUb[3 * topkPairWidth_]; MrgSort(tmpUb, srcList, params); PipeBarrier(); - DataCopy(curValueIdxUb, tmpUb, BASE_TOPK_VALUE_IDX_SIZE); - PipeBarrier(); + // 回拷必须走纯 V(bit-exact):DataCopy 走 MTE,PipeBarrier + // 不构成 fence, 多段归并下一轮 MrgSort 会读到 stale 累加器(输出 -1 + // 空槽/丢项,非确定)。 + QLIV2VaServiceVec::VecCopyExact(curValueIdxUb, tmpUb, topkPairWidth_); } // 处理不等于4的部分 @@ -1299,22 +3042,32 @@ __aicore__ inline void QLIV2VaVector::ProcessLD() { // 搬运尾块 uint64_t wsOffsetTail = static_cast(ldInfo_.workspaceIdx) * s1BaseSize_ * - BASE_TOPK_VALUE_IDX_SIZE + - static_cast(ldInfo_.mStart + j) * BASE_TOPK_VALUE_IDX_SIZE + + topkPairWidth_ + static_cast(ldProcessNum * (ldProcessLen - 1) + 1) * - s1BaseSize_ * BASE_TOPK_VALUE_IDX_SIZE; - indexValueParams.blockCount = ldTailLen; + s1BaseSize_ * topkPairWidth_ + + static_cast(ldInfo_.mStart + j) * topkPairWidth_; + // 尾段逐槽显式拷贝(blockCount=1,srcStride + // 不参与):早期多块单次搬运依赖 + // DataCopyExtParams.srcStride(字节/段间空隙语义)实现跨槽跳读,曾因单位写错 + // (按 32B 块除了 32,只跳 512B)导致 507015;修正公式后仍实测偶发读错槽 + // (非整 tile 末片形状 L=321 十轮 2 次输出混入 -1 空槽)。 + // 与上游 P10 同策略:逐槽单块拷贝,彻底绕开 stride 语义。 + SetWaitFlag(HardEvent::V_MTE2); - AscendC::DataCopyPad(curValueIdxUb[valueOffset], - vec1ResGm[wsOffsetTail], - indexValueParams, - indexValuePadParams); + for (uint32_t k = 0; k < ldTailLen; k++) { + uint64_t segSlot = wsOffsetTail + static_cast(k) * + s1BaseSize_ * topkPairWidth_; + AscendC::DataCopyPad(curValueIdxUb[valueOffset + k * topkPairWidth_], + vec1ResGm[segSlot], + indexValueParams, + indexValuePadParams); + } SetWaitFlag(HardEvent::MTE2_V); AscendC::MrgSort4Info params; - params.elementLengths[0] = BASE_TOPK; - params.elementLengths[1] = BASE_TOPK; - params.elementLengths[2] = BASE_TOPK; - params.elementLengths[3] = BASE_TOPK; + params.elementLengths[0] = topkWidth_; + params.elementLengths[1] = topkWidth_; + params.elementLengths[2] = topkWidth_; + params.elementLengths[3] = topkWidth_; params.ifExhaustedSuspension = true; if (ldTailLen == 1) { params.validBit = 0b0011; @@ -1325,35 +3078,52 @@ __aicore__ inline void QLIV2VaVector::ProcessLD() { AscendC::MrgSortSrcList srcList; srcList.src1 = curValueIdxUb[0]; - srcList.src2 = curValueIdxUb[BASE_TOPK_VALUE_IDX_SIZE]; - srcList.src3 = curValueIdxUb[2 * BASE_TOPK_VALUE_IDX_SIZE]; - srcList.src4 = curValueIdxUb[3 * BASE_TOPK_VALUE_IDX_SIZE]; + srcList.src2 = curValueIdxUb[topkPairWidth_]; + srcList.src3 = curValueIdxUb[2 * topkPairWidth_]; + srcList.src4 = curValueIdxUb[3 * topkPairWidth_]; PipeBarrier(); MrgSort(tmpUb, srcList, params); PipeBarrier(); - DataCopy(curValueIdxUb, tmpUb, BASE_TOPK_VALUE_IDX_SIZE); - PipeBarrier(); + // 回拷必须走纯 V(bit-exact):DataCopy 走 MTE,PipeBarrier + // 不构成 fence, 多段归并下一轮 MrgSort 会读到 stale 累加器(输出 -1 + // 空槽/丢项,非确定)。 + QLIV2VaServiceVec::VecCopyExact(curValueIdxUb, tmpUb, topkPairWidth_); } - // 搬出 - Extract(outValueUb, outIdxUb, curValueIdxUb, (BASE_TOPK / 32)); + // 搬出 (P3: Extract repeat = topkWidth_/32, 每 repeat 消费 32 对) + Extract(outValueUb, outIdxUb, curValueIdxUb, (topkWidth_ / 32)); PipeBarrier(); - InitSortOutBuf(curValueIdxUb, BASE_TOPK_VALUE_IDX_SIZE); + InitSortOutBuf(curValueIdxUb, topkPairWidth_); LocalTensor idxULocal1 = outIdxUb.template ReinterpretCast(); // A15: LD(decode) 路径同样加 output_idx_offset (行前缀 = // indiceOutCoreOffset/sparseCount, 即 batch 前缀 x kHeadNum + n2; 与 // ProcessVec1 消费点同语义) - if (isOutputIdxOffsetValid_) { + if (isOutputIdxOffsetValid_ && !constInfo_.useLocalVisibleLengths) { uint32_t rowGlobal = ldInfo_.mStart + j; int32_t rowOff = outputIdxOffsetGm_.GetValue( ldInfo_.indiceOutCoreOffset / constInfo_.sparseCount + rowGlobal * constInfo_.kHeadNum); if (rowOff != 0) { - for (int32_t off = 0; off < constInfo_.sparseCount; off += 64) { + // A16: 与 ProcessVec1 同口径 — 只对有效前缀加偏移, 尾部保持 -1。 + int32_t validNum = static_cast(constInfo_.sparseCount); + for (int32_t i = 0; i < static_cast(constInfo_.sparseCount); + ++i) { + if (idxULocal1.GetValue(i) < 0) { + validNum = i; + break; + } + } + int32_t off = 0; + for (; off + 64 <= validNum; off += 64) { Adds(idxULocal1[off], idxULocal1[off], rowOff, 64); } - PipeBarrier(); + if (off < validNum) { + Adds(idxULocal1[off], idxULocal1[off], rowOff, validNum - off); + } + if (validNum > 0) { + PipeBarrier(); + } } } SetWaitFlag(HardEvent::V_MTE3); @@ -1361,7 +3131,36 @@ __aicore__ inline void QLIV2VaVector::ProcessLD() { ldInfo_.indiceOutCoreOffset + (ldInfo_.mStart + j) * constInfo_.kHeadNum * constInfo_.sparseCount; AscendC::DataCopyPad(indiceOutGm[outOffset], idxULocal1, copyOutParams); + if (constInfo_.useLocalVisibleLengths) { + AscendC::DataCopyPad( + valueOutFp32Gm[outOffset], outValueUb, copyOutParams); + } SetWaitFlag(HardEvent::MTE3_V); + // return_value: LD 路径同样输出 BF16 分数 (复用已拷出的 index 缓冲作 Cast + // 目标) + if (constInfo_.returnValue != 0U && !constInfo_.useLocalVisibleLengths) { + LocalTensor valueBf16 = + outIdxUb.template ReinterpretCast(); + Cast(valueBf16, + outValueUb, + RoundMode::CAST_ROUND, + static_cast(constInfo_.sparseCount)); + PipeBarrier(); + SetWaitFlag(HardEvent::V_MTE3); + AscendC::DataCopyParams valueCopyParams; + valueCopyParams.blockCount = 1; + valueCopyParams.blockLen = constInfo_.sparseCount * sizeof(bfloat16_t); + valueCopyParams.srcStride = 0; + valueCopyParams.dstStride = 0; + AscendC::DataCopyPad(valueOutGm[outOffset], valueBf16, valueCopyParams); + SetWaitFlag(HardEvent::MTE3_V); + } + // mode=1:同一行再做一遍块级归约,输出 candidate_topk_index(块级输出无 LD + // 时由 CopyOutCandTopkIndex 直出;有 LD + // 时每段只有部分结果,必须在这里归并) + if (constInfo_.candidateMode == CANDIDATE_MODE_SOURCE) { + ReduceBlockTopkRow(ldInfo_.mStart + j); + } } SetWaitFlag(HardEvent::MTE3_V); } diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_vector.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_vector.h index 5b6f971cd7..03ec03ad8f 100644 --- a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_vector.h +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/arch22/quant_lightning_indexer_v2_va_vector.h @@ -42,6 +42,38 @@ constexpr int64_t MRG_BLOCK_2 = 2; constexpr int64_t MRG_BLOCK_3 = 3; constexpr int64_t MRG_BLOCK_4 = 4; +// Batch full FP32/INT32 vector repeats, then issue an exact masked tail. +// Level-0 repeats avoid the per-64-element mask-mode transitions of the +// Level-2 count overload. One instruction may issue at most 255 repeats. +__aicore__ inline void VecRepeatPlan(int32_t remainEleNum, + uint64_t& mask, + uint8_t& repeatTimes) { + if (remainEleNum >= static_cast(B32_VEC_ELM_NUM)) { + int32_t repeatNum = remainEleNum / static_cast(B32_VEC_ELM_NUM); + mask = static_cast(B32_VEC_ELM_NUM); + repeatTimes = + static_cast(repeatNum < static_cast(VEC_REPEAT_MAX) + ? repeatNum + : static_cast(VEC_REPEAT_MAX)); + } else { + mask = static_cast(remainEleNum); + repeatTimes = 1; + } +} + +__aicore__ inline UnaryRepeatParams B32RepeatParams() { + return UnaryRepeatParams(1, 1, B32_VEC_REPEAT_STRIDE, B32_VEC_REPEAT_STRIDE); +} + +__aicore__ inline BinaryRepeatParams B32BinaryRepeatParams() { + return BinaryRepeatParams(1, + 1, + 1, + B32_VEC_REPEAT_STRIDE, + B32_VEC_REPEAT_STRIDE, + B32_VEC_REPEAT_STRIDE); +} + template __aicore__ inline void CopyOut(const GlobalTensor& dstGm, const LocalTensor& srcUb, @@ -151,7 +183,6 @@ __aicore__ inline void SortAll(LocalTensor& src, params.validBit = 0b1111; } AscendC::MrgSort(dstTensor, srcList, params); - AscendC::PipeBarrier(); i += 1; break; } else { @@ -164,19 +195,15 @@ __aicore__ inline void SortAll(LocalTensor& src, AscendC::PipeBarrier(); } if (i % CONST_TWO == 0) { - // 尾部回拷与 MergeSort 同类问题: 若该 UB->UB DataCopy 落 MTE 管道, 其后的 - // PipeBarrier 不构成 fence, 调用方随后对 src 的 V 管道 MrgSort 读 - // (合并到 globalTopkUb_/globalBlockTopkUb_) 存在调度敏感竞态。改为 int32 - // 视图 Adds(+0) 位精确回拷, 全程 V 管道受 PipeBarrier 约束; 顺带避免 float - // vadd 把 -1 (0xFFFFFFFF, 负符号 NaN) 规范化成 0x7FFFFFFF 而破坏 - // (value,index) 对的位型。 - int32_t copyNum = static_cast(logitsNum * VALUE_AND_INDEX_NUM); - AscendC::LocalTensor dstI = - src.template ReinterpretCast(); - AscendC::LocalTensor srcI = - tmp.template ReinterpretCast(); - for (int32_t off = 0; off < copyNum; off += B32_VEC_ELM_NUM) { - AscendC::Adds(dstI[off], srcI[off], 0, B32_VEC_ELM_NUM); + // 纯 V 回拷(bit-exact):UB->UB DataCopy 走 MTE 管道,PipeBarrier + // 不构成 fence,后续读 src 的向量指令可能读到 stale 数据(同 + // MergeSortVecCopy 的教训)。 + LocalTensor dstI = src.template ReinterpretCast(); + LocalTensor srcI = tmp.template ReinterpretCast(); + for (int32_t off = 0; + off < static_cast(logitsNum * VALUE_AND_INDEX_NUM); + off += 64) { + AscendC::Adds(dstI[off], srcI[off], 0, 64); } AscendC::PipeBarrier(); } @@ -205,7 +232,13 @@ __aicore__ inline void MergeSort(const LocalTensor& mrgDst, AscendC::MrgSort(tmpTensor, srcList, params); AscendC::PipeBarrier(); - AscendC::DataCopy(mrgDst, tmpTensor, mrgDstNum * VALUE_AND_INDEX_NUM); + // 纯 V 回拷(bit-exact),同 MergeSortVecCopy / VecCopyExact 的教训 + LocalTensor dstI = mrgDst.template ReinterpretCast(); + LocalTensor srcI = tmpTensor.template ReinterpretCast(); + const int32_t copyNum = mrgDstNum * VALUE_AND_INDEX_NUM; + for (int32_t off = 0; off < copyNum; off += 64) { + AscendC::Adds(dstI[off], srcI[off], 0, 64); + } AscendC::PipeBarrier(); } @@ -230,6 +263,31 @@ __aicore__ inline void ExtractIndex(const LocalTensor& idxULocal, AscendC::PipeBarrier(); } +/** + return_value: 从排序后的 (value, index) 交错序列中抽取偶数 lane 的分数。 + src/dst 均按 uint32 视图操作, 调用方按 float 解释 dst。 + */ +__aicore__ inline void ExtractValue(const LocalTensor& valULocal, + const LocalTensor& sortLocal, + int64_t extractNum) { + AscendC::GatherMaskParams gatherMaskParams; + gatherMaskParams.repeatTimes = + Ceil(extractNum * sizeof(float) * VALUE_AND_INDEX_NUM, VEC_REPEAT_BYTES); + gatherMaskParams.src0BlockStride = 1; + gatherMaskParams.src0RepeatStride = B32_VEC_REPEAT_STRIDE; + gatherMaskParams.src1RepeatStride = 0; + uint64_t rsvdCnt = 0; + uint8_t src1Pattern = 1; // 固定模式1, 表示筛选出偶数索引的数 (value) + AscendC::GatherMask(valULocal, + sortLocal, + src1Pattern, + false, + static_cast(0), + gatherMaskParams, + rsvdCnt); + AscendC::PipeBarrier(); +} + /** 候选路径专用合并: 与 MergeSort 语义相同, 但回拷 mrgDst 用纯向量 Adds (64 分块)。 MergeSort 尾部的 UB->UB DataCopy 若走 MTE 管道, 其后的 @@ -241,17 +299,21 @@ __aicore__ inline void MergeSortVecCopy(const LocalTensor& mrgDst, int32_t mrgDstNum, LocalTensor& mrgSrc, int32_t mrgSrcNum, - LocalTensor& tmpTensor) { + LocalTensor& tmpTensor, + bool accumulatedFirst = false) { AscendC::MrgSort4Info params; - params.elementLengths[0] = mrgSrcNum; - params.elementLengths[1] = mrgDstNum; + params.elementLengths[0] = accumulatedFirst ? mrgDstNum : mrgSrcNum; + params.elementLengths[1] = accumulatedFirst ? mrgSrcNum : mrgDstNum; params.ifExhaustedSuspension = false; params.validBit = 0b0011; params.repeatTimes = 1; AscendC::MrgSortSrcList srcList; - srcList.src1 = mrgSrc; - srcList.src2 = mrgDst; + // Private local candidates retain smaller IDs when scores tie: all IDs + // already accumulated precede the current S2 tile. Legacy callers keep + // their original source order through the default argument. + srcList.src1 = accumulatedFirst ? mrgDst : mrgSrc; + srcList.src2 = accumulatedFirst ? mrgSrc : mrgDst; AscendC::MrgSort(tmpTensor, srcList, params); AscendC::PipeBarrier(); @@ -267,6 +329,23 @@ __aicore__ inline void MergeSortVecCopy(const LocalTensor& mrgDst, AscendC::PipeBarrier(); } +/** + UB→UB 位精确回拷(纯 V 管道)。DataCopy 走 MTE 管道,其后的 + PipeBarrier 不构成 fence —— 多段归并里下一轮 MrgSort 会读到 stale + 累加器(累加器出现 -inf 位型,表现为输出 顶 512 里混入 -1 空槽/丢有效项)。用 + int32 视图 Adds(+0) 分 64 元素块回拷:位精确且全程 V。 + */ +__aicore__ inline void VecCopyExact(const LocalTensor& dst, + const LocalTensor& src, + int32_t num) { + LocalTensor dstI = dst.template ReinterpretCast(); + LocalTensor srcI = src.template ReinterpretCast(); + for (int32_t off = 0; off < num; off += 64) { + AscendC::Adds(dstI[off], srcI[off], 0, 64); + } + AscendC::PipeBarrier(); +} + template __aicore__ inline void SetWaitFlag(HardEvent evt) { event_t eventId = static_cast(GetTPipePtr()->FetchEventID(evt)); diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_va_template_tiling_key.h b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_va_template_tiling_key.h index 68150d77f8..bcb093ba1e 100644 --- a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_va_template_tiling_key.h +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_va_template_tiling_key.h @@ -31,162 +31,7 @@ the full text of the License.  */ #define ASCENDC_TPL_4_BW 4 // 模板参数支持的范围定义 -#if (__CCE_AICORE__ == 310) -ASCENDC_TPL_ARGS_DECL(XllmKernelQuantLightningIndexerV2Va, // 算子OpType - ASCENDC_TPL_DTYPE_DECL(DT_Q, - QLIV2Va_TPL_FLOAT8_E4M3FN, - QLIV2Va_TPL_HIFLOAT8, - QLIV2Va_TPL_FLOAT4_E2M1, - QLIV2Va_TPL_INT8), - ASCENDC_TPL_DTYPE_DECL(DT_K, - QLIV2Va_TPL_FLOAT8_E4M3FN, - QLIV2Va_TPL_HIFLOAT8, - QLIV2Va_TPL_FLOAT4_E2M1, - QLIV2Va_TPL_INT8), - ASCENDC_TPL_DTYPE_DECL(DT_OUT, QLIV2Va_TPL_INT32), - ASCENDC_TPL_BOOL_DECL(PAGE_ATTENTION, 1, 0), - ASCENDC_TPL_UINT_DECL(Q_LAYOUT_T, - ASCENDC_TPL_4_BW, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_BSND, - QLIV2Va_LAYOUT_TND), - ASCENDC_TPL_UINT_DECL(K_LAYOUT_T, - ASCENDC_TPL_4_BW, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_BSND, - QLIV2Va_LAYOUT_TND, - QLIV2Va_LAYOUT_PA_BBND), ); -// 支持的模板参数组合 -// 用于调用GET_TPL_TILING_KEY获取TilingKey时,接口内部校验TilingKey是否合法 -ASCENDC_TPL_SEL( - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_FLOAT8_E4M3FN), - ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_FLOAT8_E4M3FN), - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), - ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_BSND, - QLIV2Va_LAYOUT_TND), - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_PA_BBND), ), - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_FLOAT8_E4M3FN), - ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_FLOAT8_E4M3FN), - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), - ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_BSND), - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_BSND), ), - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_FLOAT8_E4M3FN), - ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_FLOAT8_E4M3FN), - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), - ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_TND), - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_TND), ), - - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_HIFLOAT8), - ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_HIFLOAT8), - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), - ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_BSND, - QLIV2Va_LAYOUT_TND), - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_PA_BBND), ), - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_HIFLOAT8), - ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_HIFLOAT8), - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), - ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_BSND), - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_BSND), ), - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_HIFLOAT8), - ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_HIFLOAT8), - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), - ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_TND), - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_TND), ), - - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_FLOAT4_E2M1), - ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_FLOAT4_E2M1), - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), - ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_BSND, - QLIV2Va_LAYOUT_TND), - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_PA_BBND), ), - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_FLOAT4_E2M1), - ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_FLOAT4_E2M1), - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), - ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_BSND), - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_BSND), ), - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_FLOAT4_E2M1), - ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_FLOAT4_E2M1), - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), - ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_TND), - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_TND), ), - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_INT8), - ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_INT8), - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), - ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_BSND, - QLIV2Va_LAYOUT_TND), - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_PA_BBND), ), - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_INT8), - ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_INT8), - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), - ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_BSND), - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_BSND), ), - ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, QLIV2Va_TPL_INT8), - ASCENDC_TPL_DTYPE_SEL(DT_K, QLIV2Va_TPL_INT8), - ASCENDC_TPL_DTYPE_SEL(DT_OUT, QLIV2Va_TPL_INT32), - ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), - ASCENDC_TPL_UINT_SEL(Q_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_TND), - ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - QLIV2Va_LAYOUT_TND), )); -#else -ASCENDC_TPL_ARGS_DECL(XllmKernelQuantLightningIndexerV2Va, // 算子OpType +ASCENDC_TPL_ARGS_DECL(XllmKernelQuantLightningIndexerV3Va, // 算子OpType ASCENDC_TPL_DTYPE_DECL(DT_Q, QLIV2Va_TPL_INT8), ASCENDC_TPL_DTYPE_DECL(DT_K, QLIV2Va_TPL_INT8), ASCENDC_TPL_DTYPE_DECL(DT_OUT, QLIV2Va_TPL_INT32), @@ -236,6 +81,5 @@ ASCENDC_TPL_SEL( ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, QLIV2Va_LAYOUT_TND), ), ); -#endif #endif // QUANT_LIGHTNING_INDEXER_V2_VA_TEMPLATE_TILING_KEY_H diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/xllm_kernel_quant_lightning_indexer_v2_va.cpp b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/xllm_kernel_quant_lightning_indexer_v3_va.cpp similarity index 88% rename from xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/xllm_kernel_quant_lightning_indexer_v2_va.cpp rename to xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/xllm_kernel_quant_lightning_indexer_v3_va.cpp index 31c135d8de..16eb840d16 100644 --- a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/xllm_kernel_quant_lightning_indexer_v2_va.cpp +++ b/xllm-kernel/csrc/ascendc/quant_lightning_indexer_v2_va/op_kernel/xllm_kernel_quant_lightning_indexer_v3_va.cpp @@ -21,7 +21,9 @@ the full text of the License.  */ using namespace QLIV2VaKernel; using namespace optiling::detail; -// 含 candidate_topk_index 输入/输出 (两级TopK) +// arch22: 含 candidate_topk_index 输入/输出 (两级TopK) +// candidateBlockLength: 每行有效候选块数(可选;未传时为 nullptr,走全量 S2 +// 扫描) #define INVOKE_LI_CANDIDATE_OP_IMPL(templateClass, ...) \ do { \ templateClass> op; \ @@ -39,9 +41,12 @@ using namespace optiling::detail; outputIdxOffset, \ metadata, \ candidateTopkIndex, \ + candidateBlockLength, \ + causalSeqlensKvGlobal, \ sparseIndices, \ sparseValues, \ candidateTopkIndexOut, \ + candidateBlockLengthOut, \ user, \ tiling_data, \ &tPipe); \ @@ -54,7 +59,7 @@ template -__global__ __aicore__ void xllm_kernel_quant_lightning_indexer_v2_va( +__global__ __aicore__ void xllm_kernel_quant_lightning_indexer_v3_va( __gm__ uint8_t* query, __gm__ uint8_t* key, __gm__ uint8_t* weights, @@ -69,9 +74,12 @@ __global__ __aicore__ void xllm_kernel_quant_lightning_indexer_v2_va( __gm__ uint8_t* outputIdxOffset, __gm__ uint8_t* metadata, __gm__ uint8_t* candidateTopkIndex, + __gm__ uint8_t* candidateBlockLength, + __gm__ uint8_t* causalSeqlensKvGlobal, __gm__ uint8_t* sparseIndices, __gm__ uint8_t* sparseValues, __gm__ uint8_t* candidateTopkIndexOut, + __gm__ uint8_t* candidateBlockLengthOut, __gm__ uint8_t* workspace, __gm__ uint8_t* tiling) { TPipe tPipe; diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_graph/quant_sparse_lightning_indexer_metadata_va_proto.cpp b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_graph/quant_sparse_lightning_indexer_metadata_va_proto.cpp new file mode 100644 index 0000000000..909d1f4d7b --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_graph/quant_sparse_lightning_indexer_metadata_va_proto.cpp @@ -0,0 +1,33 @@ +// Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. + +#include "graph/operator_reg.h" +#include "graph/types.h" + +namespace ge { + +REG_OP(XllmKernelQuantSparseLightningIndexerMetadataVa) + .OPTIONAL_INPUT(cu_seqlens_q, TensorType({DT_INT32})) + .OPTIONAL_INPUT(cu_seqlens_k, TensorType({DT_INT32})) + .OPTIONAL_INPUT(seqused_q, TensorType({DT_INT32})) + .OPTIONAL_INPUT(seqused_k, TensorType({DT_INT32})) + .OPTIONAL_INPUT(cmp_residual_k, TensorType({DT_INT32})) + .OPTIONAL_INPUT(candidate_block_length, TensorType({DT_INT32})) + .OUTPUT(metadata, TensorType({DT_INT32})) + .REQUIRED_ATTR(num_heads_q, Int) + .REQUIRED_ATTR(num_heads_k, Int) + .REQUIRED_ATTR(head_dim, Int) + .REQUIRED_ATTR(topk, Int) + .REQUIRED_ATTR(quant_mode, Int) + .ATTR(batch_size, Int, 0) + .ATTR(max_seqlen_q, Int, 0) + .ATTR(max_seqlen_k, Int, 0) + .ATTR(layout_q, String, "BSND") + .ATTR(layout_k, String, "BSND") + .ATTR(mask_mode, Int, 0) + .ATTR(cmp_ratio, Int, 1) + .REQUIRED_ATTR(aic_core_num, Int) + .REQUIRED_ATTR(aiv_core_num, Int) + .REQUIRED_ATTR(soc_version, String) + .OP_END_FACTORY_REG(XllmKernelQuantSparseLightningIndexerMetadataVa) + +} // namespace ge diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.cpp b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.cpp new file mode 100644 index 0000000000..91a929509a --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.cpp @@ -0,0 +1,222 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file aclnn_quant_sparse_lightning_indexer_metadata_va.cpp + * \brief + */ + +#include "aclnn_quant_sparse_lightning_indexer_metadata_va.h" + +#include "../quant_sparse_lightning_indexer_metadata_va_check.h" +#include "aclnn/aclnn_base.h" +#include "aclnn_kernels/common/op_error_check.h" +#include "aclnn_kernels/contiguous.h" +#include "aclnn_kernels/reshape.h" +#include "opdev/common_types.h" +#include "opdev/data_type_utils.h" +#include "opdev/format_utils.h" +#include "opdev/make_op_executor.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "opdev/op_log.h" +#include "opdev/platform.h" +#include "opdev/tensor_view_utils.h" +#include "quant_sparse_lightning_indexer_metadata_va.h" + +#ifdef __cplusplus +extern "C" { +#endif + +aclnnStatus +aclnnXllmKernelQuantSparseLightningIndexerMetadataVaGetWorkspaceSize( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + const aclTensor* candidateBlockLengthOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + const aclTensor* metadata, + uint64_t* workspaceSize, + aclOpExecutor** executor) { + if (workspaceSize == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "workspaceSize is nullptr"); + return ACLNN_ERR_INNER_NULLPTR; + } + if (executor == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "executor is nullptr"); + return ACLNN_ERR_INNER_NULLPTR; + } + L2_DFX_PHASE_1(aclnnXllmKernelQuantSparseLightningIndexerMetadataVa, + DFX_IN(cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + candidateBlockLengthOptional, + numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio), + DFX_OUT(metadata)); + + auto uniqueExecutor = CREATE_EXECUTOR(); + CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + + const op::PlatformInfo& npuInfo = op::GetCurrentPlatformInfo(); + uint32_t aicCoreNum = npuInfo.GetCubeCoreNum(); + uint32_t aivCoreNum = npuInfo.GetVectorCoreNum(); + const std::string socVersion = npuInfo.GetSocLongVersion(); + + auto ret = ParamsCheckQsli(cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + metadata, + aicCoreNum, + aivCoreNum, + socVersion); + CHECK_RET(ret == ACLNN_SUCCESS, ret); + + const aclTensor* cuSeqlensQOptionalContiguous = nullptr; + if (cuSeqlensQOptional != nullptr) { + cuSeqlensQOptionalContiguous = + l0op::Contiguous(cuSeqlensQOptional, uniqueExecutor.get()); + if (cuSeqlensQOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "cu_seqlens_q contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* cuSeqlensKOptionalContiguous = nullptr; + if (cuSeqlensKOptional != nullptr) { + cuSeqlensKOptionalContiguous = + l0op::Contiguous(cuSeqlensKOptional, uniqueExecutor.get()); + if (cuSeqlensKOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "cu_seqlens_k contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* sequsedQOptionalContiguous = nullptr; + if (sequsedQOptional != nullptr) { + sequsedQOptionalContiguous = + l0op::Contiguous(sequsedQOptional, uniqueExecutor.get()); + if (sequsedQOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "seqused_q contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* sequsedKOptionalContiguous = nullptr; + if (sequsedKOptional != nullptr) { + sequsedKOptionalContiguous = + l0op::Contiguous(sequsedKOptional, uniqueExecutor.get()); + if (sequsedKOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "seqused_k contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + const aclTensor* cmpResidualLKOptionalContiguous = nullptr; + if (cmpResidualKOptional != nullptr) { + cmpResidualLKOptionalContiguous = + l0op::Contiguous(cmpResidualKOptional, uniqueExecutor.get()); + if (cmpResidualLKOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "cmp_residual_k contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + + const aclTensor* candidateBlockLengthOptionalContiguous = nullptr; + if (candidateBlockLengthOptional != nullptr) { + candidateBlockLengthOptionalContiguous = + l0op::Contiguous(candidateBlockLengthOptional, uniqueExecutor.get()); + if (candidateBlockLengthOptionalContiguous == nullptr) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, + "candidate_block_length contiguous is null"); + return ACLNN_ERR_INNER_NULLPTR; + } + } + + auto output = l0op::XllmKernelQuantSparseLightningIndexerMetadataVa( + cuSeqlensQOptionalContiguous, + cuSeqlensKOptionalContiguous, + sequsedQOptionalContiguous, + sequsedKOptionalContiguous, + cmpResidualLKOptionalContiguous, + candidateBlockLengthOptionalContiguous, + numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + aicCoreNum, + aivCoreNum, + socVersion.c_str(), + metadata, + uniqueExecutor.get()); + CHECK_RET(output != nullptr, ACLNN_ERR_INNER_NULLPTR); + + *workspaceSize = uniqueExecutor->GetWorkspaceSize(); + uniqueExecutor.ReleaseTo(executor); + return ACLNN_SUCCESS; +} + +aclnnStatus aclnnXllmKernelQuantSparseLightningIndexerMetadataVa( + void* workspace, + uint64_t workspaceSize, + aclOpExecutor* executor, + aclrtStream stream) { + L2_DFX_PHASE_2(aclnnXllmKernelQuantSparseLightningIndexerMetadataVa); + return CommonOpExecutorRun(workspace, workspaceSize, executor, stream); +} + +#ifdef __cplusplus +} +#endif diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.h b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.h new file mode 100644 index 0000000000..d88a3d349f --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/aclnn_quant_sparse_lightning_indexer_metadata_va.h @@ -0,0 +1,58 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef ACLNN_QUANT_SPARSE_LIGHTNING_INDEXER_METADATA_VA_H +#define ACLNN_QUANT_SPARSE_LIGHTNING_INDEXER_METADATA_VA_H + +#include + +#include "aclnn/aclnn_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +__attribute__((visibility("default"))) aclnnStatus +aclnnXllmKernelQuantSparseLightningIndexerMetadataVaGetWorkspaceSize( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + const aclTensor* candidateBlockLengthOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + const aclTensor* metadata, + uint64_t* workspaceSize, + aclOpExecutor** executor); + +__attribute__((visibility("default"))) aclnnStatus +aclnnXllmKernelQuantSparseLightningIndexerMetadataVa(void* workspace, + uint64_t workspaceSize, + aclOpExecutor* executor, + aclrtStream stream); + +#ifdef __cplusplus +} +#endif + +#endif // ACLNN_QUANT_SPARSE_LIGHTNING_INDEXER_METADATA_VA_AICPU_H diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/quant_sparse_lightning_indexer_metadata_va.cpp b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/quant_sparse_lightning_indexer_metadata_va.cpp new file mode 100644 index 0000000000..6d65bccbe3 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/quant_sparse_lightning_indexer_metadata_va.cpp @@ -0,0 +1,130 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_sparse_lightning_indexer_metadata_va.cpp + * \brief + */ + +#include "quant_sparse_lightning_indexer_metadata_va.h" + +#include "opdev/aicpu/aicpu_task.h" +#include "opdev/make_op_executor.h" +#include "opdev/op_def.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "opdev/op_log.h" +#include "opdev/shape_utils.h" + +using namespace op; +namespace l0op { +OP_TYPE_REGISTER(XllmKernelQuantSparseLightningIndexerMetadataVa); + +const aclTensor* XllmKernelQuantSparseLightningIndexerMetadataVa( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + const aclTensor* candidateBlockLengthOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + int64_t aicCoreNum, + int64_t aivCoreNum, + const char* socVersion, + const aclTensor* metadata, + aclOpExecutor* executor) { + L0_DFX(XllmKernelQuantSparseLightningIndexerMetadataVa, + cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + candidateBlockLengthOptional, + numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + aicCoreNum, + aivCoreNum, + socVersion, + metadata); + + static internal::AicpuTaskSpace space( + "XllmKernelQuantSparseLightningIndexerMetadataVa"); + + auto ret = ADD_TO_LAUNCHER_LIST_AICPU( + XllmKernelQuantSparseLightningIndexerMetadataVa, + OP_ATTR_NAMES({"num_heads_q", + "num_heads_k", + "head_dim", + "topk", + "quant_mode", + "batch_size", + "max_seqlen_q", + "max_seqlen_k", + "layout_q", + "layout_k", + "mask_mode", + "cmp_ratio", + "aic_core_num", + "aiv_core_num", + "soc_version"}), + OP_INPUT(cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + candidateBlockLengthOptional), + OP_OUTPUT(metadata), + OP_ATTR(numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + aicCoreNum, + aivCoreNum, + socVersion)); + + OP_CHECK(ret == ACL_SUCCESS, + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, + "XllmKernelQuantSparseLightningIndexerMetadataVa " + "ADD_TO_LAUNCHER_LIST_AICPU failed."), + return nullptr); + return metadata; +} +} // namespace l0op diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/quant_sparse_lightning_indexer_metadata_va.h b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/quant_sparse_lightning_indexer_metadata_va.h new file mode 100644 index 0000000000..38b5145b65 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/op_api/quant_sparse_lightning_indexer_metadata_va.h @@ -0,0 +1,45 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#ifndef L0_QUANT_SPARSE_LIGHTNING_INDEXER_METADATA_VA_H +#define L0_QUANT_SPARSE_LIGHTNING_INDEXER_METADATA_VA_H + +#include "opdev/op_executor.h" + +namespace l0op { +const aclTensor* XllmKernelQuantSparseLightningIndexerMetadataVa( + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + const aclTensor* candidateBlockLengthOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + int64_t aicCoreNum, + int64_t aivCoreNum, + const char* socVersion, + const aclTensor* metadata, + aclOpExecutor* executor); +} // namespace l0op + +#endif diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/quant_sparse_lightning_indexer_metadata_va_check.h b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/quant_sparse_lightning_indexer_metadata_va_check.h new file mode 100644 index 0000000000..36717dfb84 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/quant_sparse_lightning_indexer_metadata_va_check.h @@ -0,0 +1,767 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_sparse_lightning_indexer_metadata_va_check.h + * \brief + */ + +#include "../../quant_lightning_indexer_v2_va/op_host/quant_lightning_indexer_v2_va_error_log.h" +#include "../../quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h" +#include "log/log.h" +#include "opdev/data_type_utils.h" +#include "opdev/format_utils.h" +#include "opdev/op_log.h" +#include "opdev/tensor_view_utils.h" + +#ifdef __cplusplus +extern "C" { +#endif + +namespace { + +static constexpr const char* QLI_V2_ACLNN_OP_NAME = + "XllmKernelQuantSparseLightningIndexerMetadataVa"; + +inline constexpr int64_t QLI_V2_QUANT_MODE_1 = 1; +inline constexpr int64_t QLI_V2_QUANT_MODE_2 = 2; +inline constexpr int64_t QLI_V2_QUANT_MODE_3 = 3; +inline constexpr int64_t QLI_V2_QUANT_MODE_4 = 4; +inline constexpr int64_t QLI_V2_QUANT_MODE_5 = 5; +inline constexpr int64_t QLI_V2_NO_MASK_MODE = 0; +inline constexpr int64_t QLI_V2_CAUSAL_MASK_MODE = 3; +inline constexpr int64_t QLI_V2_CMP_RATIO_LOWER_BOUND = 1; +inline constexpr int64_t QLI_V2_CMP_RATIO_UPPER_BOUND = 128; +inline constexpr int64_t QLI_V2_NUM_HEADS_Q_LOWER_BOUND = 1; +inline constexpr int64_t QLI_V2_NUM_HEADS_Q_UPPER_BOUND = 64; +inline constexpr int64_t QLI_V2_NUM_HEADS_Q_G32 = + 32; // g=32 支持 (A1 对齐 v1 推导) +inline constexpr int64_t QLI_V2_TOPK_LOWER_BOUND = 1; +inline constexpr int64_t QLI_V2_A5_TOPK_UPPER_BOUND = 8192; +inline constexpr int64_t QLI_V2_A3_TOPK_UPPER_BOUND = 2048; + +inline bool IsTensorExistQsli(const aclTensor* tensor) { + return (tensor != nullptr) && (tensor->GetViewShape().GetDimNum() > 0) && + (tensor->GetViewShape().GetDim(0) > 0); +} + +int64_t GetDimNumQsli(const aclTensor* tensor) { + if (tensor == nullptr) { + return -1; + } + return tensor->GetViewShape().GetDimNum(); +} + +aclDataType GetDataTypeQsli(const aclTensor* tensor) { + aclDataType dataType = aclDataType::ACL_DT_UNDEFINED; + if (tensor == nullptr) { + return dataType; + } + aclGetDataType(tensor, &dataType); + return dataType; +} + +inline bool IsTensorSourceQsli(const std::string& source) { + return source != "batch_size"; +} + +inline int64_t GetRawShapeSizeQsli(const std::string& source, + int64_t batchValue) { + if (source.find("cu_seqlens") != std::string::npos) { + return batchValue + 1; + } + return batchValue; +} + +int64_t GetQueryBatchSizeQsli(int64_t batchSize, + const aclTensor* cuSeqlensQOptional, + const aclTensor* sequsedQOptional, + const char* layoutQOptional, + std::string& source) { + // 1. 如果sequsedQOptional 传了,使用sequsedQOptional获取BatchSize + if (IsTensorExistQsli(sequsedQOptional)) { + source = "seqused_q"; + return sequsedQOptional->GetViewShape().GetDim(0); + } + // 2. 如果sequsedQOptional 没传,使用cuSeqlensQOptional获取BatchSize + if (strcmp(layoutQOptional, "TND") == 0) { + if (IsTensorExistQsli( + cuSeqlensQOptional)) { // 前序校验已保证layout_q = + // TND时,cu_seqlens_q必须传入,此通路必达 + source = "cu_seqlens_q"; + return cuSeqlensQOptional->GetViewShape().GetDim(0) - 1; + } + } + source = "batch_size"; + // 3. 使用batchSize + return batchSize; +} + +int64_t GetKeyBatchSizeQsli(int64_t batchSize, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedKOptional, + const char* layoutKOptional, + std::string& source) { + // 1. 如果sequsedKOptional 传了,使用sequsedKOptional获取BatchSize + if (IsTensorExistQsli(sequsedKOptional)) { + source = "seqused_q"; + return sequsedKOptional->GetViewShape().GetDim(0); + } + // 如果是 TND,必须使用 cuSeqlensKOptional获取BatchSize + if (strcmp(layoutKOptional, "TND") == 0) { + if (IsTensorExistQsli( + cuSeqlensKOptional)) { // 前序校验已保证layout_k = + // TND时,cu_seqlens_k必须传入,此通路必达 + source = "cu_seqlens_q"; + return cuSeqlensKOptional->GetViewShape().GetDim(0) - 1; + } + } + source = "batch_size"; + // 3. 使用batchSize + return batchSize; +} + +aclnnStatus CheckSingleParamQsli(int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + const char* layoutQOptional, + const char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + uint32_t aicCoreNum, + uint32_t aivCoreNum, + const std::string& socVersion) { + // num_heads_k 校验 + if (numHeadsK != 1) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "num_heads_kv", + std::to_string(numHeadsK), + "The value of num_heads_kv should be 1"); + return ACLNN_ERR_PARAM_INVALID; + } + // head_dim 校验 + if (headDim != 128) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "head_dim", + std::to_string(numHeadsK), + "The value of head_dim should be 128"); + return ACLNN_ERR_PARAM_INVALID; + } + // batch_size 非负校验 + if (batchSize < 0) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "batch_size", + std::to_string(batchSize), + "The value of batch_size should not be negative"); + return ACLNN_ERR_PARAM_INVALID; + } + // max_seqlen_q 校验 + if (maxSeqlenQ < -1) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_q", + std::to_string(maxSeqlenQ), + "The value of max_seqlen_q should be >= -1"); + return ACLNN_ERR_PARAM_INVALID; + } + // max_seqlen_k 校验 + if (maxSeqlenK < -1) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_k", + std::to_string(maxSeqlenK), + "The value of max_seqlen_k should be >= -1"); + return ACLNN_ERR_PARAM_INVALID; + } + // mask_mode 校验 + if ((maskMode != QLI_V2_NO_MASK_MODE) && + (maskMode != QLI_V2_CAUSAL_MASK_MODE)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "mask_mode", + std::to_string(maskMode), + "The value of mask_mode should be " + + std::to_string(QLI_V2_NO_MASK_MODE) + " or " + + std::to_string(QLI_V2_CAUSAL_MASK_MODE)); + return ACLNN_ERR_PARAM_INVALID; + } + // layout_q 校验 + if (layoutQOptional == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, "layout_q", "Layout_q is null"); + return ACLNN_ERR_PARAM_INVALID; + } + if ((strcmp(layoutQOptional, "TND") != 0) && + (strcmp(layoutQOptional, "BSND") != 0)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "layout_q", + layoutQOptional, + "The value of layout_q must be TND or BSND"); + return ACLNN_ERR_PARAM_INVALID; + } + // layout_k 校验 + if (layoutKOptional == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, "layout_k", "Layout_k is null"); + return ACLNN_ERR_PARAM_INVALID; + } + if ((strcmp(layoutKOptional, "PA_BBND") != 0) && + (strcmp(layoutQOptional, layoutKOptional) != 0)) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "layout_q and layout_k", + std::string(layoutQOptional) + " and " + std::string(layoutKOptional), + "For layout_k != PA_BBND, layout_q and layout_k must be the same"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 A2/A3 参数 + if (socVersion.find("Ascend950") == std::string::npos) { + // num_heads_q 校验 (g=64/32, 32 参照 v1 对齐 mBaseSize=4*g 推导) + CHECK_COND((numHeadsQ == QLI_V2_NUM_HEADS_Q_UPPER_BOUND) || + (numHeadsQ == QLI_V2_NUM_HEADS_Q_G32), + ACLNN_ERR_PARAM_INVALID, + "num_heads_q should be %lld or %lld, but got %lld", + QLI_V2_NUM_HEADS_Q_UPPER_BOUND, + QLI_V2_NUM_HEADS_Q_G32, + numHeadsQ); + // topk 校验 + CHECK_COND( + topk >= QLI_V2_TOPK_LOWER_BOUND && topk <= QLI_V2_A3_TOPK_UPPER_BOUND, + ACLNN_ERR_PARAM_INVALID, + "topk should be [%lld, %lld], but got %lld", + QLI_V2_TOPK_LOWER_BOUND, + QLI_V2_A3_TOPK_UPPER_BOUND, + topk); + // quant_mode 校验 + CHECK_COND(quantMode == QLI_V2_QUANT_MODE_2, + ACLNN_ERR_PARAM_INVALID, + "quant_mode should be 2, but got %lld", + quantMode); + // cmp_ratio 校验 + CHECK_COND((cmpRatio >= QLI_V2_CMP_RATIO_LOWER_BOUND) && + (cmpRatio <= QLI_V2_CMP_RATIO_UPPER_BOUND) && + ((cmpRatio & (cmpRatio - 1)) == 0), + ACLNN_ERR_PARAM_INVALID, + "cmp_ratio should be 1/2/4/8/16/32/64/128, but got %lld", + cmpRatio); + CHECK_COND(strcmp(layoutKOptional, "PA_BBND") == 0, + ACLNN_ERR_PARAM_INVALID, + "layout_k must be PA_BBND, but got %s", + layoutKOptional); + } else { // 校验 A5参数 + // num_heads_q 校验 + if (numHeadsQ < QLI_V2_NUM_HEADS_Q_LOWER_BOUND || + numHeadsQ > QLI_V2_NUM_HEADS_Q_UPPER_BOUND) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "num_heads_q", + std::to_string(numHeadsQ), + "The value of num_heads_q should be in range [" + + std::to_string(QLI_V2_NUM_HEADS_Q_LOWER_BOUND) + ", " + + std::to_string(QLI_V2_NUM_HEADS_Q_UPPER_BOUND) + "]"); + return ACLNN_ERR_PARAM_INVALID; + } + // topk 校验 + if (topk < QLI_V2_TOPK_LOWER_BOUND || topk > QLI_V2_A5_TOPK_UPPER_BOUND) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "topk", + std::to_string(topk), + "The value of topk should be in range [" + + std::to_string(QLI_V2_TOPK_LOWER_BOUND) + ", " + + std::to_string(QLI_V2_A5_TOPK_UPPER_BOUND) + "]"); + return ACLNN_ERR_PARAM_INVALID; + } + // quant_mode 校验 + if ((quantMode != QLI_V2_QUANT_MODE_1) && + (quantMode != QLI_V2_QUANT_MODE_2) && + (quantMode != QLI_V2_QUANT_MODE_3) && + (quantMode != QLI_V2_QUANT_MODE_4) && + (quantMode != QLI_V2_QUANT_MODE_5)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "quant_mode", + std::to_string(quantMode), + "The value of quant_mode should be in [" + + std::to_string(QLI_V2_QUANT_MODE_1) + ", " + + std::to_string(QLI_V2_QUANT_MODE_2) + ", " + + std::to_string(QLI_V2_QUANT_MODE_3) + ", " + + std::to_string(QLI_V2_QUANT_MODE_4) + ", " + + std::to_string(QLI_V2_QUANT_MODE_5) + "]"); + return ACLNN_ERR_PARAM_INVALID; + } + // cmp_ratio 校验 + if ((cmpRatio < QLI_V2_CMP_RATIO_LOWER_BOUND) || + (cmpRatio > QLI_V2_CMP_RATIO_UPPER_BOUND)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cmp_ratio", + std::to_string(cmpRatio), + "The value of cmp_ratio should be in range [" + + std::to_string(QLI_V2_CMP_RATIO_LOWER_BOUND) + ", " + + std::to_string(QLI_V2_CMP_RATIO_UPPER_BOUND) + "]"); + return ACLNN_ERR_PARAM_INVALID; + } + if ((strcmp(layoutKOptional, "TND") != 0) && + (strcmp(layoutKOptional, "BSND") != 0) && + (strcmp(layoutKOptional, "PA_BBND") != 0)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "layout_k", + layoutKOptional, + "The value of layout_k must be in [TND, BSND, PA_BBND]"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 layout_q 为 BSND 时,max_seqlen_q 必须大于 0 + if ((strcmp(layoutQOptional, "BSND") == 0) && (maxSeqlenQ <= 0)) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_q", + std::to_string(maxSeqlenQ), + "When layout_q is BSND, the value of max_seqlen_q " + "must be equal to the size of the second axis of q"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 layout_k 为 BSND 时,max_seqlen_k 必须大于 0 + if ((strcmp(layoutKOptional, "BSND") == 0) && (maxSeqlenK <= 0)) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_k", + std::to_string(maxSeqlenK), + "When layout_k is BSND, the value of max_seqlen_k " + "must be equal to the size of the second axis of k"); + return ACLNN_ERR_PARAM_INVALID; + } + // 核心数校验 + CHECK_COND(aicCoreNum > 0, + ACLNN_ERR_PARAM_INVALID, + "AIC num should be larger than 0, but got %u", + aicCoreNum); + CHECK_COND(aicCoreNum <= optiling::AIC_CORE_MAX_NUM, + ACLNN_ERR_PARAM_INVALID, + "The maximum supported AIC num is %u, but got %u", + optiling::AIC_CORE_MAX_NUM, + aicCoreNum); + CHECK_COND(aivCoreNum > 0, + ACLNN_ERR_PARAM_INVALID, + "AIV num should be larger than 0, but got %u", + aivCoreNum); + CHECK_COND(aivCoreNum <= optiling::AIV_CORE_MAX_NUM, + ACLNN_ERR_PARAM_INVALID, + "The maximum supported AIV num is %u, but got %u", + optiling::AIV_CORE_MAX_NUM, + aivCoreNum); + return ACLNN_SUCCESS; +} + +aclnnStatus CheckExistenceQsli(int64_t maskMode, + int64_t cmpRatio, + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + const char* layoutQOptional, + const char* layoutKOptional, + const aclTensor* metadata) { + // cu_seqlens_q 存在性校验 + if ((strcmp(layoutQOptional, "TND") == 0) && + !IsTensorExistQsli(cuSeqlensQOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_q", + "When layout_q is TND, cu_seqlens_q must be provided"); + return ACLNN_ERR_PARAM_INVALID; + } + // layout_q BSND, seqused_q 不存在时,max_seqlen_q 不能为-1 + if (strcmp(layoutQOptional, "BSND") == 0 && + !IsTensorExistQsli(sequsedQOptional) && (maxSeqlenQ <= -1)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_q", + std::to_string(maxSeqlenQ), + "When layout_q is BSND and seqused_q is not provided, max_seqlen_q can " + "not be -1"); + return ACLNN_ERR_PARAM_INVALID; + } + // cu_seqlens_k 存在性校验 + if ((strcmp(layoutKOptional, "TND") == 0) && + !IsTensorExistQsli(cuSeqlensKOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_k", + "When layout_k is TND, cu_seqlens_k must be provided"); + return ACLNN_ERR_PARAM_INVALID; + } + // seqused_k 存在性校验 + if ((strcmp(layoutKOptional, "PA_BBND") == 0) && + !IsTensorExistQsli(sequsedKOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "seqused_k", + "When layout_k is PA_BBND, seqused_k must be provided"); + return ACLNN_ERR_PARAM_INVALID; + } + // layout_k BSND, seqused_k 不存在时,max_seqlen_k 不能为-1 + if (strcmp(layoutKOptional, "BSND") == 0 && + !IsTensorExistQsli(sequsedKOptional) && maxSeqlenK <= -1) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "max_seqlen_k", + std::to_string(maxSeqlenK), + "When layout_k is BSND and seqused_k is not provided, max_seqlen_k can " + "not be -1"); + return ACLNN_ERR_PARAM_INVALID; + } + // cmp_residual_k 存在性校验 + if ((cmpRatio != QLI_V2_CMP_RATIO_LOWER_BOUND) && + (maskMode == QLI_V2_CAUSAL_MASK_MODE) && + !IsTensorExistQsli(cmpResidualKOptional)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cmp_residual_k", + "When cmp_ratio is not 1 and mask_mode is CAUSAL, cmp_residual_k must " + "be provided"); + return ACLNN_ERR_PARAM_INVALID; + } + // metadata 存在性校验 + if (!IsTensorExistQsli(metadata)) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, "metadata", "Metadata is nullptr"); + return ACLNN_ERR_PARAM_INVALID; + } + return ACLNN_SUCCESS; +} + +aclnnStatus CheckConsistencyQsli(int64_t batchSize, + const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + const char* layoutQOptional, + const char* layoutKOptional, + const aclTensor* metadata) { + int64_t dimNum = -1; + aclDataType dataType = aclDataType::ACL_DT_UNDEFINED; + + // 校验 cu_seqlens_q + if (IsTensorExistQsli(cuSeqlensQOptional)) { + dimNum = GetDimNumQsli(cuSeqlensQOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "cu_seqlens_q", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQsli(cuSeqlensQOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_q", + ToString(dataType).GetString(), + "The dtype of cu_seqlens_q must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 cu_seqlens_k + if (IsTensorExistQsli(cuSeqlensKOptional)) { + dimNum = GetDimNumQsli(cuSeqlensKOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "cu_seqlens_k", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQsli(cuSeqlensKOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_k", + ToString(dataType).GetString(), + "The dtype of cu_seqlens_k must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 seqused_q + if (IsTensorExistQsli(sequsedQOptional)) { + dimNum = GetDimNumQsli(sequsedQOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "seqused_q", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQsli(sequsedQOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "seqused_q", + ToString(dataType).GetString(), + "The dtype of seqused_q must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 seqused_k + if (IsTensorExistQsli(sequsedKOptional)) { + dimNum = GetDimNumQsli(sequsedKOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "seqused_k", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQsli(sequsedKOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "seqused_k", + ToString(dataType).GetString(), + "The dtype of seqused_k must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 cmp_residual_k + if (IsTensorExistQsli(cmpResidualKOptional)) { + dimNum = GetDimNumQsli(cmpResidualKOptional); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "cmp_residual_k", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQsli(cmpResidualKOptional); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cmp_residual_k", + ToString(dataType).GetString(), + "The dtype of cmp_residual_k must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 metadata + if (IsTensorExistQsli(metadata)) { + dimNum = GetDimNumQsli(metadata); + if (dimNum != 1) { + OP_LOGE_FOR_INVALID_SHAPEDIM( + QLI_V2_ACLNN_OP_NAME, "metadata", std::to_string(dimNum), "1"); + return ACLNN_ERR_PARAM_INVALID; + } + dataType = GetDataTypeQsli(metadata); + if (dataType != aclDataType::ACL_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "metadata", + ToString(dataType).GetString(), + "The dtype of metadata must be int32"); + return ACLNN_ERR_PARAM_INVALID; + } + // 校验 metadata 元素数 + if (metadata->GetViewShape().GetDim(0) != + optiling::QLI_V2_METADATA_TOTAL_SIZE) { + OP_LOGE(ACLNN_ERR_PARAM_INVALID, + "The element num of metadata must be %u, but got %lld", + optiling::QLI_V2_METADATA_TOTAL_SIZE, + metadata->GetViewShape().GetDim(0)); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验batch + std::string querySource; + std::string keySource; + int64_t queryBatchSize = GetQueryBatchSizeQsli(batchSize, + cuSeqlensQOptional, + sequsedQOptional, + layoutQOptional, + querySource); + int64_t keyBatchSize = GetKeyBatchSizeQsli(batchSize, + cuSeqlensKOptional, + sequsedKOptional, + layoutKOptional, + keySource); + if (queryBatchSize != keyBatchSize) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + querySource + " and " + keySource, + std::to_string(GetRawShapeSizeQsli(querySource, queryBatchSize)) + + " and " + + std::to_string(GetRawShapeSizeQsli(keySource, keyBatchSize)), + "The batch_size obtained from query should be the same as that " + "obtained from key"); + if (IsTensorSourceQsli(querySource) && IsTensorSourceQsli(keySource)) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + querySource + " and " + keySource, + std::to_string(GetRawShapeSizeQsli(querySource, queryBatchSize)) + + " and " + + std::to_string(GetRawShapeSizeQsli(keySource, keyBatchSize)), + "The batch_size obtained from query should be the same as that " + "obtained from key"); + } else if (IsTensorSourceQsli(querySource)) { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + querySource, + std::to_string(GetRawShapeSizeQsli(querySource, queryBatchSize)), + "The batch_size obtained from query should be the same as that " + "obtained from key"); + } else { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + keySource, + std::to_string(GetRawShapeSizeQsli(keySource, keyBatchSize)), + "The batch_size obtained from query should be the same as that " + "obtained from key"); + } + return ACLNN_ERR_PARAM_INVALID; + } + // 校验TND场景q维度一致性 + if (strcmp(layoutQOptional, "TND") == 0 && + IsTensorExistQsli(sequsedQOptional)) { + int64_t cuSeqlensQBatchSize = + cuSeqlensQOptional->GetViewShape().GetDim(0) - 1; + CHECK_COND(cuSeqlensQBatchSize == queryBatchSize, + ACLNN_ERR_PARAM_INVALID, + "When layout_q is TND and seqused_q is passed, The batch_size " + "obtained from cu_seqlens_q should be the " + "same as that obtained from seqused_q, but got %lld and %lld", + cuSeqlensQBatchSize, + queryBatchSize); + if (cuSeqlensQBatchSize != queryBatchSize) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_q and seqused_q", + std::to_string(cuSeqlensQBatchSize) + " and " + + std::to_string(queryBatchSize), + "When layout_q is TND and seqused_q is passed, " + "the shape size of cu_seqlens_q minus 1 must be equal to " + "the shape size of seqused_q"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验TND场景k维度一致性 + if (strcmp(layoutKOptional, "TND") == 0 && + IsTensorExistQsli(sequsedKOptional)) { + int64_t cuSeqlensKBatchSize = + cuSeqlensKOptional->GetViewShape().GetDim(0) - 1; + if (cuSeqlensKBatchSize != keyBatchSize) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cu_seqlens_k and seqused_k", + std::to_string(cuSeqlensKBatchSize) + " and " + + std::to_string(keyBatchSize), + "When layout_k is TND and seqused_k is passed, " + "the shape size of cu_seqlens_k minus 1 must be equal to " + "the shape size of seqused_k"); + return ACLNN_ERR_PARAM_INVALID; + } + } + // 校验 cmp_residual_k 元素数 + auto cmpResidualKBatch = cmpResidualKOptional->GetViewShape().GetDim(0); + if (IsTensorExistQsli(cmpResidualKOptional) && + (cmpResidualKBatch != queryBatchSize)) { + if (IsTensorSourceQsli(querySource)) { + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cmp_residual_k and " + querySource, + std::to_string(cmpResidualKBatch) + " and " + + std::to_string(GetRawShapeSizeQsli(querySource, queryBatchSize)), + "The batch_size of cmp_residual_k should match the valid batch size"); + } else { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + QLI_V2_ACLNN_OP_NAME, + "cmp_residual_k", + std::to_string(cmpResidualKBatch), + "The batch_size of cmp_residual_k should match the valid batch size"); + } + return ACLNN_ERR_PARAM_INVALID; + } + return ACLNN_SUCCESS; +} + +aclnnStatus ParamsCheckQsli(const aclTensor* cuSeqlensQOptional, + const aclTensor* cuSeqlensKOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKOptional, + const aclTensor* cmpResidualKOptional, + int64_t numHeadsQ, + int64_t numHeadsK, + int64_t headDim, + int64_t topk, + int64_t quantMode, + int64_t batchSize, + int64_t maxSeqlenQ, + int64_t maxSeqlenK, + char* layoutQOptional, + char* layoutKOptional, + int64_t maskMode, + int64_t cmpRatio, + const aclTensor* metadata, + uint32_t aicCoreNum, + uint32_t aivCoreNum, + const std::string& socVersion) { + auto ret = CheckSingleParamQsli(numHeadsQ, + numHeadsK, + headDim, + topk, + quantMode, + batchSize, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + maskMode, + cmpRatio, + aicCoreNum, + aivCoreNum, + socVersion); + CHECK_RET(ret == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); + + ret = CheckExistenceQsli(maskMode, + cmpRatio, + cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + maxSeqlenQ, + maxSeqlenK, + layoutQOptional, + layoutKOptional, + metadata); + CHECK_RET(ret == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); + + ret = CheckConsistencyQsli(batchSize, + cuSeqlensQOptional, + cuSeqlensKOptional, + sequsedQOptional, + sequsedKOptional, + cmpResidualKOptional, + layoutQOptional, + layoutKOptional, + metadata); + CHECK_RET(ret == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); + + return ACLNN_SUCCESS; +} +} // namespace + +#ifdef __cplusplus +} +#endif diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/quant_sparse_lightning_indexer_metadata_va_infershape.cpp b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/quant_sparse_lightning_indexer_metadata_va_infershape.cpp new file mode 100644 index 0000000000..a4c2c905a1 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_host/quant_sparse_lightning_indexer_metadata_va_infershape.cpp @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_sparse_lightning_indexer_metadata_va_infershape.cpp + * \brief + */ +#include "../../quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h" +#include "register/op_impl_registry.h" + +using namespace ge; + +namespace ops { +static ge::graphStatus InferShapeQuantSparseLightningIndexerMetadata( + gert::InferShapeContext* context) { + gert::Shape* oShape = context->GetOutputShape(0); + oShape->SetDimNum(1); + oShape->SetDim(0, optiling::QLI_V2_METADATA_TOTAL_SIZE); + return GRAPH_SUCCESS; +} + +static ge::graphStatus InferDtypeQuantSparseLightningIndexerMetadata( + gert::InferDataTypeContext* context) { + context->SetOutputDataType(0, DT_INT32); + return GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(XllmKernelQuantSparseLightningIndexerMetadataVa) + .InferShape(InferShapeQuantSparseLightningIndexerMetadata) + .InferDataType(InferDtypeQuantSparseLightningIndexerMetadata); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.cpp b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.cpp new file mode 100644 index 0000000000..c7d63841d5 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.cpp @@ -0,0 +1,1245 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +#include "quant_sparse_lightning_indexer_metadata_va_aicpu.h" + +#include +#include +#include +#include + +using namespace optiling; + +namespace aicpu::xllm_qsli { +uint32_t QuantSparseLightningIndexerMetadataCpuKernel::Compute( + CpuKernelContext& ctx) { + bool success = Prepare(ctx); + if (!success) { + return KERNEL_STATUS_PARAM_INVALID; + } + SplitResult splitRes{aicCoreNum_, aivCoreNum_}; + success = BalanceSchedule(splitRes) && GenMetadata(splitRes); + return success ? KERNEL_STATUS_OK : KERNEL_STATUS_PARAM_INVALID; +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::Prepare( + CpuKernelContext& ctx) { + // input + cuSeqlensQ_ = ctx.Input(static_cast(ParamId::actSeqLenQ)); + cuSeqlensK_ = ctx.Input(static_cast(ParamId::actSeqLenK)); + sequsedQ_ = ctx.Input(static_cast(ParamId::seqUsedQ)); + sequsedK_ = ctx.Input(static_cast(ParamId::seqUsedK)); + cmpResidualK_ = ctx.Input(static_cast(ParamId::cmpResidualK)); + candidateBlockLength_ = + ctx.Input(static_cast(ParamId::candidateBlockLength)); + // output + metadata_ = ctx.Output(static_cast(ParamId::metadata)); + + bool requiredAttrs = GetAttrValue(ctx, "aic_core_num", aicCoreNum_) && + GetAttrValue(ctx, "aiv_core_num", aivCoreNum_) && + GetAttrValue(ctx, "soc_version", socVersion_) && + GetAttrValue(ctx, "num_heads_q", numHeadsQ_) && + GetAttrValue(ctx, "num_heads_k", numHeadsK_) && + GetAttrValue(ctx, "head_dim", headDim_) && + GetAttrValue(ctx, "topk", topk_); + if (!requiredAttrs) { + return false; + } + + // attributes optional + GetAttrValueOpt(ctx, "batch_size", batchSize_); + GetAttrValueOpt(ctx, "max_seqlen_q", maxSeqlenQ_); + GetAttrValueOpt(ctx, "max_seqlen_k", maxSeqlenK_); + GetAttrValueOpt(ctx, "layout_q", layoutQ_); + GetAttrValueOpt(ctx, "layout_k", layoutK_); + GetAttrValueOpt(ctx, "mask_mode", maskMode_); + GetAttrValueOpt(ctx, "cmp_ratio", cmpRatio_); + + return (ParamsCheck() && ParamsInit()); +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::ParamsCheck() { + if (metadata_ == nullptr) { + KERNEL_LOG_ERROR("Output metadata is nullptr"); + return false; + } else if (metadata_->GetData() == nullptr) { + KERNEL_LOG_ERROR("Output metadata data is nullptr"); + return false; + } + const int32_t batchSize = GetQueryBatchSize(); + return CheckCuSeqlensQ(batchSize) && CheckCuSeqlensK(batchSize) && + CheckSequsedQ(batchSize) && CheckSequsedK(batchSize) && + CheckCmpResidualK(batchSize) && CheckCandidateBlockLength(); +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::CheckCuSeqlensQ( + int32_t batchSize) const { + if (layoutQ_ != "TND" || cuSeqlensQ_ == nullptr || + cuSeqlensQ_->GetData() == nullptr) { + return true; + } + const int32_t* cuSeqlensQPtr = + static_cast(cuSeqlensQ_->GetData()); + if (cuSeqlensQPtr[0] != 0) { + KERNEL_LOG_ERROR( + "The first element of cu_seqlens_q should be 0, but got %d", + cuSeqlensQPtr[0]); + return false; + } + for (int32_t i = 1; i < batchSize + 1; ++i) { + if (cuSeqlensQPtr[i - 1] > cuSeqlensQPtr[i]) { + KERNEL_LOG_ERROR( + "The elements in cu_seqlens_q must be in ascending order, " + "but got cu_seqlens_q[%d] = %d, cu_seqlens_q[%d] = %d", + i - 1, + cuSeqlensQPtr[i - 1], + i, + cuSeqlensQPtr[i]); + return false; + } + } + return true; +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::CheckCuSeqlensK( + int32_t batchSize) const { + if (layoutK_ != "TND" || cuSeqlensK_ == nullptr || + cuSeqlensK_->GetData() == nullptr) { + return true; + } + const int32_t* cuSeqlensKPtr = + static_cast(cuSeqlensK_->GetData()); + if (cuSeqlensKPtr[0] != 0) { + KERNEL_LOG_ERROR( + "The first element of cu_seqlens_k should be 0, but got %d", + cuSeqlensKPtr[0]); + return false; + } + for (int32_t i = 1; i < batchSize + 1; ++i) { + if (cuSeqlensKPtr[i - 1] > cuSeqlensKPtr[i]) { + KERNEL_LOG_ERROR( + "The elements in cu_seqlens_k must be in ascending order, " + "but got cu_seqlens_k[%d] = %d, cu_seqlens_k[%d] = %d", + i - 1, + cuSeqlensKPtr[i - 1], + i, + cuSeqlensKPtr[i]); + return false; + } + } + return true; +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::CheckSequsedQ( + int32_t batchSize) const { + if (sequsedQ_ == nullptr || sequsedQ_->GetData() == nullptr) { + return true; + } + const int32_t* sequsedQPtr = + static_cast(sequsedQ_->GetData()); + const int32_t* cuSeqlensQPtr = + (layoutQ_ == "TND" && cuSeqlensQ_ != nullptr && + cuSeqlensQ_->GetData() != nullptr) + ? static_cast(cuSeqlensQ_->GetData()) + : nullptr; + for (int32_t i = 0; i < batchSize; ++i) { + if (sequsedQPtr[i] < 0) { + KERNEL_LOG_ERROR( + "The elements in seqused_q should be >= 0, but got seqused_q[%d] = " + "%d", + i, + sequsedQPtr[i]); + return false; + } + if (layoutQ_ == "BSND" && sequsedQPtr[i] > maxSeqlenQ_) { + KERNEL_LOG_ERROR( + "The elements in seqused_q should not be greater than max_seqlen_q " + "%d, " + "but got seqused_q[%d] = %d", + maxSeqlenQ_, + i, + sequsedQPtr[i]); + return false; + } + if (cuSeqlensQPtr != nullptr) { + const int32_t seqLen = cuSeqlensQPtr[i + 1] - cuSeqlensQPtr[i]; + if (sequsedQPtr[i] > seqLen) { + KERNEL_LOG_ERROR( + "The elements in seqused_q should not be greater than the sequence " + "length " + "from cu_seqlens_q %d, but got seqused_q[%d] = %d", + seqLen, + i, + sequsedQPtr[i]); + return false; + } + } + } + return true; +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::CheckSequsedK( + int32_t batchSize) const { + if (sequsedK_ == nullptr || sequsedK_->GetData() == nullptr) { + return true; + } + const int32_t* sequsedKPtr = + static_cast(sequsedK_->GetData()); + const int32_t* cuSeqlensKPtr = + (layoutK_ == "TND" && cuSeqlensK_ != nullptr && + cuSeqlensK_->GetData() != nullptr) + ? static_cast(cuSeqlensK_->GetData()) + : nullptr; + for (int32_t i = 0; i < batchSize; ++i) { + if (sequsedKPtr[i] < 0) { + KERNEL_LOG_ERROR( + "The elements in seqused_k should be >= 0, but got seqused_k[%d] = " + "%d", + i, + sequsedKPtr[i]); + return false; + } + if (layoutK_ == "BSND" && sequsedKPtr[i] > maxSeqlenK_) { + KERNEL_LOG_ERROR( + "The elements in seqused_k should not be greater than max_seqlen_k " + "%d, " + "but got seqused_k[%d] = %d", + maxSeqlenK_, + i, + sequsedKPtr[i]); + return false; + } + if (cuSeqlensKPtr != nullptr) { + const int32_t seqLen = cuSeqlensKPtr[i + 1] - cuSeqlensKPtr[i]; + if (sequsedKPtr[i] > seqLen) { + KERNEL_LOG_ERROR( + "The elements in seqused_k should not be greater than the sequence " + "length " + "from cu_seqlens_k %d, but got seqused_k[%d] = %d", + seqLen, + i, + sequsedKPtr[i]); + return false; + } + } + } + return true; +} + +// candidate_block_length 的校验与统计:语义与 DSL 一致 —— +// 每行有效候选块数,取值 [0, 2048]。 分核 cost model 与 DSL metadata +// 对齐:每行工作量 = max(L)×8 token(tile 粒度 256), 贪心均分(costLimit = +// 剩余负载 // 剩余核数;无 FD 时 limit 以最大行负载兜底)。 +bool QuantSparseLightningIndexerMetadataCpuKernel::CheckCandidateBlockLength() { + if (candidateBlockLength_ == nullptr || + candidateBlockLength_->GetData() == nullptr) { + KERNEL_LOG_ERROR("candidate_block_length is required for QSLI metadata"); + return false; + } + if (candidateBlockLength_->GetDataType() != DataType::DT_INT32) { + KERNEL_LOG_ERROR("candidate_block_length should be int32"); + return false; + } + constexpr int32_t kMaxCandidateBlocks = 2048; // DSL 契约:候选块长度上界 + const auto shape = candidateBlockLength_->GetTensorShape(); + if (shape == nullptr || + (shape->GetDims() != 1 && + (shape->GetDims() != 2 || shape->GetDimSize(1) != 1))) { + KERNEL_LOG_ERROR("Expected candidate lengths of shape [rows] or [rows, 1]"); + return false; + } + const int64_t rowCount = shape->GetDimSize(0); + const int32_t batch = GetQueryBatchSize(); + if (layoutQ_ == "TND") { + if (cuSeqlensQ_ == nullptr || cuSeqlensQ_->GetData() == nullptr || + static_cast(cuSeqlensQ_->GetData())[batch] > rowCount) { + KERNEL_LOG_ERROR("Candidate lengths do not cover the TND query rows"); + return false; + } + } else if (static_cast(batch) * maxSeqlenQ_ > rowCount) { + KERNEL_LOG_ERROR("Candidate lengths do not cover the BSND query rows"); + return false; + } + const int32_t* lenPtr = + static_cast(candidateBlockLength_->GetData()); + for (int64_t i = 0; i < rowCount; ++i) { + const int32_t len = lenPtr[i]; + if (len < 0) { + KERNEL_LOG_ERROR("candidate_block_length[%ld] = %d should be >= 0", + static_cast(i), + len); + return false; + } + if (len > kMaxCandidateBlocks) { + KERNEL_LOG_ERROR("candidate_block_length[%ld] = %d should be <= %d", + static_cast(i), + len, + kMaxCandidateBlocks); + return false; + } + candLenMax_ = (len > candLenMax_) ? len : candLenMax_; + candLenSum_ += len; + } + return true; +} + +// QSLI:候选长度的行映射 —— TND: cu_seqlens_q 前缀;BSND: bIdx × max_seqlen_q +uint64_t QuantSparseLightningIndexerMetadataCpuKernel::CandidateRowPrefix( + uint32_t bIdx) { + if (layoutQ_ == "TND") { + if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { + const int32_t* p = static_cast(cuSeqlensQ_->GetData()); + return static_cast(p[bIdx]); + } + return 0ULL; + } + return static_cast(bIdx) * static_cast(maxSeqlenQ_); +} + +int64_t QuantSparseLightningIndexerMetadataCpuKernel::CandidateTokensForBatch( + uint32_t bIdx) { + const int32_t* lenPtr = + static_cast(candidateBlockLength_->GetData()); + const uint64_t prefix = CandidateRowPrefix(bIdx); + const uint32_t s1Size = GetS1SeqSize(bIdx); + int64_t maxL = 0; + for (uint32_t i = 0; i < s1Size; i++) { + const int32_t l = lenPtr[prefix + i]; + if (l > maxL) { + maxL = l; + } + } + return maxL * 8; +} + +int64_t QuantSparseLightningIndexerMetadataCpuKernel::CandidateTokensForS1G( + uint32_t bIdx, + uint32_t s1GIdx) { + const int32_t* lenPtr = + static_cast(candidateBlockLength_->GetData()); + const uint64_t prefix = CandidateRowPrefix(bIdx); + const uint32_t rowsPerBlock = static_cast(mBaseSize_ / groupSize_); + const uint32_t s1Size = GetS1SeqSize(bIdx); + const uint32_t base = s1GIdx * rowsPerBlock; + int64_t maxL = 0; + for (uint32_t i = 0; i < rowsPerBlock && base + i < s1Size; i++) { + const int32_t l = lenPtr[prefix + base + i]; + if (l > maxL) { + maxL = l; + } + } + return maxL * 8; +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::CheckCmpResidualK( + int32_t batchSize) const { + if (cmpResidualK_ == nullptr || cmpResidualK_->GetData() == nullptr) { + return true; + } + const int32_t* cmpResidualKPtr = + static_cast(cmpResidualK_->GetData()); + for (int32_t i = 0; i < batchSize; ++i) { + if (cmpResidualKPtr[i] < 0 || cmpResidualKPtr[i] >= cmpRatio_) { + KERNEL_LOG_ERROR( + "The elements in cmp_residual_k should be in [0, cmpRatio_(%d)), but " + "got " + "cmp_residual_k[%d] = %d", + cmpRatio_, + i, + cmpResidualKPtr[i]); + return false; + } + } + return true; +} + +int32_t QuantSparseLightningIndexerMetadataCpuKernel::GetQueryBatchSize() { + // 1. 如果sequsedQ_传了,使用sequsedQ_获取BatchSize + if (sequsedQ_ != nullptr && sequsedQ_->GetData() != nullptr) { + if (sequsedQ_->GetTensorShape() != nullptr) { + return sequsedQ_->GetTensorShape()->GetDimSize(0); + } + } + // 2. sequsedQ_ 没传,判断 Layout + if (layoutQ_ == "TND") { + // 如果是 TND,尝试使用 cuSeqlensQ_获取BatchSize + if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { + if (cuSeqlensQ_->GetTensorShape() != nullptr) { + return cuSeqlensQ_->GetTensorShape()->GetDimSize(0) - 1; + } + } + } + // 3. 如果不是 TND,或者 cuSeqlensQ_ 为空,使用batchSize_ + return batchSize_; +} + +ValidSocVersion +QuantSparseLightningIndexerMetadataCpuKernel::ProcessSocVersion() { + const std::string ascend950 = "Ascend950"; + if (socVersion_.find(ascend950) != std::string::npos) { + return ValidSocVersion::ASCEND950; + } else { + return ValidSocVersion::ASCEND910B; + } +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::ParamsInit() { + batchSize_ = GetQueryBatchSize(); + auto mode = static_cast(maskMode_); + if (mode == SparseMode::RIGHT_DOWN_CAUSAL) { + attentionMode_ = 1; + preToken_ = INT64_MAX; + } else if (mode == SparseMode::DEFAULT_MASK) { + attentionMode_ = 0; + } else if (mode == SparseMode::BAND) { + attentionMode_ = 1; + } + groupSize_ = + static_cast(numHeadsQ_) / static_cast(numHeadsK_); + ValidSocVersion validSocVersion = ProcessSocVersion(); + if (validSocVersion == ValidSocVersion::ASCEND910B) { + mBaseSize_ = s1BaseSize_ * groupSize_; + s2BaseSize_ = 2048U; + } else if (validSocVersion == ValidSocVersion::ASCEND950) { + if (static_cast(topk_) > TOPK_6K) { + s1BaseSize_ = S1_BASE_SIZE_SMALL; + } + mBaseSize_ = s1BaseSize_ * groupSize_; + s2BaseSize_ = 128U; + } else { + mBaseSize_ = s1BaseSize_ * groupSize_; + s2BaseSize_ = 128U; + } + return true; +} + +uint32_t QuantSparseLightningIndexerMetadataCpuKernel::GetS1SeqSize( + uint32_t bIdx) { + // 1. 如果 sequsedQ_ 传了,直接使用 + if (sequsedQ_ != nullptr && sequsedQ_->GetData() != nullptr) { + const int32_t* seqUsedPtr = + static_cast(sequsedQ_->GetData()); + return static_cast(seqUsedPtr[bIdx]); + } + // 2. sequsedQ_ 没传,判断 Layout + if (layoutQ_ == "TND") { + // 如果是 TND,尝试使用 cuSeqlensQ_ + if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { + const int32_t* s1Ptr = + static_cast(cuSeqlensQ_->GetData()); + return static_cast(s1Ptr[bIdx + 1U] - s1Ptr[bIdx]); + } + } + // 3. 如果不是 TND,或者 cuSeqlensQ_ 为空,使用 querySeqSize_ + return static_cast(maxSeqlenQ_); +} + +uint32_t QuantSparseLightningIndexerMetadataCpuKernel::GetS2SeqSize( + uint32_t bIdx) { + // 如果 seqUsedKv_ 传了,直接使用 + if (sequsedK_ != nullptr && sequsedK_->GetData() != nullptr) { + const int32_t* seqUsedPtr = + static_cast(sequsedK_->GetData()); + return static_cast(seqUsedPtr[bIdx]); + } + // seqUsedKv_ 没传,判断 Layout + if (layoutK_ == "TND") { + // 如果是 TND,尝试使用 actSeqLenOriKv_ + if (cuSeqlensK_ != nullptr && cuSeqlensK_->GetData() != nullptr) { + const int32_t* s2Ptr = + static_cast(cuSeqlensK_->GetData()); + return static_cast(s2Ptr[bIdx + 1U] - s2Ptr[bIdx]); + } + } + // 使用 max_seqlen_k + return static_cast(maxSeqlenK_); +} + +uint64_t QuantSparseLightningIndexerMetadataCpuKernel::GetRevertS2Size( + uint32_t bIdx) { + uint32_t cmpS2Size = GetS2SeqSize(bIdx); + if (cmpResidualK_ != nullptr && cmpResidualK_->GetData() != nullptr) { + const int32_t* residualPtr = + static_cast(cmpResidualK_->GetData()); + return static_cast(cmpS2Size) * static_cast(cmpRatio_) + + static_cast(residualPtr[bIdx]); + } else { + return static_cast(cmpS2Size) * static_cast(cmpRatio_); + } +} + +void QuantSparseLightningIndexerMetadataCpuKernel::CalcSplitInfo( + SplitContext& splitContext) { + // 计算每个batch的切分,统计是否为空batch,记录最后有效batch(每个batch的每个N2切分是一样的) + SplitInfo& splitInfo = splitContext.splitInfo; + for (uint32_t bIdx = 0; bIdx < static_cast(batchSize_); bIdx++) { + uint32_t s1Size = GetS1SeqSize(bIdx); + const int64_t maxTok = CandidateTokensForBatch(bIdx); + maxS2Size_ = std::max(maxS2Size_, static_cast(maxTok)); + splitInfo.s1GBaseNum[bIdx] = + (static_cast(s1Size) * groupSize_ + (mBaseSize_ - 1U)) / + mBaseSize_; + splitInfo.s1GTailSize[bIdx] = + (static_cast(s1Size) * groupSize_) % mBaseSize_; + splitInfo.s2BaseNum[bIdx] = static_cast( + (maxTok + CandidateTileTokens() - 1) / CandidateTileTokens()); + splitInfo.s2TailSize[bIdx] = + static_cast(maxTok % CandidateTileTokens()); + if (splitInfo.s1GBaseNum[bIdx] != 0U && splitInfo.s2BaseNum[bIdx] != 0U) { + splitInfo.isKvSeqAllZero = false; + } + } + // V2(2026-11-05):QSLI 候选 × FD 分片开启(主算子 v16 已适配 tile 区间 + + // partial 溢写, 见 + // scripts/prof_output/qli_v2_caseopt/RESULT_candidate_driven.md §27)。 + // 判定沿用 QLI metadata 的结构、单位换成候选语义:maxS2Size_ 此时是 max(L)×8 + // 的候选 token 数, "块" = CandidateTileTokens()(512 token = 64 + // 候选块)——max(L) > 5×64=320 块才开 FD; maxS2Size_ < topk + // 时不开(每个分片须能凑满 topk 才能归约)。 + if (maxS2Size_ < static_cast(topk_)) { + supportFd_ = false; + return; + } + // V2.1(2026-11-05 晚修正):不设"行数饱和就不切"的门槛 —— 交替背靠背实测 + // case C(32 块/20 核,整行调度下 12 核扛 2 块)开 FD 反而 −2.3%~−3.2%: + // 分片的负载再平衡收益 > 溢写/归约/暖机开销。仅保留代价阈值(L > 5×64=320 + // 块)。 + supportFd_ = (maxS2Size_ > fdToleranceRatio * CandidateTileTokens()); +} + +int64_t QuantSparseLightningIndexerMetadataCpuKernel::CalcPreTokenLeftUp( + uint32_t s1Size, + uint64_t s2Size) const { + auto mode = static_cast(maskMode_); + if (mode == SparseMode::BAND) { + return static_cast(s1Size) - static_cast(s2Size) + + preToken_; + } + return preToken_; +} + +int64_t QuantSparseLightningIndexerMetadataCpuKernel::CalcNextTokenLeftUp( + uint32_t s1Size, + uint64_t s2Size) const { + auto mode = static_cast(maskMode_); + switch (mode) { + case SparseMode::DEFAULT_MASK: + case SparseMode::ALL_MASK: + case SparseMode::LEFT_UP_CAUSAL: + return nextToken_; + case SparseMode::RIGHT_DOWN_CAUSAL: + return static_cast(s2Size) - static_cast(s1Size); + case SparseMode::BAND: + return static_cast(s2Size) - static_cast(s1Size) + + nextToken_; + default: + return nextToken_; + } +} + +int64_t QuantSparseLightningIndexerMetadataCpuKernel::CalcCost( + uint32_t basicM, + uint32_t basicS2) const { + uint32_t alignCoefM = 16U; + uint32_t alignCoefS2 = 64U; + uint32_t alignBasicM = (basicM + alignCoefM - 1U) >> + 4U; // 按alignCoefM对齐,向上取整,4:移位操作实现除16 + uint32_t alignBasicS2 = + (basicS2 + alignCoefS2 - 1U) >> + 6U; // 按alignCoefS2对齐,向上取整,6:移位操作实现除64 + return static_cast(COST_WEIGHT_M * alignBasicM + + COST_WEIGHT_S2 * alignBasicS2); +} + +BlockCost QuantSparseLightningIndexerMetadataCpuKernel::CalcCostTable( + uint32_t s1NormalSize, + uint32_t s2NormalSize, + uint32_t s1GTailSize, + uint32_t s2TailSize) const { + BlockCost typeCost{}; + typeCost[NORMAL_BLOCK][NORMAL_BLOCK] = CalcCost(s1NormalSize, s2NormalSize); + typeCost[TAIL_BLOCK][NORMAL_BLOCK] = + (s1GTailSize == 0U) ? 0U : CalcCost(s1GTailSize, s2NormalSize); + typeCost[NORMAL_BLOCK][TAIL_BLOCK] = + (s2TailSize == 0U) ? 0U : CalcCost(s1NormalSize, s2TailSize); + typeCost[TAIL_BLOCK][TAIL_BLOCK] = (s1GTailSize == 0U || s2TailSize == 0U) + ? 0U + : CalcCost(s1GTailSize, s2TailSize); + return typeCost; +} + +Range QuantSparseLightningIndexerMetadataCpuKernel::CalcS2TokenRange( + uint32_t s1GIdx, + const BatchCache& batchCache) { + // no mask + if (!attentionMode_) { + return std::make_pair(0, static_cast(batchCache.revertS2Size)); + } + + // 1. calc index of s2FirstToken, s2LastToken by index of s1GFirstToken, + // s1GLastToken + int64_t s1GFirstToken = + static_cast(s1GIdx) * static_cast(mBaseSize_); + int64_t s1GLastToken = + std::min(s1GFirstToken + static_cast(mBaseSize_), + static_cast(batchCache.s1Size) * + static_cast(groupSize_)) - + 1; + int64_t s1FirstToken = 0; + int64_t s1LastToken = 0; + if (isS1G_) { + s1FirstToken = s1GFirstToken / static_cast(groupSize_); + s1LastToken = s1GLastToken / static_cast(groupSize_); + } else { + if (s1GFirstToken / batchCache.s1Size == s1GLastToken / batchCache.s1Size) { + // start and end locate in one G + s1FirstToken = s1GFirstToken % static_cast(batchCache.s1Size); + s1LastToken = s1GLastToken % static_cast(batchCache.s1Size); + } else { + // start and end locate in two or more G, but working same as crossing a + // complete block + s1FirstToken = 0; + s1LastToken = batchCache.s1Size; + } + } + + int64_t s2FirstToken = s1FirstToken - batchCache.preTokenLeftUp; + int64_t s2LastToken = s1LastToken + batchCache.nextTokenLeftUp; + + return std::make_pair(s2FirstToken, s2LastToken); +} + +void QuantSparseLightningIndexerMetadataCpuKernel::CalcBatchCache( + uint32_t bIdx, + const SplitContext& splitContext, + BatchCache& batchCache) { + const SplitInfo& splitInfo = splitContext.splitInfo; + + batchCache.bIdx = bIdx; + batchCache.s1Size = GetS1SeqSize(bIdx); + batchCache.revertS2Size = GetRevertS2Size(bIdx); + batchCache.preTokenLeftUp = + CalcPreTokenLeftUp(batchCache.s1Size, batchCache.revertS2Size); + batchCache.nextTokenLeftUp = + CalcNextTokenLeftUp(batchCache.s1Size, batchCache.revertS2Size); +} + +void QuantSparseLightningIndexerMetadataCpuKernel::CalcS1GCache( + uint32_t s1GIdx, + const SplitContext& splitContext, + const BatchCache& batchCache, + S1GCache& s1GCache) { + const SplitInfo& splitInfo = splitContext.splitInfo; + + s1GCache.bIdx = batchCache.bIdx; + s1GCache.s1GIdx = s1GIdx; + + if (splitInfo.s1GBaseNum[batchCache.bIdx] == 0 || + splitInfo.s2BaseNum[batchCache.bIdx] == 0) { + s1GCache.s1GBlock = 0; + s1GCache.s1GCost = 0; + s1GCache.s1GLastBlockCost = 0; + s1GCache.s1GNormalBlockCost = 0; + return; + } + + // QSLI:工作量 = 本行块内 max(L)×8 token,tile 粒度 256(不走 causal + // 区间;可见性由主算子掩码) + const uint32_t s2BlockTokens = CandidateTileTokens(); + int64_t s2CmpLength = CandidateTokensForS1G(batchCache.bIdx, s1GIdx); + if (s2CmpLength <= 0) { + s1GCache.s2Start = 0U; + s1GCache.s2End = 0U; + } else { + s1GCache.s2Start = 0U; + // end of block index, Right-open interval + s1GCache.s2End = (static_cast(s2CmpLength) + s2BlockTokens - 1) / + s2BlockTokens; + } + + if (s1GCache.s2Start >= s1GCache.s2End) { + s1GCache.s1GBlock = 0; + s1GCache.s1GCost = 0; + s1GCache.s1GLastBlockCost = 0; + s1GCache.s1GNormalBlockCost = 0; + return; + } + + uint32_t s2TailSize = static_cast(s2CmpLength) % s2BlockTokens; + + // 计算S2方向满块、尾块数量 + s1GCache.s1GBlock = s1GCache.s2End - s1GCache.s2Start; + uint32_t curTailS2Num = s2TailSize != 0 ? 1U : 0U; + uint32_t curNormalS2Num = s1GCache.s1GBlock - curTailS2Num; + + BlockCost typeCost = + CalcCostTable(mBaseSize_, + s2BlockTokens, + splitInfo.s1GTailSize[batchCache.bIdx], + s2TailSize); + + if (s1GIdx == (splitInfo.s1GBaseNum[batchCache.bIdx] - 1U) && + splitInfo.s1GTailSize[batchCache.bIdx] != 0U) { + s1GCache.s1GCost = typeCost[TAIL_BLOCK][NORMAL_BLOCK] * curNormalS2Num + + typeCost[TAIL_BLOCK][TAIL_BLOCK] * curTailS2Num; + s1GCache.s1GLastBlockCost = curTailS2Num > 0U + ? typeCost[TAIL_BLOCK][TAIL_BLOCK] + : typeCost[TAIL_BLOCK][NORMAL_BLOCK]; + s1GCache.s1GNormalBlockCost = typeCost[TAIL_BLOCK][NORMAL_BLOCK]; + } else { + s1GCache.s1GCost = typeCost[NORMAL_BLOCK][NORMAL_BLOCK] * curNormalS2Num + + typeCost[NORMAL_BLOCK][TAIL_BLOCK] * curTailS2Num; + s1GCache.s1GLastBlockCost = curTailS2Num > 0U + ? typeCost[NORMAL_BLOCK][TAIL_BLOCK] + : typeCost[NORMAL_BLOCK][NORMAL_BLOCK]; + s1GCache.s1GNormalBlockCost = typeCost[NORMAL_BLOCK][NORMAL_BLOCK]; + } +} + +void QuantSparseLightningIndexerMetadataCpuKernel::CalcBatchCost( + uint32_t bIdx, + const SplitContext& splitContext, + CostInfo& costInfo) { + const SplitInfo& splitInfo = splitContext.splitInfo; + + costInfo.bN2CostOfEachBatch[bIdx] = 0; + costInfo.bN2BlockOfEachBatch[bIdx] = 0U; + costInfo.bN2LastBlockCostOfEachBatch[bIdx] = 0U; + + if (GetS1SeqSize(bIdx) == 0U || GetS2SeqSize(bIdx) == 0U) { + return; + } + + BatchCache bCache; + S1GCache s1GCache; + CalcBatchCache(bIdx, splitContext, bCache); + for (uint32_t s1GIdx = 0; s1GIdx < splitInfo.s1GBaseNum[bIdx]; s1GIdx++) { + CalcS1GCache(s1GIdx, splitContext, bCache, s1GCache); + costInfo.bN2CostOfEachBatch[bIdx] += s1GCache.s1GCost; + costInfo.bN2BlockOfEachBatch[bIdx] += s1GCache.s1GBlock; + // 更新最大S1G行开销 + if (s1GCache.s1GCost > costInfo.maxS1GCost) { + costInfo.maxS1GCost = s1GCache.s1GCost; + } + + if (s1GCache.s1GBlock > 0) { + costInfo.bN2LastBlockCostOfEachBatch[bIdx] = s1GCache.s1GLastBlockCost; + } + } +} + +void QuantSparseLightningIndexerMetadataCpuKernel::CalcCostInfo( + SplitContext& splitContext) { + const SplitInfo& splitInfo = splitContext.splitInfo; + CostInfo& costInfo = splitContext.costInfo; + + if (splitInfo.isKvSeqAllZero) { + costInfo.totalCost = 0; + costInfo.totalBlockNum = 0U; + return; + } + + // 计算batch的负载并记录,用于按batch分配,需要按行计算起止点,统计块数、负载 + for (uint32_t bIdx = 0; bIdx < static_cast(batchSize_); bIdx++) { + CalcBatchCost(bIdx, splitContext, costInfo); + costInfo.totalCost += costInfo.bN2CostOfEachBatch[bIdx] * numHeadsK_; + costInfo.totalBlockNum += + costInfo.bN2BlockOfEachBatch[bIdx] * static_cast(numHeadsK_); + } +} + +void QuantSparseLightningIndexerMetadataCpuKernel::UpdateCursor( + const SplitContext& splitContext, + AssignContext& assignContext) { + const SplitInfo& splitInfo = splitContext.splitInfo; + const CostInfo& costInfo = splitContext.costInfo; + + bool UpdateS1G = false; + bool UpdateBatch = false; + + // Update S2 + if (assignContext.curS2Idx >= + assignContext.s1GCache.s2End) { // 边界assignInfo.s2End是取不到的开区间 + assignContext.curS2Idx = 0U; + assignContext.curS1GIdx++; + UpdateS1G = true; + } + + // Update S1G + if (assignContext.curS1GIdx >= splitInfo.s1GBaseNum[assignContext.curBIdx]) { + assignContext.curS1GIdx = 0U; + assignContext.curBN2Idx++; + } + + // Update Batch + if (assignContext.curBN2Idx == + static_cast(batchSize_) * + static_cast(numHeadsK_)) { // 所有负载全部分配完 + assignContext.curS1GIdx = 0U; + assignContext.curS2Idx = 0U; + assignContext.isFinished = true; + return; + } + + if (assignContext.curBN2Idx / static_cast(numHeadsK_) != + assignContext.curBIdx) { + assignContext.curBIdx = + assignContext.curBN2Idx / static_cast(numHeadsK_); + assignContext.curS1GIdx = 0U; + UpdateBatch = true; + UpdateS1G = true; + } + + // Update Cache + if (UpdateBatch) { + CalcBatchCache( + assignContext.curBIdx, splitContext, assignContext.batchCache); + assignContext.bN2Cost = costInfo.bN2CostOfEachBatch[assignContext.curBIdx]; + assignContext.bN2Block = + costInfo.bN2BlockOfEachBatch[assignContext.curBIdx]; + } + if (UpdateS1G) { + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + } +} + +void QuantSparseLightningIndexerMetadataCpuKernel::AssignByBatch( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + const CostInfo& costInfo = splitContext.costInfo; + while (assignContext.bN2Cost == 0 || + IsWithinTolerance( + assignContext.coreCache.costLimit, + costInfo.bN2LastBlockCostOfEachBatch[assignContext.curBIdx] / + FA_TOLERANCE_RATIO, + assignContext.coreCache.cost + assignContext.bN2Cost)) { + assignContext.coreCache.cost += assignContext.bN2Cost; + assignContext.coreCache.block += assignContext.bN2Block; + assignContext.curBN2Idx++; + + // to the end + if (assignContext.curBN2Idx == + static_cast(batchSize_) * static_cast(numHeadsK_)) { + assignContext.curS1GIdx = 0U; + assignContext.curS2Idx = 0U; + assignContext.isFinished = true; + return; + } + + // next batch + if (assignContext.curBN2Idx / static_cast(numHeadsK_) != + assignContext.curBIdx) { + assignContext.curBIdx = + assignContext.curBN2Idx / static_cast(numHeadsK_); + CalcBatchCache( + assignContext.curBIdx, splitContext, assignContext.batchCache); + } + + assignContext.bN2Cost = costInfo.bN2CostOfEachBatch[assignContext.curBIdx]; + assignContext.bN2Block = + costInfo.bN2BlockOfEachBatch[assignContext.curBIdx]; + assignContext.curS1GIdx = 0U; + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + } +} + +void QuantSparseLightningIndexerMetadataCpuKernel::AssignByRow( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + + while (IsWithinTolerance( + assignContext.coreCache.costLimit, + assignContext.s1GCache.s1GLastBlockCost / FA_TOLERANCE_RATIO, + assignContext.coreCache.cost + assignContext.s1GCache.s1GCost)) { + assignContext.coreCache.cost += assignContext.s1GCache.s1GCost; + assignContext.coreCache.block += assignContext.s1GCache.s1GBlock; + + // 当前batch被分配一行出去,更新剩余负载 + assignContext.bN2Cost = + assignContext.bN2Cost > assignContext.s1GCache.s1GCost + ? assignContext.bN2Cost - assignContext.s1GCache.s1GCost + : 0; + assignContext.bN2Block = + assignContext.bN2Block > assignContext.s1GCache.s1GBlock + ? assignContext.bN2Block - assignContext.s1GCache.s1GBlock + : 0U; + // 计算新一行的信息 + do { + assignContext.curS1GIdx++; + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + } while (assignContext.s1GCache.s1GBlock == 0); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + } +} + +void QuantSparseLightningIndexerMetadataCpuKernel::AssignByBlock( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + + int64_t curCost = assignContext.s1GCache.s1GNormalBlockCost; + if (assignContext.curS2Idx == (assignContext.s1GCache.s2End - 1U)) { + curCost = assignContext.s1GCache.s1GLastBlockCost; + } + + // (costLimit - curCostOnCore) * FA_TOLERANCE_RATIO > curCost;至少分配1块 + while (IsWithinTolerance(assignContext.coreCache.costLimit, + curCost / FA_TOLERANCE_RATIO, + assignContext.coreCache.cost + curCost)) { + assignContext.coreCache.cost += curCost; + assignContext.coreCache.block++; + assignContext.curS2Idx++; + // 当前batch被分配一块出去,更新剩余负载 + assignContext.bN2Cost = assignContext.bN2Cost - curCost; + // 当前行被分配一块出去,更新剩余负载 + assignContext.s1GCache.s1GCost = assignContext.s1GCache.s1GCost - curCost; + assignContext.bN2Block--; + assignContext.s1GCache.s1GBlock--; + } +} + +void QuantSparseLightningIndexerMetadataCpuKernel::ForceAssign( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + + int64_t curCost = assignContext.s1GCache.s1GNormalBlockCost; + if (assignContext.curS2Idx == (assignContext.s1GCache.s2End - 1U)) { + curCost = assignContext.s1GCache.s1GLastBlockCost; + } + + assignContext.coreCache.cost += curCost; + assignContext.coreCache.block++; + assignContext.curS2Idx++; + // 当前batch被分配一块出去,更新剩余负载 + assignContext.bN2Cost = assignContext.bN2Cost - curCost; + assignContext.bN2Block--; + // 当前行被分配一块出去,更新剩余负载 + assignContext.s1GCache.s1GCost = assignContext.s1GCache.s1GCost - curCost; + assignContext.s1GCache.s1GBlock--; + UpdateCursor(splitContext, assignContext); +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::IsNeedRecordFDInfo( + const AssignContext& assignContext, + const SplitResult& splitRes) { + // 切分点大概率不会刚好在行尾,因此滞后处理归约信息的统计,到下一个切分点再判断是否需要归约 + // 核0无需处理 + if (assignContext.curCoreIdx == 0U) { + return false; + } + // 无跨核行,无需处理 + if (assignContext.curKvSplitPart <= 1U) { + return false; + } + // 需要归约的行还未处理完 + if (assignContext.curBN2Idx == + splitRes.bN2End[assignContext.curCoreIdx - 1U] && + assignContext.curS1GIdx == + splitRes.gS1End[assignContext.curCoreIdx - 1U]) { + return false; + } + return true; +} + +void QuantSparseLightningIndexerMetadataCpuKernel::RecordFDInfo( + const SplitContext& splitContext, + const AssignContext& assignContext, + SplitResult& result) { + const SplitInfo& splitInfo = splitContext.splitInfo; + // 需要规约的行是上一个核的切分点所在位置 + uint32_t splitBIdx = result.bN2End[assignContext.curCoreIdx - 1U] / + static_cast(numHeadsK_); + uint32_t splitS1GIdx = result.gS1End[assignContext.curCoreIdx - 1U]; + uint32_t s1Size = GetS1SeqSize(splitBIdx); + + // 计算归约数据的FD均衡划分信息 + uint32_t curFdS1gSize = + (splitS1GIdx == splitInfo.s1GBaseNum[splitBIdx] - 1U) + ? (static_cast(s1Size) * groupSize_ - + static_cast(splitS1GIdx) * mBaseSize_) + : mBaseSize_; + // 记录 + result.maxS2SplitNum = + std::max(result.maxS2SplitNum, assignContext.curKvSplitPart); + // 若存在头归约,则切分点一定为上一个核结束的位置 + result.fdRes.fdBN2Idx[result.numOfFdHead] = + result.bN2End[assignContext.curCoreIdx - 1U]; + result.fdRes.fdMIdx[result.numOfFdHead] = + result.gS1End[assignContext.curCoreIdx - 1U]; + result.fdRes.fdWorkspaceIdx[result.numOfFdHead] = assignContext.preFdDataNum; + result.fdRes.fdS2SplitNum[result.numOfFdHead] = assignContext.curKvSplitPart; + result.fdRes.fdMSize[result.numOfFdHead] = curFdS1gSize / groupSize_; + result.numOfFdHead++; +} + +void QuantSparseLightningIndexerMetadataCpuKernel::AssignBlockToCore( + const SplitContext& splitContext, + AssignContext& assignContext, + SplitResult& result) { + const CostInfo& costInfo = splitContext.costInfo; + result.firstFdDataWorkspaceIdx[assignContext.curCoreIdx] = + assignContext.preFdDataNum + assignContext.curKvSplitPart - 1U; + assignContext.coreCache = {}; + assignContext.coreCache.costLimit = + assignContext.unassignedCost / (aicCoreNum_ - assignContext.curCoreIdx); + if (!supportFd_) { + assignContext.coreCache.costLimit = + costInfo.maxS1GCost > assignContext.coreCache.costLimit + ? costInfo.maxS1GCost + : assignContext.coreCache.costLimit; + } + // 1、按整batch分配 + AssignByBatch(splitContext, assignContext); + // 2、按行分配 + AssignByRow(splitContext, assignContext); + // 3、按块分配 + if (supportFd_) { + AssignByBlock(splitContext, assignContext); + // 4、强制分配 + if (assignContext.coreCache.block == 0) { + ForceAssign(splitContext, assignContext); + } + } + result.bN2End[assignContext.curCoreIdx] = assignContext.curBN2Idx; + result.gS1End[assignContext.curCoreIdx] = assignContext.curS1GIdx; + result.s2End[assignContext.curCoreIdx] = assignContext.curS2Idx; + result.maxCost = std::max(result.maxCost, assignContext.coreCache.cost); + assignContext.unassignedCost -= assignContext.coreCache.cost; + // 对之前的归约信息进行记录并清理 + if (supportFd_ && IsNeedRecordFDInfo(assignContext, result)) { + RecordFDInfo(splitContext, assignContext, result); + assignContext.preFdDataNum += assignContext.curKvSplitPart; + assignContext.curKvSplitPart = 1U; + } + // 更新S2切分信息 + if (supportFd_ && assignContext.curS2Idx > assignContext.s1GCache.s2Start && + assignContext.curS2Idx <= assignContext.s1GCache.s2End) { + assignContext.curKvSplitPart++; + } +} + +void QuantSparseLightningIndexerMetadataCpuKernel::CalcSplitPlan( + int64_t costLimit, + const SplitContext& splitContext, + SplitResult& result) { + const CostInfo& costInfo = splitContext.costInfo; + if (aicCoreNum_ == 0U) { + return; + } + result.maxCost = 0U; + result.usedCoreNum = 0U; + AssignContext assignContext{}; + assignContext.curBIdx = 0U; + assignContext.curS1GIdx = 0U; + assignContext.unassignedCost = costInfo.totalCost; + assignContext.bN2Cost = costInfo.bN2CostOfEachBatch[assignContext.curBIdx]; + assignContext.bN2Block = costInfo.bN2BlockOfEachBatch[assignContext.curBIdx]; + CalcBatchCache(assignContext.curBIdx, splitContext, assignContext.batchCache); + CalcS1GCache(assignContext.curS1GIdx, + splitContext, + assignContext.batchCache, + assignContext.s1GCache); + assignContext.curS2Idx = assignContext.s1GCache.s2Start; + for (uint32_t i = 0; i < aicCoreNum_; ++i) { + if (result.maxCost > costLimit) { + return; + } + if (assignContext.isFinished || assignContext.unassignedCost <= 0) { + break; + } + assignContext.curCoreIdx = i; + AssignBlockToCore(splitContext, assignContext, result); + // Keep trailing zero-cost batches in the last AIC range so their outputs + // are initialized. + if (!assignContext.isFinished && assignContext.unassignedCost <= 0) { + result.bN2End[i] = + static_cast(batchSize_) * static_cast(numHeadsK_); + result.gS1End[i] = 0U; + result.s2End[i] = 0U; + assignContext.isFinished = true; + } + } + result.usedCoreNum = assignContext.curCoreIdx + 1; +} + +void QuantSparseLightningIndexerMetadataCpuKernel::SplitFD( + SplitResult& splitRes) { + // 计算FD的总数据量 + uint64_t totalFDLoad = 0; + for (uint32_t i = 0; i < splitRes.numOfFdHead; i++) { + totalFDLoad += splitRes.fdRes.fdS2SplitNum[i] * splitRes.fdRes.fdMSize[i]; + } + // 计算当前最大冗余vec核数 + uint32_t emptyVectorNum = aivCoreNum_ - splitRes.numOfFdHead; + // 计算每个核处理的load + // 向上取整,避免核负载为0 + uint64_t averageLoad = (totalFDLoad + aivCoreNum_ - 1U) / aivCoreNum_; + uint32_t curCoreIndex = 0; + for (uint32_t i = 0; i < splitRes.numOfFdHead; i++) { + // 冗余vec核数为0,此时规约任务无法进行更小的切分,只能1个vec核计算1个规约任务 + if (emptyVectorNum == 0U) { + splitRes.fdRes.fdIdx[curCoreIndex] = i; + splitRes.fdRes.fdMStart[curCoreIndex] = 0U; + splitRes.fdRes.fdMNum[curCoreIndex] = splitRes.fdRes.fdMSize[i]; + curCoreIndex++; + continue; + } + // 计算当前归约任务所用核数,向下取整,避免使用核数超出总核数 + uint32_t curFDVectorNum = splitRes.fdRes.fdS2SplitNum[i] * + splitRes.fdRes.fdMSize[i] / averageLoad; + curFDVectorNum = std::max(1U, curFDVectorNum); + // 计算当前归约任务每个核的行数,向上取整,避免行数为0 + uint32_t curAveMSize = + (splitRes.fdRes.fdMSize[i] + curFDVectorNum - 1U) / curFDVectorNum; + curFDVectorNum = + (splitRes.fdRes.fdMSize[i] + curAveMSize - 1U) / curAveMSize; + // 需要使用的vec核数与当前剩余可用vec核数取最小 + curFDVectorNum = + std::min(curFDVectorNum, emptyVectorNum + 1U); // 1: Fd任务自身带一个核 + // FD负载分配 + for (uint32_t vid = 0; vid < curFDVectorNum; vid++) { + splitRes.fdRes.fdIdx[curCoreIndex] = i; + splitRes.fdRes.fdMStart[curCoreIndex] = vid * curAveMSize; + splitRes.fdRes.fdMNum[curCoreIndex] = + (vid < curFDVectorNum - 1) + ? curAveMSize + : (splitRes.fdRes.fdMSize[i] - vid * curAveMSize); + curCoreIndex++; + } + // 更新冗余vec核数 + emptyVectorNum -= (curFDVectorNum - 1U); // 1: 空余核不包含FD自身的核,要-1 + } + splitRes.fdRes.fdUsedVecNum = curCoreIndex; +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::BalanceSchedule( + SplitResult& splitRes) { + SplitContext splitContext(batchSize_); + // 1、划分基本块,统计信息 + CalcSplitInfo(splitContext); + // 全空case + if (splitContext.splitInfo.isKvSeqAllZero) { + splitRes.usedCoreNum = 1U; + splitRes.bN2End[0] = + static_cast(batchSize_) * static_cast(numHeadsK_); + splitRes.gS1End[0] = 0U; + splitRes.s2End[0] = 0U; + return true; + } + CalcCostInfo(splitContext); + + splitRes.maxCost = INT64_MAX; + splitRes.usedCoreNum = 1U; + CalcSplitPlan(splitRes.maxCost, splitContext, splitRes); + // 3、存在FD任务,对FD进行负载均衡分配 + if (supportFd_ && splitRes.numOfFdHead > 0U) { + SplitFD(splitRes); + } + splitRes.usedCoreNum = std::max(splitRes.usedCoreNum, 1U); // 至少使用1个core + return true; +} + +bool QuantSparseLightningIndexerMetadataCpuKernel::GenMetadata( + SplitResult& splitRes) { + optiling::detail::QliV2Metadata* metadataPtr = + static_cast(metadata_->GetData()); + // DSL 契约:输出为 int32[1024](128 条 × 8 字段)。QliV2Metadata 容器只覆盖 + // 36 条 LI + 72 条 LD = 864 个 int32,尾部保留区(行 + // 108..127)不在结构体内,必须显式清零; + // 否则返回给调用方的是未初始化的显存(实测两次调用结果不一致)。 + constexpr size_t kMetadataInt32Num = 1024; + int32_t* rawMetadata = static_cast(metadata_->GetData()); + for (size_t i = 0; i < kMetadataInt32Num; ++i) { + rawMetadata[i] = 0; + } + *metadataPtr = {}; + // LI Metadata Generate + for (size_t i = 0; i < aicCoreNum_; ++i) { + if (i >= splitRes.usedCoreNum) { + metadataPtr->qliV2Metadata[i][QLI_V2_CORE_ENABLE_INDEX] = + 0; // AIC disenable + continue; + } + metadataPtr->qliV2Metadata[i][QLI_V2_CORE_ENABLE_INDEX] = 1; // AIC enable + // FA START + metadataPtr->qliV2Metadata[i][QLI_V2_BN2_START_INDEX] = + i == 0 ? 0 : splitRes.bN2End[i - 1]; + metadataPtr->qliV2Metadata[i][QLI_V2_M_START_INDEX] = + i == 0 ? 0 : splitRes.gS1End[i - 1]; + metadataPtr->qliV2Metadata[i][QLI_V2_S2_START_INDEX] = + i == 0 ? 0 : splitRes.s2End[i - 1]; + // FA END + metadataPtr->qliV2Metadata[i][QLI_V2_BN2_END_INDEX] = splitRes.bN2End[i]; + metadataPtr->qliV2Metadata[i][QLI_V2_M_END_INDEX] = splitRes.gS1End[i]; + metadataPtr->qliV2Metadata[i][QLI_V2_S2_END_INDEX] = splitRes.s2End[i]; + metadataPtr + ->qliV2Metadata[i][QLI_V2_FIRST_QLD_V2_DATA_WORKSPACE_IDX_INDEX] = + splitRes.firstFdDataWorkspaceIdx[i]; + } + + // LD Metadata Generate + for (size_t i = 0; i < aivCoreNum_; ++i) { + if (i >= splitRes.fdRes.fdUsedVecNum) { + metadataPtr->qldV2Metadata[i][QLD_V2_CORE_ENABLE_INDEX] = + 0; // AIV disenable + continue; + } + metadataPtr->qldV2Metadata[i][QLD_V2_CORE_ENABLE_INDEX] = 1; // AIV enable + uint32_t curFdIdx = splitRes.fdRes.fdIdx[i]; + metadataPtr->qldV2Metadata[i][QLD_V2_BN2_IDX_INDEX] = + splitRes.fdRes.fdBN2Idx[curFdIdx]; + metadataPtr->qldV2Metadata[i][QLD_V2_M_IDX_INDEX] = + splitRes.fdRes.fdMIdx[curFdIdx]; + metadataPtr->qldV2Metadata[i][QLD_V2_WORKSPACE_IDX_INDEX] = + splitRes.fdRes.fdWorkspaceIdx[curFdIdx]; + metadataPtr->qldV2Metadata[i][QLD_V2_WORKSPACE_NUM_INDEX] = + splitRes.fdRes.fdS2SplitNum[curFdIdx]; + metadataPtr->qldV2Metadata[i][QLD_V2_M_START_INDEX] = + splitRes.fdRes.fdMStart[i]; + metadataPtr->qldV2Metadata[i][QLD_V2_M_NUM_INDEX] = + splitRes.fdRes.fdMNum[i]; + } + return true; +} + +} // namespace aicpu::xllm_qsli + +namespace aicpu { +namespace { +using xllm_qsli::QuantSparseLightningIndexerMetadataCpuKernel; +static const char* kernelType = + "XllmKernelQuantSparseLightningIndexerMetadataVa"; +REGISTER_CPU_KERNEL(kernelType, QuantSparseLightningIndexerMetadataCpuKernel); +} // namespace +} // namespace aicpu diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.h b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.h new file mode 100644 index 0000000000..dc149b9ed5 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.h @@ -0,0 +1,365 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under + * the terms and conditions of CANN Open Software License Agreement Version 2.0 + * (the "License"). Please refer to the License for details. You may not use + * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON + * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS + * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository + * for the full text of the License. + */ + +/*! + * \file quant_sparse_lightning_indexer_metadata_va_aicpu.h + * \brief + */ + +#ifndef QUANT_SPARSE_LIGHTNING_INDEXER_METADATA_VA_AICPU_H +#define QUANT_SPARSE_LIGHTNING_INDEXER_METADATA_VA_AICPU_H + +#include +#include +#include + +#include "../../quant_lightning_indexer_v2_va/op_kernel/quant_lightning_indexer_v2_metadata_va.h" +#include "cpu_context.h" +#include "cpu_kernel.h" +#include "cpu_tensor.h" +#include "log.h" +#include "quant_lightning_indexer_metadata/op_kernel_aicpu/cpu_context_util.h" + +namespace aicpu::xllm_qsli { +constexpr int64_t FA_TOLERANCE_RATIO = 2; +constexpr uint32_t COST_WEIGHT_M = 6U; +constexpr uint32_t COST_WEIGHT_S2 = 10U; +constexpr uint32_t S1_BASE_SIZE_SMALL = 2; +constexpr uint32_t TOPK_6K = 6144; + +enum BlockType : uint32_t { NORMAL_BLOCK = 0, TAIL_BLOCK, BLOCK_MAX_TYPE }; + +enum class SparseMode : uint8_t { + DEFAULT_MASK = 0, + ALL_MASK, + LEFT_UP_CAUSAL, + RIGHT_DOWN_CAUSAL, + BAND, + SPARSE_BUTT, +}; + +enum class ValidSocVersion { + ASCEND910B = 0, + ASCEND950, + RESERVED_VERSION = 99999 +}; + +template +using Range = std::pair; + +template +using BlockCost = std::array(BLOCK_MAX_TYPE)>, + static_cast(BLOCK_MAX_TYPE)>; + +template +T Clip(T value, T minValue, T maxValue) { + if (value < minValue) { + return minValue; + } + if (value > maxValue) { + return maxValue; + } + return value; +} + +template +inline bool IsWithinTolerance(T limit, T tolerance, T value) { + return limit + tolerance >= value; +} + +// 分核功能模块输出:FD信息,包含需要归约的数据索引及其分核信息 +struct FlashDecodeResult { + uint32_t fdUsedVecNum{0U}; // 归约过程使用的vector数量 + // 1、归约任务的索引信息 + std::vector + fdBN2Idx{}; // 每个归约任务的BN2索引,脚标为归约任务的序号,最大为核数-1 + std::vector + fdMIdx{}; // 每个归约任务的GS1索引,脚标为归约任务的序号 + std::vector + fdWorkspaceIdx{}; // 每个归约任务在workspace中的存放位置 + std::vector + fdS2SplitNum{}; // 每个归约任务的S2核间切分份数,脚标为归约任务的序号 + std::vector fdMSize{}; // 每个归约任务m轴大小,脚标为归约任务的序号 + // 2、FD负载均衡阶段,归约任务的分核(vec)信息 + std::vector + fdIdx{}; // FD负载均衡阶段,每个vector处理的归约任务对应ID + std::vector + fdMStart{}; // FD负载均衡阶段,每个vector处理的归约任务的m轴起点 + std::vector + fdMNum{}; // FD负载均衡阶段,每个vector处理的归约任务的m轴行数 + + FlashDecodeResult(uint32_t aicNum, uint32_t aivNum) + : fdBN2Idx(aicNum), + fdMIdx(aicNum), + fdWorkspaceIdx(aicNum), + fdS2SplitNum(aicNum), + fdMSize(aicNum), + fdIdx(aivNum), + fdMStart(aivNum), + fdMNum(aivNum) {} +}; + +// 分核功能模块输出:FA阶段的核间分核信息 +struct SplitResult { + uint32_t usedCoreNum{0U}; // 使用的核数量 + std::vector bN2End{}; // 每个核处理数据的BN2结束点 + std::vector gS1End{}; // 每个核处理数据的GS1结束点 + std::vector s2End{}; // 每个核处理数据的S2结束点 + std::vector + firstFdDataWorkspaceIdx{}; // 每个核第一份归约任务的存放位置 + int64_t maxCost{0}; // 慢核开销 + uint32_t numOfFdHead{0U}; // 归约任务数量 + uint32_t maxS2SplitNum{0U}; // 单个归约任务最大分核数量 + FlashDecodeResult fdRes{0U, 0U}; // FD信息 + + SplitResult(uint32_t aicNum, uint32_t aivNum) + : bN2End(aicNum), + gS1End(aicNum), + s2End(aicNum), + firstFdDataWorkspaceIdx(aicNum), + fdRes(aicNum, aivNum) {}; +}; + +// 分核功能模块内部使用:记录切分信息 +struct SplitInfo { + std::vector s1GBaseNum{}; // S1G方向,切了多少个基本块 + std::vector s2BaseNum{}; // S2方向,切了多少个基本块 + std::vector s1GTailSize{}; // S1G方向,尾块size + std::vector s2TailSize{}; // S2方向,尾块size + bool isKvSeqAllZero{true}; + + explicit SplitInfo(uint32_t batchSize) + : s1GBaseNum(batchSize), + s2BaseNum(batchSize), + s1GTailSize(batchSize), + s2TailSize(batchSize) {} +}; + +// 分核功能模块内部使用:记录batch的开销信息 +struct CostInfo { + std::vector bN2CostOfEachBatch{}; // 整个batch的开销 + std::vector bN2BlockOfEachBatch{}; // 整个batch的开销 + std::vector bN2LastBlockCostOfEachBatch{}; // batch最后一块的开销 + uint32_t totalBlockNum{0U}; + int64_t totalCost{0}; + uint64_t maxS1GCost{0}; // 新增 + + explicit CostInfo(uint32_t batchSize) + : bN2CostOfEachBatch(batchSize), + bN2BlockOfEachBatch(batchSize), + bN2LastBlockCostOfEachBatch(batchSize) {} +}; + +// 分核功能模块内部使用:分核过程中,case基本信息的上下文信息,组合以减少接口传参数量 +struct SplitContext { + SplitInfo splitInfo{0U}; + CostInfo costInfo{0U}; + + explicit SplitContext(uint32_t batchSize) + : splitInfo(batchSize), costInfo(batchSize) {} +}; + +// 分核功能模块内部使用:记录batch相关的临时信息 +struct BatchCache { + uint32_t bIdx{0U}; + uint32_t s1Size{0U}; + uint64_t revertS2Size{0U}; + int64_t preTokenLeftUp{0}; + int64_t nextTokenLeftUp{0}; + BlockCost typeCost{}; +}; + +// 分核功能模块内部使用:记录当前行(S1G)的临时信息 +struct S1GCache { + uint32_t bIdx{0U}; + uint32_t s1GIdx{0U}; + uint32_t s2Start{0U}; + uint32_t s2End{0U}; + int64_t s1GCost{0}; + int64_t s1GLastBlockCost{0}; + uint32_t s1GBlock{0U}; + int64_t s1GNormalBlockCost{0}; +}; + +// 分核功能模块内部使用:记录分配过程中,当前核的负载信息 +struct CoreCache { + int64_t costLimit{0}; // 负载上限 + int64_t cost{0}; // 已分配负载 + uint32_t block{0U}; // 已分配块数 +}; + +// 分核功能模块内部使用:记录分配过程中的上下文信息 +struct AssignContext { + uint32_t curBIdx{0U}; + uint32_t curBN2Idx{0U}; + uint32_t curS1GIdx{0U}; + uint32_t curS2Idx{0U}; + uint32_t curCoreIdx{0U}; + int64_t unassignedCost{0}; + uint32_t curKvSplitPart{1U}; + uint32_t preFdDataNum{0U}; + + int64_t bN2Cost{0}; + uint32_t bN2Block{0U}; + bool isFinished{false}; + BatchCache batchCache{}; + S1GCache s1GCache{}; + CoreCache coreCache{}; +}; +class QuantSparseLightningIndexerMetadataCpuKernel : public CpuKernel { + public: + QuantSparseLightningIndexerMetadataCpuKernel() = default; + ~QuantSparseLightningIndexerMetadataCpuKernel() = default; + uint32_t Compute(CpuKernelContext& ctx) override; + + private: + bool Prepare(CpuKernelContext& ctx); + bool ParamsCheck(); + bool CheckCuSeqlensQ(int32_t batchSize) const; + bool CheckCuSeqlensK(int32_t batchSize) const; + bool CheckSequsedQ(int32_t batchSize) const; + bool CheckSequsedK(int32_t batchSize) const; + bool CheckCmpResidualK(int32_t batchSize) const; + bool CheckCandidateBlockLength(); + // QSLI 调度:工作量 = max(L)×8 token,候选 tile = 512(与主算子一致) + bool HasCandidateLen() const { + return candidateBlockLength_ != nullptr && + candidateBlockLength_->GetData() != nullptr; + } + uint64_t CandidateRowPrefix(uint32_t bIdx); + int64_t CandidateTokensForBatch(uint32_t bIdx); + int64_t CandidateTokensForS1G(uint32_t bIdx, uint32_t s1GIdx); + uint32_t CandidateTileTokens() const { return 512U; } + int32_t GetQueryBatchSize(); + ValidSocVersion ProcessSocVersion(); + bool ParamsInit(); + bool BalanceSchedule(SplitResult& splitRes); + bool GenMetadata(SplitResult& splitRes); + + // util + uint32_t GetS1SeqSize(uint32_t bIdx); + uint32_t GetS2SeqSize(uint32_t bIdx); + uint64_t GetRevertS2Size(uint32_t bIdx); + int64_t CalcPreTokenLeftUp(uint32_t s1Size, uint64_t s2Size) const; + int64_t CalcNextTokenLeftUp(uint32_t s1Size, uint64_t s2Size) const; + Range CalcS2TokenRange(uint32_t s1GIdx, + const BatchCache& batchCache); + int64_t CalcCost(uint32_t basicM, uint32_t basicS2) const; + BlockCost CalcCostTable(uint32_t s1NormalSize, + uint32_t s2NormalSize, + uint32_t s1GTailSize, + uint32_t s2TailSize) const; + + // cache calculation + void CalcBatchCache(uint32_t bIdx, + const SplitContext& splitContext, + BatchCache& batchCache); + void CalcS1GCache(uint32_t s1GIdx, + const SplitContext& splitContext, + const BatchCache& batchCache, + S1GCache& s1GCache); + + // preprocess + void CalcSplitInfo(SplitContext& splitContext); + void CalcBatchCost(uint32_t bIdx, + const SplitContext& splitContext, + CostInfo& costInfo); + void CalcCostInfo(SplitContext& splitContext); + + // assign + void UpdateCursor(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignByBatch(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignByRow(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignByBlock(const SplitContext& splitContext, + AssignContext& assignContext); + void ForceAssign(const SplitContext& splitContext, + AssignContext& assignContext); + void AssignBlockToCore(const SplitContext& splitContext, + AssignContext& assignContext, + SplitResult& result); + + // FD + bool IsNeedRecordFDInfo(const AssignContext& assignContext, + const SplitResult& splitRes); + void RecordFDInfo(const SplitContext& splitContext, + const AssignContext& assignContext, + SplitResult& result); + + // main + void SplitFD(SplitResult& splitRes); + void CalcSplitPlan(int64_t costLimit, + const SplitContext& splitContext, + SplitResult& result); + + private: + // input + Tensor* cuSeqlensQ_ = nullptr; + Tensor* cuSeqlensK_ = nullptr; + Tensor* sequsedQ_ = nullptr; + Tensor* sequsedK_ = nullptr; + Tensor* cmpResidualK_ = nullptr; + // candidate_block_length(每行有效候选块数,int32,QSLI 必选输入):参与 cost + // model 调度 + Tensor* candidateBlockLength_ = nullptr; + int32_t candLenMax_ = 0; // 各行最大有效候选块数(未传时为 0) + int64_t candLenSum_ = + 0; // 各行有效候选块数之和(用于后续调度使用,本期仅记录) + // output + Tensor* metadata_ = nullptr; + // attributes + std::string socVersion_ = ""; + bool supportFd_ = false; + uint32_t aicCoreNum_ = optiling::AIC_CORE_MAX_NUM; + uint32_t aivCoreNum_ = optiling::AIV_CORE_MAX_NUM; + int32_t batchSize_ = 0; + int32_t maxSeqlenQ_ = 0; + int32_t maxSeqlenK_ = 0; + int32_t numHeadsQ_ = 0; + int32_t numHeadsK_ = 0; + int32_t headDim_ = 0; + int32_t quantMode_ = 0; + int32_t topk_ = 0; + std::string layoutQ_ = "BSND"; + std::string layoutK_ = "BSND"; + int32_t maskMode_ = 0; + int32_t cmpRatio_ = 1; + uint32_t attentionMode_ = 0; + + // SplitParams + int64_t preToken_ = INT64_MAX; + int64_t nextToken_ = INT64_MAX; + uint32_t groupSize_ = 0; + uint32_t mBaseSize_ = 256; + uint32_t s1BaseSize_ = 4; + uint32_t s2BaseSize_ = 128; + bool isS1G_ = true; + uint32_t maxS2Size_ = 0; + uint32_t fdToleranceRatio = 5U; + + private: + enum class ParamId : uint32_t { + // input + actSeqLenQ = 0, + actSeqLenK = 1, + seqUsedQ = 2, + seqUsedK = 3, + cmpResidualK = 4, + candidateBlockLength = 5, + // output + metadata = 0, + }; +}; +} // namespace aicpu::xllm_qsli +#endif diff --git a/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.json b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.json new file mode 100644 index 0000000000..3172b3ce13 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/quant_sparse_lightning_indexer_metadata_va/op_kernel_aicpu/quant_sparse_lightning_indexer_metadata_va_aicpu.json @@ -0,0 +1,15 @@ +{ + "XllmKernelQuantSparseLightningIndexerMetadataVa":{ + "opInfo":{ + "computeCost":"100", + "engine":"DNN_VM_AICPU", + "flagAsync":"False", + "flagPartial":"False", + "functionName":"RunCpuKernel", + "kernelSo":"libmath_aicpu_kernels.so", + "opKernelLib":"CUSTAICPUKernel", + "userDefined":"True", + "workspaceSize":"100" + } + } +} diff --git a/xllm-kernel/csrc/npu/v41_quant_indexer.cpp b/xllm-kernel/csrc/npu/v41_quant_indexer.cpp index 439d4b92de..e5eebd7b97 100644 --- a/xllm-kernel/csrc/npu/v41_quant_indexer.cpp +++ b/xllm-kernel/csrc/npu/v41_quant_indexer.cpp @@ -26,8 +26,18 @@ const auto& indexer_apis() { std::pair{ "aclnnXllmKernelQuantLightningIndexerV2MetadataVa", load_ascendc_api("aclnnXllmKernelQuantLightningIndexerV2MetadataVa", - "aclnnXllmKernelQuantLightningIndexerV2MetadataVaGet" - "WorkspaceSize")}, + "aclnnXllmKernelQuantLightningIndexerV2MetadataVa" + "GetWorkspaceSize")}, + std::pair{ + "aclnnXllmKernelQuantLightningIndexerV3Va", + load_ascendc_api( + "aclnnXllmKernelQuantLightningIndexerV3Va", + "aclnnXllmKernelQuantLightningIndexerV3VaGetWorkspaceSize")}, + std::pair{"aclnnXllmKernelQuantSparseLightningIndexerMetadataVa", + load_ascendc_api( + "aclnnXllmKernelQuantSparseLightningIndexerMetadataVa", + "aclnnXllmKernelQuantSparseLightningIndexerMetadataVa" + "GetWorkspaceSize")}, }; return apis; } @@ -43,7 +53,7 @@ void GetApiFunc(const char* name, return; } } - LOG(FATAL) << "Unknown QLI V2 entry point: " << name; + LOG(FATAL) << "Unknown QLI entry point: " << name; } void prepare_ascendc_v41_indexer() { indexer_apis(); } @@ -97,6 +107,51 @@ torch::Tensor quant_lightning_indexer_v2_metadata( return metadata; } +torch::Tensor quant_sparse_lightning_indexer_metadata( + const torch::Tensor& query_offsets, + const torch::Tensor& committed_lengths, + const std::optional& residual_lengths, + const torch::Tensor& candidate_lengths, + int64_t query_heads, + int64_t head_dim, + int64_t topk, + int64_t max_query_len, + int64_t max_committed_len, + int64_t compression_ratio) { + const torch::DeviceGuard guard(query_offsets.device()); + auto metadata = + query_offsets.new_empty({optiling::QLI_V2_METADATA_TOTAL_SIZE}); + auto empty = query_offsets.new_empty({0}); + const auto& residual = + residual_lengths.has_value() ? *residual_lengths : empty; + const int64_t batch_size = committed_lengths.numel(); + char query_layout[] = "TND"; + char key_layout[] = "PA_BBND"; + char* layout_query = query_layout; + char* layout_key = key_layout; + EXEC_NPU_CMD_EXT(aclnnXllmKernelQuantSparseLightningIndexerMetadataVa, + query_offsets, + /*cu_seqlens_k=*/empty, + /*seqused_q=*/empty, + committed_lengths, + residual, + candidate_lengths, + query_heads, + kKeyHeads, + head_dim, + topk, + kInt8QuantMode, + batch_size, + max_query_len, + max_committed_len, + layout_query, + layout_key, + kRightDownCausal, + compression_ratio, + metadata); + return metadata; +} + std::tuple quant_lightning_indexer_v2( const torch::Tensor& query, const torch::Tensor& key, @@ -166,6 +221,92 @@ std::tuple quant_lightning_indexer_v2( return {indices, candidates}; } +std::tuple +quant_lightning_indexer_v3( + const torch::Tensor& query, + const torch::Tensor& key, + const torch::Tensor& weights, + const torch::Tensor& query_scale, + const torch::Tensor& key_scale, + const torch::Tensor& query_offsets, + const torch::Tensor& committed_lengths, + const std::optional& residual_lengths, + const torch::Tensor& block_table, + const torch::Tensor& metadata, + const std::optional& candidate_blocks, + const std::optional& candidate_lengths, + int64_t topk, + int64_t max_query_len, + int64_t compression_ratio, + int64_t candidate_mode, + int64_t candidate_count, + int64_t candidate_block_size) { + const torch::DeviceGuard guard(query.device()); + const int64_t rows = query.size(0); + const int64_t key_heads = key.size(2); + auto output_options = query.options().dtype(torch::kInt32); + auto indices = torch::empty({rows, key_heads, topk}, output_options); + auto values = torch::empty({0}, query.options().dtype(torch::kBFloat16)); + auto candidates = + candidate_mode == kCandidateSource + ? torch::empty({rows, key_heads, candidate_count}, output_options) + : torch::empty({0}, output_options); + // All-padding rows can be skipped by the source kernel. + auto lengths = candidate_mode == kCandidateSource + ? torch::zeros({rows, key_heads}, output_options) + : torch::empty({0}, output_options); + const std::optional absent; + const int64_t key_page_stride = key.stride(0); + const int64_t scale_page_stride = key_scale.stride(0); + char query_layout[] = "TND"; + char key_layout[] = "PA_BBND"; + char* layout_query = query_layout; + char* layout_key = key_layout; + const bool enable_dcp = false; + const int64_t cp_world = 1; + const int64_t cp_rank = 0; + const int64_t cp_kv_cache_interleave_size = 1; + EXEC_NPU_CMD_EXT(aclnnXllmKernelQuantLightningIndexerV3Va, + query, + key, + weights, + query_scale, + key_scale, + query_offsets, + /*cu_seqlens_k=*/absent, + /*seqused_q=*/absent, + committed_lengths, + residual_lengths, + block_table, + /*output_idx_offset=*/absent, + metadata, + candidate_blocks, + candidate_lengths, + /*causal_seqlens_kv_global=*/absent, + topk, + kInt8QuantMode, + max_query_len, + layout_query, + layout_key, + kRightDownCausal, + compression_ratio, + kNoReturnValue, + candidate_mode, + candidate_count, + candidate_block_size, + key_page_stride, + scale_page_stride, + enable_dcp, + cp_world, + cp_rank, + cp_kv_cache_interleave_size, + indices, + values, + candidates, + lengths); + return {indices, candidates, lengths}; +} + TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { m.def("prepare_ascendc_v41_indexer() -> ()", &prepare_ascendc_v41_indexer); m.def( @@ -181,9 +322,24 @@ TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { "Tensor metadata, Tensor? candidate_blocks, int topk, int max_query_len, " "int compression_ratio, int candidate_mode, int candidate_count, " "int candidate_block_size) -> (Tensor, Tensor)"); + m.def( + "quant_sparse_lightning_indexer_metadata(Tensor query_offsets, Tensor " + "committed_lengths, Tensor? residual_lengths, Tensor candidate_lengths, " + "int query_heads, int head_dim, int topk, int max_query_len, int " + "max_committed_len, int compression_ratio) -> Tensor"); + m.def( + "quant_lightning_indexer_v3(Tensor query, Tensor key, Tensor weights, " + "Tensor query_scale, Tensor key_scale, Tensor query_offsets, Tensor " + "committed_lengths, Tensor? residual_lengths, Tensor block_table, Tensor " + "metadata, Tensor? candidate_blocks, Tensor? candidate_lengths, int " + "topk, int max_query_len, int compression_ratio, int candidate_mode, int " + "candidate_count, int candidate_block_size) -> (Tensor, Tensor, Tensor)"); } TORCH_LIBRARY_IMPL(xllm_kernel, PrivateUse1, m) { + m.impl("quant_sparse_lightning_indexer_metadata", + TORCH_FN(quant_sparse_lightning_indexer_metadata)); + m.impl("quant_lightning_indexer_v3", TORCH_FN(quant_lightning_indexer_v3)); m.impl("quant_lightning_indexer_v2_metadata", TORCH_FN(quant_lightning_indexer_v2_metadata)); m.impl("quant_lightning_indexer_v2", TORCH_FN(quant_lightning_indexer_v2)); diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/__init__.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/__init__.py index a424eb4b8a..ebf4248346 100644 --- a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/__init__.py +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/__init__.py @@ -121,11 +121,15 @@ def v41_c2_decode_pool_norm( for name in ( "quant_lightning_indexer_v2_metadata", "quant_lightning_indexer_v2", + "quant_sparse_lightning_indexer_metadata", + "quant_lightning_indexer_v3", "sparse_flash_mla_metadata", "sparse_flash_mla", ) ) -(_INDEXER_METADATA, _INDEXER, _SPARSE_FLASH_MLA_METADATA, _SPARSE_FLASH_MLA) = ASCENDC_OPERATIONS +(_INDEXER_METADATA, _INDEXER, _SPARSE_INDEXER_METADATA, _INDEXER_V3, _SPARSE_FLASH_MLA_METADATA, _SPARSE_FLASH_MLA) = ( + ASCENDC_OPERATIONS +) OPERATIONS = TILELANG_OPERATIONS + TRITON_OPERATIONS + ASCENDC_OPERATIONS diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/ascendc.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/ascendc.py index d958488128..f6d1166041 100644 --- a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/ascendc.py +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/ascendc.py @@ -16,6 +16,8 @@ ( "Device query offsets, committed compressed lengths and optional residual lengths on Ascend A3.", "Paged INT8 index keys with FP16 scales and optional sparse candidate blocks on Ascend A3.", + "Device-side candidate counts and committed lengths for sparse QLI on Ascend A3.", + "Paged INT8 index keys with candidate block IDs and per-row valid block counts on Ascend A3.", "Device lengths for the sliding window and optional compressed KV cache on Ascend A3.", "BF16 sliding-window attention with optional compressed sparse KV on Ascend A3.", ), diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/indexer.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/indexer.py index a914ba5a32..890b838fbd 100644 --- a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/indexer.py +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/indexer.py @@ -1,11 +1,11 @@ # Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. -"""Paged INT8 QLI V2 with candidate-block selection and reuse on Ascend A3.""" +"""Paged INT8 QLI with candidate-block selection and reuse on Ascend A3.""" from __future__ import annotations from typing import TYPE_CHECKING -from xllm_kernel.ops.attention.dsv41 import _INDEXER, _INDEXER_METADATA +from xllm_kernel.ops.attention.dsv41 import _INDEXER, _INDEXER_METADATA, _INDEXER_V3, _SPARSE_INDEXER_METADATA if TYPE_CHECKING: import torch @@ -73,3 +73,72 @@ def quant_lightning_indexer_v2( candidate_count, candidate_block_size, ) + + +def quant_sparse_lightning_indexer_metadata( + query_offsets: torch.Tensor, + committed_lengths: torch.Tensor, + residual_lengths: torch.Tensor | None, + candidate_lengths: torch.Tensor, + query_heads: int, + head_dim: int, + topk: int, + max_query_len: int, + max_committed_len: int, + compression_ratio: int, +) -> torch.Tensor: + return _SPARSE_INDEXER_METADATA.get_prepared().function( + query_offsets, + committed_lengths, + residual_lengths, + candidate_lengths, + query_heads, + head_dim, + topk, + max_query_len, + max_committed_len, + compression_ratio, + ) + + +def quant_lightning_indexer_v3( + query: torch.Tensor, + key: torch.Tensor, + weights: torch.Tensor, + query_scale: torch.Tensor, + key_scale: torch.Tensor, + query_offsets: torch.Tensor, + committed_lengths: torch.Tensor, + residual_lengths: torch.Tensor | None, + block_table: torch.Tensor, + metadata: torch.Tensor, + candidate_blocks: torch.Tensor | None, + candidate_lengths: torch.Tensor | None, + topk: int, + max_query_len: int, + compression_ratio: int, + candidate_mode: int, + candidate_count: int, + candidate_block_size: int, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Return selected tokens, source candidate blocks and their device-resident counts.""" + return _INDEXER_V3.get_prepared().function( + query, + key, + weights, + query_scale, + key_scale, + query_offsets, + committed_lengths, + residual_lengths, + block_table, + metadata, + candidate_blocks, + candidate_lengths, + topk, + max_query_len, + compression_ratio, + candidate_mode, + candidate_count, + candidate_block_size, + ) diff --git a/xllm-kernel/test/npu/test_dsv41_sparse_attention_npu.py b/xllm-kernel/test/npu/test_dsv41_sparse_attention_npu.py index 788422a967..d48b9defef 100644 --- a/xllm-kernel/test/npu/test_dsv41_sparse_attention_npu.py +++ b/xllm-kernel/test/npu/test_dsv41_sparse_attention_npu.py @@ -5,7 +5,12 @@ import pytest import torch -from xllm_kernel.ops.attention.dsv41.indexer import quant_lightning_indexer_v2, quant_lightning_indexer_v2_metadata +from xllm_kernel.ops.attention.dsv41.indexer import ( + quant_lightning_indexer_v2, + quant_lightning_indexer_v2_metadata, + quant_lightning_indexer_v3, + quant_sparse_lightning_indexer_metadata, +) from xllm_kernel.ops.attention.dsv41.mla import sparse_flash_mla, sparse_flash_mla_metadata pytestmark = pytest.mark.skipif(not torch.npu.get_device_name().startswith("Ascend910_93"), reason="requires Ascend A3") @@ -46,6 +51,82 @@ def test_indexer_uses_supplied_candidate_blocks() -> None: torch.testing.assert_close(indices.cpu().flatten().sort().values, torch.arange(512, 1024, dtype=torch.int32)) +def test_indexer_source_and_consumer_share_device_counts() -> None: + heads, topk, page_size = 32, 512, 128 + query = torch.ones((2, heads, 128), dtype=torch.int8, device="npu") + # Pages have unused physical padding, and logical page order is reversed. + storage = torch.full((8, 2 * page_size, 1, 128), 63, dtype=torch.int8) + storage[:4, :page_size].fill_(2) + storage[4:, :page_size].fill_(1) + keys = storage.npu()[:, :page_size] + scales = torch.ones(storage.shape[:-1], dtype=torch.float16, device="npu")[:, :page_size] + weights = torch.ones((2, heads), dtype=torch.float16, device="npu") + offsets = torch.tensor([0, 1, 2], dtype=torch.int32, device="npu") + lengths = torch.tensor([1024, 256], dtype=torch.int32, device="npu") + table = torch.tensor([list(reversed(range(8)))] * 2, dtype=torch.int32, device="npu") + common = (query, keys, weights, torch.ones_like(weights), scales, offsets, lengths, None, table) + args = (topk, 1, 1) + metadata = quant_lightning_indexer_v2_metadata(offsets, lengths, None, heads, 128, topk, 1, 1024, 1) + _, candidates, counts = quant_lightning_indexer_v3(*common, metadata, None, None, *args, 1, 64, 8) + sparse_meta = quant_sparse_lightning_indexer_metadata(offsets, lengths, None, counts, heads, 128, topk, 1, 1024, 1) + indices, _, _ = quant_lightning_indexer_v3(*common, sparse_meta, candidates, counts, *args, 2, 64, 8) + torch.testing.assert_close(counts.cpu(), torch.tensor([[64], [32]], dtype=torch.int32)) + first, second = indices.cpu().reshape(2, topk) + torch.testing.assert_close(first.sort().values, torch.arange(512, 1024, dtype=torch.int32)) + torch.testing.assert_close(second[second >= 0].sort().values, torch.arange(256, dtype=torch.int32)) + + +def test_indexer_graph_rereads_candidate_lengths() -> None: + heads, topk = 32, 512 + query = torch.ones((1, heads, 128), dtype=torch.int8, device="npu") + keys = torch.ones((8, 128, 1, 128), dtype=torch.int8) + keys[4:].fill_(2) + keys = keys.npu() + scales = torch.ones(keys.shape[:-1], dtype=torch.float16, device="npu") + weights = torch.ones((1, heads), dtype=torch.float16, device="npu") + offsets = torch.tensor([0, 1], dtype=torch.int32, device="npu") + lengths = torch.tensor([1024], dtype=torch.int32, device="npu") + table = torch.arange(8, dtype=torch.int32, device="npu").reshape(1, 8) + candidates = torch.arange(128, dtype=torch.int32, device="npu").reshape(1, 1, 128) + counts = torch.tensor([[128]], dtype=torch.int32, device="npu") + + def consume() -> torch.Tensor: + metadata = quant_sparse_lightning_indexer_metadata(offsets, lengths, None, counts, heads, 128, topk, 1, 1024, 1) + indices, _, _ = quant_lightning_indexer_v3( + query, + keys, + weights, + weights, + scales, + offsets, + lengths, + None, + table, + metadata, + candidates, + counts, + topk, + 1, + 1, + 2, + 128, + 8, + ) + return indices + + consume() + graph = torch.npu.NPUGraph() + with torch.npu.graph(graph): + indices = consume() + first = torch.arange(topk, dtype=torch.int32) + last = first + topk + empty = torch.full_like(first, -1) + for count, expected in [(64, first), (0, empty), (128, last), (64, first)]: + counts.fill_(count) + graph.replay() + torch.testing.assert_close(indices.cpu().flatten().sort().values, expected) + + @pytest.mark.parametrize(("sink_logit", "expected"), [(None, 2.0), (math.log(128), 1.0)]) def test_sparse_mla_applies_window_after_page_lookup(sink_logit: float | None, expected: float) -> None: heads, head_dim, window = 16, 512, 128 From 6fbebc8e3d7d8af50a470fc36364a67fb8163bfa Mon Sep 17 00:00:00 2001 From: PixelFlat <329975279+PixelFlat@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:07:34 +0800 Subject: [PATCH 6/6] refactor: share sparse MLA with the external CANN provider. --- xllm-kernel/csrc/ascendc/CMakeLists.txt | 2 - .../csrc/ascendc/sparse_flash_mla/SOURCE.txt | 7 - .../op_host/checkers/base_checker.cpp | 240 -- .../checkers/base_checker_sparse_flash_mla.h | 64 - .../op_host/checkers/checker_adapter.h | 103 - .../op_host/checkers/checker_context.h | 108 - .../op_host/checkers/checker_runner.cpp | 63 - .../op_host/checkers/checker_runner.h | 44 - .../op_host/checkers/common_checker.cpp | 366 -- .../common_checker_sparse_flash_mla.h | 44 - .../op_host/checkers/mask_checker.cpp | 81 - .../checkers/mask_checker_sparse_flash_mla.h | 30 - .../op_host/checkers/metadata_checker.cpp | 53 - .../metadata_checker_sparse_flash_mla.h | 31 - .../checkers/paged_attention_checker.cpp | 138 - ...paged_attention_checker_sparse_flash_mla.h | 37 - .../op_host/checkers/seq_len_checker.cpp | 192 - .../seq_len_checker_sparse_flash_mla.h | 41 - .../op_host/checkers/sinks_checker.cpp | 63 - .../checkers/sinks_checker_sparse_flash_mla.h | 32 - .../op_host/checkers/softmax_lse_checker.cpp | 63 - .../softmax_lse_checker_sparse_flash_mla.h | 30 - .../checkers/sparse_compression_checker.cpp | 323 -- .../checkers/sparse_compression_checker.h | 47 - .../checkers/sparse_flash_mla_checker.cpp | 38 - .../checkers/sparse_flash_mla_checker.h | 32 - .../sparse_flash_mla/op_host/common/log.h | 776 ---- .../sparse_flash_mla/op_host/common/ops_err.h | 37 - .../op_host/common/smla_host_common_defs.h | 83 - .../op_host/common/smla_infershape_common.h | 228 -- .../op_host/sparse_flash_mla_def.cpp | 152 - .../op_host/sparse_flash_mla_infershape.cpp | 56 - .../op_host/sparse_flash_mla_tiling.cpp | 3255 ----------------- .../op_host/sparse_flash_mla_tiling.h | 567 --- .../arch22/sparse_flash_mla_arch22_metadata.h | 85 - .../arch22/sparse_flash_mla_common_arch22.h | 408 --- .../arch22/sparse_flash_mla_csa_block_cube.h | 1013 ----- .../sparse_flash_mla_csa_block_vector.h | 1517 -------- .../arch22/sparse_flash_mla_csa_kernel.h | 1123 ------ .../arch22/sparse_flash_mla_swa_block_cube.h | 1539 -------- .../sparse_flash_mla_swa_block_vector.h | 1688 --------- .../arch22/sparse_flash_mla_swa_kernel.h | 1238 ------- .../arch35/common/smla_metadata_common.h | 75 - .../sparse_flash_mla_kernel_metadata.h | 42 - .../sparse_flash_mla_template_tiling_key.h | 140 - .../xllm_kernel_sparse_flash_mla.cpp | 155 - .../sparse_flash_mla_metadata/SOURCE.txt | 5 - .../sparse_flash_mla_metadata_proto.cpp | 57 - .../aclnn_sparse_flash_mla_metadata.cpp | 319 -- .../op_api/aclnn_sparse_flash_mla_metadata.h | 65 - .../op_api/sparse_flash_mla_metadata.cpp | 156 - .../op_api/sparse_flash_mla_metadata.h | 55 - .../op_host/sparse_flash_mla_metadata_check.h | 1464 -------- .../sparse_flash_mla_metadata_infershape.cpp | 41 - .../sparse_flash_mla_metadata_aicpu.cpp | 1954 ---------- .../sparse_flash_mla_metadata_aicpu.h | 430 --- .../sparse_flash_mla_metadata_aicpu.json | 15 - xllm-kernel/csrc/ascendc/v41_sparse_mla.cmake | 48 - xllm-kernel/csrc/npu/v41_quant_indexer.cpp | 15 +- xllm-kernel/csrc/npu/v41_sparse_mla.cpp | 206 -- .../ops/attention/dsv41/__init__.py | 10 +- .../ops/attention/dsv41/ascendc.py | 5 +- .../ops/attention/dsv41/indexer.py | 4 +- .../xllm_kernel/ops/attention/dsv41/mla.py | 87 - xllm-kernel/setup.py | 1 - ...py => test_dsv41_candidate_indexer_npu.py} | 50 +- 66 files changed, 20 insertions(+), 21416 deletions(-) delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/SOURCE.txt delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/base_checker.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/base_checker_sparse_flash_mla.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_adapter.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_context.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_runner.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_runner.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/common_checker.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/common_checker_sparse_flash_mla.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/mask_checker.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/mask_checker_sparse_flash_mla.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/metadata_checker.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/metadata_checker_sparse_flash_mla.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/paged_attention_checker.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/paged_attention_checker_sparse_flash_mla.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/seq_len_checker.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/seq_len_checker_sparse_flash_mla.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sinks_checker.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sinks_checker_sparse_flash_mla.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/softmax_lse_checker.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/softmax_lse_checker_sparse_flash_mla.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_compression_checker.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_compression_checker.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_flash_mla_checker.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_flash_mla_checker.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/log.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/ops_err.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/smla_host_common_defs.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/smla_infershape_common.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_def.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_infershape.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_tiling.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_tiling.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_arch22_metadata.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_common_arch22.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_block_cube.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_block_vector.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_kernel.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_block_cube.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_block_vector.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_kernel.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch35/common/smla_metadata_common.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/sparse_flash_mla_kernel_metadata.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/sparse_flash_mla_template_tiling_key.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/xllm_kernel_sparse_flash_mla.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/SOURCE.txt delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_graph/sparse_flash_mla_metadata_proto.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/aclnn_sparse_flash_mla_metadata.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/aclnn_sparse_flash_mla_metadata.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/sparse_flash_mla_metadata.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/sparse_flash_mla_metadata.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/sparse_flash_mla_metadata_check.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/sparse_flash_mla_metadata_infershape.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.cpp delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.h delete mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.json delete mode 100644 xllm-kernel/csrc/ascendc/v41_sparse_mla.cmake delete mode 100644 xllm-kernel/csrc/npu/v41_sparse_mla.cpp delete mode 100644 xllm-kernel/python/xllm_kernel/ops/attention/dsv41/mla.py rename xllm-kernel/test/npu/{test_dsv41_sparse_attention_npu.py => test_dsv41_candidate_indexer_npu.py} (71%) diff --git a/xllm-kernel/csrc/ascendc/CMakeLists.txt b/xllm-kernel/csrc/ascendc/CMakeLists.txt index def251c9fc..8a2ad6381e 100644 --- a/xllm-kernel/csrc/ascendc/CMakeLists.txt +++ b/xllm-kernel/csrc/ascendc/CMakeLists.txt @@ -205,7 +205,6 @@ foreach(component IN LISTS native_components) list(APPEND native_api "${ASCEND_AUTOGEN_PATH}/aclnn_xllm_kernel_${component}.cpp") endif() endforeach() -include("${CMAKE_CURRENT_SOURCE_DIR}/v41_sparse_mla.cmake") npu_op_code_gen( SRC ${op_definitions} PACKAGE ${vendor} @@ -470,7 +469,6 @@ npu_op_kernel_options(ascendc_kernels XllmKernelQuantLightningIndexer -mllvm -cce-vf-remove-membar=false -mllvm -cce-aicore-hoist-movemask=false "-I${CMAKE_CURRENT_SOURCE_DIR}" "-I${qli}/op_kernel") if("ascend910_93" IN_LIST ASCEND_COMPUTE_UNIT) - v41_sparse_mla_kernel() npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelQuantLightningIndexerV3Va KERNEL_DIR quant_lightning_indexer_v2_va/op_kernel KERNEL_FILE xllm_kernel_quant_lightning_indexer_v3_va.cpp) npu_op_kernel_options(ascendc_kernels XllmKernelQuantLightningIndexerV3Va diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/SOURCE.txt b/xllm-kernel/csrc/ascendc/sparse_flash_mla/SOURCE.txt deleted file mode 100644 index 08d92a2435..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/SOURCE.txt +++ /dev/null @@ -1,7 +0,0 @@ -Source: https://gitcode.com/cann/ops-transformer, commit 814116886e54f04053f8870a400dfd31c46bf53c -Directory: attention/sparse_flash_mla -License: CANN Open Software License Agreement Version 2.0 (see CANN_LICENSE.txt). -The xllm-kernel package builds the Ascend A3 implementation with a distinct -operator name. The metadata protocol and kernel inputs follow the upstream ABI. -The CANN 9.0 logging compatibility header is adapted from -mc2/common/utils/mc2_log_compat.h at the same revision. diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/base_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/base_checker.cpp deleted file mode 100644 index bf86fe6b41..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/base_checker.cpp +++ /dev/null @@ -1,240 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#include -#include - -#include "base_checker_sparse_flash_mla.h" -#include "sparse_flash_mla/op_host/common/log.h" - -namespace optiling { -namespace sparse_mla_checker { -namespace { -const char* GetOpName(const CheckContext& context) { - return context.opName == nullptr ? "SparseMla" : context.opName; -} - -std::string ShapeToString(const gert::Shape* shape) { - if (shape == nullptr) { - return "nullptr"; - } - std::ostringstream oss; - oss << "("; - for (size_t i = 0; i < shape->GetDimNum(); ++i) { - if (i > 0) { - oss << ", "; - } - oss << shape->GetDim(i); - } - oss << ")"; - return oss.str(); -} - -template -std::string ValuesToString(std::initializer_list values) { - std::ostringstream oss; - bool first = true; - for (const auto value : values) { - if (!first) { - oss << ", "; - } - oss << static_cast(value); - first = false; - } - return oss.str(); -} -} // namespace - -ge::graphStatus BaseChecker::CheckSinglePara( - const CheckContext& context) const { - (void)context; - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus BaseChecker::CheckParaExistence( - const CheckContext& context) const { - (void)context; - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus BaseChecker::CheckFeature(const CheckContext& context) const { - (void)context; - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus BaseChecker::CheckMultiPara(const CheckContext& context) const { - (void)context; - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus BaseChecker::CheckTensorDesc( - const CheckContext& context, - const TensorParam& param, - const char* name, - std::initializer_list dtypes) const { - if (!param.present) { - return ge::GRAPH_SUCCESS; - } - OP_CHECK_IF(param.desc == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - GetOpName(context), name, "Tensor desc cannot be null"), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - param.desc->GetOriginFormat() != ge::FORMAT_ND, - OP_LOGE_FOR_INVALID_FORMAT( - GetOpName(context), - name, - std::to_string(static_cast(param.desc->GetOriginFormat())) - .c_str(), - "ND"), - return ge::GRAPH_FAILED); - const ge::DataType actual = param.desc->GetDataType(); - const std::string expectedDtypes = ValuesToString(dtypes); - OP_CHECK_IF(std::find(dtypes.begin(), dtypes.end(), actual) == dtypes.end(), - OP_LOGE_FOR_INVALID_DTYPE( - GetOpName(context), - name, - std::to_string(static_cast(actual)).c_str(), - expectedDtypes.c_str()), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus BaseChecker::CheckDimNum( - const CheckContext& context, - const TensorParam& param, - const char* name, - std::initializer_list dimNums) const { - if (!param.present) { - return ge::GRAPH_SUCCESS; - } - OP_CHECK_IF(param.shape == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - GetOpName(context), name, "Tensor shape cannot be null"), - return ge::GRAPH_FAILED); - const size_t actual = param.shape->GetDimNum(); - const std::string expectedDimNums = ValuesToString(dimNums); - OP_CHECK_IF( - std::find(dimNums.begin(), dimNums.end(), actual) == dimNums.end(), - OP_LOGE_FOR_INVALID_SHAPEDIM(GetOpName(context), - name, - std::to_string(actual).c_str(), - expectedDimNums.c_str()), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus BaseChecker::CheckNoEmptyDim(const CheckContext& context, - const TensorParam& param, - const char* name) const { - if (!param.present) { - return ge::GRAPH_SUCCESS; - } - OP_CHECK_IF(param.shape == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - GetOpName(context), name, "Tensor shape cannot be null"), - return ge::GRAPH_FAILED); - for (size_t i = 0; i < param.shape->GetDimNum(); ++i) { - OP_CHECK_IF(param.shape->GetDim(i) <= 0, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - GetOpName(context), - name, - ShapeToString(param.shape).c_str(), - "Each dimension must be greater than 0"), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus BaseChecker::CheckShape( - const CheckContext& context, - const TensorParam& param, - const char* name, - std::initializer_list expected) const { - if (!param.present) { - return ge::GRAPH_SUCCESS; - } - OP_CHECK_IF( - param.shape == nullptr || param.shape->GetDimNum() != expected.size(), - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - GetOpName(context), - name, - ShapeToString(param.shape).c_str(), - "Shape dim number does not match the documented shape"), - return ge::GRAPH_FAILED); - size_t index = 0; - for (const int64_t value : expected) { - OP_CHECK_IF(param.shape->GetDim(index) != value, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - GetOpName(context), - name, - ShapeToString(param.shape).c_str(), - ("Dimension " + std::to_string(index) + " must be " + - std::to_string(value)) - .c_str()), - return ge::GRAPH_FAILED); - ++index; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus BaseChecker::CheckSameShape(const CheckContext& context, - const TensorParam& left, - const char* leftName, - const TensorParam& right, - const char* rightName) const { - OP_CHECK_IF(left.shape == nullptr || right.shape == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - GetOpName(context), - (std::string(leftName) + " and " + rightName).c_str(), - "Tensor shape cannot be null"), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - left.shape->GetDimNum() != right.shape->GetDimNum(), - OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( - GetOpName(context), - (std::string(leftName) + " and " + rightName).c_str(), - (ShapeToString(left.shape) + " and " + ShapeToString(right.shape)) - .c_str(), - "Tensor dim numbers must be the same"), - return ge::GRAPH_FAILED); - for (size_t i = 0; i < left.shape->GetDimNum(); ++i) { - OP_CHECK_IF( - left.shape->GetDim(i) != right.shape->GetDim(i), - OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( - GetOpName(context), - (std::string(leftName) + " and " + rightName).c_str(), - (ShapeToString(left.shape) + " and " + ShapeToString(right.shape)) - .c_str(), - ("Dimension " + std::to_string(i) + " must be the same").c_str()), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; -} - -int64_t BaseChecker::GetDim(const TensorParam& param, size_t index) const { - if (param.shape == nullptr || index >= param.shape->GetDimNum()) { - return -1; - } - return param.shape->GetDim(index); -} - -bool BaseChecker::CanOmitSequsedOriKv(const CheckContext& context) const { - return context.oriTopkLength.present; -} - -bool BaseChecker::CanOmitSequsedCmpKv(const CheckContext& context) const { - return context.cmpTopkLength.present; -} - -} // namespace sparse_mla_checker -} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/base_checker_sparse_flash_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/base_checker_sparse_flash_mla.h deleted file mode 100644 index ed99879d71..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/base_checker_sparse_flash_mla.h +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#ifndef SPARSE_MLA_BASE_CHECKER_SPARSE_FLASH_MLA_H -#define SPARSE_MLA_BASE_CHECKER_SPARSE_FLASH_MLA_H - -#include -#include - -#include "checker_context.h" - -namespace optiling { -namespace sparse_mla_checker { - -class BaseChecker { - public: - BaseChecker() = default; - virtual ~BaseChecker() = default; - - virtual ge::graphStatus CheckSinglePara(const CheckContext& context) const; - virtual ge::graphStatus CheckParaExistence(const CheckContext& context) const; - virtual ge::graphStatus CheckFeature(const CheckContext& context) const; - virtual ge::graphStatus CheckMultiPara(const CheckContext& context) const; - - protected: - ge::graphStatus CheckTensorDesc( - const CheckContext& context, - const TensorParam& param, - const char* name, - std::initializer_list dtypes) const; - ge::graphStatus CheckDimNum(const CheckContext& context, - const TensorParam& param, - const char* name, - std::initializer_list dimNums) const; - ge::graphStatus CheckNoEmptyDim(const CheckContext& context, - const TensorParam& param, - const char* name) const; - ge::graphStatus CheckShape(const CheckContext& context, - const TensorParam& param, - const char* name, - std::initializer_list expected) const; - ge::graphStatus CheckSameShape(const CheckContext& context, - const TensorParam& left, - const char* leftName, - const TensorParam& right, - const char* rightName) const; - int64_t GetDim(const TensorParam& param, size_t index) const; - bool CanOmitSequsedOriKv(const CheckContext& context) const; - bool CanOmitSequsedCmpKv(const CheckContext& context) const; -}; - -} // namespace sparse_mla_checker -} // namespace optiling - -#endif // SPARSE_MLA_BASE_CHECKER_SPARSE_FLASH_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_adapter.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_adapter.h deleted file mode 100644 index b23d7c58ad..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_adapter.h +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#ifndef SPARSE_MLA_CHECKER_ADAPTER_H -#define SPARSE_MLA_CHECKER_ADAPTER_H - -#include "checker_context.h" - -namespace optiling { -namespace sparse_mla_checker { - -template -void PopulateOptionalTensorParam(gert::TilingContext* context, - uint32_t index, - OptionalParam& param) { - param.desc = context->GetOptionalInputDesc(index); - param.shape = context->GetOptionalInputShape(index); - param.tensor = context->GetOptionalInputTensor(index); -} - -template -TensorParam MakeRequiredTensor(const RequiredParam& param) { - return {param.desc, - param.shape == nullptr ? nullptr : ¶m.shape->GetStorageShape(), - param.desc != nullptr || param.shape != nullptr}; -} - -template -TensorParam MakeOptionalTensor(const OptionalParam& param) { - const gert::Shape* shape = - param.shape == nullptr ? nullptr : ¶m.shape->GetStorageShape(); - if (shape == nullptr && param.tensor != nullptr) { - shape = ¶m.tensor->GetStorageShape(); - } - return {param.desc, shape, shape != nullptr}; -} - -inline int64_t GetLastDim(const TensorParam& param) { - return param.shape == nullptr || param.shape->GetDimNum() == 0 - ? 0 - : param.shape->GetDim(param.shape->GetDimNum() - 1); -} - -template -void PopulateCommonContext(CheckContext& context, const TilingInfo& info) { - const auto& param = info.opParamInfo; - context.opName = info.opName; - context.q = MakeRequiredTensor(param.q); - context.oriKv = MakeOptionalTensor(param.oriKv); - context.cmpKv = MakeOptionalTensor(param.cmpKv); - context.oriSparseIndices = MakeOptionalTensor(param.oriSparseIndices); - context.cmpSparseIndices = MakeOptionalTensor(param.cmpSparseIndices); - context.oriBlockTable = MakeOptionalTensor(param.oriBlockTable); - context.cmpBlockTable = MakeOptionalTensor(param.cmpBlockTable); - context.cuSeqlensQ = MakeOptionalTensor(param.cuSeqLensQ); - context.cuSeqlensOriKv = MakeOptionalTensor(param.cuSeqLensOriKv); - context.cuSeqlensCmpKv = MakeOptionalTensor(param.cuSeqLensCmpKv); - context.sequsedQ = MakeOptionalTensor(param.seqUsedQ); - context.sequsedOriKv = MakeOptionalTensor(param.sequsedOriKv); - context.sequsedCmpKv = MakeOptionalTensor(param.sequsedCmpKv); - context.cmpResidualKv = MakeOptionalTensor(param.cmpResidualKv); - context.oriTopkLength = MakeOptionalTensor(param.oriTopkLength); - context.cmpTopkLength = MakeOptionalTensor(param.cmpTopkLength); - context.sinks = MakeOptionalTensor(param.sinks); - context.metadata = MakeOptionalTensor(param.metadata); - context.attentionOut = MakeRequiredTensor(param.attnOut); - context.softmaxLse = MakeRequiredTensor(param.softmaxLse); - - context.qLayout = static_cast(static_cast(info.qLayout)); - context.kvLayout = static_cast(static_cast(info.kvLayout)); - context.npuArch = info.npuArch; - context.bSize = info.bSize; - context.qNumHeads = info.n1Size; - context.kvNumHeads = info.n2Size; - context.qSeqSize = info.s1Size; - context.qTotalSize = info.qTSize; - context.oriBlockSize = info.oriBlockSize; - context.cmpBlockSize = info.cmpBlockSize; - context.oriTopk = GetLastDim(context.oriSparseIndices); - context.cmpTopk = GetLastDim(context.cmpSparseIndices); - context.softmaxScale = info.softmaxScale; - context.cmpRatio = info.cmpRatio; - context.oriMaskMode = static_cast(info.oriMaskMode); - context.cmpMaskMode = static_cast(info.cmpMaskMode); - context.oriWinLeft = info.oriWinLeft; - context.oriWinRight = info.oriWinRight; - context.topkValueMode = info.topkValueMode; - context.returnSoftmaxLse = info.returnSoftmaxLse; -} - -} // namespace sparse_mla_checker -} // namespace optiling - -#endif // SPARSE_MLA_CHECKER_ADAPTER_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_context.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_context.h deleted file mode 100644 index 195f45d934..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_context.h +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#ifndef SPARSE_MLA_CHECKER_CONTEXT_H -#define SPARSE_MLA_CHECKER_CONTEXT_H - -#include -#include - -#include "exe_graph/runtime/tiling_context.h" -#include "platform/platform_info.h" -#include "platform/soc_spec.h" -#include "sparse_flash_mla/op_host/common/log.h" -#include "tiling/tiling_api.h" - -namespace optiling { -namespace sparse_mla_checker { - -enum class OperatorVariant : uint32_t { - SPARSE = 0, - MIXED_QUANT = 1, - QUANT = 2, -}; - -enum class Layout : uint32_t { - BSND = 0, - TND = 1, - PA_BBND = 2, -}; - -struct TensorParam { - const gert::CompileTimeTensorDesc* desc = nullptr; - const gert::Shape* shape = nullptr; - bool present = false; -}; - -struct CheckContext { - const char* opName = nullptr; - OperatorVariant variant = OperatorVariant::SPARSE; - NpuArch npuArch = NpuArch::DAV_2201; - - TensorParam q; - TensorParam oriKv; - TensorParam cmpKv; - TensorParam qDescale; - TensorParam oriKvDescale; - TensorParam cmpKvDescale; - TensorParam oriSparseIndices; - TensorParam cmpSparseIndices; - TensorParam oriBlockTable; - TensorParam cmpBlockTable; - TensorParam cuSeqlensQ; - TensorParam cuSeqlensOriKv; - TensorParam cuSeqlensCmpKv; - TensorParam sequsedQ; - TensorParam sequsedOriKv; - TensorParam sequsedCmpKv; - TensorParam cmpResidualKv; - TensorParam oriTopkLength; - TensorParam cmpTopkLength; - TensorParam sinks; - TensorParam metadata; - TensorParam attentionOut; - TensorParam softmaxLse; - - Layout qLayout = Layout::BSND; - Layout kvLayout = Layout::BSND; - int64_t bSize = 0; - int64_t qNumHeads = 0; - int64_t kvNumHeads = 0; - int64_t qSeqSize = 0; - int64_t qTotalSize = 0; - int64_t qHeadDim = 0; - int64_t oriKvHeadDim = 0; - int64_t cmpKvHeadDim = 0; - int64_t oriBlockSize = 0; - int64_t cmpBlockSize = 0; - int64_t oriTopk = 0; - int64_t cmpTopk = 0; - - int64_t quantMode = 0; - int64_t ropeHeadDim = 0; - float softmaxScale = 1.0F; - int64_t cmpRatio = 1; - int64_t oriMaskMode = 0; - int64_t cmpMaskMode = 0; - int64_t oriWinLeft = -1; - int64_t oriWinRight = -1; - int64_t topkValueMode = 1; - bool returnSoftmaxLse = false; - - std::vector oriKvStrides; - std::vector cmpKvStrides; -}; - -} // namespace sparse_mla_checker -} // namespace optiling - -#endif // SPARSE_MLA_CHECKER_CONTEXT_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_runner.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_runner.cpp deleted file mode 100644 index e44cd29b6f..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_runner.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#include "checker_runner.h" - -#include "common_checker_sparse_flash_mla.h" -#include "mask_checker_sparse_flash_mla.h" -#include "metadata_checker_sparse_flash_mla.h" -#include "paged_attention_checker_sparse_flash_mla.h" -#include "seq_len_checker_sparse_flash_mla.h" -#include "sinks_checker_sparse_flash_mla.h" -#include "softmax_lse_checker_sparse_flash_mla.h" -#include "sparse_compression_checker.h" - -namespace optiling { -namespace sparse_mla_checker { - -void CheckerRunner::Add(std::unique_ptr checker) { - checkers_.push_back(std::move(checker)); -} - -ge::graphStatus CheckerRunner::Run(CheckMethod method, - const CheckContext& context) const { - for (const auto& checker : checkers_) { - if ((checker.get()->*method)(context) != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus CheckerRunner::Process(const CheckContext& context) const { - if (Run(&BaseChecker::CheckSinglePara, context) != ge::GRAPH_SUCCESS || - Run(&BaseChecker::CheckParaExistence, context) != ge::GRAPH_SUCCESS || - Run(&BaseChecker::CheckFeature, context) != ge::GRAPH_SUCCESS || - Run(&BaseChecker::CheckMultiPara, context) != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -void RegisterCommonCheckers(CheckerRunner& runner) { - runner.Add(std::make_unique()); - runner.Add(std::make_unique()); - runner.Add(std::make_unique()); - runner.Add(std::make_unique()); - runner.Add(std::make_unique()); - runner.Add(std::make_unique()); - runner.Add(std::make_unique()); - runner.Add(std::make_unique()); -} - -} // namespace sparse_mla_checker -} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_runner.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_runner.h deleted file mode 100644 index 0677279f43..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/checker_runner.h +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#ifndef SPARSE_MLA_CHECKER_RUNNER_H -#define SPARSE_MLA_CHECKER_RUNNER_H - -#include -#include - -#include "base_checker_sparse_flash_mla.h" - -namespace optiling { -namespace sparse_mla_checker { - -class CheckerRunner { - public: - CheckerRunner() = default; - ~CheckerRunner() = default; - - void Add(std::unique_ptr checker); - ge::graphStatus Process(const CheckContext& context) const; - - private: - using CheckMethod = - ge::graphStatus (BaseChecker::*)(const CheckContext&) const; - ge::graphStatus Run(CheckMethod method, const CheckContext& context) const; - std::vector> checkers_; -}; - -void RegisterCommonCheckers(CheckerRunner& runner); - -} // namespace sparse_mla_checker -} // namespace optiling - -#endif // SPARSE_MLA_CHECKER_RUNNER_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/common_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/common_checker.cpp deleted file mode 100644 index 853aadfea5..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/common_checker.cpp +++ /dev/null @@ -1,366 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#include -#include - -#include "common_checker_sparse_flash_mla.h" -#include "sparse_flash_mla/op_host/common/log.h" - -namespace optiling { -namespace sparse_mla_checker { -constexpr int64_t TURBO_QUANT_MODE = 3; -constexpr uint32_t DIM_IDX_TWO = 2; -constexpr uint32_t DIM_IDX_THREE = 3; - -namespace { -const char* Op(const CheckContext& context) { - return context.opName == nullptr ? "SparseMla" : context.opName; -} - -bool IsTurboQuantEmptyTndTensor(const CheckContext& context, - const TensorParam& param) { - return context.variant == OperatorVariant::MIXED_QUANT && - context.quantMode == TURBO_QUANT_MODE && - context.qLayout == Layout::TND && param.shape != nullptr && - param.shape->GetDimNum() > 0 && param.shape->GetDim(0) == 0; -} -} // namespace - -ge::graphStatus CommonChecker::CheckQuery(const CheckContext& context) const { - if (!context.q.present) { - return ge::GRAPH_SUCCESS; - } - ge::graphStatus status = ge::GRAPH_FAILED; - if (context.variant == OperatorVariant::SPARSE) { - status = - CheckTensorDesc(context, context.q, "q", {ge::DT_FLOAT16, ge::DT_BF16}); - } else if (context.variant == OperatorVariant::MIXED_QUANT) { - status = context.quantMode == TURBO_QUANT_MODE - ? CheckTensorDesc( - context, context.q, "q", {ge::DT_FLOAT16, ge::DT_BF16}) - : CheckTensorDesc(context, context.q, "q", {ge::DT_BF16}); - } else { - status = CheckTensorDesc(context, context.q, "q", {ge::DT_HIFLOAT8}); - } - if (status != ge::GRAPH_SUCCESS || - (!IsTurboQuantEmptyTndTensor(context, context.q) && - CheckNoEmptyDim(context, context.q, "q") != ge::GRAPH_SUCCESS)) { - return ge::GRAPH_FAILED; - } - const size_t expectedDimNum = context.qLayout == Layout::BSND ? 4U : 3U; - return CheckDimNum(context, context.q, "q", {expectedDimNum}); -} - -ge::graphStatus CommonChecker::CheckKv(const CheckContext& context, - const TensorParam& kv, - const char* name) const { - if (!kv.present) { - return ge::GRAPH_SUCCESS; - } - ge::graphStatus status = ge::GRAPH_FAILED; - if (context.variant == OperatorVariant::SPARSE) { - status = CheckTensorDesc(context, kv, name, {ge::DT_FLOAT16, ge::DT_BF16}); - } else if (context.variant == OperatorVariant::MIXED_QUANT) { - if (context.quantMode == TURBO_QUANT_MODE) { - status = std::string(name) == "cmp_kv" - ? CheckTensorDesc(context, kv, name, {ge::DT_UINT8}) - : CheckTensorDesc( - context, kv, name, {ge::DT_FLOAT16, ge::DT_BF16}); - } else { - status = CheckTensorDesc(context, kv, name, {ge::DT_FLOAT8_E4M3FN}); - } - } else { - status = CheckTensorDesc(context, kv, name, {ge::DT_HIFLOAT8}); - } - if (status != ge::GRAPH_SUCCESS || - CheckNoEmptyDim(context, kv, name) != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - const size_t expectedDimNum = context.kvLayout == Layout::TND ? 3U : 4U; - return CheckDimNum(context, kv, name, {expectedDimNum}); -} - -ge::graphStatus CommonChecker::CheckOutput(const CheckContext& context) const { - if (!context.attentionOut.present) { - return ge::GRAPH_SUCCESS; - } - ge::graphStatus status = ge::GRAPH_FAILED; - if (context.variant == OperatorVariant::SPARSE || - (context.variant == OperatorVariant::MIXED_QUANT && - context.quantMode == TURBO_QUANT_MODE)) { - status = CheckTensorDesc(context, - context.attentionOut, - "attention_out", - {ge::DT_FLOAT16, ge::DT_BF16}); - } else { - status = CheckTensorDesc( - context, context.attentionOut, "attention_out", {ge::DT_BF16}); - } - if (status != ge::GRAPH_SUCCESS || - (!IsTurboQuantEmptyTndTensor(context, context.attentionOut) && - CheckNoEmptyDim(context, context.attentionOut, "attention_out") != - ge::GRAPH_SUCCESS)) { - return ge::GRAPH_FAILED; - } - const size_t expectedDimNum = context.qLayout == Layout::BSND ? 4U : 3U; - return CheckDimNum( - context, context.attentionOut, "attention_out", {expectedDimNum}); -} - -ge::graphStatus CommonChecker::CheckSinglePara( - const CheckContext& context) const { - OP_CHECK_IF( - context.qLayout != Layout::BSND && context.qLayout != Layout::TND, - OP_LOGE_FOR_INVALID_VALUE( - Op(context), - "layout_q", - std::to_string(static_cast(context.qLayout)).c_str(), - "BSND or TND"), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - context.kvLayout != Layout::BSND && context.kvLayout != Layout::TND && - context.kvLayout != Layout::PA_BBND, - OP_LOGE_FOR_INVALID_VALUE( - Op(context), - "layout_kv", - std::to_string(static_cast(context.kvLayout)).c_str(), - "BSND, TND or PA_BBND"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(!std::isfinite(context.softmaxScale), - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - Op(context), - "softmax_scale", - std::to_string(context.softmaxScale).c_str(), - "Softmax_scale must be finite"), - return ge::GRAPH_FAILED); - if (CheckQuery(context) != ge::GRAPH_SUCCESS || - CheckKv(context, context.oriKv, "ori_kv") != ge::GRAPH_SUCCESS || - CheckKv(context, context.cmpKv, "cmp_kv") != ge::GRAPH_SUCCESS || - CheckOutput(context) != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus CommonChecker::CheckParaExistence( - const CheckContext& context) const { - OP_CHECK_IF(!context.q.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), "q", "Q is required"), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - !context.oriKv.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), "ori_kv", "Ori_kv is required in all supported modes"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(!context.attentionOut.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), "attention_out", "Attention_out is required"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus CommonChecker::CheckFeature(const CheckContext& context) const { - OP_CHECK_IF( - context.kvLayout != Layout::PA_BBND && - context.qLayout != context.kvLayout, - OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( - Op(context), - "layout_q and layout_kv", - (std::to_string(static_cast(context.qLayout)) + " and " + - std::to_string(static_cast(context.kvLayout))) - .c_str(), - "Non-PA layout_q and layout_kv must be the same"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus CommonChecker::CheckQueryAxes( - const CheckContext& context) const { - const int64_t qSeq = GetDim(context.q, 0); - int64_t qHeads = -1; - int64_t qDim = -1; - if (context.qLayout == Layout::BSND) { - OP_CHECK_IF(GetDim(context.q, 0) <= 0 || GetDim(context.q, 1) <= 0, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - Op(context), - "q", - ("Batch=" + std::to_string(GetDim(context.q, 0)) + - ", sequence=" + std::to_string(GetDim(context.q, 1))) - .c_str(), - "Batch and sequence dimensions must be greater than 0"), - return ge::GRAPH_FAILED); - qHeads = GetDim(context.q, DIM_IDX_TWO); - qDim = GetDim(context.q, DIM_IDX_THREE); - } else { - const bool turboQuant = context.variant == OperatorVariant::MIXED_QUANT && - context.quantMode == TURBO_QUANT_MODE; - OP_CHECK_IF(qSeq < 0 || (!turboQuant && qSeq == 0), - OP_LOGE_FOR_INVALID_SHAPESIZE(Op(context), - "q_t", - std::to_string(qSeq).c_str(), - turboQuant ? ">= 0" : "> 0"), - return ge::GRAPH_FAILED); - qHeads = GetDim(context.q, 1); - qDim = GetDim(context.q, DIM_IDX_TWO); - } - OP_CHECK_IF( - qHeads <= 0 || qHeads > 128, // 128:最大支持的注意力头数 - OP_LOGE_FOR_INVALID_VALUE( - Op(context), "q_n", std::to_string(qHeads).c_str(), "[1, 128]"), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - qDim != 512, // 512:每个注意力头的固定维度大小 - OP_LOGE_FOR_INVALID_VALUE( - Op(context), "q head dimension", std::to_string(qDim).c_str(), "512"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus CommonChecker::CheckKvAxes(const CheckContext& context, - const TensorParam& kv, - const char* name) const { - if (!kv.present) { - return ge::GRAPH_SUCCESS; - } - int64_t numHeads = -1; - int64_t headDim = -1; - if (context.kvLayout == Layout::TND) { - numHeads = GetDim(kv, 1); - headDim = GetDim(kv, DIM_IDX_TWO); - } else { - numHeads = GetDim(kv, DIM_IDX_TWO); - headDim = GetDim(kv, DIM_IDX_THREE); - } - OP_CHECK_IF(numHeads != 1, - OP_LOGE_FOR_INVALID_VALUE(Op(context), - (std::string(name) + " kv_n").c_str(), - std::to_string(numHeads).c_str(), - "1"), - return ge::GRAPH_FAILED); - int64_t expectedDim = 512; // 512:预期维度大小 - if (context.variant == OperatorVariant::MIXED_QUANT) { - if (context.quantMode == TURBO_QUANT_MODE) { - // TurboQuant uses 512 dimensions for ori_kv and 258 bytes for packed - // cmp_kv. - expectedDim = std::string(name) == "cmp_kv" ? 258 : 512; - } else { - expectedDim = - context.quantMode == 1 - ? 608 - : 584; // 608,584:混合量化模式下根据量化模式选择不同维度 - } - } - OP_CHECK_IF( - headDim != expectedDim, - OP_LOGE_FOR_INVALID_VALUE(Op(context), - (std::string(name) + " head dimension").c_str(), - std::to_string(headDim).c_str(), - std::to_string(expectedDim).c_str()), - return ge::GRAPH_FAILED); - if (context.kvLayout == Layout::PA_BBND) { - const int64_t blockSize = GetDim(kv, 1); - OP_CHECK_IF( - blockSize <= 0 || blockSize > 1024, - OP_LOGE_FOR_INVALID_VALUE(Op(context), - (std::string(name) + " block size").c_str(), - std::to_string(blockSize).c_str(), - "[1, 1024]"), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus CommonChecker::CheckMultiPara( - const CheckContext& context) const { - if (CheckSameShape( - context, context.q, "q", context.attentionOut, "attention_out") != - ge::GRAPH_SUCCESS || - CheckQueryAxes(context) != ge::GRAPH_SUCCESS || - CheckKvAxes(context, context.oriKv, "ori_kv") != ge::GRAPH_SUCCESS || - CheckKvAxes(context, context.cmpKv, "cmp_kv") != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - OP_CHECK_IF( - (context.variant == OperatorVariant::SPARSE || - (context.variant == OperatorVariant::MIXED_QUANT && - context.quantMode == TURBO_QUANT_MODE)) && - context.q.desc->GetDataType() != - context.attentionOut.desc->GetDataType(), - OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( - Op(context), - "q and attention_out", - (std::to_string(static_cast(context.q.desc->GetDataType())) + - " and " + - std::to_string( - static_cast(context.attentionOut.desc->GetDataType()))) - .c_str(), - "Q and attention_out dtype must be the same"), - return ge::GRAPH_FAILED); - if (context.variant == OperatorVariant::SPARSE || - (context.variant == OperatorVariant::MIXED_QUANT && - context.quantMode == TURBO_QUANT_MODE)) { - OP_CHECK_IF( - context.q.desc->GetDataType() != context.oriKv.desc->GetDataType(), - OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( - Op(context), - "q and ori_kv", - (std::to_string( - static_cast(context.q.desc->GetDataType())) + - " and " + - std::to_string( - static_cast(context.oriKv.desc->GetDataType()))) - .c_str(), - "Q and ori_kv dtype must be the same"), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - context.variant == OperatorVariant::SPARSE && context.cmpKv.present && - context.q.desc->GetDataType() != context.cmpKv.desc->GetDataType(), - OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( - Op(context), - "q and cmp_kv", - (std::to_string( - static_cast(context.q.desc->GetDataType())) + - " and " + - std::to_string( - static_cast(context.cmpKv.desc->GetDataType()))) - .c_str(), - "Q and cmp_kv dtype must be the same"), - return ge::GRAPH_FAILED); - } - if (context.kvLayout == Layout::BSND) { - const int64_t qBatch = GetDim(context.q, 0); - OP_CHECK_IF(GetDim(context.oriKv, 0) != qBatch, - OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( - Op(context), - "q and ori_kv batch", - (std::to_string(qBatch) + " and " + - std::to_string(GetDim(context.oriKv, 0))) - .c_str(), - "Ori_kv batch must equal q batch"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(context.cmpKv.present && GetDim(context.cmpKv, 0) != qBatch, - OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( - Op(context), - "q and cmp_kv batch", - (std::to_string(qBatch) + " and " + - std::to_string(GetDim(context.cmpKv, 0))) - .c_str(), - "Cmp_kv batch must equal q batch"), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; -} - -} // namespace sparse_mla_checker -} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/common_checker_sparse_flash_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/common_checker_sparse_flash_mla.h deleted file mode 100644 index ab5a7746ad..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/common_checker_sparse_flash_mla.h +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#ifndef SPARSE_MLA_COMMON_CHECKER_SPARSE_FLASH_MLA_H -#define SPARSE_MLA_COMMON_CHECKER_SPARSE_FLASH_MLA_H - -#include "base_checker_sparse_flash_mla.h" - -namespace optiling { -namespace sparse_mla_checker { - -class CommonChecker : public BaseChecker { - public: - ge::graphStatus CheckSinglePara(const CheckContext& context) const override; - ge::graphStatus CheckParaExistence( - const CheckContext& context) const override; - ge::graphStatus CheckFeature(const CheckContext& context) const override; - ge::graphStatus CheckMultiPara(const CheckContext& context) const override; - - private: - ge::graphStatus CheckQuery(const CheckContext& context) const; - ge::graphStatus CheckKv(const CheckContext& context, - const TensorParam& kv, - const char* name) const; - ge::graphStatus CheckOutput(const CheckContext& context) const; - ge::graphStatus CheckQueryAxes(const CheckContext& context) const; - ge::graphStatus CheckKvAxes(const CheckContext& context, - const TensorParam& kv, - const char* name) const; -}; - -} // namespace sparse_mla_checker -} // namespace optiling - -#endif // SPARSE_MLA_COMMON_CHECKER_SPARSE_FLASH_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/mask_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/mask_checker.cpp deleted file mode 100644 index ccb9283fe9..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/mask_checker.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#include "mask_checker_sparse_flash_mla.h" -#include "sparse_flash_mla/op_host/common/log.h" - -namespace optiling { -namespace sparse_mla_checker { -namespace { -const char* Op(const CheckContext& context) { - return context.opName == nullptr ? "SparseMla" : context.opName; -} -} // namespace - -ge::graphStatus MaskChecker::CheckSinglePara( - const CheckContext& context) const { - OP_CHECK_IF( - context.oriMaskMode != 0 && context.oriMaskMode != 3 && - context.oriMaskMode != 4, // 3: RightDownCausal模式 4: Band模式 - OP_LOGE_FOR_INVALID_VALUE(Op(context), - "ori_mask_mode", - std::to_string(context.oriMaskMode).c_str(), - "0, 3 or 4"), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - context.cmpMaskMode != 0 && - context.cmpMaskMode != 3, // 3: RightDownCausal模式 - OP_LOGE_FOR_INVALID_VALUE(Op(context), - "cmp_mask_mode", - std::to_string(context.cmpMaskMode).c_str(), - "0 or 3"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(context.oriWinLeft < -1 || context.oriWinRight < -1, - OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( - Op(context), - "ori_win_left and ori_win_right", - (std::to_string(context.oriWinLeft) + ", " + - std::to_string(context.oriWinRight)) - .c_str(), - "Both values must be -1 or non-negative"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus MaskChecker::CheckFeature(const CheckContext& context) const { - if (context.oriMaskMode != 4) { // 4: Band模式 - OP_CHECK_IF(context.oriWinLeft != -1 || context.oriWinRight != -1, - OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( - Op(context), - "ori_win_left and ori_win_right", - (std::to_string(context.oriWinLeft) + ", " + - std::to_string(context.oriWinRight)) - .c_str(), - "Ori_win_left and ori_win_right must be -1 when " - "ori_mask_mode is not 4"), - return ge::GRAPH_FAILED); - } - - if (!context.cmpKv.present) { - OP_CHECK_IF(context.cmpMaskMode != 0, - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - Op(context), - "cmp_mask_mode", - std::to_string(context.cmpMaskMode).c_str(), - "Cmp_mask_mode must be 0 when cmp_kv is absent"), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; -} - -} // namespace sparse_mla_checker -} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/mask_checker_sparse_flash_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/mask_checker_sparse_flash_mla.h deleted file mode 100644 index fa594c4fe4..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/mask_checker_sparse_flash_mla.h +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#ifndef SPARSE_MLA_MASK_CHECKER_SPARSE_FLASH_MLA_H -#define SPARSE_MLA_MASK_CHECKER_SPARSE_FLASH_MLA_H - -#include "base_checker_sparse_flash_mla.h" - -namespace optiling { -namespace sparse_mla_checker { - -class MaskChecker : public BaseChecker { - public: - ge::graphStatus CheckSinglePara(const CheckContext& context) const override; - ge::graphStatus CheckFeature(const CheckContext& context) const override; -}; - -} // namespace sparse_mla_checker -} // namespace optiling - -#endif // SPARSE_MLA_MASK_CHECKER_SPARSE_FLASH_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/metadata_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/metadata_checker.cpp deleted file mode 100644 index 78da616ff4..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/metadata_checker.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#include "metadata_checker_sparse_flash_mla.h" -#include "sparse_flash_mla/op_host/common/log.h" - -namespace optiling { -namespace sparse_mla_checker { -namespace { -constexpr int64_t METADATA_SIZE_DEFAULT = 2048; - -const char* Op(const CheckContext& context) { - return context.opName == nullptr ? "SparseMla" : context.opName; -} -} // namespace - -ge::graphStatus MetadataChecker::CheckSinglePara( - const CheckContext& context) const { - if (!context.metadata.present) { - return ge::GRAPH_SUCCESS; - } - if (CheckTensorDesc(context, context.metadata, "metadata", {ge::DT_INT32}) != - ge::GRAPH_SUCCESS || - CheckShape( - context, context.metadata, "metadata", {METADATA_SIZE_DEFAULT}) != - ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus MetadataChecker::CheckParaExistence( - const CheckContext& context) const { - OP_CHECK_IF(!context.metadata.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "metadata", - "Metadata is required in the current version"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -} // namespace sparse_mla_checker -} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/metadata_checker_sparse_flash_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/metadata_checker_sparse_flash_mla.h deleted file mode 100644 index f879706a9e..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/metadata_checker_sparse_flash_mla.h +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#ifndef SPARSE_MLA_METADATA_CHECKER_SPARSE_FLASH_MLA_H -#define SPARSE_MLA_METADATA_CHECKER_SPARSE_FLASH_MLA_H - -#include "base_checker_sparse_flash_mla.h" - -namespace optiling { -namespace sparse_mla_checker { - -class MetadataChecker : public BaseChecker { - public: - ge::graphStatus CheckSinglePara(const CheckContext& context) const override; - ge::graphStatus CheckParaExistence( - const CheckContext& context) const override; -}; - -} // namespace sparse_mla_checker -} // namespace optiling - -#endif // SPARSE_MLA_METADATA_CHECKER_SPARSE_FLASH_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/paged_attention_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/paged_attention_checker.cpp deleted file mode 100644 index 3b57f98e1d..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/paged_attention_checker.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#include "paged_attention_checker_sparse_flash_mla.h" -#include "sparse_flash_mla/op_host/common/log.h" - -namespace optiling { -namespace sparse_mla_checker { -constexpr int64_t TURBO_QUANT_MODE = 3; -namespace { -const char* Op(const CheckContext& context) { - return context.opName == nullptr ? "SparseMla" : context.opName; -} -} // namespace - -ge::graphStatus PagedAttentionChecker::CheckBlockTable( - const CheckContext& context, - const TensorParam& param, - const char* name) const { - if (!param.present) { - return ge::GRAPH_SUCCESS; - } - if (CheckTensorDesc(context, param, name, {ge::DT_INT32}) != - ge::GRAPH_SUCCESS || - CheckDimNum(context, param, name, {2U}) != ge::GRAPH_SUCCESS || - CheckNoEmptyDim(context, param, name) != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus PagedAttentionChecker::CheckSinglePara( - const CheckContext& context) const { - if (CheckBlockTable(context, context.oriBlockTable, "ori_block_table") != - ge::GRAPH_SUCCESS || - CheckBlockTable(context, context.cmpBlockTable, "cmp_block_table") != - ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus PagedAttentionChecker::CheckParaExistence( - const CheckContext& context) const { - if (context.variant == OperatorVariant::MIXED_QUANT && - context.quantMode == TURBO_QUANT_MODE) { - OP_CHECK_IF( - !context.oriBlockTable.present || !context.cmpBlockTable.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "ori_block_table/cmp_block_table", - "TurboQuant requires both block tables"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; - } - if (context.kvLayout != Layout::PA_BBND) { - OP_CHECK_IF( - context.oriBlockTable.present || context.cmpBlockTable.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "ori_block_table and cmp_block_table", - "Block tables are only supported when layout_kv is PA_BBND"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; - } - - OP_CHECK_IF(!context.oriBlockTable.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "ori_block_table", - "Ori_block_table is required when layout_kv is PA_BBND"), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - context.cmpKv.present != context.cmpBlockTable.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "cmp_block_table", - "Cmp_block_table must be present exactly when PA cmp_kv is present"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(context.oriBlockTable.present && !context.sequsedOriKv.present && - !CanOmitSequsedOriKv(context), - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "seqused_ori_kv and ori_topk_length", - "Seqused_ori_kv is required with ori_block_table unless " - "ORI_SPARSE or ORI_CMP_SPARSE uses " - "mask_mode=0 with ori_topk_length"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(context.cmpBlockTable.present && !context.sequsedCmpKv.present && - !CanOmitSequsedCmpKv(context), - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "seqused_cmp_kv and cmp_topk_length", - "Seqused_cmp_kv is required with cmp_block_table unless " - "ORI_CMP_SPARSE uses mask_mode=0 " - "with cmp_topk_length"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus PagedAttentionChecker::CheckMultiPara( - const CheckContext& context) const { - if (context.oriBlockTable.present) { - OP_CHECK_IF(GetDim(context.oriBlockTable, 0) != context.bSize, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - Op(context), - "ori_block_table", - std::to_string(GetDim(context.oriBlockTable, 0)).c_str(), - ("The first dimension must equal batch size " + - std::to_string(context.bSize)) - .c_str()), - return ge::GRAPH_FAILED); - } - if (context.cmpBlockTable.present) { - OP_CHECK_IF(GetDim(context.cmpBlockTable, 0) != context.bSize, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - Op(context), - "cmp_block_table", - std::to_string(GetDim(context.cmpBlockTable, 0)).c_str(), - ("The first dimension must equal batch size " + - std::to_string(context.bSize)) - .c_str()), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; -} - -} // namespace sparse_mla_checker -} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/paged_attention_checker_sparse_flash_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/paged_attention_checker_sparse_flash_mla.h deleted file mode 100644 index 07f1c0cb42..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/paged_attention_checker_sparse_flash_mla.h +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#ifndef SPARSE_MLA_PAGED_ATTENTION_CHECKER_SPARSE_FLASH_MLA_H -#define SPARSE_MLA_PAGED_ATTENTION_CHECKER_SPARSE_FLASH_MLA_H - -#include "base_checker_sparse_flash_mla.h" - -namespace optiling { -namespace sparse_mla_checker { - -class PagedAttentionChecker : public BaseChecker { - public: - ge::graphStatus CheckSinglePara(const CheckContext& context) const override; - ge::graphStatus CheckParaExistence( - const CheckContext& context) const override; - ge::graphStatus CheckMultiPara(const CheckContext& context) const override; - - private: - ge::graphStatus CheckBlockTable(const CheckContext& context, - const TensorParam& param, - const char* name) const; -}; - -} // namespace sparse_mla_checker -} // namespace optiling - -#endif // SPARSE_MLA_PAGED_ATTENTION_CHECKER_SPARSE_FLASH_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/seq_len_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/seq_len_checker.cpp deleted file mode 100644 index 44df821d24..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/seq_len_checker.cpp +++ /dev/null @@ -1,192 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#include "seq_len_checker_sparse_flash_mla.h" -#include "sparse_flash_mla/op_host/common/log.h" - -namespace optiling { -namespace sparse_mla_checker { -constexpr int64_t TURBO_QUANT_MODE = 3; -namespace { -const char* Op(const CheckContext& context) { - return context.opName == nullptr ? "SparseMla" : context.opName; -} -} // namespace - -ge::graphStatus SeqLenChecker::CheckLengthTensor(const CheckContext& context, - const TensorParam& param, - const char* name) const { - if (!param.present) { - return ge::GRAPH_SUCCESS; - } - if (CheckTensorDesc(context, param, name, {ge::DT_INT32}) != - ge::GRAPH_SUCCESS || - CheckDimNum(context, param, name, {1U}) != ge::GRAPH_SUCCESS || - CheckNoEmptyDim(context, param, name) != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SeqLenChecker::CheckSinglePara( - const CheckContext& context) const { - if (CheckLengthTensor(context, context.cuSeqlensQ, "cu_seqlens_q") != - ge::GRAPH_SUCCESS || - CheckLengthTensor(context, context.cuSeqlensOriKv, "cu_seqlens_ori_kv") != - ge::GRAPH_SUCCESS || - CheckLengthTensor(context, context.cuSeqlensCmpKv, "cu_seqlens_cmp_kv") != - ge::GRAPH_SUCCESS || - CheckLengthTensor(context, context.sequsedQ, "seqused_q") != - ge::GRAPH_SUCCESS || - CheckLengthTensor(context, context.sequsedOriKv, "seqused_ori_kv") != - ge::GRAPH_SUCCESS || - CheckLengthTensor(context, context.sequsedCmpKv, "seqused_cmp_kv") != - ge::GRAPH_SUCCESS || - CheckLengthTensor(context, context.cmpResidualKv, "cmp_residual_kv") != - ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SeqLenChecker::CheckParaExistence( - const CheckContext& context) const { - if (context.variant == OperatorVariant::MIXED_QUANT && - context.quantMode == TURBO_QUANT_MODE) { - OP_CHECK_IF(!context.cuSeqlensQ.present || !context.sequsedOriKv.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "cu_seqlens_q/seqused_ori_kv", - "TurboQuant requires both inputs"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(context.cuSeqlensOriKv.present || - context.cuSeqlensCmpKv.present || - context.sequsedQ.present || context.sequsedCmpKv.present || - context.cmpResidualKv.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "sequence inputs", - "Unsupported sequence inputs were supplied for TurboQuant"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; - } - if (context.qLayout == Layout::TND) { - OP_CHECK_IF(!context.cuSeqlensQ.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "cu_seqlens_q", - "Cu_seqlens_q is required when layout_q is TND"), - return ge::GRAPH_FAILED); - } else { - OP_CHECK_IF(context.cuSeqlensQ.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "cu_seqlens_q", - "Cu_seqlens_q is only supported when layout_q is TND"), - return ge::GRAPH_FAILED); - } - - if (context.kvLayout == Layout::TND) { - OP_CHECK_IF(!context.cuSeqlensOriKv.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "cu_seqlens_ori_kv", - "Cu_seqlens_ori_kv is required when layout_kv is TND"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(context.cmpKv.present && !context.cuSeqlensCmpKv.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "cu_seqlens_cmp_kv", - "Cu_seqlens_cmp_kv is required when TND cmp_kv is present"), - return ge::GRAPH_FAILED); - } else { - OP_CHECK_IF( - context.cuSeqlensOriKv.present || context.cuSeqlensCmpKv.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "cu_seqlens_ori_kv and cu_seqlens_cmp_kv", - "KV cu_seqlens inputs are only supported when layout_kv is TND"), - return ge::GRAPH_FAILED); - } - - if (context.kvLayout == Layout::PA_BBND) { - OP_CHECK_IF(!context.sequsedOriKv.present && !CanOmitSequsedOriKv(context), - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "seqused_ori_kv and ori_topk_length", - "Seqused_ori_kv is required for Paged Attention unless " - "ORI_SPARSE or ORI_CMP_SPARSE " - "uses mask_mode=0 with ori_topk_length"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(context.cmpKv.present && !context.sequsedCmpKv.present && - !CanOmitSequsedCmpKv(context), - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "seqused_cmp_kv and cmp_topk_length", - "Seqused_cmp_kv is required for Paged Attention cmp_kv " - "unless ORI_CMP_SPARSE uses " - "mask_mode=0 with cmp_topk_length"), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SeqLenChecker::CheckLength(const CheckContext& context, - const TensorParam& param, - const char* name, - int64_t expected) const { - if (!param.present) { - return ge::GRAPH_SUCCESS; - } - OP_CHECK_IF(GetDim(param, 0) != expected, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - Op(context), - name, - std::to_string(GetDim(param, 0)).c_str(), - ("The length must be " + std::to_string(expected)).c_str()), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SeqLenChecker::CheckMultiPara( - const CheckContext& context) const { - const int64_t batch = context.bSize; - OP_CHECK_IF(batch <= 0, - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - Op(context), - "batch size", - std::to_string(batch).c_str(), - "Batch size must be greater than 0"), - return ge::GRAPH_FAILED); - if (CheckLength(context, context.cuSeqlensQ, "cu_seqlens_q", batch + 1) != - ge::GRAPH_SUCCESS || - CheckLength( - context, context.cuSeqlensOriKv, "cu_seqlens_ori_kv", batch + 1) != - ge::GRAPH_SUCCESS || - CheckLength( - context, context.cuSeqlensCmpKv, "cu_seqlens_cmp_kv", batch + 1) != - ge::GRAPH_SUCCESS || - CheckLength(context, context.sequsedQ, "seqused_q", batch) != - ge::GRAPH_SUCCESS || - CheckLength(context, context.sequsedOriKv, "seqused_ori_kv", batch) != - ge::GRAPH_SUCCESS || - CheckLength(context, context.sequsedCmpKv, "seqused_cmp_kv", batch) != - ge::GRAPH_SUCCESS || - CheckLength(context, context.cmpResidualKv, "cmp_residual_kv", batch) != - ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -} // namespace sparse_mla_checker -} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/seq_len_checker_sparse_flash_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/seq_len_checker_sparse_flash_mla.h deleted file mode 100644 index 131b1d7fb9..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/seq_len_checker_sparse_flash_mla.h +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#ifndef SPARSE_MLA_SEQ_LEN_CHECKER_SPARSE_FLASH_MLA_H -#define SPARSE_MLA_SEQ_LEN_CHECKER_SPARSE_FLASH_MLA_H - -#include "base_checker_sparse_flash_mla.h" - -namespace optiling { -namespace sparse_mla_checker { - -class SeqLenChecker : public BaseChecker { - public: - ge::graphStatus CheckSinglePara(const CheckContext& context) const override; - ge::graphStatus CheckParaExistence( - const CheckContext& context) const override; - ge::graphStatus CheckMultiPara(const CheckContext& context) const override; - - private: - ge::graphStatus CheckLengthTensor(const CheckContext& context, - const TensorParam& param, - const char* name) const; - ge::graphStatus CheckLength(const CheckContext& context, - const TensorParam& param, - const char* name, - int64_t expected) const; -}; - -} // namespace sparse_mla_checker -} // namespace optiling - -#endif // SPARSE_MLA_SEQ_LEN_CHECKER_SPARSE_FLASH_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sinks_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sinks_checker.cpp deleted file mode 100644 index 110d90fe1c..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sinks_checker.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#include "sinks_checker_sparse_flash_mla.h" -#include "sparse_flash_mla/op_host/common/log.h" - -namespace optiling { -namespace sparse_mla_checker { -namespace { -const char* Op(const CheckContext& context) { - return context.opName == nullptr ? "SparseMla" : context.opName; -} -} // namespace - -ge::graphStatus SinksChecker::CheckSinglePara( - const CheckContext& context) const { - if (!context.sinks.present) { - return ge::GRAPH_SUCCESS; - } - if (CheckTensorDesc(context, context.sinks, "sinks", {ge::DT_FLOAT}) != - ge::GRAPH_SUCCESS || - CheckDimNum(context, context.sinks, "sinks", {1U}) != ge::GRAPH_SUCCESS || - CheckNoEmptyDim(context, context.sinks, "sinks") != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SinksChecker::CheckParaExistence( - const CheckContext& context) const { - OP_CHECK_IF( - !context.sinks.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), "sinks", "Sinks is required in the current version"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SinksChecker::CheckMultiPara( - const CheckContext& context) const { - OP_CHECK_IF( - GetDim(context.sinks, 0) != context.qNumHeads, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - Op(context), - "sinks", - std::to_string(GetDim(context.sinks, 0)).c_str(), - ("The length must equal q_n " + std::to_string(context.qNumHeads)) - .c_str()), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -} // namespace sparse_mla_checker -} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sinks_checker_sparse_flash_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sinks_checker_sparse_flash_mla.h deleted file mode 100644 index f5dbee4785..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sinks_checker_sparse_flash_mla.h +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#ifndef SPARSE_MLA_SINKS_CHECKER_SPARSE_FLASH_MLA_H -#define SPARSE_MLA_SINKS_CHECKER_SPARSE_FLASH_MLA_H - -#include "base_checker_sparse_flash_mla.h" - -namespace optiling { -namespace sparse_mla_checker { - -class SinksChecker : public BaseChecker { - public: - ge::graphStatus CheckSinglePara(const CheckContext& context) const override; - ge::graphStatus CheckParaExistence( - const CheckContext& context) const override; - ge::graphStatus CheckMultiPara(const CheckContext& context) const override; -}; - -} // namespace sparse_mla_checker -} // namespace optiling - -#endif // SPARSE_MLA_SINKS_CHECKER_SPARSE_FLASH_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/softmax_lse_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/softmax_lse_checker.cpp deleted file mode 100644 index 633aba8331..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/softmax_lse_checker.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#include "softmax_lse_checker_sparse_flash_mla.h" -#include "sparse_flash_mla/op_host/common/log.h" - -namespace optiling { -namespace sparse_mla_checker { -namespace { -const char* Op(const CheckContext& context) { - return context.opName == nullptr ? "SparseMla" : context.opName; -} -} // namespace - -ge::graphStatus SoftmaxLseChecker::CheckSinglePara( - const CheckContext& context) const { - if (!context.returnSoftmaxLse || !context.softmaxLse.present) { - return ge::GRAPH_SUCCESS; - } - return CheckTensorDesc( - context, context.softmaxLse, "softmax_lse", {ge::DT_FLOAT}); -} - -ge::graphStatus SoftmaxLseChecker::CheckMultiPara( - const CheckContext& context) const { - if (!context.returnSoftmaxLse || !context.softmaxLse.present) { - return ge::GRAPH_SUCCESS; - } - - OP_CHECK_IF(context.qNumHeads % context.kvNumHeads != 0, - OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( - Op(context), - "qNumHeads and kvNumHeads", - (std::to_string(context.qNumHeads) + ", " + - std::to_string(context.kvNumHeads)) - .c_str(), - "QNumHeads must be divisible by kvNumHeads for softmax_lse"), - return ge::GRAPH_FAILED); - const int64_t group = context.qNumHeads / context.kvNumHeads; - if (context.qLayout == Layout::BSND) { - return CheckShape( - context, - context.softmaxLse, - "softmax_lse", - {context.bSize, context.kvNumHeads, context.qSeqSize, group}); - } - return CheckShape(context, - context.softmaxLse, - "softmax_lse", - {context.kvNumHeads, context.qTotalSize, group}); -} - -} // namespace sparse_mla_checker -} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/softmax_lse_checker_sparse_flash_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/softmax_lse_checker_sparse_flash_mla.h deleted file mode 100644 index 59aeb3dd64..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/softmax_lse_checker_sparse_flash_mla.h +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#ifndef SPARSE_MLA_SOFTMAX_LSE_CHECKER_SPARSE_FLASH_MLA_H -#define SPARSE_MLA_SOFTMAX_LSE_CHECKER_SPARSE_FLASH_MLA_H - -#include "base_checker_sparse_flash_mla.h" - -namespace optiling { -namespace sparse_mla_checker { - -class SoftmaxLseChecker : public BaseChecker { - public: - ge::graphStatus CheckSinglePara(const CheckContext& context) const override; - ge::graphStatus CheckMultiPara(const CheckContext& context) const override; -}; - -} // namespace sparse_mla_checker -} // namespace optiling - -#endif // SPARSE_MLA_SOFTMAX_LSE_CHECKER_SPARSE_FLASH_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_compression_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_compression_checker.cpp deleted file mode 100644 index dce2d151a2..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_compression_checker.cpp +++ /dev/null @@ -1,323 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#include "sparse_compression_checker.h" - -#include "sparse_flash_mla/op_host/common/log.h" - -namespace optiling { -namespace sparse_mla_checker { -constexpr int64_t TURBO_QUANT_MODE = 3; -namespace { -const char* Op(const CheckContext& context) { - return context.opName == nullptr ? "SparseMla" : context.opName; -} - -bool IsTurboQuantEmptyTndIndex(const CheckContext& context, - const TensorParam& param, - const char* name) { - return context.variant == OperatorVariant::MIXED_QUANT && - context.quantMode == TURBO_QUANT_MODE && - context.qLayout == Layout::TND && - std::string(name) == "cmp_sparse_indices" && param.shape != nullptr && - param.shape->GetDimNum() > 0 && param.shape->GetDim(0) == 0; -} -} // namespace - -ge::graphStatus SparseCompressionChecker::CheckIndex( - const CheckContext& context, - const TensorParam& param, - const char* name) const { - if (!param.present) { - return ge::GRAPH_SUCCESS; - } - const size_t dimNum = context.qLayout == Layout::BSND ? 4U : 3U; - if (CheckTensorDesc(context, param, name, {ge::DT_INT32}) != - ge::GRAPH_SUCCESS || - CheckDimNum(context, param, name, {dimNum}) != ge::GRAPH_SUCCESS || - (!IsTurboQuantEmptyTndIndex(context, param, name) && - CheckNoEmptyDim(context, param, name) != ge::GRAPH_SUCCESS)) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SparseCompressionChecker::CheckTopkLength( - const CheckContext& context, - const TensorParam& param, - const char* name) const { - if (!param.present) { - return ge::GRAPH_SUCCESS; - } - const size_t dimNum = context.qLayout == Layout::BSND ? 3U : 2U; - if (CheckTensorDesc(context, param, name, {ge::DT_INT32}) != - ge::GRAPH_SUCCESS || - CheckDimNum(context, param, name, {dimNum}) != ge::GRAPH_SUCCESS || - CheckNoEmptyDim(context, param, name) != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SparseCompressionChecker::CheckSinglePara( - const CheckContext& context) const { - OP_CHECK_IF(context.cmpRatio < 1 || context.cmpRatio > 128, - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - Op(context), - "cmp_ratio", - std::to_string(context.cmpRatio).c_str(), - "Cmp_ratio must be in range [1, 128]"), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - context.topkValueMode != 1 && context.topkValueMode != 2, - OP_LOGE_FOR_INVALID_VALUE(Op(context), - "topk_value_mode", - std::to_string(context.topkValueMode).c_str(), - "1 or 2"), - return ge::GRAPH_FAILED); - if (CheckIndex(context, context.oriSparseIndices, "ori_sparse_indices") != - ge::GRAPH_SUCCESS || - CheckIndex(context, context.cmpSparseIndices, "cmp_sparse_indices") != - ge::GRAPH_SUCCESS || - CheckTopkLength(context, context.oriTopkLength, "ori_topk_length") != - ge::GRAPH_SUCCESS || - CheckTopkLength(context, context.cmpTopkLength, "cmp_topk_length") != - ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SparseCompressionChecker::CheckParaExistence( - const CheckContext& context) const { - if (context.variant == OperatorVariant::MIXED_QUANT && - context.quantMode == TURBO_QUANT_MODE) { - OP_CHECK_IF(!context.cmpKv.present || !context.cmpSparseIndices.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "cmp_kv/cmp_sparse_indices", - "TurboQuant requires both inputs"), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - context.oriSparseIndices.present || context.cmpResidualKv.present || - context.oriTopkLength.present || context.cmpTopkLength.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "unsupported TurboQuant inputs", - "ori_sparse_indices, cmp_residual_kv and topk length inputs must " - "be absent"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; - } - if (!context.cmpKv.present) { - OP_CHECK_IF(context.cmpSparseIndices.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "cmp_sparse_indices", - "Cmp_sparse_indices requires cmp_kv"), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - context.cmpTopkLength.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), "cmp_topk_length", "Cmp_topk_length requires cmp_kv"), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - context.cmpResidualKv.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), "cmp_residual_kv", "Cmp_residual_kv requires cmp_kv"), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - context.cmpBlockTable.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), "cmp_block_table", "Cmp_block_table requires cmp_kv"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(context.cuSeqlensCmpKv.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "cu_seqlens_cmp_kv", - "Cu_seqlens_cmp_kv requires cmp_kv"), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - context.sequsedCmpKv.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), "seqused_cmp_kv", "Seqused_cmp_kv requires cmp_kv"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(context.cmpRatio != 1, - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - Op(context), - "cmp_ratio", - std::to_string(context.cmpRatio).c_str(), - "Cmp_ratio must be 1 when cmp_kv is absent"), - return ge::GRAPH_FAILED); - } - - const bool needResidual = context.cmpKv.present && context.cmpMaskMode == 3 && - context.cmpRatio != 1; - OP_CHECK_IF(needResidual && !context.cmpResidualKv.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "cmp_residual_kv", - "Cmp_residual_kv is required when cmp_mask_mode is 3 and " - "cmp_ratio is not 1"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(context.cmpResidualKv.present && - (context.cmpMaskMode == 0 || context.cmpRatio == 1), - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "cmp_residual_kv", - std::string("Cmp_residual_kv is not supported when " - "cmp_mask_mode is 0 or cmp_ratio is 1, " - "but got cmp_mask_mode=") + - std::to_string(context.cmpMaskMode) + - ", cmp_ratio=" + std::to_string(context.cmpRatio)), - return ge::GRAPH_FAILED); - OP_CHECK_IF(context.oriSparseIndices.present && context.oriMaskMode == 0 && - !context.oriTopkLength.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "ori_topk_length", - "Ori_topk_length is required when ori_sparse_indices is " - "present and ori_mask_mode is 0"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(context.cmpSparseIndices.present && context.cmpMaskMode == 0 && - !context.cmpTopkLength.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "cmp_topk_length", - "Cmp_topk_length is required when cmp_sparse_indices is " - "present and cmp_mask_mode is 0"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SparseCompressionChecker::CheckFeature( - const CheckContext& context) const { - if (context.topkValueMode == 2) { // 2:top-k - OP_CHECK_IF( - context.kvLayout != Layout::PA_BBND, - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - Op(context), - "topk_value_mode", - std::to_string(static_cast(context.kvLayout)).c_str(), - "Topk_value_mode 2 is only supported when layout_kv is PA_BBND"), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - !context.oriSparseIndices.present && !context.cmpSparseIndices.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "ori_sparse_indices/cmp_sparse_indices", - "At least one sparse_indices input is required when " - "topk_value_mode is 2"), - return ge::GRAPH_FAILED); - } - OP_CHECK_IF(context.cmpSparseIndices.present && !context.cmpKv.present, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Op(context), - "cmp_sparse_indices", - "Cmp_sparse_indices requires cmp_kv"), - return ge::GRAPH_FAILED); - if (context.cmpSparseIndices.present) { - OP_CHECK_IF(context.cmpTopk <= 0, - OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( - Op(context), - "cmp_sparse_indices", - std::to_string(context.cmpTopk).c_str(), - "The last dimension must be greater than 0 when " - "cmp_sparse_indices is present"), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SparseCompressionChecker::CheckIndexShape( - const CheckContext& context, - const TensorParam& param, - const char* name) const { - if (!param.present) { - return ge::GRAPH_SUCCESS; - } - if (context.qLayout == Layout::BSND) { - const std::string actualShape = "(" + std::to_string(GetDim(param, 0)) + - ", " + std::to_string(GetDim(param, 1)) + - ", " + std::to_string(GetDim(param, 2)) + - ", " + std::to_string(GetDim(param, 3)) + - ")"; - OP_CHECK_IF( - GetDim(param, 0) != GetDim(context.q, 0) || - GetDim(param, 1) != GetDim(context.q, 1) || GetDim(param, 2) != 1, - OP_LOGE_FOR_INVALID_SHAPE( - Op(context), name, actualShape.c_str(), "(b, q_s, kv_n, topk)"), - return ge::GRAPH_FAILED); - } else { - const std::string actualShape = "(" + std::to_string(GetDim(param, 0)) + - ", " + std::to_string(GetDim(param, 1)) + - ", " + std::to_string(GetDim(param, 2)) + - ")"; - OP_CHECK_IF( - GetDim(param, 0) != GetDim(context.q, 0) || GetDim(param, 1) != 1, - OP_LOGE_FOR_INVALID_SHAPE( - Op(context), name, actualShape.c_str(), "(q_t, kv_n, topk)"), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SparseCompressionChecker::CheckTopkLengthShape( - const CheckContext& context, - const TensorParam& param, - const char* name) const { - if (!param.present) { - return ge::GRAPH_SUCCESS; - } - if (context.qLayout == Layout::BSND) { - const std::string actualShape = "(" + std::to_string(GetDim(param, 0)) + - ", " + std::to_string(GetDim(param, 1)) + - ", " + std::to_string(GetDim(param, 2)) + - ")"; - OP_CHECK_IF(GetDim(param, 0) != GetDim(context.q, 0) || - GetDim(param, 1) != GetDim(context.q, 1) || - GetDim(param, 2) != 1, - OP_LOGE_FOR_INVALID_SHAPE( - Op(context), name, actualShape.c_str(), "(b, q_s, kv_n)"), - return ge::GRAPH_FAILED); - } else { - const std::string actualShape = "(" + std::to_string(GetDim(param, 0)) + - ", " + std::to_string(GetDim(param, 1)) + - ")"; - OP_CHECK_IF( - GetDim(param, 0) != GetDim(context.q, 0) || GetDim(param, 1) != 1, - OP_LOGE_FOR_INVALID_SHAPE( - Op(context), name, actualShape.c_str(), "(q_t, kv_n)"), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SparseCompressionChecker::CheckMultiPara( - const CheckContext& context) const { - if (CheckIndexShape(context, - context.oriSparseIndices, - "ori_sparse_indices") != ge::GRAPH_SUCCESS || - CheckIndexShape(context, - context.cmpSparseIndices, - "cmp_sparse_indices") != ge::GRAPH_SUCCESS || - CheckTopkLengthShape(context, context.oriTopkLength, "ori_topk_length") != - ge::GRAPH_SUCCESS || - CheckTopkLengthShape(context, context.cmpTopkLength, "cmp_topk_length") != - ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -} // namespace sparse_mla_checker -} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_compression_checker.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_compression_checker.h deleted file mode 100644 index 20a6c96c12..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_compression_checker.h +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#ifndef SPARSE_MLA_SPARSE_COMPRESSION_CHECKER_H -#define SPARSE_MLA_SPARSE_COMPRESSION_CHECKER_H - -#include "base_checker_sparse_flash_mla.h" - -namespace optiling { -namespace sparse_mla_checker { - -class SparseCompressionChecker : public BaseChecker { - public: - ge::graphStatus CheckSinglePara(const CheckContext& context) const override; - ge::graphStatus CheckParaExistence( - const CheckContext& context) const override; - ge::graphStatus CheckFeature(const CheckContext& context) const override; - ge::graphStatus CheckMultiPara(const CheckContext& context) const override; - - private: - ge::graphStatus CheckIndex(const CheckContext& context, - const TensorParam& param, - const char* name) const; - ge::graphStatus CheckTopkLength(const CheckContext& context, - const TensorParam& param, - const char* name) const; - ge::graphStatus CheckIndexShape(const CheckContext& context, - const TensorParam& param, - const char* name) const; - ge::graphStatus CheckTopkLengthShape(const CheckContext& context, - const TensorParam& param, - const char* name) const; -}; - -} // namespace sparse_mla_checker -} // namespace optiling - -#endif // SPARSE_MLA_SPARSE_COMPRESSION_CHECKER_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_flash_mla_checker.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_flash_mla_checker.cpp deleted file mode 100644 index cdb25ca88c..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_flash_mla_checker.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#include "sparse_flash_mla_checker.h" - -#include "checker_adapter.h" -#include "checker_runner.h" - -namespace optiling { -namespace { -using sparse_mla_checker::CheckContext; -CheckContext BuildContext(const SMLATilingInfo& info) { - CheckContext context; - sparse_mla_checker::PopulateCommonContext(context, info); - context.variant = sparse_mla_checker::OperatorVariant::SPARSE; - context.qHeadDim = info.qHeadDim; - context.oriKvHeadDim = info.oriKvHeadDim; - context.cmpKvHeadDim = info.cmpKvHeadDim; - return context; -} -} // namespace - -ge::graphStatus SparseFlashMlaChecker::Process() const { - sparse_mla_checker::CheckerRunner runner; - sparse_mla_checker::RegisterCommonCheckers(runner); - return runner.Process(BuildContext(info_)); -} - -} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_flash_mla_checker.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_flash_mla_checker.h deleted file mode 100644 index 02bdabf41d..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/checkers/sparse_flash_mla_checker.h +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#ifndef SPARSE_FLASH_MLA_CHECKER_H -#define SPARSE_FLASH_MLA_CHECKER_H - -#include "graph/ge_error_codes.h" -#include "sparse_flash_mla/op_host/sparse_flash_mla_tiling.h" - -namespace optiling { - -class SparseFlashMlaChecker { - public: - explicit SparseFlashMlaChecker(const SMLATilingInfo& info) : info_(info) {} - ge::graphStatus Process() const; - - private: - const SMLATilingInfo& info_; -}; - -} // namespace optiling - -#endif // SPARSE_FLASH_MLA_CHECKER_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/log.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/log.h deleted file mode 100644 index 2b6a6c370f..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/log.h +++ /dev/null @@ -1,776 +0,0 @@ -/** - * Copyright (c) 2025 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file mc2_log_compat.h - * \brief Forward compatibility: provides OP_LOGE_LIBOPAPI_REPORT and - * OP_LOGE_FOR_* macros (EZ0008-EZ0034) when using an older log.h that only - * defines EZ0001-EZ0007. Includes log/log.h internally; include this file as - * the sole log header. - */ - -#ifndef SMLA_LOG_COMPAT_H -#define SMLA_LOG_COMPAT_H - -#include -#include -#include - -#include "log/log.h" - -// ============================================================================ -// OP_LOGE_LIBOPAPI_REPORT fallback -// New log.h defines this macro; old log.h does not. -// For opapi build (OP_LOG_LIBOPAPI_ONLY): use opdev's DOplogSub -// to avoid type conflicts with old log.h's GetOpInfo template. -// For host build: use old log.h's D_OP_LOGE via Ops::Base::GetOpInfo. -// ============================================================================ -#ifndef OP_LOGE_LIBOPAPI_REPORT -#ifdef OP_LOG_LIBOPAPI_ONLY -#define OP_LOGE_LIBOPAPI_REPORT(opName, fmt, ...) \ - DOplogSub(static_cast(OP_ID), \ - OPAPI_SUBMOD_NAME, \ - OP_LOG_ERROR, \ - "[%s][%lu] OpName:[%s] " fmt, \ - __FUNCTION__, \ - op::OpLog::GetTid(), \ - opName, \ - ##__VA_ARGS__) -#else -#define OP_LOGE_LIBOPAPI_REPORT(opName, fmt, ...) \ - D_OP_LOGE(Ops::Base::GetOpInfo(opName), fmt, ##__VA_ARGS__) -#endif /* OP_LOG_LIBOPAPI_ONLY */ -#endif /* OP_LOGE_LIBOPAPI_REPORT */ - -// ============================================================================ -// For opapi build (OP_LOG_LIBOPAPI_ONLY): old log.h unconditionally defines -// OP_LOGE, D_OP_LOGE, OpLogErrSub, etc. with signatures that differ from -// opdev/op_log.h's versions. The opapi source code expects opdev's signatures -// (e.g. OP_LOGE(errno, ...) where first arg is an error code, not opName). -// Undefine old log.h's versions and provide opdev-compatible replacements. -// ============================================================================ -#ifdef OP_LOG_LIBOPAPI_ONLY -#undef OpLogSub -#undef OpLogErrSub -#undef D_OP_LOGI -#undef D_OP_LOGW -#undef D_OP_LOGE -#undef D_OP_LOGD -#undef OP_LOGI -#undef OP_LOGW -#undef OP_LOGE_WITHOUT_REPORT -#undef OP_LOGE -#undef OP_LOGD -#undef OP_CHECK_IF -#undef OP_CHECK_NULL_WITH_CONTEXT - -// Restore opdev/op_log.h signatures after old log.h shadowed them. -// DOplogSub, GetOpName, GetFileName, -// and op::OpLog::GetTid() are from opdev/op_log.h and NOT redefined by old -// log.h (different names), so they remain available. -#define OpLogSub(moduleId, level, op_info, fmt, ...) \ - DOplogSub(static_cast(moduleId), \ - OPAPI_SUBMOD_NAME, \ - level, \ - "[%s][%lu] %s" fmt, \ - __FUNCTION__, \ - op::OpLog::GetTid(), \ - op_info, \ - ##__VA_ARGS__) - -#define OpLogErrSub(moduleId, level, op_info, errno, fmt, ...) \ - DOplogSub(static_cast(moduleId), \ - OPAPI_SUBMOD_NAME, \ - level, \ - "[%s][%lu] errno[%d] %s" fmt, \ - __FUNCTION__, \ - op::OpLog::GetTid(), \ - errno, \ - op_info, \ - ##__VA_ARGS__) - -#define OpDfxLogSub(moduleId, level, file, line, func, op_info, fmt, ...) \ - DDfxlogSub(static_cast(moduleId), \ - OPAPI_SUBMOD_NAME, \ - level, \ - GetFileName(file), \ - line, \ - "[%s][%lu] %s" fmt, \ - func, \ - op::OpLog::GetTid(), \ - op_info, \ - ##__VA_ARGS__) - -#define D_OP_LOGI(opname, fmt, ...) \ - OpLogSub(OP_ID, OP_LOG_INFO, opname, fmt, ##__VA_ARGS__) -#define D_OP_LOGW(opname, fmt, ...) \ - OpLogSub(OP_ID, OP_LOG_WARN, opname, fmt, ##__VA_ARGS__) -#define D_OP_LOGE(opname, errno, fmt, ...) \ - OpLogErrSub(OP_ID, OP_LOG_ERROR, opname, errno, fmt, ##__VA_ARGS__) -#define D_OP_LOGD(opname, fmt, ...) \ - OpLogSub(OP_ID, OP_LOG_DEBUG, opname, fmt, ##__VA_ARGS__) -#define D_OP_EVENT(opname, fmt, ...) \ - OpLogSub(OP_ID, OP_LOG_EVENT, opname, fmt, ##__VA_ARGS__) - -#define OP_LOGI(...) D_OP_LOGI(GetOpName().c_str(), __VA_ARGS__) -#define OP_LOGW(...) D_OP_LOGW(GetOpName().c_str(), __VA_ARGS__) -#define OP_LOGE_WITHOUT_REPORT(errno, ...) \ - D_OP_LOGE(GetOpName().c_str(), errno, __VA_ARGS__) -#define OP_LOGE(errno, ...) \ - do { \ - OP_LOGE_WITHOUT_REPORT(errno, __VA_ARGS__); \ - REPORT_ERROR_MESSAGE(errno, __VA_ARGS__); \ - } while (false) -#define OP_LOGD(...) D_OP_LOGD(GetOpName().c_str(), __VA_ARGS__) -#define OP_EVENT(...) D_OP_EVENT(GetOpName().c_str(), __VA_ARGS__) -#endif /* OP_LOG_LIBOPAPI_ONLY */ - -// ============================================================================ -// OP_LOGE_FOR_* macros (EZ0008-EZ0034) -// New log.h defines these; old log.h does not. -// ============================================================================ -#ifndef OP_LOGE_FOR_INVALID_SHAPE - -// EZ0008: Parameter shape error (single parameter, with correct shape) -#define OP_LOGE_FOR_INVALID_SHAPE( \ - opName, paramName, incorrectShape, correctShape) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramName_(paramName); \ - std::string _safe_incorrectShape_(incorrectShape); \ - std::string _safe_correctShape_(correctShape); \ - OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ - "Parameter %s of operator %s has incorrect shape " \ - "%s. It should be %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectShape_.c_str(), \ - _safe_correctShape_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0008", \ - "Parameter %s of operator %s has incorrect shape " \ - "%s. It should be %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectShape_.c_str(), \ - _safe_correctShape_.c_str()); \ - } while (0) - -// EZ0009: Parameter shape error (single parameter, with reason) -#define OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( \ - opName, paramName, incorrectShape, reason) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramName_(paramName); \ - std::string _safe_incorrectShape_(incorrectShape); \ - std::string _safe_reason_(reason); \ - OP_LOGE_LIBOPAPI_REPORT( \ - _safe_opName_.c_str(), \ - "Parameter %s of operator %s has incorrect shape %s. Reason: %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectShape_.c_str(), \ - _safe_reason_.c_str()); \ - REPORT_INNER_ERR_MSG( \ - "EZ0009", \ - "Parameter %s of operator %s has incorrect shape %s. Reason: %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectShape_.c_str(), \ - _safe_reason_.c_str()); \ - } while (0) - -// EZ0010: Parameters shape error (multiple parameters, with reason) -#define OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( \ - opName, paramNames, incorrectShapes, reason) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramNames_(paramNames); \ - std::string _safe_incorrectShapes_(incorrectShapes); \ - std::string _safe_reason_(reason); \ - OP_LOGE_LIBOPAPI_REPORT( \ - _safe_opName_.c_str(), \ - "Parameters %s of operator %s have incorrect shapes %s. Reason: %s.", \ - _safe_paramNames_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectShapes_.c_str(), \ - _safe_reason_.c_str()); \ - REPORT_INNER_ERR_MSG( \ - "EZ0010", \ - "Parameters %s of operator %s have incorrect shapes %s. Reason: %s.", \ - _safe_paramNames_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectShapes_.c_str(), \ - _safe_reason_.c_str()); \ - } while (0) - -// EZ0011: Parameter shape dim error (single parameter, with correct dim) -#define OP_LOGE_FOR_INVALID_SHAPEDIM( \ - opName, paramName, incorrectDim, correctDim) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramName_(paramName); \ - std::string _safe_incorrectDim_(incorrectDim); \ - std::string _safe_correctDim_(correctDim); \ - OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ - "Parameter %s of operator %s has incorrect shape " \ - "dim %s. It should be %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectDim_.c_str(), \ - _safe_correctDim_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0011", \ - "Parameter %s of operator %s has incorrect shape " \ - "dim %s. It should be %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectDim_.c_str(), \ - _safe_correctDim_.c_str()); \ - } while (0) - -// EZ0012: Parameter shape dim error (single parameter, with reason) -#define OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( \ - opName, paramName, incorrectDim, reason) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramName_(paramName); \ - std::string _safe_incorrectDim_(incorrectDim); \ - std::string _safe_reason_(reason); \ - OP_LOGE_LIBOPAPI_REPORT( \ - _safe_opName_.c_str(), \ - "Parameter %s of operator %s has incorrect shape dim %s. Reason: %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectDim_.c_str(), \ - _safe_reason_.c_str()); \ - REPORT_INNER_ERR_MSG( \ - "EZ0012", \ - "Parameter %s of operator %s has incorrect shape dim %s. Reason: %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectDim_.c_str(), \ - _safe_reason_.c_str()); \ - } while (0) - -// EZ0013: Parameters shape dim error (multiple parameters, with reason) -#define OP_LOGE_FOR_INVALID_SHAPEDIMS_WITH_REASON( \ - opName, paramNames, incorrectDims, reason) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramNames_(paramNames); \ - std::string _safe_incorrectDims_(incorrectDims); \ - std::string _safe_reason_(reason); \ - OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ - "Parameters %s of operator %s have incorrect " \ - "shape dims %s. Reason: %s.", \ - _safe_paramNames_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectDims_.c_str(), \ - _safe_reason_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0013", \ - "Parameters %s of operator %s have incorrect shape " \ - "dims %s. Reason: %s.", \ - _safe_paramNames_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectDims_.c_str(), \ - _safe_reason_.c_str()); \ - } while (0) - -// EZ0014: Parameter shape size error (single parameter, with correct size) -#define OP_LOGE_FOR_INVALID_SHAPESIZE( \ - opName, paramName, incorrectSize, correctSize) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramName_(paramName); \ - std::string _safe_incorrectSize_(incorrectSize); \ - std::string _safe_correctSize_(correctSize); \ - OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ - "Parameter %s of operator %s has incorrect shape " \ - "size %s. It should be %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectSize_.c_str(), \ - _safe_correctSize_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0014", \ - "Parameter %s of operator %s has incorrect shape " \ - "size %s. It should be %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectSize_.c_str(), \ - _safe_correctSize_.c_str()); \ - } while (0) - -// EZ0015: Parameter shape size error (single parameter, with reason) -#define OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( \ - opName, paramName, incorrectSize, reason) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramName_(paramName); \ - std::string _safe_incorrectSize_(incorrectSize); \ - std::string _safe_reason_(reason); \ - OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ - "Parameter %s of operator %s has incorrect shape " \ - "size %s. Reason: %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectSize_.c_str(), \ - _safe_reason_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0015", \ - "Parameter %s of operator %s has incorrect shape " \ - "size %s. Reason: %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectSize_.c_str(), \ - _safe_reason_.c_str()); \ - } while (0) - -// EZ0016: Parameters shape size error (multiple parameters, with reason) -#define OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( \ - opName, paramNames, incorrectSizes, reason) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramNames_(paramNames); \ - std::string _safe_incorrectSizes_(incorrectSizes); \ - std::string _safe_reason_(reason); \ - OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ - "Parameters %s of operator %s have incorrect " \ - "shape sizes %s. Reason: %s.", \ - _safe_paramNames_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectSizes_.c_str(), \ - _safe_reason_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0016", \ - "Parameters %s of operator %s have incorrect shape " \ - "sizes %s. Reason: %s.", \ - _safe_paramNames_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectSizes_.c_str(), \ - _safe_reason_.c_str()); \ - } while (0) - -// EZ0017: Parameter format error (single parameter, with correct format) -#define OP_LOGE_FOR_INVALID_FORMAT( \ - opName, paramName, incorrectFormat, correctFormat) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramName_(paramName); \ - std::string _safe_incorrectFormat_(incorrectFormat); \ - std::string _safe_correctFormat_(correctFormat); \ - OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ - "Parameter %s of operator %s has incorrect " \ - "format %s. It should be %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectFormat_.c_str(), \ - _safe_correctFormat_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0017", \ - "Parameter %s of operator %s has incorrect format " \ - "%s. It should be %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectFormat_.c_str(), \ - _safe_correctFormat_.c_str()); \ - } while (0) - -// EZ0018: Parameters format error (multiple parameters, with reason) -#define OP_LOGE_FOR_INVALID_FORMATS_WITH_REASON( \ - opName, paramNames, incorrectFormats, reason) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramNames_(paramNames); \ - std::string _safe_incorrectFormats_(incorrectFormats); \ - std::string _safe_reason_(reason); \ - OP_LOGE_LIBOPAPI_REPORT( \ - _safe_opName_.c_str(), \ - "Parameters %s of operator %s have incorrect formats %s. Reason: %s.", \ - _safe_paramNames_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectFormats_.c_str(), \ - _safe_reason_.c_str()); \ - REPORT_INNER_ERR_MSG( \ - "EZ0018", \ - "Parameters %s of operator %s have incorrect formats %s. Reason: %s.", \ - _safe_paramNames_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectFormats_.c_str(), \ - _safe_reason_.c_str()); \ - } while (0) - -// EZ0019: Parameter dtype error (single parameter, with correct dtype) -#define OP_LOGE_FOR_INVALID_DTYPE( \ - opName, paramName, incorrectDtype, correctDtype) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramName_(paramName); \ - std::string _safe_incorrectDtype_(incorrectDtype); \ - std::string _safe_correctDtype_(correctDtype); \ - OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ - "Parameter %s of operator %s has incorrect dtype " \ - "%s. It should be %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectDtype_.c_str(), \ - _safe_correctDtype_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0019", \ - "Parameter %s of operator %s has incorrect dtype " \ - "%s. It should be %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectDtype_.c_str(), \ - _safe_correctDtype_.c_str()); \ - } while (0) - -// EZ0020: Parameter dtype error (single parameter, with reason) -#define OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( \ - opName, paramName, incorrectDtype, reason) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramName_(paramName); \ - std::string _safe_incorrectDtype_(incorrectDtype); \ - std::string _safe_reason_(reason); \ - OP_LOGE_LIBOPAPI_REPORT( \ - _safe_opName_.c_str(), \ - "Parameter %s of operator %s has incorrect dtype %s. Reason: %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectDtype_.c_str(), \ - _safe_reason_.c_str()); \ - REPORT_INNER_ERR_MSG( \ - "EZ0020", \ - "Parameter %s of operator %s has incorrect dtype %s. Reason: %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectDtype_.c_str(), \ - _safe_reason_.c_str()); \ - } while (0) - -// EZ0021: Parameters dtype error (multiple parameters, with reason) -#define OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( \ - opName, paramNames, incorrectDtypes, reason) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramNames_(paramNames); \ - std::string _safe_incorrectDtypes_(incorrectDtypes); \ - std::string _safe_reason_(reason); \ - OP_LOGE_LIBOPAPI_REPORT( \ - _safe_opName_.c_str(), \ - "Parameters %s of operator %s have incorrect dtypes %s. Reason: %s.", \ - _safe_paramNames_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectDtypes_.c_str(), \ - _safe_reason_.c_str()); \ - REPORT_INNER_ERR_MSG( \ - "EZ0021", \ - "Parameters %s of operator %s have incorrect dtypes %s. Reason: %s.", \ - _safe_paramNames_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectDtypes_.c_str(), \ - _safe_reason_.c_str()); \ - } while (0) - -// EZ0022: Parameter tensor num error (single parameter, with correct num) -#define OP_LOGE_FOR_INVALID_TENSORNUM( \ - opName, paramName, incorrectNum, correctNum) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramName_(paramName); \ - std::string _safe_correctNum_(correctNum); \ - OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ - "Parameter %s of operator %s has invalid tensor " \ - "num %ld. It should be %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - static_cast(incorrectNum), \ - _safe_correctNum_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0022", \ - "Parameter %s of operator %s has invalid tensor num " \ - "%ld. It should be %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - static_cast(incorrectNum), \ - _safe_correctNum_.c_str()); \ - } while (0) - -// EZ0023: Parameters tensor num error (multiple parameters, with reason) -#define OP_LOGE_FOR_INVALID_TENSORNUMS_WITH_REASON( \ - opName, paramNames, incorrectNums, reason) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramNames_(paramNames); \ - std::string _safe_incorrectNums_(incorrectNums); \ - std::string _safe_reason_(reason); \ - OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ - "Parameters %s of operator %s have invalid " \ - "tensor nums %s. Reason: %s.", \ - _safe_paramNames_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectNums_.c_str(), \ - _safe_reason_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0023", \ - "Parameters %s of operator %s have invalid tensor " \ - "nums %s. Reason: %s.", \ - _safe_paramNames_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectNums_.c_str(), \ - _safe_reason_.c_str()); \ - } while (0) - -// EZ0024: Parameter value error (single parameter, with correct value) -#define OP_LOGE_FOR_INVALID_VALUE( \ - opName, paramName, incorrectValue, correctValue) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramName_(paramName); \ - std::string _safe_incorrectValue_(incorrectValue); \ - std::string _safe_correctValue_(correctValue); \ - OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ - "Parameter %s of operator %s has incorrect value " \ - "%s. It should be %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectValue_.c_str(), \ - _safe_correctValue_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0024", \ - "Parameter %s of operator %s has incorrect value " \ - "%s. It should be %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectValue_.c_str(), \ - _safe_correctValue_.c_str()); \ - } while (0) - -// EZ0025: Parameter list size error (single parameter, with correct size) -#define OP_LOGE_FOR_INVALID_LISTSIZE( \ - opName, paramName, incorrectSize, correctSize) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramName_(paramName); \ - std::string _safe_incorrectSize_(incorrectSize); \ - std::string _safe_correctSize_(correctSize); \ - OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ - "Parameter %s of operator %s has incorrect " \ - "element nums %s. It should be %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectSize_.c_str(), \ - _safe_correctSize_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0025", \ - "Parameter %s of operator %s has incorrect element " \ - "nums %s. It should be %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectSize_.c_str(), \ - _safe_correctSize_.c_str()); \ - } while (0) - -// EZ0026: Parameter value error (single parameter, with reason) -#define OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( \ - opName, paramName, incorrectValue, reason) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramName_(paramName); \ - std::string _safe_incorrectValue_(incorrectValue); \ - std::string _safe_reason_(reason); \ - OP_LOGE_LIBOPAPI_REPORT( \ - _safe_opName_.c_str(), \ - "Parameter %s of operator %s has incorrect value %s. Reason: %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectValue_.c_str(), \ - _safe_reason_.c_str()); \ - REPORT_INNER_ERR_MSG( \ - "EZ0026", \ - "Parameter %s of operator %s has incorrect value %s. Reason: %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectValue_.c_str(), \ - _safe_reason_.c_str()); \ - } while (0) - -// EZ0027: Parameters value error (multiple parameters, with reason) -#define OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( \ - opName, paramNames, incorrectValues, reason) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramNames_(paramNames); \ - std::string _safe_incorrectValues_(incorrectValues); \ - std::string _safe_reason_(reason); \ - OP_LOGE_LIBOPAPI_REPORT( \ - _safe_opName_.c_str(), \ - "Parameters %s of operator %s have incorrect values %s. Reason: %s.", \ - _safe_paramNames_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectValues_.c_str(), \ - _safe_reason_.c_str()); \ - REPORT_INNER_ERR_MSG( \ - "EZ0027", \ - "Parameters %s of operator %s have incorrect values %s. Reason: %s.", \ - _safe_paramNames_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectValues_.c_str(), \ - _safe_reason_.c_str()); \ - } while (0) - -// EZ0028: Parameter stride error (single parameter, with correct stride) -#define OP_LOGE_FOR_INVALID_STRIDE( \ - opName, paramName, incorrectStride, correctStride) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_paramName_(paramName); \ - std::string _safe_incorrectStride_(incorrectStride); \ - std::string _safe_correctStride_(correctStride); \ - OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ - "Parameter %s of operator %s has incorrect " \ - "stride %s, it should be %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectStride_.c_str(), \ - _safe_correctStride_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0028", \ - "Parameter %s of operator %s has incorrect stride " \ - "%s, it should be %s.", \ - _safe_paramName_.c_str(), \ - _safe_opName_.c_str(), \ - _safe_incorrectStride_.c_str(), \ - _safe_correctStride_.c_str()); \ - } while (0) - -// EZ0029: File operation path error -#define OP_LOGE_FOR_FILE_PATH(opName, filePath, reason) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_filePath_(filePath); \ - std::string _safe_reason_(reason); \ - OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ - "Input path %s is invalid. Reason: %s.", \ - _safe_filePath_.c_str(), \ - _safe_reason_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0029", \ - "Input path %s is invalid. Reason: %s.", \ - _safe_filePath_.c_str(), \ - _safe_reason_.c_str()); \ - } while (0) - -// EZ0030: File operation open error -#define OP_LOGE_FOR_FILE_OPEN(opName, filePath, reason) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_filePath_(filePath); \ - std::string _safe_reason_(reason); \ - OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ - "Failed to open file %s. Reason: %s.", \ - _safe_filePath_.c_str(), \ - _safe_reason_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0030", \ - "Failed to open file %s. Reason: %s.", \ - _safe_filePath_.c_str(), \ - _safe_reason_.c_str()); \ - } while (0) - -// EZ0031: File operation parse error -#define OP_LOGE_FOR_FILE_PARSE(opName, fileName, reason) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_fileName_(fileName); \ - std::string _safe_reason_(reason); \ - OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ - "Failed to parse file %s. Reason: %s.", \ - _safe_fileName_.c_str(), \ - _safe_reason_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0031", \ - "Failed to parse file %s. Reason: %s.", \ - _safe_fileName_.c_str(), \ - _safe_reason_.c_str()); \ - } while (0) - -// EZ0032: Config error (single item, with expect) -#define OP_LOGE_FOR_INVALID_CONFIG(opName, configFile, item, value, expect) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_configFile_(configFile); \ - std::string _safe_item_(item); \ - std::string _safe_value_(value); \ - std::string _safe_expect_(expect); \ - OP_LOGE_LIBOPAPI_REPORT( \ - _safe_opName_.c_str(), \ - "Value %s of configuration item %s in configuration file %s is " \ - "invalid, it should be %s.", \ - _safe_value_.c_str(), \ - _safe_item_.c_str(), \ - _safe_configFile_.c_str(), \ - _safe_expect_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0032", \ - "Value %s of configuration item %s in configuration " \ - "file %s is invalid, it should be %s.", \ - _safe_value_.c_str(), \ - _safe_item_.c_str(), \ - _safe_configFile_.c_str(), \ - _safe_expect_.c_str()); \ - } while (0) - -// EZ0033: Config error (single item, with reason) -#define OP_LOGE_FOR_INVALID_CONFIG_WITH_REASON( \ - opName, configFile, item, value, reason) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_configFile_(configFile); \ - std::string _safe_item_(item); \ - std::string _safe_value_(value); \ - std::string _safe_reason_(reason); \ - OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ - "Value %s of configuration item %s in " \ - "configuration file %s is invalid. Reason: %s.", \ - _safe_value_.c_str(), \ - _safe_item_.c_str(), \ - _safe_configFile_.c_str(), \ - _safe_reason_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0033", \ - "Value %s of configuration item %s in configuration " \ - "file %s is invalid. Reason: %s.", \ - _safe_value_.c_str(), \ - _safe_item_.c_str(), \ - _safe_configFile_.c_str(), \ - _safe_reason_.c_str()); \ - } while (0) - -// EZ0034: Config error (multiple items, with reason) -#define OP_LOGE_FOR_INVALID_CONFIGS_WITH_REASON( \ - opName, configFile, items, values, reason) \ - do { \ - std::string _safe_opName_(opName); \ - std::string _safe_configFile_(configFile); \ - std::string _safe_items_(items); \ - std::string _safe_values_(values); \ - std::string _safe_reason_(reason); \ - OP_LOGE_LIBOPAPI_REPORT(_safe_opName_.c_str(), \ - "Values %s of configuration items %s in " \ - "configuration file %s are invalid. Reason: %s.", \ - _safe_values_.c_str(), \ - _safe_items_.c_str(), \ - _safe_configFile_.c_str(), \ - _safe_reason_.c_str()); \ - REPORT_INNER_ERR_MSG("EZ0034", \ - "Values %s of configuration items %s in " \ - "configuration file %s are invalid. Reason: %s.", \ - _safe_values_.c_str(), \ - _safe_items_.c_str(), \ - _safe_configFile_.c_str(), \ - _safe_reason_.c_str()); \ - } while (0) - -#endif /* OP_LOGE_FOR_INVALID_SHAPE */ - -#ifndef OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON -#define OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(op, name, reason) \ - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(op, name, "", reason) -#endif - -#endif /* SMLA_LOG_COMPAT_H */ diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/ops_err.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/ops_err.h deleted file mode 100644 index 45425615e0..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/ops_err.h +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2025 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under -the terms and conditions of  * CANN Open Software License Agreement Version 2.0 -(the "License").  * Please refer to the License for details. You may not use -this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON -AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * -INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A -PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for -the full text of the License.  */ - -/*! - * \file ops_err.h - * \brief - */ - -#ifndef Transformer_COMMON_OPS_ERR_H -#define Transformer_COMMON_OPS_ERR_H - -#include "sparse_flash_mla/op_host/common/log.h" - -constexpr int32_t OP_TRANSFORMER_MODULE_ID = 63; - -#define OPS_INNER_ERR_STUB(ERR_CODE_STR, OPS_DESC, FMT, ...) \ - do { \ - OpLogSub( \ - OP_TRANSFORMER_MODULE_ID, DLOG_ERROR, OPS_DESC, FMT, ##__VA_ARGS__); \ - REPORT_INNER_ERR_MSG(ERR_CODE_STR, FMT, ##__VA_ARGS__); \ - } while (0) - -/* 基础报错 */ -#define OPS_REPORT_VECTOR_INNER_ERR(OPS_DESC, ...) \ - OPS_INNER_ERR_STUB("E89999", OPS_DESC, __VA_ARGS__) -#define OPS_REPORT_CUBE_INNER_ERR(OPS_DESC, ...) \ - OPS_INNER_ERR_STUB("E69999", OPS_DESC, __VA_ARGS__) - -#endif // Transformer_COMMON_OPS_ERR_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/smla_host_common_defs.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/smla_host_common_defs.h deleted file mode 100644 index 8f1c3f4e12..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/smla_host_common_defs.h +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file smla_host_common_defs.h - * \brief sparse_flash_mla / mixed_quant_sparse_flash_mla / - * quant_sparse_flash_mla 三个算子 op_host 侧共用的 枚举、Tiling 入参信息 POD - * 与索引常量定义。 - */ - -#ifndef SMLA_HOST_COMMON_DEFS_H -#define SMLA_HOST_COMMON_DEFS_H - -#include - -#include - -#include "register/tilingdata_base.h" - -namespace optiling { - -// ------------------公共定义-------------------------- -struct SMLATilingRequiredParaInfo { - const gert::CompileTimeTensorDesc* desc; - const gert::StorageShape* shape; -}; - -struct SMLATilingOptionalParaInfo { - const gert::CompileTimeTensorDesc* desc; - const gert::Tensor* tensor; - const gert::StorageShape* shape; -}; - -enum class SMLALayout : uint32_t { BSND = 0, TND = 1, PA_BBND = 2 }; - -enum class SMLAAxis : uint32_t { - B = 0, - S = 1, - N = 2, - D = 3, - K = 3, // sparse_indices的K和key的D枚举值相同,表达相同位置, 最后一维 - T = 5, - Bn = 6, // block number - Bs = 7 // block size -}; - -enum class SMLATemplateMode : uint32_t { - SWA_TEMPLATE_MODE = 0, - HCA_TEMPLATE_MODE = 1, - CSA_TEMPLATE_MODE = 2, - ORI_SPARSE_TEMPLATE_MODE = 3, - ORI_CMP_SPARSE_TEMPLATE_MODE = 4 -}; - -// Dim Index -constexpr uint32_t DIM_IDX_ZERO = 0; -constexpr uint32_t DIM_IDX_ONE = 1; -constexpr uint32_t DIM_IDX_TWO = 2; -constexpr uint32_t DIM_IDX_THREE = 3; -constexpr uint32_t DIM_IDX_FOUR = 4; - -// Dim Num -constexpr uint32_t DIM_NUM_ONE = 1; -constexpr uint32_t DIM_NUM_TWO = 2; -constexpr uint32_t DIM_NUM_THREE = 3; -constexpr uint32_t DIM_NUM_FOUR = 4; - -// Outputs Index -constexpr uint32_t ATTN_OUT_INDEX = 0; -constexpr uint32_t SOFTMAX_LSE_INDEX = 1; - -} // namespace optiling - -#endif // SMLA_HOST_COMMON_DEFS_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/smla_infershape_common.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/smla_infershape_common.h deleted file mode 100644 index 9007a34e47..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/common/smla_infershape_common.h +++ /dev/null @@ -1,228 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file smla_infershape_common.h - * \brief sparse_flash_mla / mixed_quant_sparse_flash_mla / - * quant_sparse_flash_mla 三个算子 InferShape / InferDataType 公共子函数。 - */ - -#ifndef SMLA_INFERSHAPE_COMMON_H -#define SMLA_INFERSHAPE_COMMON_H - -#include -#include -#include -#include - -#include -#include -#include - -#include "smla_host_common_defs.h" -#include "sparse_flash_mla/op_host/common/log.h" -#include "sparse_flash_mla/op_host/common/ops_err.h" - -namespace optiling { - -// 算子原型输入索引(三个算子 Q / ori_kv / cmp_kv 位置一致) -constexpr uint32_t SMLA_QUERY_INPUT_INDEX = 0; -constexpr uint32_t SMLA_ORI_KV_INPUT_INDEX = 1; -constexpr uint32_t SMLA_CMP_KV_INPUT_INDEX = 2; - -inline std::vector SMLAToVector(const gert::Shape* shape) { - size_t shapeSize = shape->GetDimNum(); - std::vector shapeVec(shapeSize, 0); - for (size_t i = 0; i < shapeSize; i++) { - shapeVec[i] = shape->GetDim(i); - } - return shapeVec; -} - -inline std::string SMLAToString(const gert::Shape* shape) { - std::ostringstream oss; - auto v = SMLAToVector(shape); - if (v.size() > 0) { - for (size_t i = 0; i < v.size() - 1; ++i) { - oss << v[i] << ", "; - } - oss << v[v.size() - 1]; - } - return oss.str(); -} - -inline int64_t SMLAGetKvHeadNum(const gert::Shape* kvShape, - const std::string& layoutKv) { - if (layoutKv == "TND") { - return kvShape->GetDim(DIM_IDX_ONE); - } - return kvShape->GetDim(DIM_IDX_TWO); -} - -inline ge::graphStatus SMLACheckKvHeadNum(const char* opName, - const gert::Shape* kvShape, - int64_t kvHeadNum) { - OP_CHECK_IF( - kvHeadNum <= 0, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName, - "ori_kv or cmp_kv", - SMLAToString(kvShape).c_str(), - "The head num of ori_kv or cmp_kv should be greater than 0 but got " + - std::to_string(kvHeadNum)), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -inline void SMLASetSoftmaxLseShape(gert::Shape* softmaxLseShape, - const gert::Shape* queryShape, - int64_t kvHeadNum, - bool isTnd, - bool returnSoftmaxLse) { - if (!returnSoftmaxLse) { - softmaxLseShape->SetDimNum(DIM_NUM_ONE); - softmaxLseShape->SetDim(DIM_IDX_ZERO, 0); - return; - } - if (isTnd) { - softmaxLseShape->SetDimNum(DIM_NUM_THREE); - softmaxLseShape->SetDim(DIM_IDX_ZERO, kvHeadNum); - softmaxLseShape->SetDim(DIM_IDX_ONE, queryShape->GetDim(DIM_IDX_ZERO)); - softmaxLseShape->SetDim(DIM_IDX_TWO, - queryShape->GetDim(DIM_IDX_ONE) / kvHeadNum); - } else { - softmaxLseShape->SetDimNum(DIM_NUM_FOUR); - softmaxLseShape->SetDim(DIM_IDX_ZERO, queryShape->GetDim(DIM_IDX_ZERO)); - softmaxLseShape->SetDim(DIM_IDX_ONE, kvHeadNum); - softmaxLseShape->SetDim(DIM_IDX_TWO, queryShape->GetDim(DIM_IDX_ONE)); - softmaxLseShape->SetDim(DIM_IDX_THREE, - queryShape->GetDim(DIM_IDX_TWO) / kvHeadNum); - } -} - -struct SMLAInferShapeBase { - const gert::Shape* queryShape = nullptr; - gert::Shape* attentionOutShape = nullptr; - gert::Shape* softmaxLseShape = nullptr; - const gert::RuntimeAttrs* attrs = nullptr; - const bool* returnSoftmaxLsePtr = nullptr; - const gert::Shape* kvShape = nullptr; -}; - -// 解析 query 输入、两个输出、attr 及 return_softmax_lse 指针 -inline ge::graphStatus SMLAGetInferShapeBase(gert::InferShapeContext* context, - uint32_t returnSoftmaxLseAttrIdx, - SMLAInferShapeBase& base) { - base.queryShape = context->GetInputShape(SMLA_QUERY_INPUT_INDEX); - OP_CHECK_IF((base.queryShape) == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - context->GetNodeName(), "q", "Null input"), - return ge::GRAPH_FAILED); - base.attentionOutShape = context->GetOutputShape(ATTN_OUT_INDEX); - OP_CHECK_IF((base.attentionOutShape) == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - context->GetNodeName(), - "base.attentionOutShape", - "Required base.attentionOutShape metadata is null; " - "context->GetOutputShape(ATTN_OUT_INDEX) must provide a " - "valid object."), - return ge::GRAPH_FAILED); - *base.attentionOutShape = *base.queryShape; - - base.softmaxLseShape = context->GetOutputShape(SOFTMAX_LSE_INDEX); - OP_CHECK_IF((base.softmaxLseShape) == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - context->GetNodeName(), - "base.softmaxLseShape", - "Required base.softmaxLseShape metadata is null; " - "context->GetOutputShape(SOFTMAX_LSE_INDEX) must provide a " - "valid object."), - return ge::GRAPH_FAILED); - base.attrs = context->GetAttrs(); - OP_CHECK_IF((base.attrs) == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - context->GetNodeName(), - "base.attrs", - "Required base.attrs metadata is null; context->GetAttrs() " - "must provide a valid object."), - return ge::GRAPH_FAILED); - base.returnSoftmaxLsePtr = - base.attrs->GetAttrPointer(returnSoftmaxLseAttrIdx); - return ge::GRAPH_SUCCESS; -} - -// 三个算子统一的 InferShape 主体:ori_kv / cmp_kv 均为可选输入,layout_q / -// layout_kv 为 String attr -inline ge::graphStatus SMLAInferShape(gert::InferShapeContext* context, - const char* opName, - uint32_t returnSoftmaxLseAttrIdx, - uint32_t layoutQAttrIdx, - uint32_t layoutKvAttrIdx) { - SMLAInferShapeBase base; - if (SMLAGetInferShapeBase(context, returnSoftmaxLseAttrIdx, base) != - ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - const gert::Shape* oriKvShape = - context->GetOptionalInputShape(SMLA_ORI_KV_INPUT_INDEX); - const gert::Shape* cmpKvShape = - context->GetOptionalInputShape(SMLA_CMP_KV_INPUT_INDEX); - base.kvShape = (oriKvShape != nullptr) ? oriKvShape : cmpKvShape; - OP_CHECK_IF((base.kvShape) == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - context->GetNodeName(), - "base.kvShape", - "Required base.kvShape metadata is null; (oriKvShape != " - "nullptr) ? oriKvShape : " - "cmpKvShape must provide a valid object."), - return ge::GRAPH_FAILED); - - const char* layoutQ = base.attrs->GetStr(layoutQAttrIdx); - const char* layoutKv = base.attrs->GetStr(layoutKvAttrIdx); - std::string layoutQStr = (layoutQ != nullptr) ? std::string(layoutQ) : "BSND"; - std::string layoutKvStr = - (layoutKv != nullptr) ? std::string(layoutKv) : "BSND"; - bool returnSoftmaxLse = - (base.returnSoftmaxLsePtr != nullptr) ? *base.returnSoftmaxLsePtr : false; - int64_t kvHeadNum = SMLAGetKvHeadNum(base.kvShape, layoutKvStr); - if (SMLACheckKvHeadNum(opName, base.kvShape, kvHeadNum) != - ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - SMLASetSoftmaxLseShape(base.softmaxLseShape, - base.queryShape, - kvHeadNum, - layoutQStr == "TND", - returnSoftmaxLse); - return ge::GRAPH_SUCCESS; -} - -// sparse_flash_mla / mixed_quant_sparse_flash_mla 的 InferDataType(输出 dtype -// 跟随 query 输入) -inline ge::graphStatus SMLAInferDataTypeByInput( - gert::InferDataTypeContext* context, - const char* opName) { - OP_CHECK_IF( - context == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(Ops::Base::GetOpInfo(opName), - "context", - "InferShapeContext is nullptr"), - return ge::GRAPH_FAILED); - const auto inputDataType = context->GetInputDataType(SMLA_QUERY_INPUT_INDEX); - context->SetOutputDataType(ATTN_OUT_INDEX, inputDataType); - context->SetOutputDataType(SOFTMAX_LSE_INDEX, ge::DT_FLOAT); - return ge::GRAPH_SUCCESS; -} - -} // namespace optiling - -#endif // SMLA_INFERSHAPE_COMMON_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_def.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_def.cpp deleted file mode 100644 index 84d6e7d2ca..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_def.cpp +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under -the terms and conditions of  * CANN Open Software License Agreement Version 2.0 -(the "License").  * Please refer to the License for details. You may not use -this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON -AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * -INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A -PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for -the full text of the License.  */ - -/*! - * \file sparse_flash_mla_def.cpp - * \brief - */ - -#include "register/op_def_registry.h" - -namespace ops { -class XllmKernelSparseFlashMla : public OpDef { - public: - explicit XllmKernelSparseFlashMla(const char* name) : OpDef(name) { - this->Input("q") - .ParamType(REQUIRED) - .DataType({ge::DT_FLOAT16, ge::DT_BF16}) - .FormatList({ge::FORMAT_ND}) - .AutoContiguous(); - this->Input("ori_kv") - .ParamType(OPTIONAL) - .DataType({ge::DT_FLOAT16, ge::DT_BF16}) - .FormatList({ge::FORMAT_ND}) - .IgnoreContiguous(); - this->Input("cmp_kv") - .ParamType(OPTIONAL) - .DataType({ge::DT_FLOAT16, ge::DT_BF16}) - .FormatList({ge::FORMAT_ND}) - .IgnoreContiguous(); - this->Input("ori_sparse_indices") - .ParamType(OPTIONAL) - .DataTypeList({ge::DT_INT32}) - .FormatList({ge::FORMAT_ND}) - .AutoContiguous(); - this->Input("cmp_sparse_indices") - .ParamType(OPTIONAL) - .DataTypeList({ge::DT_INT32}) - .FormatList({ge::FORMAT_ND}) - .AutoContiguous(); - this->Input("ori_block_table") - .ParamType(OPTIONAL) - .DataTypeList({ge::DT_INT32}) - .FormatList({ge::FORMAT_ND}) - .AutoContiguous(); - this->Input("cmp_block_table") - .ParamType(OPTIONAL) - .DataTypeList({ge::DT_INT32}) - .FormatList({ge::FORMAT_ND}) - .AutoContiguous(); - this->Input("cu_seqlens_q") - .ParamType(OPTIONAL) - .DataTypeList({ge::DT_INT32}) - .FormatList({ge::FORMAT_ND}) - .AutoContiguous(); - this->Input("cu_seqlens_ori_kv") - .ParamType(OPTIONAL) - .DataTypeList({ge::DT_INT32}) - .FormatList({ge::FORMAT_ND}) - .AutoContiguous(); - this->Input("cu_seqlens_cmp_kv") - .ParamType(OPTIONAL) - .DataTypeList({ge::DT_INT32}) - .FormatList({ge::FORMAT_ND}) - .AutoContiguous(); - this->Input("seqused_q") - .ParamType(OPTIONAL) - .DataTypeList({ge::DT_INT32}) - .FormatList({ge::FORMAT_ND}) - .AutoContiguous(); - this->Input("seqused_ori_kv") - .ParamType(OPTIONAL) - .DataTypeList({ge::DT_INT32}) - .FormatList({ge::FORMAT_ND}) - .AutoContiguous(); - this->Input("seqused_cmp_kv") - .ParamType(OPTIONAL) - .DataTypeList({ge::DT_INT32}) - .FormatList({ge::FORMAT_ND}) - .AutoContiguous(); - this->Input("cmp_residual_kv") - .ParamType(OPTIONAL) - .DataTypeList({ge::DT_INT32}) - .FormatList({ge::FORMAT_ND}) - .AutoContiguous(); - this->Input("ori_topk_length") - .ParamType(OPTIONAL) - .DataTypeList({ge::DT_INT32}) - .FormatList({ge::FORMAT_ND}) - .AutoContiguous(); - this->Input("cmp_topk_length") - .ParamType(OPTIONAL) - .DataTypeList({ge::DT_INT32}) - .FormatList({ge::FORMAT_ND}) - .AutoContiguous(); - this->Input("sinks") - .ParamType(OPTIONAL) - .DataTypeList({ge::DT_FLOAT}) - .FormatList({ge::FORMAT_ND}) - .AutoContiguous(); - this->Input("metadata") - .ParamType(OPTIONAL) - .DataTypeList({ge::DT_INT32}) - .FormatList({ge::FORMAT_ND}) - .AutoContiguous(); - this->Output("attn_out") - .ParamType(REQUIRED) - .DataType({ge::DT_FLOAT16, ge::DT_BF16}) - .FormatList({ge::FORMAT_ND}); - this->Output("softmax_lse") - .ParamType(OPTIONAL) - .DataTypeList({ge::DT_FLOAT}) - .FormatList({ge::FORMAT_ND}); - this->Attr("softmax_scale").AttrType(OPTIONAL).Float(1.0); - this->Attr("cmp_ratio").AttrType(OPTIONAL).Int(1); - this->Attr("ori_mask_mode") - .AttrType(OPTIONAL) - .Int(0); // ori_mask_mode默认值0 - this->Attr("cmp_mask_mode") - .AttrType(OPTIONAL) - .Int(0); // cmp_mask_mode默认值0 - this->Attr("ori_win_left") - .AttrType(OPTIONAL) - .Int(-1); // ori_win_left默认值-1 - this->Attr("ori_win_right") - .AttrType(OPTIONAL) - .Int(-1); // ori_win_right默认值-1 - this->Attr("layout_q").AttrType(OPTIONAL).String("BSND"); - this->Attr("layout_kv").AttrType(OPTIONAL).String("BSND"); - this->Attr("topk_value_mode").AttrType(OPTIONAL).Int(1); - this->Attr("return_softmax_lse").AttrType(OPTIONAL).Bool(false); - - OpAICoreConfig aicore_config; - aicore_config.DynamicCompileStaticFlag(true) - .DynamicFormatFlag(true) - .DynamicRankSupportFlag(true) - .DynamicShapeSupportFlag(true) - .NeedCheckSupportFlag(false) - .PrecisionReduceFlag(true) - .ExtendCfgInfo("aclnnSupport.value", "support_aclnn"); - this->AICore().AddConfig("ascend910_93", aicore_config); - } -}; -OP_ADD(XllmKernelSparseFlashMla); -} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_infershape.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_infershape.cpp deleted file mode 100644 index eb7050bfe5..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_infershape.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under -the terms and conditions of  * CANN Open Software License Agreement Version 2.0 -(the "License").  * Please refer to the License for details. You may not use -this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON -AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * -INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A -PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for -the full text of the License.  */ - -/*! - * \file sparse_flash_mla_infershape.cpp - * \brief - */ - -#include -#include - -#include - -#include "common/smla_infershape_common.h" -#include "sparse_flash_mla/op_host/common/log.h" -#include "sparse_flash_mla/op_host/common/ops_err.h" - -using namespace ge; - -namespace ops { -constexpr uint32_t RETURN_SOFTMAX_INDEX = 9; -constexpr uint32_t LAYOUT_Q_ATTR_INDEX = 6; -constexpr uint32_t LAYOUT_KV_ATTR_INDEX = 7; - -ge::graphStatus InferShapeSparseFlashMla(gert::InferShapeContext* context) { - OP_CHECK_IF( - context == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON("XllmKernelSparseFlashMla", - "context", - "InferShapeContext is nullptr"), - return ge::GRAPH_FAILED); - return optiling::SMLAInferShape(context, - "XllmKernelSparseFlashMla", - RETURN_SOFTMAX_INDEX, - LAYOUT_Q_ATTR_INDEX, - LAYOUT_KV_ATTR_INDEX); -} - -ge::graphStatus InferDataTypeSparseFlashMla( - gert::InferDataTypeContext* context) { - return optiling::SMLAInferDataTypeByInput(context, - "XllmKernelSparseFlashMla"); -} - -IMPL_OP_INFERSHAPE(XllmKernelSparseFlashMla) - .InferShape(InferShapeSparseFlashMla) - .InferDataType(InferDataTypeSparseFlashMla); -} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_tiling.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_tiling.cpp deleted file mode 100644 index 18e2215009..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_tiling.cpp +++ /dev/null @@ -1,3255 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under -the terms and conditions of  * CANN Open Software License Agreement Version 2.0 -(the "License").  * Please refer to the License for details. You may not use -this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON -AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * -INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A -PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for -the full text of the License.  */ - -/*! - * \file sparse_flash_mla_tiling.cpp - * \brief - */ - -#include "sparse_flash_mla_tiling.h" - -#include -#include - -#include "checkers/checker_adapter.h" -#include "checkers/sparse_flash_mla_checker.h" -#include "register/op_def_registry.h" -#include "sparse_flash_mla/op_host/common/log.h" -#include "sparse_flash_mla/op_host/common/ops_err.h" -#include "sparse_flash_mla/op_kernel/sparse_flash_mla_template_tiling_key.h" - -using namespace ge; -using namespace AscendC; -using std::map; -using std::pair; -using std::string; - -namespace optiling { - -static const std::string QUERY_NAME = "query"; - -static const std::string ORI_KV_NAME = "ori_kv"; -static const std::string CMP_KV_NAME = "cmp_kv"; -static const std::string CU_SEQLENS_ORI_KV_NAME = "cu_seqlens_ori_kv"; -static const std::string CU_SEQLENS_CMP_KV_NAME = "cu_seqlens_cmp_kv"; -static const std::string ORI_SPARSE_INDICES = "ori_sparse_indices"; -static const std::string CMP_SPARSE_INDICES = "cmp_sparse_indices"; -static const std::string ORI_BLOCK_TABLE_NAME = "ori_block_table"; -static const std::string CMP_BLOCK_TABLE_NAME = "cmp_block_table"; -static const std::string SINKS_NAME = "sinks"; -static const std::string METADATA_NAME = "metadata"; -static const std::string ATTEN_OUT_NAME = "attn_out"; -static const std::string CU_SEQLENS_Q_NAME = "cu_seqlens_q"; -static const std::string SEQUSED_Q_NAME = "seqused_q"; -static const std::string SEQUSED_ORI_KV_NAME = "seqused_ori_kv"; -static const std::string SEQUSED_CMP_KV_NAME = "seqused_cmp_kv"; -static const std::string CMP_RESIDUAL_KV_NAME = "cmp_residual_kv"; -static const std::string ORI_TOPK_LENGTH_NAME = "ori_topk_length"; -static const std::string CMP_TOPK_LENGTH_NAME = "cmp_topk_length"; -static const std::string A2_A3_PLATFORM_LOG = "A2/A3"; -static const std::string A5_PLATFORM_LOG = "A5"; -static const std::string A6_PLATFORM_LOG = "A6"; -constexpr uint32_t FD_MAX_S2_SPLIT_NUM = 2U; -constexpr uint32_t BATCH_CONSISTENCY_MAX_REDUCE_BLOCK_NUM = 33U; -constexpr uint32_t FD_BROADCAST_ELEMS = 8U; -constexpr int64_t BATCH_CONSISTENCY_LEVEL = 3; - -static std::vector ToVector(const gert::Shape& shape) { - size_t shapeSize = shape.GetDimNum(); - std::vector shapeVec(shapeSize, 0); - - for (size_t i = 0; i < shapeSize; i++) { - shapeVec[i] = shape.GetDim(i); - } - return shapeVec; -} - -static std::string ToStringRaw(const gert::Shape& shape) { - std::ostringstream oss; - const size_t dimCount = shape.GetDimNum(); - for (size_t dimIndex = 0; dimIndex < dimCount; ++dimIndex) { - if (dimIndex != 0U) { - oss << ", "; - } - oss << shape.GetDim(dimIndex); - } - return oss.str(); -} - -static bool IsNonEmptyOptionalTensor(const gert::Tensor* tensor) { - return tensor != nullptr && tensor->GetShapeSize() > 0; -} - -static bool IsPowerOfTwoInRange(uint32_t value, - uint32_t minValue, - uint32_t maxValue) { - return value >= minValue && value <= maxValue && (value & (value - 1U)) == 0U; -} - -static bool IsA5Arch(NpuArch npuArch) { return npuArch == NpuArch::DAV_3510; } -static bool IsA6Arch(NpuArch npuArch) { - return npuArch == NpuArch::DAV_9201 || npuArch == NpuArch::DAV_9202; -} - -static bool IsPowerOfTwo(uint64_t value) { - return value != 0U && (value & (value - 1U)) == 0U; -} - -static void CalcMagicP(uint32_t blockSize, - uint32_t& p, - uint32_t& mLow, - uint32_t& mHigh) { - constexpr uint32_t SHIFT_LOW_BOUND = 30U; - constexpr uint32_t SHIFT_UP_BOUND = 41U; - constexpr uint32_t HIGH_32BIT_SHIFT = 32U; - constexpr uint64_t X_MAX = (1ULL << 30U) - 1U; - uint64_t multiplier = 1U; - p = 0U; - if (IsPowerOfTwo(blockSize)) { - uint32_t value = blockSize; - while ((value >>= 1U) != 0U) { - ++p; - } - mLow = 1U; - mHigh = 0U; - return; - } - for (uint32_t shift = SHIFT_LOW_BOUND; shift < SHIFT_UP_BOUND; ++shift) { - const uint64_t power = 1ULL << shift; - const uint64_t remainder = power % blockSize; - const uint64_t error = (blockSize - remainder) % blockSize; - if (error == 0U || power > X_MAX * error) { - multiplier = (power + blockSize - 1U) / blockSize; - p = shift; - } - } - mLow = static_cast(multiplier); - mHigh = static_cast(multiplier >> HIGH_32BIT_SHIFT); -} - -static bool IsPaBlockSizeSupport(NpuArch npuArch, int32_t blockSize) { - if (IsA5Arch(npuArch) || IsA6Arch(npuArch)) { - return blockSize >= 1 && - blockSize <= static_cast(BLOCK_SIZE_LIMIT); - } - return blockSize >= 16U && - blockSize <= static_cast(BLOCK_SIZE_LIMIT) && - blockSize % 16U == 0; -} - -static const std::map> - DTYPE_SUPPORT_MAP = {{QUERY_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, - {ORI_KV_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, - {CMP_KV_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, - {CU_SEQLENS_ORI_KV_NAME, {ge::DT_INT32}}, - {CU_SEQLENS_CMP_KV_NAME, {ge::DT_INT32}}, - {ORI_SPARSE_INDICES, {ge::DT_INT32}}, - {CMP_SPARSE_INDICES, {ge::DT_INT32}}, - {ATTEN_OUT_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, - {ORI_BLOCK_TABLE_NAME, {ge::DT_INT32}}, - {CMP_BLOCK_TABLE_NAME, {ge::DT_INT32}}, - {SINKS_NAME, {ge::DT_FLOAT}}, - {METADATA_NAME, {ge::DT_INT32}}, - {CU_SEQLENS_Q_NAME, {ge::DT_INT32}}, - {SEQUSED_Q_NAME, {ge::DT_INT32}}, - {SEQUSED_ORI_KV_NAME, {ge::DT_INT32}}, - {SEQUSED_CMP_KV_NAME, {ge::DT_INT32}}, - {CMP_RESIDUAL_KV_NAME, {ge::DT_INT32}}, - {ORI_TOPK_LENGTH_NAME, {ge::DT_INT32}}, - {CMP_TOPK_LENGTH_NAME, {ge::DT_INT32}}}; - -static const std::map> LAYOUT_SUPPORT_MAP = - { - {QUERY_NAME, {SMLALayout::BSND, SMLALayout::TND}}, - {ORI_KV_NAME, {SMLALayout::PA_BBND, SMLALayout::TND, SMLALayout::BSND}}, - {CMP_KV_NAME, {SMLALayout::PA_BBND, SMLALayout::TND, SMLALayout::BSND}}, - {ATTEN_OUT_NAME, {SMLALayout::BSND, SMLALayout::TND}}, - {ORI_SPARSE_INDICES, {SMLALayout::BSND, SMLALayout::TND}}, - {CMP_SPARSE_INDICES, {SMLALayout::BSND, SMLALayout::TND}}, -}; - -static const std::map DATATYPE_TO_STRING_MAP = { - {ge::DT_UNDEFINED, - "DT_UNDEFINED"}, // Used to indicate a DataType field has not been set. - {ge::DT_FLOAT, "DT_FLOAT"}, // float type - {ge::DT_FLOAT16, "DT_FLOAT16"}, // fp16 type - {ge::DT_INT8, "DT_INT8"}, // int8 type - {ge::DT_INT16, "DT_INT16"}, // int16 type - {ge::DT_UINT16, "DT_UINT16"}, // uint16 type - {ge::DT_UINT8, "DT_UINT8"}, // uint8 type - {ge::DT_INT64, "DT_INT64"}, // int64 type - {ge::DT_INT32, "DT_INT32"}, // uint32 type - {ge::DT_UINT32, "DT_UINT32"}, // unsigned int32 - {ge::DT_UINT64, "DT_UINT64"}, // unsigned int64 - {ge::DT_DOUBLE, "DT_DOUBLE"}, // double type - {ge::DT_BOOL, "DT_BOOL"}, // bool type - {ge::DT_DUAL, "DT_DUAL"}, // dual output type - {ge::DT_DUAL_SUB_INT8, "DT_DUAL_SUB_INT8"}, // dual output int8 type - {ge::DT_DUAL_SUB_UINT8, "DT_DUAL_SUB_UINT8"}, // dual output uint8 type - {ge::DT_COMPLEX64, "DT_COMPLEX64"}, // complex64 type - {ge::DT_COMPLEX32, "DT_COMPLEX32"}, // complex32 type - {ge::DT_COMPLEX128, "DT_COMPLEX128"}, // complex128 type - {ge::DT_QINT8, "DT_QINT8"}, // qint8 type - {ge::DT_QINT16, "DT_QINT16"}, // qint16 type - {ge::DT_QINT32, "DT_QINT32"}, // qint32 type - {ge::DT_QUINT16, "DT_QUINT16"}, // quint16 type - {ge::DT_QUINT8, "DT_QUINT8"}, // quint8 type - {ge::DT_RESOURCE, "DT_RESOURCE"}, // resource type - {ge::DT_STRING_REF, "DT_STRING_REF"}, // string ref type - {ge::DT_STRING, "DT_STRING"}, // string type - {ge::DT_VARIANT, "DT_VARIANT"}, // dt_variant type - {ge::DT_BF16, "DT_BFLOAT16"}, // dt_bfloat16 type - {ge::DT_UINT1, "DT_UINT1"}, // dt_variant type - {ge::DT_INT4, "DT_INT4"}, // dt_variant type - {ge::DT_INT2, "DT_INT2"}, // dt_variant type - {ge::DT_UINT2, "DT_UINT2"} // dt_variant type -}; - -static uint64_t GetStorageShapeStride0(const gert::Shape& storageShape) { - if (storageShape.GetDimNum() <= DIM_NUM_ONE) { - return 0ULL; - } - - uint64_t stride0 = 1ULL; - for (size_t i = 1; i < storageShape.GetDimNum(); ++i) { - int64_t dim = storageShape.GetDim(i); - if (dim <= 0) { - return 0ULL; - } - stride0 *= static_cast(dim); - } - return stride0; -} - -template -static auto GetStride0FromStrideObject(const StrideT& stride, int) - -> decltype(stride.GetDimNum(), stride.GetStride(0), uint64_t()) { - if (stride.GetDimNum() <= 0) { - return 0ULL; - } - int64_t stride0 = stride.GetStride(0); - return stride0 > 0 ? static_cast(stride0) : 0ULL; -} - -template -static uint64_t GetStride0FromStrideObject(const StrideT&, ...) { - return 0ULL; -} - -template -static auto GetStride0FromStrideScalar(const StrideT& stride, int) - -> decltype(stride > 0, static_cast(stride)) { - return stride > 0 ? static_cast(stride) : 0ULL; -} - -template -static uint64_t GetStride0FromStrideScalar(const StrideT&, ...) { - return 0ULL; -} - -template -static uint64_t GetStride0FromStrideElement(const StrideT& stride) { - // CANN stride APIs return a dimension-wise stride array. In newer headers, - // stride[0] is scalar stride0. In compatibility headers it may be a stride - // object. Non-positive stride is treated as unavailable and falls back to the - // storage-shape contiguous calculation. - uint64_t stride0 = GetStride0FromStrideScalar(stride, 0); - if (stride0 > 0) { - return stride0; - } - return GetStride0FromStrideObject(stride, 0); -} - -template -static uint64_t GetStride0FromStrideArray(const StrideT* stride) { - if (stride == nullptr) { - return 0ULL; - } - return GetStride0FromStrideElement(stride[0]); -} - -template -static auto TryGetOptionalInputStride0(ContextT* context, - uint32_t inputIndex, - int) - -> decltype(context->GetOptionalInputStride(inputIndex), uint64_t()) { - return GetStride0FromStrideArray(context->GetOptionalInputStride(inputIndex)); -} - -template -static uint64_t TryGetOptionalInputStride0(ContextT*, uint32_t, ...) { - return 0ULL; -} - -// Compatibility path for CANN headers that do not expose -// GetOptionalInputStride. Some tiling contexts only provide real stride for -// view inputs through InputIsView/GetInputStride. Returning 0 means the stride -// is unavailable; the caller then falls back to storage-shape contiguous -// stride. -template -static auto TryGetInputViewStride0(ContextT* context, uint32_t inputIndex, int) - -> decltype(context->InputIsView(inputIndex), - context->GetInputStride(inputIndex), - uint64_t()) { - if (!context->InputIsView(inputIndex)) { - return 0ULL; - } - return GetStride0FromStrideArray(context->GetInputStride(inputIndex)); -} - -template -static uint64_t TryGetInputViewStride0(ContextT*, uint32_t, ...) { - return 0ULL; -} - -std::string SMLALayoutToSerialString(SMLALayout layout) { - switch (layout) { - case SMLALayout::BSND: - return "BSND"; - case SMLALayout::TND: - return "TND"; - case SMLALayout::PA_BBND: - return "PA_BBND"; - default: - return "UNKNOWN"; - } -} - -struct SMLACompileInfo { - int64_t core_num; -}; - -static const std::map> SMLA_LAYOUT_AXIS_MAP = - { - {SMLALayout::BSND, - {SMLAAxis::B, SMLAAxis::S, SMLAAxis::N, SMLAAxis::D}}, - {SMLALayout::TND, {SMLAAxis::T, SMLAAxis::N, SMLAAxis::D}}, - {SMLALayout::PA_BBND, - {SMLAAxis::Bn, SMLAAxis::Bs, SMLAAxis::N, SMLAAxis::D}}, -}; - -static const std::map SMLA_LAYOUT_DIM_MAP = { - {SMLALayout::BSND, DIM_NUM_FOUR}, - {SMLALayout::TND, DIM_NUM_THREE}, - {SMLALayout::PA_BBND, DIM_NUM_FOUR}, -}; - -static std::string SMLADataTypeToSerialString(ge::DataType type) { - const auto it = DATATYPE_TO_STRING_MAP.find(type); - if (it != DATATYPE_TO_STRING_MAP.end()) { - return it->second; - } else { - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - "sparseFlashMla", - "data_type", - std::to_string(type), - "datatype " + std::to_string(type) + " not support"); - return "UNDEFINED"; - } -} - -// --------------------------SMLAInfoParser类成员函数定义------------------------------------ -ge::graphStatus SMLAInfoParser::CheckRequiredInOutExistence() const { - OP_CHECK_IF(opParamInfo_.q.shape == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, "query", "The shape of query is nullptr"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(opParamInfo_.q.desc == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, "query", "The desc of query is nullptr"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(opParamInfo_.oriKv.tensor == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, "ori_kv", "The tensor of ori_kv is nullptr"), - return ge::GRAPH_FAILED); - if (perfMode_ == SMLATemplateMode::HCA_TEMPLATE_MODE) { - OP_CHECK_IF(opParamInfo_.cmpKv.tensor == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, "cmp_kv", "The tensor of cmp_kv is nullptr"), - return ge::GRAPH_FAILED); - } - if (perfMode_ == SMLATemplateMode::CSA_TEMPLATE_MODE) { - OP_CHECK_IF(opParamInfo_.cmpKv.tensor == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, "cmp_kv", "The tensor of cmp_kv is nullptr"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(opParamInfo_.cmpSparseIndices.tensor == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "cmp_sparse_indices", - "The tensor of cmp_sparse_indices is nullptr"), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::CheckRequiredAttrExistence() const { - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::CheckRequiredParaExistence() const { - if (CheckRequiredInOutExistence() != ge::GRAPH_SUCCESS || - CheckRequiredAttrExistence() != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::CheckUnrequiredParaExistence() const { - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetOpName() { - if (context_->GetNodeName() == nullptr) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - "XllmKernelSparseFlashMla", - "TilingContext", - "opName got from TilingContext is nullptr"); - return ge::GRAPH_FAILED; - } - opName_ = context_->GetNodeName(); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetNpuInfo() { - platformInfo_ = context_->GetPlatformInfo(); - OP_CHECK_IF( - platformInfo_ == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(Ops::Base::GetOpInfo(opName_), - "platformInfo_", - "GetPlatformInfo is nullptr."), - return ge::GRAPH_FAILED); - - auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo_); - aivNum_ = ascendcPlatform.GetCoreNumAiv(); - aicNum_ = ascendcPlatform.GetCoreNumAic(); - if (aicNum_ == 0 || aivNum_ == 0) { - OP_LOGE_LIBOPAPI_REPORT( - Ops::Base::GetOpInfo(opName_), "%s", "num of core obtained is 0."); - REPORT_PREDEFINED_ERR_MSG( - "EZ1008", - std::vector({"opName", "reason"}), - std::vector( - {Ops::Base::GetOpInfo(opName_), "num of core obtained is 0."})); - return ge::GRAPH_FAILED; - } - - npuArch_ = ascendcPlatform.GetCurNpuArch(); - if (npuArch_ != NpuArch::DAV_2201 && npuArch_ != NpuArch::DAV_3510 && - npuArch_ != NpuArch::DAV_9201 && npuArch_ != NpuArch::DAV_9202) { - OP_LOGE(opName_, - "Npu Arch Version[%d] is not support.", - static_cast(npuArch_)); - return ge::GRAPH_FAILED; - } - batchConsistency_ = - (context_->GetDeterministicLevel() == BATCH_CONSISTENCY_LEVEL); - OP_LOGD(opName_, "deterministic_level=%d", context_->GetDeterministicLevel()); - - return ge::GRAPH_SUCCESS; -} - -void SMLAInfoParser::GetOptionalInputParaInfo() { - sparse_mla_checker::PopulateOptionalTensorParam( - context_, ORI_KV_INDEX, opParamInfo_.oriKv); - sparse_mla_checker::PopulateOptionalTensorParam( - context_, CMP_KV_INDEX, opParamInfo_.cmpKv); - sparse_mla_checker::PopulateOptionalTensorParam( - context_, ORI_SPARSE_INDICES_INDEX, opParamInfo_.oriSparseIndices); - sparse_mla_checker::PopulateOptionalTensorParam( - context_, CMP_SPARSE_INDICES_INDEX, opParamInfo_.cmpSparseIndices); - sparse_mla_checker::PopulateOptionalTensorParam( - context_, ORI_BLOCK_TABLE_INDEX, opParamInfo_.oriBlockTable); - sparse_mla_checker::PopulateOptionalTensorParam( - context_, CMP_BLOCK_TABLE_INDEX, opParamInfo_.cmpBlockTable); - sparse_mla_checker::PopulateOptionalTensorParam( - context_, SINKS_INDEX, opParamInfo_.sinks); - sparse_mla_checker::PopulateOptionalTensorParam( - context_, CU_SEQLENS_Q_INDEX, opParamInfo_.cuSeqLensQ); - sparse_mla_checker::PopulateOptionalTensorParam( - context_, CU_SEQLENS_ORI_KV_INDEX, opParamInfo_.cuSeqLensOriKv); - sparse_mla_checker::PopulateOptionalTensorParam( - context_, CU_SEQLENS_CMP_KV_INDEX, opParamInfo_.cuSeqLensCmpKv); - sparse_mla_checker::PopulateOptionalTensorParam( - context_, SEQUSED_Q_INDEX, opParamInfo_.seqUsedQ); - sparse_mla_checker::PopulateOptionalTensorParam( - context_, SEQUSED_ORI_KV_INDEX, opParamInfo_.sequsedOriKv); - sparse_mla_checker::PopulateOptionalTensorParam( - context_, SEQUSED_CMP_KV_INDEX, opParamInfo_.sequsedCmpKv); - sparse_mla_checker::PopulateOptionalTensorParam( - context_, CMP_RESIDUAL_KV_INDEX, opParamInfo_.cmpResidualKv); - sparse_mla_checker::PopulateOptionalTensorParam( - context_, ORI_TOPK_LENGTH_INDEX, opParamInfo_.oriTopkLength); - sparse_mla_checker::PopulateOptionalTensorParam( - context_, CMP_TOPK_LENGTH_INDEX, opParamInfo_.cmpTopkLength); - sparse_mla_checker::PopulateOptionalTensorParam( - context_, METADATA_INDEX, opParamInfo_.metadata); -} - -void SMLAInfoParser::GetInputParaInfo() { - opParamInfo_.q.desc = context_->GetInputDesc(Q_INDEX); - opParamInfo_.q.shape = context_->GetInputShape(Q_INDEX); - GetOptionalInputParaInfo(); -} - -void SMLAInfoParser::GetOutputParaInfo() { - opParamInfo_.attnOut.desc = context_->GetOutputDesc(ATTN_OUT_INDEX); - opParamInfo_.attnOut.shape = context_->GetOutputShape(ATTN_OUT_INDEX); - opParamInfo_.softmaxLse.desc = context_->GetOutputDesc(SOFTMAX_LSE_INDEX); - opParamInfo_.softmaxLse.shape = context_->GetOutputShape(SOFTMAX_LSE_INDEX); -} - -ge::graphStatus SMLAInfoParser::GetAttrParaInfo() { - auto attrs = context_->GetAttrs(); - OP_CHECK_IF( - attrs == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - context_->GetNodeName(), "attrs", "attrs got from ge is nullptr"), - return ge::GRAPH_FAILED); - OP_LOGI(context_->GetNodeName(), "GetAttrParaInfo start"); - opParamInfo_.softmaxScale = - attrs->GetAttrPointer(ATTR_SOFTMAX_SCALE_INDEX); - opParamInfo_.cmpRatio = attrs->GetAttrPointer(ATTR_CMP_RATIO_INDEX); - opParamInfo_.oriMaskMode = - attrs->GetAttrPointer(ATTR_ORI_MASK_MODE_INDEX); - opParamInfo_.cmpMaskMode = - attrs->GetAttrPointer(ATTR_CMP_MASK_MODE_INDEX); - opParamInfo_.oriWinLeft = - attrs->GetAttrPointer(ATTR_ORI_WIN_LEFT_INDEX); - opParamInfo_.oriWinRight = - attrs->GetAttrPointer(ATTR_ORI_WIN_RIGHT_INDEX); - opParamInfo_.layoutQ = attrs->GetStr(ATTR_LAYOUT_Q_INDEX); - opParamInfo_.layoutKv = attrs->GetStr(ATTR_LAYOUT_KV_INDEX); - opParamInfo_.topkValueMode = - attrs->GetAttrPointer(ATTR_TOPK_VALUE_MODE_INDEX); - opParamInfo_.returnSoftmaxLse = - attrs->GetAttrPointer(ATTR_RETURN_SOFTMAX_LSE_INDEX); - - auto oriKeyStrides = context_->GetDynamicInputStride(ORI_KV_INDEX, 0); - if (oriKeyStrides != nullptr && oriKeyStrides->GetDimNum() > 0) { - for (size_t i = 0; i < oriKeyStrides->GetDimNum(); i++) { - oriKeyStridesVec_.push_back(oriKeyStrides->GetStride(i)); - } - } - auto cmpKeyStrides = context_->GetDynamicInputStride(CMP_KV_INDEX, 0); - if (cmpKeyStrides != nullptr && cmpKeyStrides->GetDimNum() > 0) { - for (size_t i = 0; i < cmpKeyStrides->GetDimNum(); i++) { - cmpKeyStridesVec_.push_back(cmpKeyStrides->GetStride(i)); - } - } - - OP_LOGI(context_->GetNodeName(), "GetAttrParaInfo end"); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetOpParaInfo() { - GetInputParaInfo(); - GetOutputParaInfo(); - if (ge::GRAPH_SUCCESS != GetAttrParaInfo()) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -uint64_t SMLAInfoParser::GetOptionalInputStride0(uint32_t inputIndex) const { - const gert::Tensor* inputTensor = nullptr; - if (inputIndex == ORI_KV_INDEX) { - inputTensor = opParamInfo_.oriKv.tensor; - } else if (inputIndex == CMP_KV_INDEX) { - inputTensor = opParamInfo_.cmpKv.tensor; - } - if (inputTensor == nullptr) { - return 0ULL; - } - - uint64_t stride0 = TryGetOptionalInputStride0(context_, inputIndex, 0); - if (stride0 > 0) { - return stride0; - } - - // Compatible with CANN packages that only expose view stride by normal input - // index. - stride0 = TryGetInputViewStride0(context_, inputIndex, 0); - if (stride0 > 0) { - return stride0; - } - - const gert::Shape& storageShape = inputTensor->GetStorageShape(); - stride0 = GetStorageShapeStride0(storageShape); - const char* inputName = inputIndex == ORI_KV_INDEX ? "ori_kv" : "cmp_kv"; - OP_LOGW(context_->GetNodeName(), - "Cannot get %s stride0 from tiling context stride APIs. Use storage " - "shape to infer contiguous " - "stride0(%lu). Non-contiguous %s requires GetOptionalInputStride or " - "GetInputStride support.", - inputName, - stride0, - inputName); - return stride0; -} -ge::graphStatus SMLAInfoParser::GetInOutDataType() { - qType_ = opParamInfo_.q.desc->GetDataType(); - outputType_ = opParamInfo_.attnOut.desc->GetDataType(); - if (opParamInfo_.oriKv.desc != nullptr) { - oriKvType_ = opParamInfo_.oriKv.desc->GetDataType(); - } - if (opParamInfo_.cmpKv.desc != nullptr) { - cmpKvType_ = opParamInfo_.cmpKv.desc->GetDataType(); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetSMLATemplateMode() { - if (opParamInfo_.oriKv.desc != nullptr) { - if (opParamInfo_.cmpKv.desc != nullptr && - opParamInfo_.cmpSparseIndices.tensor != nullptr) { - if (opParamInfo_.oriSparseIndices.tensor != nullptr) { - perfMode_ = SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE; - } else { - perfMode_ = SMLATemplateMode::CSA_TEMPLATE_MODE; - } - } else if (opParamInfo_.cmpKv.desc != nullptr && - opParamInfo_.cmpSparseIndices.tensor == nullptr) { - perfMode_ = SMLATemplateMode::HCA_TEMPLATE_MODE; - } else if (opParamInfo_.cmpKv.desc == nullptr && - opParamInfo_.cmpSparseIndices.tensor == nullptr) { - if (opParamInfo_.oriSparseIndices.tensor != nullptr) { - // A2A3此处dspark用 - // SWA_TEMPLATE_MODE+hasOri判断;给A5留ORI_SPARSE_TEMPLATE_MODE分支 - if (IsA5Arch(npuArch_) || IsA6Arch(npuArch_)) { - perfMode_ = SMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE; - } else { - // DSpark: oriMaskMode=0 + ori_sparse_indices on SWA kernel path. - if (opParamInfo_.oriMaskMode == nullptr || - *opParamInfo_.oriMaskMode != 0U) { - const std::string errorReason = - ("SWA ori sparse (DSpark) requires oriMaskMode 0, but got " + - std::to_string(opParamInfo_.oriMaskMode != nullptr - ? *opParamInfo_.oriMaskMode - : UINT32_MAX) + - "."); - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - Ops::Base::GetOpInfo(opName_), - "ori_sparse_indices, ori_mask_mode", - errorReason); - return ge::GRAPH_FAILED; - } - perfMode_ = SMLATemplateMode::SWA_TEMPLATE_MODE; - } - } else { - perfMode_ = SMLATemplateMode::SWA_TEMPLATE_MODE; - } - } else { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "cmp_kv", - "When cmp_sparse_indices is not nullptr, cmp_kv cannot be nullptr"); - return ge::GRAPH_FAILED; - } - if (perfMode_ == SMLATemplateMode::HCA_TEMPLATE_MODE || - perfMode_ == SMLATemplateMode::CSA_TEMPLATE_MODE) { - if (kvLayout_ == SMLALayout::TND && - opParamInfo_.cuSeqLensCmpKv.tensor == nullptr) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "cu_seqlens_cmp_kv", - "The layout_kv is" + SMLALayoutToSerialString(kvLayout_) + - ", seqlens_cmp_kv must be provided"); - return ge::GRAPH_FAILED; - } - } - } else { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, "ori_kv", "ori_kv is nullptr"); - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetQueryAndOutLayout() { - const map> layoutMap = { - {"BSND", {SMLALayout::BSND, SMLALayout::BSND}}, - {"TND", {SMLALayout::TND, SMLALayout::TND}}, - }; - std::string layout(opParamInfo_.layoutQ); - auto it = layoutMap.find(layout); - if (it != layoutMap.end()) { - qLayout_ = it->second.first; - outLayout_ = it->second.second; - oriSparseIndicesLayout_ = qLayout_; - cmpSparseIndicesLayout_ = qLayout_; - } else { - OP_LOGE_FOR_INVALID_VALUE( - opName_, "layout_q", layout.c_str(), "BSND or TND"); - return ge::GRAPH_FAILED; - } - if (qLayout_ == SMLALayout::BSND) { - OP_CHECK_IF(opParamInfo_.cuSeqLensQ.tensor != nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "cu_seqlens_q", - "When layout_q is BSND, cu_seqlens_q should be null"), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetKvLayout() { - const map layoutKVMap = { - {"PA_BBND", SMLALayout::PA_BBND}, - {"TND", SMLALayout::TND}, - {"BSND", SMLALayout::BSND}, - }; - std::string layout(opParamInfo_.layoutKv); - auto it = layoutKVMap.find(layout); - if (it != layoutKVMap.end()) { - kvLayout_ = it->second; - } else { - OP_LOGE_FOR_INVALID_VALUE( - opName_, "layout_kv", layout.c_str(), "BSND, PA_BBND or TND"); - return ge::GRAPH_FAILED; - } - if (kvLayout_ != SMLALayout::PA_BBND && qLayout_ != kvLayout_) { - OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( - opName_, - "layout_q and layout_kv", - SMLALayoutToSerialString(qLayout_) + " and " + - SMLALayoutToSerialString(kvLayout_), - "Layout_q and layout_kv only support BSND/BSND, TND/TND, BSND/PA_BBND " - "or TND/PA_BBND"); - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -// =============Parser function==================== -bool SMLAInfoParser::HasAxis(const SMLAAxis& axis, - const SMLALayout& layout, - const gert::Shape& shape) const { - const auto& layoutIt = SMLA_LAYOUT_AXIS_MAP.find(layout); - if (layoutIt == SMLA_LAYOUT_AXIS_MAP.end()) { - return false; - } - - const std::vector& axes = layoutIt->second; - const auto& axisIt = std::find(axes.begin(), axes.end(), axis); - if (axisIt == axes.end()) { - return false; - } - const auto& dimIt = SMLA_LAYOUT_DIM_MAP.find(layout); - if (dimIt == SMLA_LAYOUT_DIM_MAP.end() || - dimIt->second != shape.GetDimNum()) { - return false; - } - return true; -} - -size_t SMLAInfoParser::GetAxisIdx(const SMLAAxis& axis, - const SMLALayout& layout) const { - const std::vector& axes = SMLA_LAYOUT_AXIS_MAP.find(layout)->second; - const auto& axisIt = std::find(axes.begin(), axes.end(), axis); - return std::distance(axes.begin(), axisIt); -} - -int64_t SMLAInfoParser::GetAxisNum(const gert::Shape& shape, - const SMLAAxis& axis, - const SMLALayout& layout) const { - return HasAxis(axis, layout, shape) ? shape.GetDim(GetAxisIdx(axis, layout)) - : invalidDimValue_; -} - -ge::graphStatus SMLAInfoParser::SetSMLAShape() { - qShape_ = opParamInfo_.q.shape->GetStorageShape(); - if (opParamInfo_.oriKv.tensor != nullptr) { - oriKvShape_ = opParamInfo_.oriKv.tensor->GetStorageShape(); - } else { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, "oriKv", "OriKv is nullptr, please check input parameters"); - return ge::GRAPH_FAILED; - } - if (opParamInfo_.cmpKv.tensor != nullptr) { - cmpKvShape_ = opParamInfo_.cmpKv.tensor->GetStorageShape(); - } - if (opParamInfo_.oriSparseIndices.tensor != nullptr) { - oriSparseIndicesShape_ = - opParamInfo_.oriSparseIndices.tensor->GetStorageShape(); - hasOriSparseIndices_ = true; - oriSparseIndexWidth_ = GetAxisNum( - oriSparseIndicesShape_, SMLAAxis::K, oriSparseIndicesLayout_); - } - if (perfMode_ == SMLATemplateMode::CSA_TEMPLATE_MODE || - perfMode_ == SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { - if (opParamInfo_.cmpSparseIndices.tensor != nullptr) { - cmpSparseIndicesShape_ = - opParamInfo_.cmpSparseIndices.tensor->GetStorageShape(); - } else { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "cmp_sparse_indices", - "Cmp_sparse_indices is nullptr, please check input parameters"); - return ge::GRAPH_FAILED; - } - } - - if (perfMode_ == SMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE || - perfMode_ == SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { - if (opParamInfo_.oriSparseIndices.tensor != nullptr) { - oriSparseIndicesShape_ = - opParamInfo_.oriSparseIndices.tensor->GetStorageShape(); - } - } - - return ge::GRAPH_SUCCESS; -} - -// 根据layout计算期望的连续stride -std::vector SMLAInfoParser::GetKvstride( - const gert::Shape& shape, - const SMLALayout& layout) const { - std::vector expectedStrides; - if (layout == SMLALayout::BSND || layout == SMLALayout::PA_BBND) { - uint64_t dim1 = static_cast(shape.GetDim(1)); - uint64_t dim2 = static_cast(shape.GetDim(2)); - uint64_t dim3 = static_cast(shape.GetDim(3)); - expectedStrides = {dim1 * dim2 * dim3, dim2 * dim3, dim3, 1}; - } else if (layout == SMLALayout::TND) { - uint64_t dim1 = static_cast(shape.GetDim(1)); - uint64_t dim2 = static_cast(shape.GetDim(2)); - expectedStrides = {dim1 * dim2, dim2, 1}; - } - return expectedStrides; -} - -// 非连续校验:通过shape计算expected stride进行校验 -// PA_BBND时,只允许0轴非连续,其余轴必须连续 -// 非PA_BBND时,所有轴都必须连续 -ge::graphStatus SMLAInfoParser::CheckContiguous() const { - bool oriKeyNonContiguous = false; - bool cmpKeyNonContiguous = false; - size_t checkStartIdx = (kvLayout_ == SMLALayout::PA_BBND) ? 1 : 0; - if (opParamInfo_.oriKv.tensor != nullptr && !oriKeyStridesVec_.empty() && - opParamInfo_.oriKv.tensor->GetShapeSize() > 0) { - std::vector oriExpectedStrides = - GetKvstride(oriKvShape_, kvLayout_); - OP_CHECK_IF(oriKeyStridesVec_.size() != oriExpectedStrides.size(), - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "ori_kv", - "Ori_kv strideVec size[" + - std::to_string(oriKeyStridesVec_.size()) + - "] not match layout_kv expect len[" + - std::to_string(oriExpectedStrides.size()) + "]"), - return ge::GRAPH_FAILED); - oriKeyNonContiguous = - static_cast(oriKeyStridesVec_[checkStartIdx]) != - oriExpectedStrides[checkStartIdx]; - } - if (opParamInfo_.cmpKv.tensor != nullptr && !cmpKeyStridesVec_.empty() && - opParamInfo_.cmpKv.tensor->GetShapeSize() > 0) { - std::vector cmpExpectedStrides = - GetKvstride(cmpKvShape_, kvLayout_); - OP_CHECK_IF(cmpKeyStridesVec_.size() != cmpExpectedStrides.size(), - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "cmp_kv", - "Cmp_kv strideVec size[" + - std::to_string(cmpKeyStridesVec_.size()) + - "] not match kvLayout expect len[" + - std::to_string(cmpExpectedStrides.size()) + "]"), - return ge::GRAPH_FAILED); - cmpKeyNonContiguous = - static_cast(cmpKeyStridesVec_[checkStartIdx]) != - cmpExpectedStrides[checkStartIdx]; - } - - OP_CHECK_IF(oriKeyNonContiguous, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "ori_kv", - "Ori_kv only support non-continuous keying on the 0-axis"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(cmpKeyNonContiguous, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "cmp_kv", - "Cmp_kv only support non-continuous keying on the 0-axis"), - return ge::GRAPH_FAILED); - - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetN1Size() { - n1Size_ = GetAxisNum(qShape_, SMLAAxis::N, qLayout_); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetN2Size() { - if (opParamInfo_.oriKv.tensor != nullptr) { - n2Size_ = GetAxisNum(oriKvShape_, SMLAAxis::N, kvLayout_); - } - if (opParamInfo_.cmpKv.tensor != nullptr) { - n2Size_ = GetAxisNum(cmpKvShape_, SMLAAxis::N, kvLayout_); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetGSize() { - if (n2Size_ != 0) { - gSize_ = n1Size_ / n2Size_; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetActualSeqLenSize( - int64_t& size, - const gert::Tensor* tensor, - SMLALayout& layout, - const std::string& name) const { - if ((tensor == nullptr)) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - name.c_str(), - "When layout_q is " + SMLALayoutToSerialString(layout) + ", " + name + - " must be provided"); - return ge::GRAPH_FAILED; - } - int64_t shapeSize = tensor->GetShapeSize(); - if (shapeSize <= 0) { - OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( - opName_, - name.c_str(), - std::to_string(shapeSize).c_str(), - "The shape size of " + name + " should be greater than 0"); - return ge::GRAPH_FAILED; - } - size = shapeSize - 1; - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetActualSeqLenQSize(int64_t& size) { - return GetActualSeqLenSize( - size, opParamInfo_.cuSeqLensQ.tensor, qLayout_, "cu_seqlens_q"); -} - -ge::graphStatus SMLAInfoParser::GetBatchSize() { - // 获取B基准 // 1、非TND: 以query的batch_size维度为基 - // 2、TND: actual_seq_lens_q必须传入, 以actual_seq_lens_q数组的长度为B轴大小 - if (qLayout_ == SMLALayout::TND) { - return GetActualSeqLenQSize(bSize_); - } else { // BSND - bSize_ = GetAxisNum(qShape_, SMLAAxis::B, qLayout_); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetQTSize() { - // 获取query的T基准 // 1、非TND: 以query的batch_size维度为基准 - // 2、TND: actual_seq_lens_q必须传入, 以actual_seq_lens_q数组的长度为B轴大小 - qTSize_ = (qLayout_ == SMLALayout::TND) - ? GetAxisNum(qShape_, SMLAAxis::T, qLayout_) - : 0; - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetS1Size() { - // 获取S1基准 // 1、非TND: 以query的S维度为基准 - // 2、TND: actual_seq_lens_q必须传入, 以actual_seq_lens_q数组中的最大值为基准 - if (qLayout_ == SMLALayout::TND) { - s1Size_ = GetAxisNum(qShape_, SMLAAxis::T, qLayout_); - } else { // BSND - s1Size_ = GetAxisNum(qShape_, SMLAAxis::S, qLayout_); - } - if (perfMode_ == SMLATemplateMode::CSA_TEMPLATE_MODE || - perfMode_ == SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { - if (cmpSparseIndicesLayout_ == SMLALayout::TND) { - uint32_t cmpSparseIndicesT = GetAxisNum( - cmpSparseIndicesShape_, SMLAAxis::T, cmpSparseIndicesLayout_); - OP_CHECK_IF(cmpSparseIndicesT != s1Size_, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "cmp_sparse_indices", - Ops::Base::ToString(cmpSparseIndicesShape_), - "T size check failed"), - return ge::GRAPH_FAILED); - } else { - uint32_t cmpSparseIndicesS1 = GetAxisNum( - cmpSparseIndicesShape_, SMLAAxis::S, cmpSparseIndicesLayout_); - OP_CHECK_IF(cmpSparseIndicesS1 != s1Size_, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "cmp_sparse_indices", - Ops::Base::ToString(cmpSparseIndicesShape_), - "S1 size check failed"), - return ge::GRAPH_FAILED); - } - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetMaxBlockNumPerBatch() { - if (opParamInfo_.oriBlockTable.tensor == nullptr) { - return ge::GRAPH_SUCCESS; - } - uint32_t oriDimNum = - opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDimNum(); - if (oriDimNum != DIM_NUM_TWO) { - OP_LOGE_FOR_INVALID_SHAPEDIM(opName_, - "ori_block_table", - std::to_string(oriDimNum).c_str(), - std::to_string(DIM_NUM_TWO).c_str()); - return ge::GRAPH_FAILED; - } - if (opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDim(1) < 0) { - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "ori_block_table", - ToStringRaw(opParamInfo_.oriBlockTable.tensor->GetStorageShape()) - .c_str(), - "Ori_block_table's second dimension(" + - std::to_string( - opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDim( - 1)) + - ") should be non-negative number"); - return ge::GRAPH_FAILED; - } - oriMaxBlockNumPerBatch_ = - opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDim(1); - - if (opParamInfo_.cmpBlockTable.tensor != nullptr) { - uint32_t cmpDimNum = - opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDimNum(); - if (cmpDimNum != DIM_NUM_TWO) { - OP_LOGE_FOR_INVALID_SHAPEDIM(opName_, - "cmp_block_table", - std::to_string(cmpDimNum).c_str(), - std::to_string(DIM_NUM_TWO).c_str()); - return ge::GRAPH_FAILED; - } - if (qLayout_ == SMLALayout::TND || qLayout_ == SMLALayout::BSND) { - if (opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim(0) != - bSize_) { - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "cmp_block_table", - ToStringRaw(opParamInfo_.cmpBlockTable.tensor->GetStorageShape()) - .c_str(), - "Cmp_block_table's first dimension(" + - std::to_string( - opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim( - 0)) + - ") should be equal to query's B(" + std::to_string(bSize_) + - ")"); - return ge::GRAPH_FAILED; - } - } - if (opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim(1) <= 0) { - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "cmp_block_table", - ToStringRaw(opParamInfo_.cmpBlockTable.tensor->GetStorageShape()) - .c_str(), - "cmp_block_table's second dimension(" + - std::to_string( - opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim( - 1)) + - ") should be greater than 0"); - return ge::GRAPH_FAILED; - } - cmpMaxBlockNumPerBatch_ = - opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim(1); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetBlockSize() { - if (kvLayout_ != SMLALayout::PA_BBND) { - return ge::GRAPH_SUCCESS; - } - if (opParamInfo_.oriKv.tensor != nullptr) { - oriBlockSize_ = GetAxisNum(oriKvShape_, SMLAAxis::Bs, kvLayout_); - } - if (opParamInfo_.cmpKv.tensor != nullptr) { - cmpBlockSize_ = GetAxisNum(cmpKvShape_, SMLAAxis::Bs, kvLayout_); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::SmlaGetMagicPM() { - if (!IsA6Arch(npuArch_) || kvLayout_ != SMLALayout::PA_BBND) { - return ge::GRAPH_SUCCESS; - } - if (oriBlockSize_ <= 0) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, - "ori_block_size", - "ori block size(" + - std::to_string(oriBlockSize_) + - ") must be greater than 0."); - return ge::GRAPH_FAILED; - } - CalcMagicP(static_cast(oriBlockSize_), oriP_, oriMLow_, oriMHigh_); - if (opParamInfo_.cmpKv.tensor != nullptr) { - if (cmpBlockSize_ <= 0) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "cmp_block_size", - "cmp block size(" + std::to_string(cmpBlockSize_) + - ") must be greater than 0."); - return ge::GRAPH_FAILED; - } - CalcMagicP( - static_cast(cmpBlockSize_), cmpP_, cmpMLow_, cmpMHigh_); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetS2SizeForPageAttention() { - if (GetMaxBlockNumPerBatch() != ge::GRAPH_SUCCESS || - GetBlockSize() != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - s2Size_ = oriMaxBlockNumPerBatch_ * oriBlockSize_; - cmpS2Size_ = cmpMaxBlockNumPerBatch_ * cmpBlockSize_; - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetS2Size() { - if (kvLayout_ == SMLALayout::TND) { - s2Size_ = GetAxisNum(oriKvShape_, SMLAAxis::T, kvLayout_); - cmpS2Size_ = GetAxisNum(cmpKvShape_, SMLAAxis::T, kvLayout_); - return ge::GRAPH_SUCCESS; - } else if (kvLayout_ == SMLALayout::BSND) { - s2Size_ = GetAxisNum(oriKvShape_, SMLAAxis::S, kvLayout_); - cmpS2Size_ = GetAxisNum(cmpKvShape_, SMLAAxis::S, kvLayout_); - return ge::GRAPH_SUCCESS; - } else if (kvLayout_ == SMLALayout::PA_BBND) { - // 获取S2基准PAGE_ATTENTION S2 = block_table.dim1 * block_size - return GetS2SizeForPageAttention(); - } - return ge::GRAPH_FAILED; -} - -ge::graphStatus SMLAInfoParser::GetQHeadDim() { - qHeadDim_ = GetAxisNum(qShape_, SMLAAxis::D, qLayout_); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetValueHeadDim() { - if (opParamInfo_.oriKv.tensor != nullptr) { - oriKvHeadDim_ = GetAxisNum(oriKvShape_, SMLAAxis::D, kvLayout_); - } - if (opParamInfo_.cmpKv.tensor != nullptr) { - cmpKvHeadDim_ = GetAxisNum(cmpKvShape_, SMLAAxis::D, kvLayout_); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetSparseBlockCount() { - if (opParamInfo_.oriSparseIndices.tensor != nullptr) { - oriSparseBlockCount_ = GetAxisNum( - oriSparseIndicesShape_, SMLAAxis::K, oriSparseIndicesLayout_); - } - if (opParamInfo_.cmpSparseIndices.tensor != nullptr) { - cmpSparseBlockCount_ = GetAxisNum( - cmpSparseIndicesShape_, SMLAAxis::K, cmpSparseIndicesLayout_); - } - - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetSinks() { - if (opParamInfo_.sinks.tensor == nullptr) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, "sinks", "sinks must be provided"); - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLAInfoParser::GetActualseqInfo() { - if (qLayout_ == SMLALayout::TND) { - if (opParamInfo_.cuSeqLensQ.tensor != nullptr) { - if (opParamInfo_.cuSeqLensQ.tensor->GetShapeSize() != bSize_ + 1) { - OP_LOGE_FOR_INVALID_SHAPESIZE( - opName_, - "cu_seqlens_q", - std::to_string(opParamInfo_.cuSeqLensQ.tensor->GetShapeSize()) - .c_str(), - std::to_string(bSize_ + 1)); - return ge::GRAPH_FAILED; - } - actualLenDimsQ_ = opParamInfo_.cuSeqLensQ.tensor->GetShapeSize() - - 1; // cuSeqLensQ shape is B+1 - } else { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "cu_seqlens_q", - "When layout_q is TND, cu_seqlens_q must be provided"); - return ge::GRAPH_FAILED; - } - } else { - if (opParamInfo_.seqUsedQ.tensor != nullptr) { - actualLenDimsQ_ = opParamInfo_.seqUsedQ.tensor->GetShapeSize(); - } - } - if (kvLayout_ != SMLALayout::PA_BBND && kvLayout_ != SMLALayout::BSND && - kvLayout_ != SMLALayout::TND) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - opName_, - "layout_kv", - SMLALayoutToSerialString(kvLayout_), - "Ori_kv and cmp_kv only support PA_BBND, BSND and TND"); - return ge::GRAPH_FAILED; - } - if (opParamInfo_.sequsedOriKv.tensor != nullptr) { - actualLenDimsOriKV_ = opParamInfo_.sequsedOriKv.tensor->GetShapeSize(); - } - if (opParamInfo_.sequsedCmpKv.tensor != nullptr) { - actualLenDimsCmpKV_ = opParamInfo_.sequsedCmpKv.tensor->GetShapeSize(); - if (opParamInfo_.sequsedCmpKv.tensor->GetShapeSize() != bSize_) { - OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( - opName_, - "seqused_cmp_kv", - std::to_string(opParamInfo_.sequsedCmpKv.tensor->GetShapeSize()), - "Seqused_cmp_kv's dimension should be equal to " + - std::to_string(bSize_)); - return ge::GRAPH_FAILED; - } - } - if (opParamInfo_.cmpResidualKv.tensor != nullptr) { - cmpResidualKVSize_ = opParamInfo_.cmpResidualKv.tensor->GetShapeSize(); - if (opParamInfo_.cmpResidualKv.tensor->GetShapeSize() != bSize_) { - OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( - opName_, - "cmp_residual_kv", - std::to_string(opParamInfo_.cmpResidualKv.tensor->GetShapeSize()), - "Cmp_residual_kv's dimension should be equal to " + - std::to_string(bSize_)); - return ge::GRAPH_FAILED; - } - } - if (!IsA5Arch(npuArch_) && !IsA6Arch(npuArch_) && - IsNonEmptyOptionalTensor(opParamInfo_.cmpTopkLength.tensor)) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "cmp_topk_length", - "cmp_topk_length is reserved and does not support non-empty tensor " - "on " + - std::string(A2_A3_PLATFORM_LOG.c_str()) + "."); - return ge::GRAPH_FAILED; - } - if (kvLayout_ == SMLALayout::PA_BBND) { - if (opParamInfo_.sequsedOriKv.tensor != nullptr) { - if (qLayout_ == SMLALayout::BSND) { - if (opParamInfo_.sequsedOriKv.tensor->GetShapeSize() != bSize_) { - OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( - opName_, - "seqused_ori_kv", - std::to_string(opParamInfo_.sequsedOriKv.tensor->GetShapeSize()), - "Seqused_ori_kv's dimension should be equal to " + - std::to_string(bSize_)); - return ge::GRAPH_FAILED; - } - } else { - if (opParamInfo_.sequsedOriKv.tensor->GetShapeSize() != bSize_) { - OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( - opName_, - "seqused_ori_kv", - std::to_string(opParamInfo_.sequsedOriKv.tensor->GetShapeSize()), - "Seqused_ori_kv's dimension should be equal to " + - std::to_string(bSize_)); - return ge::GRAPH_FAILED; - } - } - actualLenDimsKV_ = opParamInfo_.sequsedOriKv.tensor->GetShapeSize(); - } else if (perfMode_ != SMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE && - perfMode_ != SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "seqused_ori_kv", - "Seqused_ori_kv must be provided when layout_kv is PA_BBND"); - return ge::GRAPH_FAILED; - } - } else if (kvLayout_ == SMLALayout::TND) { - } else if (kvLayout_ == SMLALayout::BSND) { - actualLenDimsKV_ = actualLenDimsOriKV_; - } else { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - opName_, - "layout_kv", - SMLALayoutToSerialString(kvLayout_), - "Ori_kv and cmp_kv only support PA_BBND, TND and BSND"); - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -void SMLAInfoParser::GenerateInfo(SMLATilingInfo& smlaInfo) { - smlaInfo.opName = opName_; - smlaInfo.platformInfo = platformInfo_; - smlaInfo.opParamInfo = opParamInfo_; - smlaInfo.npuArch = npuArch_; - - smlaInfo.bSize = bSize_; - smlaInfo.n1Size = n1Size_; - smlaInfo.n2Size = n2Size_; - smlaInfo.s1Size = s1Size_; - smlaInfo.s2Size = s2Size_; - smlaInfo.cmpS2Size = cmpS2Size_; - smlaInfo.gSize = gSize_; - smlaInfo.qHeadDim = qHeadDim_; - smlaInfo.oriKvHeadDim = oriKvHeadDim_; - smlaInfo.cmpKvHeadDim = cmpKvHeadDim_; - smlaInfo.qTSize = qTSize_; - smlaInfo.oriSparseBlockCount = oriSparseBlockCount_; - smlaInfo.cmpSparseBlockCount = cmpSparseBlockCount_; - smlaInfo.sparseBlockCount = cmpSparseBlockCount_; - smlaInfo.hasOriSparseIndices = hasOriSparseIndices_; - smlaInfo.oriSparseIndexWidth = oriSparseIndexWidth_; - smlaInfo.oriWinLeft = oriWinLeft_; - smlaInfo.oriWinRight = oriWinRight_; - smlaInfo.qType = qType_; - smlaInfo.oriKvType = oriKvType_; - smlaInfo.cmpKvType = cmpKvType_; - smlaInfo.outputType = outputType_; - smlaInfo.perfMode = perfMode_; - - smlaInfo.sparseBlockSize = 1; - smlaInfo.oriBlockSize = oriBlockSize_; - smlaInfo.cmpBlockSize = cmpBlockSize_; - smlaInfo.oriP = oriP_; - smlaInfo.oriMLow = oriMLow_; - smlaInfo.oriMHigh = oriMHigh_; - smlaInfo.cmpP = cmpP_; - smlaInfo.cmpMLow = cmpMLow_; - smlaInfo.cmpMHigh = cmpMHigh_; - smlaInfo.oriMaxBlockNumPerBatch = oriMaxBlockNumPerBatch_; - smlaInfo.cmpMaxBlockNumPerBatch = cmpMaxBlockNumPerBatch_; - - smlaInfo.actualLenDimsQ = actualLenDimsQ_; - smlaInfo.actualLenDimsKV = actualLenDimsKV_; - - smlaInfo.softmaxScale = *opParamInfo_.softmaxScale; - smlaInfo.cmpRatio = *opParamInfo_.cmpRatio; - smlaInfo.oriMaskMode = *opParamInfo_.oriMaskMode; - smlaInfo.cmpMaskMode = *opParamInfo_.cmpMaskMode; - smlaInfo.oriKvStride0 = GetOptionalInputStride0(ORI_KV_INDEX); - smlaInfo.cmpKvStride0 = GetOptionalInputStride0(CMP_KV_INDEX); - smlaInfo.oriWinLeft = *opParamInfo_.oriWinLeft; - smlaInfo.oriWinRight = *opParamInfo_.oriWinRight; - - smlaInfo.topkValueMode = *opParamInfo_.topkValueMode; - - smlaInfo.qLayout = qLayout_; - smlaInfo.oriSparseIndicesLayout = oriSparseIndicesLayout_; - smlaInfo.cmpSparseIndicesLayout = cmpSparseIndicesLayout_; - smlaInfo.kvLayout = kvLayout_; - smlaInfo.outLayout = outLayout_; - smlaInfo.returnSoftmaxLse = *opParamInfo_.returnSoftmaxLse; - smlaInfo.batchConsistency = batchConsistency_; - - smlaInfo.actualLenDimsOriKV = actualLenDimsOriKV_; - smlaInfo.actualLenDimsCmpKV = actualLenDimsCmpKV_; - smlaInfo.cmpResidualKVSize = cmpResidualKVSize_; - - if (!IsA5Arch(npuArch_) && !IsA6Arch(npuArch_)) { - smlaInfo.oriKeyStride0 = 0; - smlaInfo.cmpKeyStride0 = 0; - } else { - if (!oriKeyStridesVec_.empty()) { - smlaInfo.oriKeyStride0 = static_cast(oriKeyStridesVec_[0]); - } else { - smlaInfo.oriKeyStride0 = GetKvstride(oriKvShape_, kvLayout_)[0]; - } - - if (!cmpKeyStridesVec_.empty()) { - smlaInfo.cmpKeyStride0 = static_cast(cmpKeyStridesVec_[0]); - } else { - smlaInfo.cmpKeyStride0 = GetKvstride(cmpKvShape_, kvLayout_)[0]; - } - } -} - -ge::graphStatus SMLAInfoParser::Parse(SMLATilingInfo& smlaInfo) { - if (context_ == nullptr) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - "SparseFlashAttention", "context_", "tiling context is nullptr!"); - return ge::GRAPH_FAILED; - } - - if (ge::GRAPH_SUCCESS != GetOpName() || ge::GRAPH_SUCCESS != GetNpuInfo() || - ge::GRAPH_SUCCESS != GetOpParaInfo() || - ge::GRAPH_SUCCESS != CheckRequiredParaExistence() || - ge::GRAPH_SUCCESS != CheckUnrequiredParaExistence()) { - return ge::GRAPH_FAILED; - } - - if (ge::GRAPH_SUCCESS != GetInOutDataType() || - ge::GRAPH_SUCCESS != GetQueryAndOutLayout() || - ge::GRAPH_SUCCESS != GetKvLayout() || - ge::GRAPH_SUCCESS != GetSMLATemplateMode()) { - return ge::GRAPH_FAILED; - } - - if (ge::GRAPH_SUCCESS != SetSMLAShape()) { - return ge::GRAPH_FAILED; - } - if (ge::GRAPH_SUCCESS != GetN1Size() || ge::GRAPH_SUCCESS != GetN2Size() || - ge::GRAPH_SUCCESS != GetGSize() || ge::GRAPH_SUCCESS != GetBatchSize() || - ge::GRAPH_SUCCESS != GetQTSize() || ge::GRAPH_SUCCESS != GetS1Size() || - ge::GRAPH_SUCCESS != GetS2Size() || - ge::GRAPH_SUCCESS != SmlaGetMagicPM() || - ge::GRAPH_SUCCESS != GetQHeadDim() || - ge::GRAPH_SUCCESS != GetValueHeadDim() || - ge::GRAPH_SUCCESS != GetSparseBlockCount() || - ge::GRAPH_SUCCESS != GetSinks()) { - return ge::GRAPH_FAILED; - } - if (ge::GRAPH_SUCCESS != GetActualseqInfo()) { - return ge::GRAPH_FAILED; - } - if (ge::GRAPH_SUCCESS != CheckContiguous()) { - return ge::GRAPH_FAILED; - } - GenerateInfo(smlaInfo); - return ge::GRAPH_SUCCESS; -} - -void SMLATilingCheck::Init() { - opName_ = smlaInfo_.opName; - platformInfo_ = smlaInfo_.platformInfo; - opParamInfo_ = smlaInfo_.opParamInfo; - npuArch_ = smlaInfo_.npuArch; - bSize_ = smlaInfo_.bSize; - n1Size_ = smlaInfo_.n1Size; - n2Size_ = smlaInfo_.n2Size; - s1Size_ = smlaInfo_.s1Size; - s2Size_ = smlaInfo_.s2Size; - cmpS2Size_ = smlaInfo_.cmpS2Size; - gSize_ = smlaInfo_.gSize; - qHeadDim_ = smlaInfo_.qHeadDim; - oriKvHeadDim_ = smlaInfo_.oriKvHeadDim; - cmpKvHeadDim_ = smlaInfo_.cmpKvHeadDim; - oriBlockSize_ = smlaInfo_.oriBlockSize; - cmpBlockSize_ = smlaInfo_.cmpBlockSize; - qTSize_ = smlaInfo_.qTSize; - qType_ = smlaInfo_.qType; - oriKvType_ = smlaInfo_.oriKvType; - cmpKvType_ = smlaInfo_.cmpKvType; - outputType_ = smlaInfo_.outputType; - cmpRatio_ = smlaInfo_.cmpRatio; - qLayout_ = smlaInfo_.qLayout; - oriSparseIndicesLayout_ = smlaInfo_.oriSparseIndicesLayout; - cmpSparseIndicesLayout_ = smlaInfo_.cmpSparseIndicesLayout; - oriWinLeft_ = smlaInfo_.oriWinLeft; - oriWinRight_ = smlaInfo_.oriWinRight; - hasOriSparseIndices_ = smlaInfo_.hasOriSparseIndices; - oriSparseIndexWidth_ = smlaInfo_.oriSparseIndexWidth; - kvLayout_ = smlaInfo_.kvLayout; - outLayout_ = smlaInfo_.outLayout; - topkValueMode_ = smlaInfo_.topkValueMode; -} - -void SMLATilingCheck::LogErrorDtypeSupport( - const std::vector& expectDtypeList, - const ge::DataType& actualDtype, - const std::string& name) const { - std::ostringstream oss; - for (size_t i = 0; i < expectDtypeList.size(); ++i) { - oss << SMLADataTypeToSerialString(expectDtypeList[i]); - if (i < expectDtypeList.size() - 1) { - oss << ", "; - } - } - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - opName_, - name.c_str(), - SMLADataTypeToSerialString(actualDtype).c_str(), - "The dtype of " + name + " only supports " + oss.str()); -} - -ge::graphStatus SMLATilingCheck::CheckDtypeSupport( - const gert::CompileTimeTensorDesc* desc, - const std::string& name) const { - if (desc != nullptr) { - const auto& it = DTYPE_SUPPORT_MAP.find(name); - if (it == DTYPE_SUPPORT_MAP.end()) { - const std::string errorReason = - (name + - " datatype support list should be specify in DTYPE_SUPPORT_MAP"); - OP_LOGE_LIBOPAPI_REPORT( - Ops::Base::GetOpInfo(opName_), "%s", errorReason.c_str()); - REPORT_PREDEFINED_ERR_MSG( - "EZ1008", - std::vector({"opName", "reason"}), - std::vector( - {Ops::Base::GetOpInfo(opName_), errorReason.c_str()})); - return ge::GRAPH_FAILED; - } - auto& expectDtypeList = it->second; - OP_CHECK_IF( - std::find(expectDtypeList.begin(), - expectDtypeList.end(), - desc->GetDataType()) == expectDtypeList.end(), - LogErrorDtypeSupport(expectDtypeList, desc->GetDataType(), name), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; -} - -void SMLATilingCheck::LogErrorLayoutSupport( - const std::vector& expectLayoutList, - const SMLALayout& actualLayout, - const std::string& name) const { - std::ostringstream oss; - for (size_t i = 0; i < expectLayoutList.size(); ++i) { - oss << SMLALayoutToSerialString(expectLayoutList[i]); - if (i < expectLayoutList.size() - 1) { - oss << ", "; - } - } - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - opName_, - name.c_str(), - SMLALayoutToSerialString(actualLayout).c_str(), - "Tensor " + name + " only supports layout " + oss.str()); -} - -ge::graphStatus SMLATilingCheck::CheckLayoutSupport( - const SMLALayout& actualLayout, - const std::string& name) const { - const auto& it = LAYOUT_SUPPORT_MAP.find(name); - if (it == LAYOUT_SUPPORT_MAP.end()) { - const std::string errorReason = - (name + " layout support list should be specify in LAYOUT_SUPPORT_MAP"); - OP_LOGE_LIBOPAPI_REPORT( - Ops::Base::GetOpInfo(opName_), "%s", errorReason.c_str()); - REPORT_PREDEFINED_ERR_MSG( - "EZ1008", - std::vector({"opName", "reason"}), - std::vector( - {Ops::Base::GetOpInfo(opName_), errorReason.c_str()})); - return ge::GRAPH_FAILED; - } - auto& expectLayoutList = it->second; - OP_CHECK_IF(std::find(expectLayoutList.begin(), - expectLayoutList.end(), - actualLayout) == expectLayoutList.end(), - LogErrorLayoutSupport(expectLayoutList, actualLayout, name), - return ge::GRAPH_FAILED); - - return ge::GRAPH_SUCCESS; -} - -template -void SMLATilingCheck::LogErrorNumberSupport( - const std::vector& expectNumberList, - const T& actualValue, - const std::string& name, - const std::string subName) const { - std::ostringstream oss; - for (size_t i = 0; i < expectNumberList.size(); ++i) { - oss << std::to_string(expectNumberList[i]); - if (i < expectNumberList.size() - 1) { - oss << ", "; - } - } - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - name, - name + " " + std::string(subName.c_str()) + " only supports " + - oss.str() + ", but got " + - std::string(std::to_string(actualValue).c_str())); -} - -template -void SMLATilingCheck::LogErrorDimNumSupport( - const std::vector& expectNumberList, - const T& actualValue, - const std::string& name) const { - LogErrorNumberSupport(expectNumberList, actualValue, name, "dimension"); -} - -ge::graphStatus SMLATilingCheck::CheckDimNumSupport( - const gert::StorageShape* shape, - const std::vector& expectDimNumList, - const std::string& name) const { - if (shape == nullptr) { - return ge::GRAPH_SUCCESS; - } - - if (std::find(expectDimNumList.begin(), - expectDimNumList.end(), - shape->GetStorageShape().GetDimNum()) == - expectDimNumList.end()) { - LogErrorDimNumSupport( - expectDimNumList, shape->GetStorageShape().GetDimNum(), name); - return ge::GRAPH_FAILED; - } - - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckDimNumInLayoutSupport( - const SMLALayout& layout, - const gert::StorageShape* shape, - const std::string& name) const { - const auto& dimIt = SMLA_LAYOUT_DIM_MAP.find(layout); - OP_CHECK_IF(shape->GetStorageShape().GetDimNum() != dimIt->second, - OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( - opName_, - name.c_str(), - std::to_string(shape->GetStorageShape().GetDimNum()).c_str(), - "When layout is " + SMLALayoutToSerialString(layout) + - ", the shape dim of " + name + " should be " + - std::to_string(dimIt->second)), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaQuery() const { - if (opParamInfo_.q.desc == nullptr || opParamInfo_.q.shape == nullptr) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, "q", "Q must be provided"); - return ge::GRAPH_FAILED; - } - const std::vector queryDimNumList = {DIM_NUM_THREE, DIM_NUM_FOUR}; - if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.q.desc, QUERY_NAME) || - ge::GRAPH_SUCCESS != CheckLayoutSupport(qLayout_, QUERY_NAME) || - ge::GRAPH_SUCCESS != CheckDimNumSupport(opParamInfo_.q.shape, - queryDimNumList, - QUERY_NAME) || - ge::GRAPH_SUCCESS != CheckDimNumInLayoutSupport( - qLayout_, opParamInfo_.q.shape, QUERY_NAME)) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaOriKv() const { - const std::vector oriKvDimNumList = {DIM_NUM_THREE, DIM_NUM_FOUR}; - if (ge::GRAPH_SUCCESS != - CheckDtypeSupport(opParamInfo_.oriKv.desc, ORI_KV_NAME) || - ge::GRAPH_SUCCESS != CheckLayoutSupport(kvLayout_, ORI_KV_NAME) || - ge::GRAPH_SUCCESS != - CheckDimNumSupport(&opParamInfo_.oriKv.tensor->GetShape(), - oriKvDimNumList, - ORI_KV_NAME) || - ge::GRAPH_SUCCESS != - CheckDimNumInLayoutSupport( - kvLayout_, &opParamInfo_.oriKv.tensor->GetShape(), ORI_KV_NAME)) { - return ge::GRAPH_FAILED; - } - if (kvLayout_ == SMLALayout::BSND) { - OP_CHECK_IF( - opParamInfo_.oriKv.tensor->GetStorageShape().GetDim(0) != bSize_, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "ori_kv", - ToStringRaw(opParamInfo_.oriKv.tensor->GetStorageShape()), - "Ori_kv's batch dimension(" + - std::to_string( - opParamInfo_.oriKv.tensor->GetStorageShape().GetDim(0)) + - ") should be equal to B(" + std::to_string(bSize_) + ")"), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaCmpKv() const { - if (smlaInfo_.perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE || - smlaInfo_.perfMode == SMLATemplateMode::HCA_TEMPLATE_MODE || - smlaInfo_.perfMode == SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { - const std::vector cmpKvDimNumList = {DIM_NUM_THREE, DIM_NUM_FOUR}; - if (ge::GRAPH_SUCCESS != - CheckDtypeSupport(opParamInfo_.cmpKv.desc, CMP_KV_NAME) || - ge::GRAPH_SUCCESS != CheckLayoutSupport(kvLayout_, CMP_KV_NAME) || - ge::GRAPH_SUCCESS != - CheckDimNumSupport(&opParamInfo_.cmpKv.tensor->GetShape(), - cmpKvDimNumList, - CMP_KV_NAME) || - ge::GRAPH_SUCCESS != - CheckDimNumInLayoutSupport(kvLayout_, - &opParamInfo_.cmpKv.tensor->GetShape(), - CMP_KV_NAME)) { - return ge::GRAPH_FAILED; - } - if (kvLayout_ == SMLALayout::BSND) { - OP_CHECK_IF( - opParamInfo_.cmpKv.tensor->GetStorageShape().GetDim(0) != bSize_, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "cmp_kv", - ToStringRaw(opParamInfo_.cmpKv.tensor->GetStorageShape()), - "Cmp_kv's batch dimension(" + - std::to_string( - opParamInfo_.cmpKv.tensor->GetStorageShape().GetDim(0)) + - ") should be equal to B(" + std::to_string(bSize_) + ")"), - return ge::GRAPH_FAILED); - } - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaCuSeqLensQ() const { - if (opParamInfo_.cuSeqLensQ.tensor == nullptr) { - return ge::GRAPH_SUCCESS; - } - const std::vector dimNumList = {DIM_NUM_ONE}; - if (ge::GRAPH_SUCCESS != - CheckDtypeSupport(opParamInfo_.cuSeqLensQ.desc, CU_SEQLENS_Q_NAME) || - ge::GRAPH_SUCCESS != - CheckDimNumSupport(&opParamInfo_.cuSeqLensQ.tensor->GetShape(), - dimNumList, - CU_SEQLENS_Q_NAME)) { - return ge::GRAPH_FAILED; - } - OP_CHECK_IF(opParamInfo_.cuSeqLensQ.tensor->GetShapeSize() != bSize_ + 1, - OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( - opName_, - "cu_seqlens_q", - std::to_string(opParamInfo_.cuSeqLensQ.tensor->GetShapeSize()) - .c_str(), - "The shape size of cu_seqlens_q is not equal to B + 1:" + - std::to_string(bSize_ + 1)), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaCuSeqLensOriKv() const { - if (opParamInfo_.cuSeqLensOriKv.tensor == nullptr) { - return ge::GRAPH_SUCCESS; - } - const std::vector dimNumList = {DIM_NUM_ONE}; - if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.cuSeqLensOriKv.desc, - CU_SEQLENS_ORI_KV_NAME) || - ge::GRAPH_SUCCESS != - CheckDimNumSupport(&opParamInfo_.cuSeqLensOriKv.tensor->GetShape(), - dimNumList, - CU_SEQLENS_ORI_KV_NAME)) { - return ge::GRAPH_FAILED; - } - OP_CHECK_IF( - opParamInfo_.cuSeqLensOriKv.tensor->GetShapeSize() != bSize_ + 1, - OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( - opName_, - "cu_seqlens_ori_kv", - std::to_string(opParamInfo_.cuSeqLensOriKv.tensor->GetShapeSize()) - .c_str(), - "The shape size of cu_seqlens_ori_kv is not equal to B + 1:" + - std::to_string(bSize_ + 1)), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaCuSeqLensCmpKv() const { - if (opParamInfo_.cuSeqLensCmpKv.tensor == nullptr) { - return ge::GRAPH_SUCCESS; - } - const std::vector dimNumList = {DIM_NUM_ONE}; - if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.cuSeqLensCmpKv.desc, - CU_SEQLENS_CMP_KV_NAME) || - ge::GRAPH_SUCCESS != - CheckDimNumSupport(&opParamInfo_.cuSeqLensCmpKv.tensor->GetShape(), - dimNumList, - CU_SEQLENS_CMP_KV_NAME)) { - return ge::GRAPH_FAILED; - } - OP_CHECK_IF( - opParamInfo_.cuSeqLensCmpKv.tensor->GetShapeSize() != bSize_ + 1, - OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( - opName_, - "cu_seqlens_cmp_kv", - std::to_string(opParamInfo_.cuSeqLensCmpKv.tensor->GetShapeSize()) - .c_str(), - "The shape size of cu_seqlens_cmp_kv is not equal to B + 1:" + - std::to_string(bSize_ + 1)), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaNumHeads() const { - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaKvHeadNums() const { - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaOriSparseIndices() const { - if (opParamInfo_.oriSparseIndices.tensor == nullptr) { - return ge::GRAPH_SUCCESS; - } - if (!IsA5Arch(npuArch_) && !IsA6Arch(npuArch_)) { - OP_CHECK_IF(smlaInfo_.perfMode != SMLATemplateMode::SWA_TEMPLATE_MODE, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "ori_sparse_indices", - "ori_sparse_indices is only supported in SWA mode."), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - opParamInfo_.oriMaskMode == nullptr || *opParamInfo_.oriMaskMode != 0U, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "ori_sparse_indices, ori_mask_mode", - "ori_sparse_indices SWA (DSpark) requires oriMaskMode 0."), - return ge::GRAPH_FAILED); - } - OP_CHECK_IF( - opParamInfo_.oriSparseIndices.tensor->GetStorageShape().GetShapeSize() == - 0, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "ori_sparse_indices", - "Ori_sparse_indices cannot be empty tensor"), - return ge::GRAPH_FAILED); - const std::vector oriSparseIndicesDimNumList = {DIM_NUM_THREE, - DIM_NUM_FOUR}; - if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.oriSparseIndices.desc, - ORI_SPARSE_INDICES) || - ge::GRAPH_SUCCESS != - CheckLayoutSupport(oriSparseIndicesLayout_, ORI_SPARSE_INDICES) || - ge::GRAPH_SUCCESS != - CheckDimNumSupport(&opParamInfo_.oriSparseIndices.tensor->GetShape(), - oriSparseIndicesDimNumList, - ORI_SPARSE_INDICES) || - ge::GRAPH_SUCCESS != - CheckDimNumInLayoutSupport( - oriSparseIndicesLayout_, - &opParamInfo_.oriSparseIndices.tensor->GetShape(), - ORI_SPARSE_INDICES)) { - return ge::GRAPH_FAILED; - } - if (oriSparseIndicesLayout_ == SMLALayout::BSND) { - OP_CHECK_IF( - opParamInfo_.oriSparseIndices.tensor->GetStorageShape().GetDim(0) != - bSize_, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "ori_sparse_indices", - ToStringRaw( - opParamInfo_.oriSparseIndices.tensor->GetStorageShape()), - "Ori_sparse_indices's batch dimension(" + - std::to_string( - opParamInfo_.oriSparseIndices.tensor->GetStorageShape() - .GetDim(0)) + - ") should be equal to B(" + std::to_string(bSize_) + ")"), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaCmpSparseIndices() const { - if (smlaInfo_.perfMode == optiling::SMLATemplateMode::CSA_TEMPLATE_MODE || - smlaInfo_.perfMode == - optiling::SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { - OP_CHECK_IF(opParamInfo_.cmpSparseIndices.tensor->GetStorageShape() - .GetShapeSize() == 0, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "cmp_sparse_indices", - "When cmp_sparse_indices is not nullptr(CSA), " - "cmp_sparse_indices cannot be empty tensor"), - return ge::GRAPH_FAILED); - const std::vector cmpSparseIndicesDimNumList = {DIM_NUM_THREE, - DIM_NUM_FOUR}; - if (ge::GRAPH_SUCCESS != - CheckDtypeSupport(opParamInfo_.cmpSparseIndices.desc, - CMP_SPARSE_INDICES) || - ge::GRAPH_SUCCESS != - CheckLayoutSupport(cmpSparseIndicesLayout_, CMP_SPARSE_INDICES) || - ge::GRAPH_SUCCESS != - CheckDimNumSupport( - &opParamInfo_.cmpSparseIndices.tensor->GetShape(), - cmpSparseIndicesDimNumList, - CMP_SPARSE_INDICES) || - ge::GRAPH_SUCCESS != - CheckDimNumInLayoutSupport( - cmpSparseIndicesLayout_, - &opParamInfo_.cmpSparseIndices.tensor->GetShape(), - CMP_SPARSE_INDICES)) { - return ge::GRAPH_FAILED; - } - const auto& indicesShape = - opParamInfo_.cmpSparseIndices.tensor->GetStorageShape(); - const int64_t topk = indicesShape.GetDim(indicesShape.GetDimNum() - 1); - OP_CHECK_IF( - npuArch_ == NpuArch::DAV_2201 && (topk < 1 || topk > TOPK_LIMIT), - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "cmp_sparse_indices", - "cmp_sparse_indices last dimension must be in [1, " + - std::to_string(TOPK_LIMIT) + "], but got " + - std::to_string(static_cast(topk)) + "."), - return ge::GRAPH_FAILED); - if (cmpSparseIndicesLayout_ == SMLALayout::BSND) { - OP_CHECK_IF( - opParamInfo_.cmpSparseIndices.tensor->GetStorageShape().GetDim(0) != - bSize_, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "cmp_sparse_indices", - ToStringRaw( - opParamInfo_.cmpSparseIndices.tensor->GetStorageShape()), - "Cmp_sparse_indices's batch dimension(" + - std::to_string( - opParamInfo_.cmpSparseIndices.tensor->GetStorageShape() - .GetDim(0)) + - ") should be equal to B(" + std::to_string(bSize_) + ")"), - return ge::GRAPH_FAILED); - } - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaOriBlockTable() const { - if (kvLayout_ != SMLALayout::PA_BBND) { - return ge::GRAPH_SUCCESS; - } - const std::vector oriBlockTableDimNumList = {DIM_NUM_TWO}; - if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.oriBlockTable.desc, - ORI_BLOCK_TABLE_NAME) || - ge::GRAPH_SUCCESS != - CheckDimNumSupport(&opParamInfo_.oriBlockTable.tensor->GetShape(), - oriBlockTableDimNumList, - ORI_BLOCK_TABLE_NAME)) { - return ge::GRAPH_FAILED; - } - OP_CHECK_IF( - opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDim(0) != bSize_, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "ori_block_table", - ToStringRaw(opParamInfo_.oriBlockTable.tensor->GetStorageShape()), - "Ori_block_table's first dimension(" + - std::to_string( - opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDim( - 0)) + - ") should be equal to B(" + std::to_string(bSize_) + ")"), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - !IsPaBlockSizeSupport(npuArch_, oriBlockSize_), - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "ori_kv", - ToStringRaw(opParamInfo_.oriKv.tensor->GetStorageShape()).c_str(), - "OriBlockSize_ should be in [1, 1024] on " + - (IsA6Arch(npuArch_) ? A6_PLATFORM_LOG : A5_PLATFORM_LOG) + - " or 16-aligned [16, 1024] on " + A2_A3_PLATFORM_LOG + - ", but got: " + std::to_string(oriBlockSize_)), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaCmpBlockTable() const { - if (kvLayout_ != SMLALayout::PA_BBND) { - return ge::GRAPH_SUCCESS; - } - if (smlaInfo_.perfMode == optiling::SMLATemplateMode::CSA_TEMPLATE_MODE || - smlaInfo_.perfMode == optiling::SMLATemplateMode::HCA_TEMPLATE_MODE || - smlaInfo_.perfMode == - optiling::SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { - OP_CHECK_IF(opParamInfo_.cmpBlockTable.tensor == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "cmp_block_table", - "Cmp_block_table must be provided when layout_kv is " - "PA_BBND in CSA/HCA/ORI_CMP_SPARSE mode"), - return ge::GRAPH_FAILED); - const std::vector cmpBlockTableDimNumList = {DIM_NUM_TWO}; - if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.cmpBlockTable.desc, - CMP_BLOCK_TABLE_NAME) || - ge::GRAPH_SUCCESS != - CheckDimNumSupport(&opParamInfo_.cmpBlockTable.tensor->GetShape(), - cmpBlockTableDimNumList, - CMP_BLOCK_TABLE_NAME)) { - return ge::GRAPH_FAILED; - } - OP_CHECK_IF( - opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim(0) != - bSize_, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "cmp_block_table", - ToStringRaw(opParamInfo_.cmpBlockTable.tensor->GetStorageShape()), - "cmp_block_table's first dimension(" + - std::to_string( - opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim( - 0)) + - ") should be equal to B(" + std::to_string(bSize_) + ")"), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - !IsPaBlockSizeSupport(npuArch_, cmpBlockSize_), - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "cmp_kv", - ToStringRaw(opParamInfo_.oriKv.tensor->GetStorageShape()).c_str(), - "CmpBlockSize should be in [1, 1024] on " + - (IsA6Arch(npuArch_) ? A6_PLATFORM_LOG : A5_PLATFORM_LOG) + - " or 16-aligned [16, 1024] on " + A2_A3_PLATFORM_LOG + - ", but got: " + std::to_string(cmpBlockSize_)), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaSinks() const { - OP_CHECK_IF(opParamInfo_.sinks.tensor->GetStorageShape().GetShapeSize() == 0, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, "sinks", "Sinks cannot be empty tensor"), - return ge::GRAPH_FAILED); - if (opParamInfo_.sinks.tensor->GetStorageShape().GetDimNum() != DIM_NUM_ONE) { - OP_LOGE_FOR_INVALID_SHAPEDIM( - opName_, - SINKS_NAME.c_str(), - std::to_string(opParamInfo_.sinks.tensor->GetStorageShape().GetDimNum()) - .c_str(), - std::to_string(DIM_NUM_ONE).c_str()); - return ge::GRAPH_FAILED; - } - if (opParamInfo_.sinks.tensor->GetStorageShape().GetDim(0) != n1Size_) { - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "sinks", - ToStringRaw(opParamInfo_.sinks.tensor->GetStorageShape()), - "Sinks's dimension(" + - std::to_string( - opParamInfo_.sinks.tensor->GetStorageShape().GetDim(0)) + - ") should be equal to the head num of query(" + - std::to_string(n1Size_) + ")"); - return ge::GRAPH_FAILED; - } - OP_CHECK_IF( - opParamInfo_.sinks.desc->GetDataType() != ge::DT_FLOAT, - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - opName_, - "sinks", - SMLADataTypeToSerialString(opParamInfo_.sinks.desc->GetDataType()) - .c_str(), - "The dtype of sinks must be DT_FLOAT"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaMetadata() const { - if (opParamInfo_.metadata.tensor == nullptr) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, "metadata", "Metadata must be provided"); - return ge::GRAPH_FAILED; - } - const std::vector dimNumList = {DIM_NUM_ONE}; - if (ge::GRAPH_SUCCESS != - CheckDimNumSupport(&opParamInfo_.metadata.tensor->GetShape(), - dimNumList, - METADATA_NAME)) { - return ge::GRAPH_FAILED; - } - OP_CHECK_IF((opParamInfo_.metadata.tensor->GetShapeSize() != METADATA_LIMIT), - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "metadata", - ToStringRaw(opParamInfo_.metadata.tensor->GetStorageShape()), - "metadata dim 0 must be" + std::to_string(METADATA_LIMIT)), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - opParamInfo_.metadata.desc->GetDataType() != ge::DT_INT32, - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - opName_, - "metadata", - SMLADataTypeToSerialString(opParamInfo_.metadata.desc->GetDataType()) - .c_str(), - "The dtype of metadata must be DT_INT32"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaCmpRatio() const { - const auto checkRatio = [this](bool isSupported, - const char* expectedRatios, - const char* modeName, - const char* modeReason) { - OP_CHECK_IF(!isSupported, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "cmp_ratio", - "cmpRatio should be " + std::string(expectedRatios) + - " in " + std::string(modeName) + " on " + - std::string(A2_A3_PLATFORM_LOG.c_str()) + " " + - std::string(modeReason) + ", but got " + - std::to_string(cmpRatio_) + "."), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; - }; - - switch (smlaInfo_.perfMode) { - case SMLATemplateMode::CSA_TEMPLATE_MODE: - // {2, 4}:压缩比倍数 - return checkRatio(cmpRatio_ == 1 || cmpRatio_ == 2 || cmpRatio_ == 4, - "1, 2 or 4", - "CSA", - "when cmp_sparse_indices is provided"); - case SMLATemplateMode::HCA_TEMPLATE_MODE: - // 128:压缩比倍数 - return checkRatio(cmpRatio_ == 128, - "128", - "HCA", - "when cmp_sparse_indices is not provided"); - default: - return ge::GRAPH_SUCCESS; - } -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaOriMaskMode() const { - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaCmpMaskMode() const { - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaOriWinLeft() const { - OP_CHECK_IF(oriWinLeft_ < -1, - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - opName_, - "ori_win_left", - std::to_string(oriWinLeft_).c_str(), - "Ori_win_left should be -1(unlimited) or non-negative"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaOriWinRight() const { - OP_CHECK_IF(oriWinRight_ < -1, - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - opName_, - "ori_win_right", - std::to_string(oriWinRight_).c_str(), - "Ori_win_right should be -1(unlimited) or non-negative"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaCmpResidualKv() const { - bool isCmpTemplate = - smlaInfo_.perfMode == SMLATemplateMode::HCA_TEMPLATE_MODE || - smlaInfo_.perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE; - if (isCmpTemplate && *opParamInfo_.cmpMaskMode == 3 && - cmpRatio_ != 1) { // 3: RightDownCausal模式 - OP_CHECK_IF(opParamInfo_.cmpResidualKv.tensor == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "cmp_residual_kv", - "Cmp_residual_kv is required when cmp_mask_mode=3 and " - "cmp_ratio != 1"), - return ge::GRAPH_FAILED); - } - if (opParamInfo_.cmpResidualKv.tensor == nullptr) { - return ge::GRAPH_SUCCESS; - } - const std::vector dimNumList = {DIM_NUM_ONE}; - if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.cmpResidualKv.desc, - CMP_RESIDUAL_KV_NAME) || - ge::GRAPH_SUCCESS != - CheckDimNumSupport(&opParamInfo_.cmpResidualKv.tensor->GetShape(), - dimNumList, - CMP_RESIDUAL_KV_NAME)) { - return ge::GRAPH_FAILED; - } - OP_CHECK_IF( - opParamInfo_.cmpResidualKv.tensor->GetShapeSize() != bSize_, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "cmp_residual_kv", - ToStringRaw(opParamInfo_.cmpResidualKv.tensor->GetStorageShape()), - "Cmp_residual_kv's first dimension(" + - std::to_string( - opParamInfo_.cmpResidualKv.tensor->GetShapeSize()) + - ") should be equal to B(" + std::to_string(bSize_) + ")"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSingleParaTopkLength() const { - if (IsA5Arch(npuArch_) || IsA6Arch(npuArch_)) { - if (opParamInfo_.oriTopkLength.tensor != nullptr) { - const std::vector dimNumList = {DIM_NUM_TWO, DIM_NUM_THREE}; - if (ge::GRAPH_SUCCESS != - CheckDtypeSupport(opParamInfo_.oriTopkLength.desc, - ORI_TOPK_LENGTH_NAME) || - ge::GRAPH_SUCCESS != - CheckDimNumSupport(&opParamInfo_.oriTopkLength.tensor->GetShape(), - dimNumList, - ORI_TOPK_LENGTH_NAME)) { - return ge::GRAPH_FAILED; - } - OP_CHECK_IF( - opParamInfo_.oriTopkLength.desc->GetDataType() != ge::DT_INT32, - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - opName_, - "ori_topk_length", - SMLADataTypeToSerialString( - opParamInfo_.oriTopkLength.desc->GetDataType()) - .c_str(), - "The dtype of ori_topk_length must be DT_INT32"), - return ge::GRAPH_FAILED); - } - if (opParamInfo_.cmpTopkLength.tensor != nullptr) { - const std::vector dimNumList = {DIM_NUM_TWO, DIM_NUM_THREE}; - if (ge::GRAPH_SUCCESS != - CheckDtypeSupport(opParamInfo_.cmpTopkLength.desc, - CMP_TOPK_LENGTH_NAME) || - ge::GRAPH_SUCCESS != - CheckDimNumSupport(&opParamInfo_.cmpTopkLength.tensor->GetShape(), - dimNumList, - CMP_TOPK_LENGTH_NAME)) { - return ge::GRAPH_FAILED; - } - OP_CHECK_IF( - opParamInfo_.cmpTopkLength.desc->GetDataType() != ge::DT_INT32, - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - opName_, - "cmp_topk_length", - SMLADataTypeToSerialString( - opParamInfo_.cmpTopkLength.desc->GetDataType()) - .c_str(), - "The dtype of cmp_topk_length must be DT_INT32"), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; - } - if (IsNonEmptyOptionalTensor(opParamInfo_.cmpTopkLength.tensor)) { - OP_CHECK_IF(smlaInfo_.perfMode != SMLATemplateMode::CSA_TEMPLATE_MODE, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "cmp_topk_length", - "Cmp_topk_length is only supported in CSA mode"), - return ge::GRAPH_FAILED); - } - if (!IsNonEmptyOptionalTensor(opParamInfo_.oriTopkLength.tensor)) { - OP_CHECK_IF(hasOriSparseIndices_ && - smlaInfo_.perfMode == SMLATemplateMode::SWA_TEMPLATE_MODE, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "ori_topk_length", - "Ori_topk_length is required for SWA ori sparse"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; - } - OP_CHECK_IF(opParamInfo_.oriSparseIndices.tensor == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "ori_sparse_indices", - "Ori_topk_length requires ori_sparse_indices"), - return ge::GRAPH_FAILED); - if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.oriTopkLength.desc, - ORI_TOPK_LENGTH_NAME)) { - return ge::GRAPH_FAILED; - } - OP_CHECK_IF(opParamInfo_.oriTopkLength.desc->GetDataType() != ge::DT_INT32, - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - opName_, - "ori_topk_length", - SMLADataTypeToSerialString( - opParamInfo_.oriTopkLength.desc->GetDataType()) - .c_str(), - "The dtype of ori_topk_length must be DT_INT32"), - return ge::GRAPH_FAILED); - const gert::Shape& topkLenShape = - opParamInfo_.oriTopkLength.tensor->GetStorageShape(); - const gert::Shape& sparseShape = - opParamInfo_.oriSparseIndices.tensor->GetStorageShape(); - if (oriSparseIndicesLayout_ == SMLALayout::TND) { - OP_CHECK_IF(topkLenShape.GetDimNum() != 2 || sparseShape.GetDimNum() != 3, - OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( - opName_, - "ori_topk_length and ori_sparse_indices", - Ops::Base::ToString(topkLenShape) + " and " + - Ops::Base::ToString(sparseShape), - "TND ori_topk_length shape must be [T, N2], " - "ori_sparse_indices [T, N2, K]"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(topkLenShape.GetDim(0) != sparseShape.GetDim(0) || - topkLenShape.GetDim(1) != sparseShape.GetDim(1), - OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( - opName_, - "ori_topk_length and ori_sparse_indices", - Ops::Base::ToString(topkLenShape) + " and " + - Ops::Base::ToString(sparseShape), - "Ori_topk_length shape must match ori_sparse_indices " - "without K dim"), - return ge::GRAPH_FAILED); - } else { - OP_CHECK_IF(topkLenShape.GetDimNum() != 3 || sparseShape.GetDimNum() != 4, - OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( - opName_, - "ori_topk_length", - Ops::Base::ToString(topkLenShape), - "BSND ori_topk_length shape must be [B, S1, N2]"), - return ge::GRAPH_FAILED); - OP_CHECK_IF(topkLenShape.GetDim(0) != sparseShape.GetDim(0) || - topkLenShape.GetDim(1) != sparseShape.GetDim(1) || - topkLenShape.GetDim(2) != sparseShape.GetDim(2), - OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( - opName_, - "ori_topk_length and ori_sparse_indices", - Ops::Base::ToString(topkLenShape) + " and " + - Ops::Base::ToString(sparseShape), - "Ori_topk_length shape must match ori_sparse_indices " - "without K dim"), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckSinglePara() const { - if (ge::GRAPH_SUCCESS != CheckSingleParaQuery() || - ge::GRAPH_SUCCESS != CheckSingleParaOriKv() || - ge::GRAPH_SUCCESS != CheckSingleParaCmpKv() || - ge::GRAPH_SUCCESS != CheckSingleParaCuSeqLensQ() || - ge::GRAPH_SUCCESS != CheckSingleParaCuSeqLensOriKv() || - ge::GRAPH_SUCCESS != CheckSingleParaCuSeqLensCmpKv() || - ge::GRAPH_SUCCESS != CheckSingleParaCmpRatio() || - ge::GRAPH_SUCCESS != CheckSingleParaCmpResidualKv() || - ge::GRAPH_SUCCESS != CheckSingleParaTopkLength() || - ge::GRAPH_SUCCESS != CheckSingleParaNumHeads() || - ge::GRAPH_SUCCESS != CheckSingleParaKvHeadNums() || - ge::GRAPH_SUCCESS != CheckSingleParaOriSparseIndices() || - ge::GRAPH_SUCCESS != CheckSingleParaCmpSparseIndices() || - ge::GRAPH_SUCCESS != CheckSingleParaOriBlockTable() || - ge::GRAPH_SUCCESS != CheckSingleParaCmpBlockTable() || - ge::GRAPH_SUCCESS != CheckSingleParaSinks() || - ge::GRAPH_SUCCESS != CheckSingleParaMetadata() || - ge::GRAPH_SUCCESS != CheckSingleParaOriMaskMode() || - ge::GRAPH_SUCCESS != CheckSingleParaCmpMaskMode() || - ge::GRAPH_SUCCESS != CheckSingleParaOriWinLeft() || - ge::GRAPH_SUCCESS != CheckSingleParaOriWinRight()) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckExists(const void* pointer, - const std::string& name) const { - OP_CHECK_IF(pointer == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, name.c_str(), name + " should not be null"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckNotExists(const void* pointer, - const std::string& name) const { - OP_CHECK_IF(pointer != nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, name.c_str(), name + " should not be null"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckExistsByMap( - const std::map& paramMap) const { - for (const auto& kv : paramMap) { - if (CheckExists(kv.second, kv.first) != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckNotExistsByMap( - const std::map& paramMap) const { - for (const auto& kv : paramMap) { - if (CheckNotExists(kv.second, kv.first) != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckExistenceByMap( - std::map& existMap, - std::map& notExistMap) const { - if (CheckExistsByMap(existMap) != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - if (CheckNotExistsByMap(notExistMap) != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckParaExistence() const { - if (IsA5Arch(npuArch_) || IsA6Arch(npuArch_)) { - OP_CHECK_IF((kvLayout_ == SMLALayout::TND && - opParamInfo_.cuSeqLensOriKv.tensor == nullptr), - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "cu_seqlens_ori_kv", - "cu_seqlens_ori_kv must be provided when kv layout is TND"), - return ge::GRAPH_FAILED); - } else { - if (kvLayout_ == SMLALayout::PA_BBND) { - std::map ParamExistMap = { - {"actualSeqLengths", opParamInfo_.sequsedOriKv.tensor}, - {"oriBlockTable", opParamInfo_.oriBlockTable.tensor}, - }; - std::map ParamNotExistMap = {}; - if (CheckExistenceByMap(ParamExistMap, ParamNotExistMap) != - ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - } - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckFeatureShape() const { - if (qLayout_ == SMLALayout::TND) { - OP_CHECK_IF( - bSize_ <= 0, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "cu_seqlens_q", - ToStringRaw(opParamInfo_.cuSeqLensQ.tensor->GetStorageShape()) - .c_str(), - "Batch_size should be greater than 0, but got " + - std::to_string(bSize_)), - return ge::GRAPH_FAILED); - } else { // BSND - OP_CHECK_IF( - bSize_ <= 0, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "q", - ToStringRaw(opParamInfo_.q.shape->GetStorageShape()).c_str(), - "Batch_size should be greater than 0, but got " + - std::to_string(bSize_)), - return ge::GRAPH_FAILED); - } - - OP_CHECK_IF(qTSize_ <= 0 && (qLayout_ == SMLALayout::TND), - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "q", - ToStringRaw(opParamInfo_.q.shape->GetStorageShape()).c_str(), - "T_size of q should be greater than 0, but got " + - std::to_string(qTSize_)), - return ge::GRAPH_FAILED); - - if (IsA5Arch(npuArch_) || IsA6Arch(npuArch_)) { - OP_CHECK_IF( - n1Size_ < 1 || n1Size_ > 128, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "q", - ToStringRaw(opParamInfo_.q.shape->GetStorageShape()).c_str(), - "The head num of q should be in [1, 128] on" + - (IsA6Arch(npuArch_) ? A6_PLATFORM_LOG : A5_PLATFORM_LOG) + - ", but got " + std::to_string(n1Size_)), - return ge::GRAPH_FAILED); - } else { - OP_CHECK_IF(!IsPowerOfTwoInRange(n1Size_, 1, 128), - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "query", - "q_head_num should be power of two in [1, 128] on " + - std::string(A2_A3_PLATFORM_LOG.c_str()) + ", but got " + - std::to_string(n1Size_)), - return ge::GRAPH_FAILED); - } - - if (opParamInfo_.oriKv.tensor != nullptr) { - OP_CHECK_IF( - n2Size_ != 1, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "ori_kv", - ToStringRaw(opParamInfo_.oriKv.tensor->GetStorageShape()).c_str(), - "The head num of ori_kv should be 1, but got " + - std::to_string(n2Size_)), - return ge::GRAPH_FAILED); - - OP_CHECK_IF( - n1Size_ % n2Size_ != 0, - OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( - opName_, - "q and ori_kv", - Ops::Base::ToString(opParamInfo_.q.shape->GetStorageShape()) + - " and " + - Ops::Base::ToString( - opParamInfo_.oriKv.tensor->GetStorageShape()), - "The head num of q(" + std::to_string(n1Size_) + - ") must be divisible by the head num of ori_kv(" + - std::to_string(n2Size_) + ")"), - return ge::GRAPH_FAILED); - } - if (opParamInfo_.cmpKv.tensor != nullptr) { - OP_CHECK_IF( - n2Size_ != 1, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "cmp_kv", - ToStringRaw(opParamInfo_.cmpKv.tensor->GetStorageShape()).c_str(), - "The head num of cmp_kv should be 1, but got " + - std::to_string(n2Size_)), - return ge::GRAPH_FAILED); - - OP_CHECK_IF( - n1Size_ % n2Size_ != 0, - OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( - opName_, - "q and cmp_kv", - Ops::Base::ToString(opParamInfo_.q.shape->GetStorageShape()) + - " and " + - Ops::Base::ToString( - opParamInfo_.cmpKv.tensor->GetStorageShape()), - "The head num of q(" + std::to_string(n1Size_) + - ") must be divisible by the head num of cmp_kv(" + - std::to_string(n2Size_) + ")"), - return ge::GRAPH_FAILED); - } - - if (IsA5Arch(npuArch_) || IsA6Arch(npuArch_)) { - if (opParamInfo_.oriKv.tensor != nullptr) { - OP_CHECK_IF( - gSize_ < 1 || gSize_ > 128, - OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( - opName_, - "q and ori_kv", - Ops::Base::ToString(opParamInfo_.q.shape->GetStorageShape()) + - " and " + - Ops::Base::ToString( - opParamInfo_.oriKv.tensor->GetStorageShape()), - "The value of (the head num of q ceildivided by the head num of " - "ori_kv) " - "should be in [1, 128] on " + - (IsA6Arch(npuArch_) ? A6_PLATFORM_LOG : A5_PLATFORM_LOG) + - ", but got " + std::to_string(gSize_)), - return ge::GRAPH_FAILED); - } - if (opParamInfo_.cmpKv.tensor != nullptr) { - OP_CHECK_IF( - gSize_ < 1 || gSize_ > 128, - OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( - opName_, - "q and cmp_kv", - Ops::Base::ToString(opParamInfo_.q.shape->GetStorageShape()) + - " and " + - Ops::Base::ToString( - opParamInfo_.cmpKv.tensor->GetStorageShape()), - "The value of (the head num of q ceildivided by the head num of " - "cmp_kv) " - "should be in [1, 128] on " + - (IsA6Arch(npuArch_) ? A6_PLATFORM_LOG : A5_PLATFORM_LOG) + - ", but got " + std::to_string(gSize_)), - return ge::GRAPH_FAILED); - } - } else { - OP_CHECK_IF(!IsPowerOfTwoInRange(gSize_, 1, 128), - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "query, key", - "group num should be power of two in [1, 128] on " + - std::string(A2_A3_PLATFORM_LOG.c_str()) + ", but got " + - std::to_string(gSize_)), - return ge::GRAPH_FAILED); - } - - OP_CHECK_IF( - qHeadDim_ != DIM_LIMIT, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "q", - ToStringRaw(opParamInfo_.q.shape->GetStorageShape()).c_str(), - "The head num of q only support " + std::to_string(DIM_LIMIT) + - ", but got " + std::to_string(qHeadDim_)), - return ge::GRAPH_FAILED); - - if (opParamInfo_.oriKv.tensor != nullptr) { - OP_CHECK_IF( - oriKvHeadDim_ != DIM_LIMIT, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "ori_kv", - ToStringRaw(opParamInfo_.oriKv.tensor->GetStorageShape()).c_str(), - "The head num of ori_kv only support " + std::to_string(DIM_LIMIT) + - ", but got " + std::to_string(oriKvHeadDim_)), - return ge::GRAPH_FAILED); - } - if (!(smlaInfo_.perfMode == SMLATemplateMode::SWA_TEMPLATE_MODE || - smlaInfo_.perfMode == SMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE) && - (opParamInfo_.cmpKv.tensor != nullptr)) { - OP_CHECK_IF( - cmpKvHeadDim_ != DIM_LIMIT, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "cmp_kv", - ToStringRaw(opParamInfo_.cmpKv.tensor->GetStorageShape()).c_str(), - "The head num of cmp_kv only support " + std::to_string(DIM_LIMIT) + - ", but got " + std::to_string(cmpKvHeadDim_)), - return ge::GRAPH_FAILED); - } - - OP_CHECK_IF(!(qType_ == oriKvType_), - OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( - opName_, - "q and ori_kv", - SMLADataTypeToSerialString(qType_) + " and " + - SMLADataTypeToSerialString(oriKvType_), - "The dtype of q and ori_kv must be same"), - return ge::GRAPH_FAILED); - - if (IsA5Arch(npuArch_) || IsA6Arch(npuArch_)) { - OP_CHECK_IF( - *opParamInfo_.oriMaskMode != 0 && *opParamInfo_.oriMaskMode != 3 && - *opParamInfo_.oriMaskMode != 4, - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - opName_, - "ori_mask_mode", - std::to_string(*opParamInfo_.oriMaskMode).c_str(), - "Ori_mask_mode should be {0, 3, 4} on " + - (IsA6Arch(npuArch_) ? A6_PLATFORM_LOG : A5_PLATFORM_LOG)), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - *opParamInfo_.cmpMaskMode != 0 && *opParamInfo_.cmpMaskMode != 3, - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - opName_, - "cmp_mask_mode", - std::to_string(*opParamInfo_.cmpMaskMode).c_str(), - "Cmp_mask_mode should be {0, 3} on " + - (IsA6Arch(npuArch_) ? A6_PLATFORM_LOG : A5_PLATFORM_LOG)), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - oriWinLeft_ < -1, - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - opName_, - "ori_win_left", - std::to_string(oriWinLeft_).c_str(), - "Ori_win_left should be -1(unlimited) or non-negative on " + - (IsA6Arch(npuArch_) ? A6_PLATFORM_LOG : A5_PLATFORM_LOG)), - return ge::GRAPH_FAILED); - OP_CHECK_IF( - oriWinRight_ < -1, - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - opName_, - "ori_win_right", - std::to_string(oriWinRight_).c_str(), - "Ori_win_right should be -1(unlimited) or non-negative on " + - (IsA6Arch(npuArch_) ? A6_PLATFORM_LOG : A5_PLATFORM_LOG)), - return ge::GRAPH_FAILED); - } else { - OP_CHECK_IF(topkValueMode_ != 1, - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - opName_, - "topk_value_mode", - std::to_string(topkValueMode_).c_str(), - "Topk_value_mode should be 1 on " + A2_A3_PLATFORM_LOG), - return ge::GRAPH_FAILED); - if (smlaInfo_.perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE || - smlaInfo_.perfMode == SMLATemplateMode::HCA_TEMPLATE_MODE) { - OP_CHECK_IF( - *opParamInfo_.cmpMaskMode != 3, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "cmp_mask_mode", - "cmpMaskMode should be 3 on " + - std::string(A2_A3_PLATFORM_LOG.c_str()) + ", but got " + - std::to_string(*opParamInfo_.cmpMaskMode)), - return ge::GRAPH_FAILED); - } - if (hasOriSparseIndices_) { - OP_CHECK_IF( - *opParamInfo_.oriMaskMode != 0U, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "ori_mask_mode", - "oriMaskMode must be 0 for SWA ori sparse (DSpark) on " + - std::string(A2_A3_PLATFORM_LOG.c_str()) + ", but got " + - std::to_string(*opParamInfo_.oriMaskMode) + "."), - return ge::GRAPH_FAILED); - OP_CHECK_IF(oriWinLeft_ < 0 || oriWinRight_ < 0, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "ori_win_left", - "ori_win_left/right should be non-negative for ori " - "sparse SWA on " + - std::string(A2_A3_PLATFORM_LOG.c_str()) + "."), - return ge::GRAPH_FAILED); - } else { - OP_CHECK_IF(*opParamInfo_.oriMaskMode != 4U, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "ori_sparse_indices, ori_mask_mode", - "oriMaskMode should be 4 on " + - std::string(A2_A3_PLATFORM_LOG.c_str()) + - " when ori_sparse_indices is empty, but got " + - std::to_string(*opParamInfo_.oriMaskMode)), - return ge::GRAPH_FAILED); - OP_CHECK_IF(oriWinLeft_ != 127, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "ori_sparse_indices, ori_win_left", - "oriWinLeft_ should be 127 on " + - std::string(A2_A3_PLATFORM_LOG.c_str()) + - " when ori_sparse_indices is empty, but got " + - std::to_string(oriWinLeft_)), - return ge::GRAPH_FAILED); - OP_CHECK_IF(oriWinRight_ != 0, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, - "ori_sparse_indices, ori_win_right", - "oriWinRight_ should be 0 on " + - std::string(A2_A3_PLATFORM_LOG.c_str()) + - " when ori_sparse_indices is empty, but got " + - std::to_string(oriWinRight_)), - return ge::GRAPH_FAILED); - } - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckFeatureLayout() const { - const std::vector layoutQuerySupportList = {"BSND", "TND"}; - std::string layoutQuery = opParamInfo_.layoutQ; - OP_CHECK_IF(std::find(layoutQuerySupportList.begin(), - layoutQuerySupportList.end(), - layoutQuery) == layoutQuerySupportList.end(), - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - opName_, - "layout_q", - layoutQuery.c_str(), - "Layout_q only supports BSND or TND"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckFeatureDtype() const { - OP_CHECK_IF(qType_ != ge::DT_BF16 && qType_ != ge::DT_FLOAT16, - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - opName_, - "q", - SMLADataTypeToSerialString(qType_).c_str(), - "The dtype of q only supports " + - SMLADataTypeToSerialString(ge::DT_BF16) + " and " + - SMLADataTypeToSerialString(ge::DT_FLOAT16)), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckFeaturePa() const { - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckFeature() const { - if (ge::GRAPH_SUCCESS != CheckFeatureShape() || - ge::GRAPH_SUCCESS != CheckFeatureLayout() || - ge::GRAPH_SUCCESS != CheckFeatureDtype() || - ge::GRAPH_SUCCESS != CheckFeaturePa()) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckDTypeConsistency( - const ge::DataType& actualDtype, - const ge::DataType& expectDtype, - const std::string& name) const { - if (actualDtype != expectDtype) { - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - opName_, - name.c_str(), - SMLADataTypeToSerialString(actualDtype).c_str(), - "The dtype of " + name + " should be " + - SMLADataTypeToSerialString(expectDtype)); - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckOriAndCmpKv() const { - if (smlaInfo_.perfMode == SMLATemplateMode::HCA_TEMPLATE_MODE || - smlaInfo_.perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE || - smlaInfo_.perfMode == SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { - if (ge::GRAPH_SUCCESS != - CheckDTypeConsistency(cmpKvType_, oriKvType_, CMP_KV_NAME)) { - return ge::GRAPH_FAILED; - } - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckAttenOut() const { - if (opParamInfo_.attnOut.desc == nullptr) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - opName_, "attn_out", "Attn_out must be provided"); - return ge::GRAPH_FAILED; - } - const std::vector dimNumList = {DIM_NUM_THREE, DIM_NUM_FOUR}; - if (ge::GRAPH_SUCCESS != - CheckDtypeSupport(opParamInfo_.attnOut.desc, ATTEN_OUT_NAME) || - ge::GRAPH_SUCCESS != CheckLayoutSupport(outLayout_, ATTEN_OUT_NAME) || - ge::GRAPH_SUCCESS != CheckDimNumSupport(opParamInfo_.attnOut.shape, - dimNumList, - ATTEN_OUT_NAME) || - ge::GRAPH_SUCCESS != - CheckDimNumInLayoutSupport( - outLayout_, opParamInfo_.attnOut.shape, ATTEN_OUT_NAME)) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckActualSeqLensQ() const { - if (opParamInfo_.seqUsedQ.tensor == nullptr) { - return ge::GRAPH_SUCCESS; - } - const std::vector dimNumList = {DIM_NUM_ONE}; - if (ge::GRAPH_SUCCESS != - CheckDtypeSupport(opParamInfo_.seqUsedQ.desc, SEQUSED_Q_NAME) || - ge::GRAPH_SUCCESS != - CheckDimNumSupport(&opParamInfo_.seqUsedQ.tensor->GetShape(), - dimNumList, - SEQUSED_Q_NAME)) { - return ge::GRAPH_FAILED; - } - OP_CHECK_IF( - opParamInfo_.seqUsedQ.tensor->GetShapeSize() != bSize_, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "seqused_q", - ToStringRaw(opParamInfo_.seqUsedQ.tensor->GetStorageShape()), - "Seqused_q's first dimension(" + - std::to_string(opParamInfo_.seqUsedQ.tensor->GetShapeSize()) + - ") should be equal to B(" + std::to_string(bSize_) + ")"), - return ge::GRAPH_FAILED); - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::CheckActualSeqLens() const { - if (opParamInfo_.sequsedOriKv.tensor != nullptr) { - const std::vector dimNumList = {DIM_NUM_ONE}; - if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.sequsedOriKv.desc, - SEQUSED_ORI_KV_NAME) || - ge::GRAPH_SUCCESS != - CheckDimNumSupport(&opParamInfo_.sequsedOriKv.tensor->GetShape(), - dimNumList, - SEQUSED_ORI_KV_NAME)) { - return ge::GRAPH_FAILED; - } - OP_CHECK_IF( - opParamInfo_.sequsedOriKv.tensor->GetShapeSize() != bSize_, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "seqused_ori_kv", - ToStringRaw(opParamInfo_.sequsedOriKv.tensor->GetStorageShape()), - "Seqused_ori_kv's first dimension(" + - std::to_string( - opParamInfo_.sequsedOriKv.tensor->GetShapeSize()) + - ") should be equal to B(" + std::to_string(bSize_) + ")"), - return ge::GRAPH_FAILED); - } - if (opParamInfo_.sequsedCmpKv.tensor != nullptr) { - const std::vector dimNumList = {DIM_NUM_ONE}; - if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.sequsedCmpKv.desc, - SEQUSED_CMP_KV_NAME) || - ge::GRAPH_SUCCESS != - CheckDimNumSupport(&opParamInfo_.sequsedCmpKv.tensor->GetShape(), - dimNumList, - SEQUSED_CMP_KV_NAME)) { - return ge::GRAPH_FAILED; - } - OP_CHECK_IF( - opParamInfo_.sequsedCmpKv.tensor->GetShapeSize() != bSize_, - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - opName_, - "seqused_cmp_kv", - ToStringRaw(opParamInfo_.sequsedCmpKv.tensor->GetStorageShape()), - "Seqused_cmp_kv's first dimension(" + - std::to_string( - opParamInfo_.sequsedCmpKv.tensor->GetShapeSize()) + - ") should be equal to B(" + std::to_string(bSize_) + ")"), - return ge::GRAPH_FAILED); - } - return ge::GRAPH_SUCCESS; -} -ge::graphStatus SMLATilingCheck::CheckMultiParaConsistency() const { - if (ge::GRAPH_SUCCESS != CheckOriAndCmpKv() || - ge::GRAPH_SUCCESS != CheckAttenOut() || - ge::GRAPH_SUCCESS != CheckActualSeqLensQ() || - ge::GRAPH_SUCCESS != CheckActualSeqLens()) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -ge::graphStatus SMLATilingCheck::Process() { - Init(); - if (CheckSinglePara() != ge::GRAPH_SUCCESS || - CheckParaExistence() != ge::GRAPH_SUCCESS || - CheckFeature() != ge::GRAPH_SUCCESS || - CheckMultiParaConsistency() != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - return ge::GRAPH_SUCCESS; -} - -void SparseFlashMlaTiling::CalcUbBmm(const SMLATilingInfo* tilingInfo) { - uint32_t cubeMSize = tilingInfo->gSize * tilingInfo->s1Size; - uint32_t maxMSize = mBaseSize_; - if (cubeMSize > maxMSize) { - cubeMSize = maxMSize; - } - mmResUbSize_ = - sInnerSizeAlign_ * - Align(cubeMSize, - 16U); // kernel按照16对齐写出,tiling按照这个原则分配内存 - bmm2ResUbSize_ = - headDimAlign_ * - Align(cubeMSize, - 16U); // kernel按照16对齐写出,tiling按照这个原则分配内存 -} - -void SparseFlashMlaTiling::SplitBalanced(SMLATilingInfo* tilingInfo) { - sInnerSizeAlign_ = Align(sInnerSize_, BYTE_BLOCK); - if (tilingInfo->npuArch == NpuArch::DAV_2201) { - mBaseSize_ = - tilingInfo->perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE - ? tilingInfo->gSize - : (256 / tilingInfo->gSize) * - tilingInfo->gSize; // 256:DAV_2201架构下的基础计算块大小 - // DSpark ori_sparse_indices are per query token; keep one S1 row per M - // block. - if (tilingInfo->hasOriSparseIndices && - tilingInfo->perfMode == SMLATemplateMode::SWA_TEMPLATE_MODE) { - mBaseSize_ = tilingInfo->gSize; - } - } - headDimAlign_ = Align(tilingInfo->qHeadDim, BYTE_BLOCK); - CalcUbBmm(tilingInfo); - - tilingData_.baseParams.set_mBaseSize(mBaseSize_); - tilingData_.baseParams.set_s2BaseSize(sInnerSize_); - tilingData_.baseParams.set_mmResUbSize(mmResUbSize_); - tilingData_.baseParams.set_bmm2ResUbSize(bmm2ResUbSize_); -} - -uint32_t SparseFlashMlaTiling::CalcFdLogicalSlotCount( - const SMLATilingInfo* tilingInfo, - uint32_t aicNum) const { - bool isSplitG = - (IsA5Arch(tilingInfo->npuArch) || IsA6Arch(tilingInfo->npuArch)) && - tilingInfo->gSize > 64; - if (isSplitG) { - return aicNum >> 1U; - } - return aicNum; -} - -uint64_t SparseFlashMlaTiling::CalcFdStagingWorkspaceSize( - const SMLATilingInfo* tilingInfo, - uint32_t aicNum) const { - if ((!IsA5Arch(tilingInfo->npuArch) && !IsA6Arch(tilingInfo->npuArch)) || - aicNum == 0U) { - return 0ULL; - } - - const uint64_t logicalCoreSlots = CalcFdLogicalSlotCount(tilingInfo, aicNum); - const uint64_t bytesPerSlot = tilingInfo->gSize * sizeof(float) * - (headDimAlign_ + 2ULL * FD_BROADCAST_ELEMS); - if (tilingInfo->batchConsistency) { - // Intra-core reduction ping-pongs by multiCoreIdxMod2. Cross-core staging - // keeps one reduce-block range for every physical AIC. - const uint64_t intraCoreSlots = 2ULL * logicalCoreSlots; - const uint64_t crossCoreSlots = - static_cast(aicNum) * BATCH_CONSISTENCY_MAX_REDUCE_BLOCK_NUM; - return (intraCoreSlots + crossCoreSlots) * bytesPerSlot; - } - return logicalCoreSlots * FD_MAX_S2_SPLIT_NUM * bytesPerSlot; -} - -uint64_t SparseFlashMlaTiling::CalcVectorizeKvPhyAddrWorkspaceSize( - const SMLATilingInfo* tilingInfo, - uint32_t& vectorizeFlag) const { - vectorizeFlag = 0U; - if (!IsA5Arch(tilingInfo->npuArch) && !IsA6Arch(tilingInfo->npuArch)) { - return 0ULL; - } - constexpr uint32_t SPARSE_BLOCK_ALIGN_NUM = 128; - constexpr uint32_t A5_SIZE = 184 * 1024; - constexpr uint32_t A6_SIZE = 376 * 1024; - const uint32_t SIZE = IsA6Arch(tilingInfo->npuArch) ? A6_SIZE : A5_SIZE; - uint32_t alignedOriSparseBlockCount = - (tilingInfo->oriSparseBlockCount + SPARSE_BLOCK_ALIGN_NUM - 1) / - SPARSE_BLOCK_ALIGN_NUM * SPARSE_BLOCK_ALIGN_NUM; - uint32_t alignedCmpSparseBlockCount = - (tilingInfo->cmpSparseBlockCount + SPARSE_BLOCK_ALIGN_NUM - 1) / - SPARSE_BLOCK_ALIGN_NUM * SPARSE_BLOCK_ALIGN_NUM; - bool isPa = (tilingInfo->kvLayout == SMLALayout::PA_BBND); - uint32_t oriBlockSize = static_cast(tilingInfo->oriBlockSize); - uint32_t cmpBlockSize = static_cast(tilingInfo->cmpBlockSize); - uint32_t oriBlocksizeFlag = - static_cast(oriBlockSize & (oriBlockSize - 1)) == 0; - uint32_t cmpBlocksizeFlag = - static_cast(cmpBlockSize & (cmpBlockSize - 1)) == 0; - uint32_t blocksizeFlag = - isPa ? ((tilingInfo->perfMode == - SMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE) - ? oriBlocksizeFlag - : (oriBlocksizeFlag != 0 && cmpBlocksizeFlag != 0)) - : 1U; - uint64_t paExtraUb = - std::max(static_cast(tilingInfo->oriMaxBlockNumPerBatch) * - sizeof(int32_t), - static_cast(tilingInfo->cmpMaxBlockNumPerBatch) * - sizeof(int32_t)); - uint64_t cmpUbSize = - (isPa ? paExtraUb : 0U) + - static_cast(alignedCmpSparseBlockCount) * sizeof(int32_t) + - static_cast(alignedCmpSparseBlockCount) * sizeof(int64_t); - uint64_t oriUbSize = - (isPa ? paExtraUb : 0U) + - static_cast(alignedOriSparseBlockCount) * sizeof(int32_t) + - static_cast(alignedOriSparseBlockCount) * sizeof(int64_t); - uint64_t vectorizeUbSize = std::max(cmpUbSize, oriUbSize); - vectorizeFlag = static_cast( - (tilingInfo->perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE || - tilingInfo->perfMode == SMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE || - tilingInfo->perfMode == - SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) && - tilingInfo->topkValueMode == 1 && (vectorizeUbSize <= SIZE) && - (blocksizeFlag != 0)); - - if (vectorizeFlag == 0U) { - return 0ULL; - } - uint32_t totalBS1 = (tilingInfo->qLayout == SMLALayout::TND) - ? tilingInfo->s1Size - : (tilingInfo->bSize * tilingInfo->s1Size); - uint64_t oriPhyAddrSize = 0; - if (tilingInfo->perfMode == SMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE || - tilingInfo->perfMode == SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { - oriPhyAddrSize = static_cast(totalBS1) * - alignedOriSparseBlockCount * sizeof(int64_t); - } - uint64_t cmpPhyAddrSize = 0; - if (tilingInfo->perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE || - tilingInfo->perfMode == SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { - cmpPhyAddrSize = static_cast(totalBS1) * - alignedCmpSparseBlockCount * sizeof(int64_t); - } - return oriPhyAddrSize + cmpPhyAddrSize; -} - -// --------------------------SparseFlashMlaTiling类成员函数定义---------------------- -ge::graphStatus SparseFlashMlaTiling::DoOpTiling(SMLATilingInfo* tilingInfo) { - auto ascendcPlatform = - platform_ascendc::PlatformAscendC(tilingInfo->platformInfo); - uint32_t aivNum = ascendcPlatform.GetCoreNumAiv(); - uint32_t aicNum = ascendcPlatform.GetCoreNumAic(); - uint32_t blockDim = ascendcPlatform.CalcTschBlockDim(aivNum, aicNum, aivNum); - context_->SetBlockDim(blockDim); - OP_LOGI(tilingInfo->opName, - "SMLA block dim: %u aiv Num: %u aic Num: %u.", - blockDim, - aivNum, - aicNum); - - SplitBalanced(tilingInfo); - - constexpr uint32_t MM1_RES_ELEM_SIZE = 4; - constexpr uint32_t VEC1_RES_ELEM_SIZE = 2; - constexpr uint32_t MM2_RES_ELEM_SIZE = 4; - constexpr uint32_t VEC2_RES_ELEM_SIZE = 4; - constexpr uint32_t PRELOAD_NUM = 2; - - size_t workspaceSize = ascendcPlatform.GetLibApiWorkSpaceSize(); - if (IsA5Arch(tilingInfo->npuArch) || IsA6Arch(tilingInfo->npuArch)) { - bool isSplitG = tilingInfo->gSize > 64; - if (isSplitG || - tilingInfo->perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE || - tilingInfo->perfMode == SMLATemplateMode::ORI_SPARSE_TEMPLATE_MODE || - tilingInfo->perfMode == - SMLATemplateMode::ORI_CMP_SPARSE_TEMPLATE_MODE) { - constexpr uint32_t TRIPLE_BUFFER_NUM = 3; - constexpr uint32_t S2_BASE_SIZE = 128; - constexpr uint32_t D_SIZE = 512; - constexpr uint32_t VEC_RES_ELEM_SIZE = 2; - uint32_t gmSize = - S2_BASE_SIZE * D_SIZE * VEC_RES_ELEM_SIZE * TRIPLE_BUFFER_NUM; - if (isSplitG) { - gmSize *= (aicNum >> 1U); - } else { - gmSize *= aicNum; - } - workspaceSize += gmSize; - constexpr uint32_t S2_REAL_BUF_LEN = 128; - workspaceSize += - TRIPLE_BUFFER_NUM * S2_REAL_BUF_LEN * sizeof(int32_t) * aivNum; - } - } else { - workspaceSize += PRELOAD_NUM * mmResUbSize_ * MM1_RES_ELEM_SIZE * aicNum; - workspaceSize += PRELOAD_NUM * mmResUbSize_ * VEC1_RES_ELEM_SIZE * aicNum; - workspaceSize += PRELOAD_NUM * bmm2ResUbSize_ * MM2_RES_ELEM_SIZE * aicNum; - workspaceSize += PRELOAD_NUM * bmm2ResUbSize_ * VEC2_RES_ELEM_SIZE * aicNum; - if (tilingInfo->perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE || - (tilingInfo->perfMode == SMLATemplateMode::SWA_TEMPLATE_MODE && - tilingInfo->hasOriSparseIndices)) { - constexpr uint32_t MERGE_CACHE_GM_BUF_NUM = 3; // 3:缓存缓冲区数量 - workspaceSize += MERGE_CACHE_GM_BUF_NUM * 512 * 512 * 2 * - aicNum; // 缓冲区的尺寸为512x512字节,2表示双缓冲 - } - } - - // 计算vectorizeFlag (稀疏KV物理地址向量化) - uint32_t vectorizeFlag = 0U; - workspaceSize += - CalcVectorizeKvPhyAddrWorkspaceSize(tilingInfo, vectorizeFlag); - - workspaceSize += CalcFdStagingWorkspaceSize(tilingInfo, aicNum); - size_t* workSpaces = context_->GetWorkspaceSizes(1); - workSpaces[0] = workspaceSize; - - tilingData_.baseParams.set_batchSize(tilingInfo->bSize); - tilingData_.baseParams.set_kvSeqSize(tilingInfo->s2Size); - tilingData_.baseParams.set_qSeqSize(tilingInfo->s1Size); - tilingData_.baseParams.set_nNumOfQInOneGroup(tilingInfo->gSize); - tilingData_.baseParams.set_paBlockSize(tilingInfo->blockSize); - tilingData_.baseParams.set_oriBlockSize(tilingInfo->oriBlockSize); - tilingData_.baseParams.set_cmpBlockSize(tilingInfo->cmpBlockSize); - tilingData_.baseParams.set_oriP(tilingInfo->oriP); - tilingData_.baseParams.set_oriMLow(tilingInfo->oriMLow); - tilingData_.baseParams.set_oriMHigh(tilingInfo->oriMHigh); - tilingData_.baseParams.set_oriMaxBlockNumPerBatch( - tilingInfo->oriMaxBlockNumPerBatch); - tilingData_.baseParams.set_actualLenDimsQ(tilingInfo->actualLenDimsQ); - tilingData_.baseParams.set_actualLenDimsKV(tilingInfo->actualLenDimsKV); - - tilingData_.baseParams.set_softmaxScale(tilingInfo->softmaxScale); - tilingData_.baseParams.set_outputLayout( - static_cast(tilingInfo->outLayout)); - tilingData_.baseParams.set_oriMaskMode(tilingInfo->oriMaskMode); - tilingData_.baseParams.set_oriKvStride0(tilingInfo->oriKvStride0); - tilingData_.baseParams.set_oriWinLeft(tilingInfo->oriWinLeft); - tilingData_.baseParams.set_oriWinRight(tilingInfo->oriWinRight); - tilingData_.baseParams.set_sparseBlockSize(tilingInfo->sparseBlockSize); - tilingData_.baseParams.set_returnSoftmaxLse(tilingInfo->returnSoftmaxLse); - - tilingData_.cmpParams.set_cmpMaxBlockNumPerBatch( - tilingInfo->cmpMaxBlockNumPerBatch); - tilingData_.cmpParams.set_cmpRatio(tilingInfo->cmpRatio); - tilingData_.cmpParams.set_cmpMaskMode(tilingInfo->cmpMaskMode); - tilingData_.cmpParams.set_cmpKvStride0(tilingInfo->cmpKvStride0); - tilingData_.cmpParams.set_cmpP(tilingInfo->cmpP); - tilingData_.cmpParams.set_cmpMLow(tilingInfo->cmpMLow); - tilingData_.cmpParams.set_cmpMHigh(tilingInfo->cmpMHigh); - tilingData_.cmpParams.set_cmpKvSeqSize(tilingInfo->cmpS2Size); - tilingData_.baseParams.set_actualLenDimsOriKV(tilingInfo->actualLenDimsOriKV); - tilingData_.baseParams.set_actualLenDimsCmpKV(tilingInfo->actualLenDimsCmpKV); - tilingData_.baseParams.set_cmpResidualKVSize(tilingInfo->cmpResidualKVSize); - tilingData_.baseParams.set_oriKeyStride0(tilingInfo->oriKeyStride0); - tilingData_.baseParams.set_hasOriSparseIndices( - tilingInfo->hasOriSparseIndices ? 1U : 0U); - tilingData_.baseParams.set_oriSparseIndexWidth( - tilingInfo->oriSparseIndexWidth); - tilingData_.cmpParams.set_cmpKeyStride0(tilingInfo->cmpKeyStride0); - - if (IsA5Arch(tilingInfo->npuArch) || IsA6Arch(tilingInfo->npuArch)) { - tilingData_.baseParams.set_oriSparseBlockCount( - tilingInfo->oriSparseBlockCount); - tilingData_.baseParams.set_topkValueMode(tilingInfo->topkValueMode); - tilingData_.cmpParams.set_cmpSparseBlockCount( - tilingInfo->cmpSparseBlockCount); - } else { - tilingData_.cmpParams.set_sparseBlockCount(tilingInfo->sparseBlockCount); - } - - usedCoreNum_ = aicNum; - tilingData_.baseParams.set_usedCoreNum(usedCoreNum_); - tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), - context_->GetRawTilingData()->GetCapacity()); - context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize()); - - uint32_t qLayout = static_cast(tilingInfo->qLayout); - uint32_t inputKvLayout = static_cast(tilingInfo->kvLayout); - - uint64_t tilingKey; - uint32_t splitG = 0U; - uint32_t headRatioOne = static_cast( - tilingInfo->npuArch == NpuArch::DAV_2201 && - tilingInfo->perfMode == SMLATemplateMode::CSA_TEMPLATE_MODE && - tilingInfo->gSize == 1U); - if (IsA5Arch(tilingInfo->npuArch) || IsA6Arch(tilingInfo->npuArch)) { - splitG = static_cast(tilingInfo->gSize > 64); // 64:分组拆分阈值 - } - uint32_t isDspark = static_cast( - tilingInfo->npuArch == NpuArch::DAV_2201 && - tilingInfo->perfMode == SMLATemplateMode::SWA_TEMPLATE_MODE && - tilingInfo->hasOriSparseIndices); - tilingKey = - GET_TPL_TILING_KEY(0U, - qLayout, - inputKvLayout, - static_cast(tilingInfo->perfMode), - splitG, - headRatioOne, - static_cast(tilingInfo->batchConsistency), - vectorizeFlag, - static_cast(tilingInfo->topkValueMode), - isDspark); - context_->SetScheduleMode(1); - context_->SetTilingKey(tilingKey); - - return ge::GRAPH_SUCCESS; -} - -} // namespace optiling - -namespace optiling { -// --------------------------TilingPrepare函数定义------------------------------------- -static ge::graphStatus TilingPrepareForSparseFlashMla( - gert::TilingParseContext* /* context */) { - return ge::GRAPH_SUCCESS; -} - -// --------------------------Tiling函数定义--------------------------- -ge::graphStatus TilingForSparseFlashMla(gert::TilingContext* context) { - OP_CHECK_IF( - context == nullptr, - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - "XllmKernelSparseFlashMla", "context", "Tiling context is null."), - return ge::GRAPH_FAILED); - - SMLATilingInfo smlaInfo; - SMLAInfoParser smlaInfoParser(context); - if (smlaInfoParser.Parse(smlaInfo) != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - - if (smlaInfo.npuArch == NpuArch::DAV_2201) { - SMLATilingCheck smlaTilingChecker(smlaInfo); - if (smlaTilingChecker.Process() != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - } else { - SparseFlashMlaChecker smlaTilingChecker(smlaInfo); - if (smlaTilingChecker.Process() != ge::GRAPH_SUCCESS) { - return ge::GRAPH_FAILED; - } - } - - SparseFlashMlaTiling tiling(context); - return tiling.DoOpTiling(&smlaInfo); -} -// --------------------------Tiling函数及TilingPrepare函数注册-------- -IMPL_OP_OPTILING(XllmKernelSparseFlashMla) - .Tiling(TilingForSparseFlashMla) - .TilingParse(TilingPrepareForSparseFlashMla); -} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_tiling.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_tiling.h deleted file mode 100644 index a894c55ee0..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_host/sparse_flash_mla_tiling.h +++ /dev/null @@ -1,567 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under -the terms and conditions of  * CANN Open Software License Agreement Version 2.0 -(the "License").  * Please refer to the License for details. You may not use -this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON -AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * -INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A -PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for -the full text of the License.  */ - -/*! - * \file sparse_flash_mla_tiling.h - * \brief - */ -#ifndef SPARSE_FLASH_MLA_TILING_H -#define SPARSE_FLASH_MLA_TILING_H - -#include "common/smla_host_common_defs.h" -#include "platform/soc_spec.h" - -namespace optiling { - -// ------------------算子原型索引常量定义---------------- -// Inputs Index (0-10, common) -constexpr uint32_t Q_INDEX = 0; -constexpr uint32_t ORI_KV_INDEX = 1; -constexpr uint32_t CMP_KV_INDEX = 2; -constexpr uint32_t ORI_SPARSE_INDICES_INDEX = 3; -constexpr uint32_t CMP_SPARSE_INDICES_INDEX = 4; -constexpr uint32_t ORI_BLOCK_TABLE_INDEX = 5; -constexpr uint32_t CMP_BLOCK_TABLE_INDEX = 6; -constexpr uint32_t CU_SEQLENS_Q_INDEX = 7; -constexpr uint32_t CU_SEQLENS_ORI_KV_INDEX = 8; -constexpr uint32_t CU_SEQLENS_CMP_KV_INDEX = 9; -constexpr uint32_t SEQUSED_Q_INDEX = 10; -constexpr uint32_t SEQUSED_ORI_KV_INDEX = 11; -constexpr uint32_t SEQUSED_CMP_KV_INDEX = 12; -constexpr uint32_t CMP_RESIDUAL_KV_INDEX = 13; -constexpr uint32_t ORI_TOPK_LENGTH_INDEX = 14; -constexpr uint32_t CMP_TOPK_LENGTH_INDEX = 15; -constexpr uint32_t SINKS_INDEX = 16; -constexpr uint32_t METADATA_INDEX = 17; - -// Attributes Index -constexpr uint32_t ATTR_SOFTMAX_SCALE_INDEX = 0; -constexpr uint32_t ATTR_CMP_RATIO_INDEX = 1; -constexpr uint32_t ATTR_ORI_MASK_MODE_INDEX = 2; -constexpr uint32_t ATTR_CMP_MASK_MODE_INDEX = 3; -constexpr uint32_t ATTR_ORI_WIN_LEFT_INDEX = 4; -constexpr uint32_t ATTR_ORI_WIN_RIGHT_INDEX = 5; -constexpr uint32_t ATTR_LAYOUT_Q_INDEX = 6; -constexpr uint32_t ATTR_LAYOUT_KV_INDEX = 7; -constexpr uint32_t ATTR_TOPK_VALUE_MODE_INDEX = 8; // A2/A3 -constexpr uint32_t ATTR_RETURN_SOFTMAX_LSE_INDEX = 9; - -// 常量 -constexpr uint32_t BYTE_BLOCK = 32; - -// 入参限制常量 -constexpr uint32_t METADATA_LIMIT = 2048; -constexpr uint32_t DIM_LIMIT = 512; -constexpr uint32_t TOPK_LIMIT = 8192; -constexpr uint32_t BLOCK_SIZE_LIMIT = 1024; - -// -----------算子TilingData定义(A2/A3字段顺序 + A5追加字段)--------------- -BEGIN_TILING_DATA_DEF(XllmKernelSparseFlashMlaSwaParams) -TILING_DATA_FIELD_DEF(uint32_t, batchSize) -TILING_DATA_FIELD_DEF(uint32_t, qSeqSize) -TILING_DATA_FIELD_DEF(uint32_t, kvSeqSize) -TILING_DATA_FIELD_DEF(int64_t, paBlockSize) -TILING_DATA_FIELD_DEF(int64_t, oriBlockSize) -TILING_DATA_FIELD_DEF(int64_t, cmpBlockSize) -TILING_DATA_FIELD_DEF(uint32_t, oriMaxBlockNumPerBatch) -TILING_DATA_FIELD_DEF(uint32_t, nNumOfQInOneGroup) -TILING_DATA_FIELD_DEF(uint32_t, actualLenDimsQ) -TILING_DATA_FIELD_DEF(uint32_t, actualLenDimsKV) -TILING_DATA_FIELD_DEF(float, softmaxScale) // 即 scaleValue -TILING_DATA_FIELD_DEF(uint32_t, outputLayout) -TILING_DATA_FIELD_DEF(uint64_t, oriMaskMode) -TILING_DATA_FIELD_DEF(int64_t, oriKvStride0) // A2/A3 -TILING_DATA_FIELD_DEF(int64_t, oriWinLeft) -TILING_DATA_FIELD_DEF(int64_t, oriWinRight) -TILING_DATA_FIELD_DEF(int64_t, sparseBlockSize) -TILING_DATA_FIELD_DEF(uint32_t, oriSparseBlockCount) // A5 - -TILING_DATA_FIELD_DEF(int64_t, topkValueMode) - -TILING_DATA_FIELD_DEF(uint32_t, usedCoreNum); - -TILING_DATA_FIELD_DEF(uint32_t, mmResUbSize); -TILING_DATA_FIELD_DEF(uint32_t, bmm2ResUbSize); -TILING_DATA_FIELD_DEF(uint32_t, returnSoftmaxLse) -TILING_DATA_FIELD_DEF(uint32_t, mBaseSize) -TILING_DATA_FIELD_DEF(uint32_t, s2BaseSize) - -TILING_DATA_FIELD_DEF(uint32_t, actualLenDimsOriKV) -TILING_DATA_FIELD_DEF(uint32_t, actualLenDimsCmpKV) -TILING_DATA_FIELD_DEF(uint32_t, cmpResidualKVSize) -TILING_DATA_FIELD_DEF(uint32_t, kvHeadNum) -TILING_DATA_FIELD_DEF(uint32_t, oriKeyStride0) // A5 -TILING_DATA_FIELD_DEF(uint32_t, hasOriSparseIndices) -TILING_DATA_FIELD_DEF(uint32_t, oriSparseIndexWidth) -TILING_DATA_FIELD_DEF(uint32_t, oriP) -TILING_DATA_FIELD_DEF(uint32_t, oriMLow) -TILING_DATA_FIELD_DEF(uint32_t, oriMHigh) -END_TILING_DATA_DEF -REGISTER_TILING_DATA_CLASS(XllmKernelSparseFlashMlaSwaParamsOp, - XllmKernelSparseFlashMlaSwaParams) - -BEGIN_TILING_DATA_DEF(XllmKernelSparseFlashMlaCmpParams) -TILING_DATA_FIELD_DEF(uint32_t, cmpMaxBlockNumPerBatch) -TILING_DATA_FIELD_DEF(uint32_t, sparseBlockCount) // A2/A3 -TILING_DATA_FIELD_DEF(int64_t, cmpRatio) -TILING_DATA_FIELD_DEF(uint64_t, cmpMaskMode) -TILING_DATA_FIELD_DEF(int64_t, cmpKvStride0) // A2/A3 -TILING_DATA_FIELD_DEF(uint32_t, cmpSparseBlockCount) // A5 -TILING_DATA_FIELD_DEF(uint32_t, cmpKvSeqSize) // A5 -TILING_DATA_FIELD_DEF(uint32_t, cmpKeyStride0) // A5 -TILING_DATA_FIELD_DEF(uint32_t, cmpP) -TILING_DATA_FIELD_DEF(uint32_t, cmpMLow) -TILING_DATA_FIELD_DEF(uint32_t, cmpMHigh) -END_TILING_DATA_DEF -REGISTER_TILING_DATA_CLASS(XllmKernelSparseFlashMlaCmpParamsOp, - XllmKernelSparseFlashMlaCmpParams) - -BEGIN_TILING_DATA_DEF(SparseFlashMlaTilingData) -TILING_DATA_FIELD_DEF_STRUCT(XllmKernelSparseFlashMlaSwaParams, baseParams); -TILING_DATA_FIELD_DEF_STRUCT(XllmKernelSparseFlashMlaCmpParams, cmpParams); -END_TILING_DATA_DEF -REGISTER_TILING_DATA_CLASS(XllmKernelSparseFlashMla, SparseFlashMlaTilingData) - -struct SMLAParaInfo { - SMLATilingRequiredParaInfo q = {nullptr, nullptr}; - SMLATilingOptionalParaInfo oriKv = {nullptr, nullptr}; - SMLATilingOptionalParaInfo cmpKv = {nullptr, nullptr}; - SMLATilingOptionalParaInfo oriSparseIndices = {nullptr, nullptr}; - SMLATilingOptionalParaInfo cmpSparseIndices = {nullptr, nullptr}; - SMLATilingOptionalParaInfo oriBlockTable = {nullptr, nullptr}; - SMLATilingOptionalParaInfo cmpBlockTable = {nullptr, nullptr}; - SMLATilingOptionalParaInfo cuSeqLensQ = {nullptr, nullptr}; - SMLATilingOptionalParaInfo cuSeqLensOriKv = {nullptr, nullptr}; // A5 - SMLATilingOptionalParaInfo cuSeqLensCmpKv = {nullptr, nullptr}; // A5 - SMLATilingOptionalParaInfo cuSeqLensKv = {nullptr, nullptr}; // A2/A3 - SMLATilingOptionalParaInfo seqUsedQ = {nullptr, nullptr}; - SMLATilingOptionalParaInfo sequsedOriKv = {nullptr, nullptr}; - SMLATilingOptionalParaInfo sequsedCmpKv = {nullptr, nullptr}; - SMLATilingOptionalParaInfo cmpResidualKv = {nullptr, nullptr}; - SMLATilingOptionalParaInfo oriTopkLength = {nullptr, nullptr}; - SMLATilingOptionalParaInfo cmpTopkLength = {nullptr, nullptr}; - SMLATilingOptionalParaInfo sinks = {nullptr, nullptr}; - SMLATilingOptionalParaInfo metadata = {nullptr, nullptr}; - SMLATilingRequiredParaInfo attnOut = {nullptr, nullptr}; - SMLATilingRequiredParaInfo softmaxLse = {nullptr, nullptr}; - - const float* softmaxScale = nullptr; - const uint32_t* cmpRatio = nullptr; - const uint32_t* oriMaskMode = nullptr; - const uint32_t* cmpMaskMode = nullptr; - const int32_t* oriWinLeft = nullptr; - const int32_t* oriWinRight = nullptr; - const char* layoutQ = nullptr; - const char* layoutKv = nullptr; - const uint32_t* topkValueMode = nullptr; - const bool* returnSoftmaxLse = nullptr; -}; - -static std::string SMLADataTypeToSerialString(ge::DataType type); -std::string SMLALayoutToSerialString(SMLALayout layout); - -// -----------算子Tiling入参信息类--------------- -class SMLATilingInfo { - public: - const char* opName = nullptr; - fe::PlatFormInfos* platformInfo = nullptr; - SMLAParaInfo opParamInfo; - - // Base Param - NpuArch npuArch = NpuArch::DAV_2201; - uint32_t bSize = 0; - uint32_t n1Size = 0; - uint32_t n2Size = 0; - uint32_t s1Size = 0; - int64_t s2Size = 0; - int64_t cmpS2Size = 0; // A5 - uint32_t gSize = 0; - uint32_t qHeadDim = 0; - uint32_t oriKvHeadDim = 0; - uint32_t cmpKvHeadDim = 0; - uint32_t qTSize = 0; // 仅TND时生效 - - uint32_t actualLenDimsQ = 0; - uint32_t actualLenDimsKV = 0; - - uint32_t actualLenDimsOriKV = 0; - uint32_t actualLenDimsCmpKV = 0; - uint32_t cmpResidualKVSize = 0; - - uint32_t oriKeyStride0 = 0; // A5 - uint32_t cmpKeyStride0 = 0; // A5 - - float softmaxScale = 0; - int64_t cmpRatio = 1; - uint64_t oriMaskMode = 0; - uint64_t cmpMaskMode = 0; - uint64_t oriKvStride0 = 0; // A2/A3 - uint64_t cmpKvStride0 = 0; // A2/A3 - int64_t oriWinLeft = 0; - int64_t oriWinRight = 0; - int64_t sparseBlockSize = 0; - int64_t oriSparseBlockCount = 0; - int64_t cmpSparseBlockCount = 0; - int64_t sparseBlockCount = 0; // A2/A3 - bool hasOriSparseIndices = false; - uint32_t oriSparseIndexWidth = 0; - - int64_t topkValueMode = 0; - // Others Flag - bool returnSoftmaxLse = false; - bool batchConsistency = false; - - // PageAttention - uint32_t oriMaxBlockNumPerBatch = 0; - int32_t blockSize = 0; - int32_t oriBlockSize = 0; - int32_t cmpBlockSize = 0; - uint32_t cmpMaxBlockNumPerBatch = 0; - uint32_t oriP = 0; - uint32_t oriMLow = 0; - uint32_t oriMHigh = 0; - uint32_t cmpP = 0; - uint32_t cmpMLow = 0; - uint32_t cmpMHigh = 0; - - // DType - ge::DataType qType = ge::DT_FLOAT16; - ge::DataType oriKvType = ge::DT_FLOAT16; - ge::DataType cmpKvType = ge::DT_FLOAT16; - ge::DataType outputType = ge::DT_FLOAT16; - - // Layout - SMLALayout qLayout = SMLALayout::TND; - SMLALayout cmpSparseIndicesLayout = SMLALayout::TND; - SMLALayout oriSparseIndicesLayout = SMLALayout::TND; - SMLALayout kvLayout = SMLALayout::PA_BBND; - SMLALayout outLayout = SMLALayout::BSND; - - // template mode - SMLATemplateMode perfMode = SMLATemplateMode::SWA_TEMPLATE_MODE; -}; - -// -----------算子Tiling入参信息解析及Check类--------------- -class SMLATilingCheck { - public: - explicit SMLATilingCheck(const SMLATilingInfo& smlaInfo) - : smlaInfo_(smlaInfo) {}; - ~SMLATilingCheck() = default; - virtual ge::graphStatus Process(); - - private: - void Init(); - - void LogErrorDtypeSupport(const std::vector& expectDtypeList, - const ge::DataType& actualDtype, - const std::string& name) const; - ge::graphStatus CheckLayoutSupport(const SMLALayout& actualLayout, - const std::string& name) const; - template - void LogErrorDimNumSupport(const std::vector& expectNumberList, - const T& actualValue, - const std::string& name) const; - template - void LogErrorNumberSupport(const std::vector& expectNumberList, - const T& actualValue, - const std::string& name, - const std::string subName) const; - ge::graphStatus CheckDimNumSupport( - const gert::StorageShape* shape, - const std::vector& expectDimNumList, - const std::string& name) const; - void LogErrorLayoutSupport(const std::vector& expectLayoutList, - const SMLALayout& actualLayout, - const std::string& name) const; - ge::graphStatus CheckDimNumInLayoutSupport(const SMLALayout& layout, - const gert::StorageShape* shape, - const std::string& name) const; - ge::graphStatus CheckDtypeSupport(const gert::CompileTimeTensorDesc* desc, - const std::string& name) const; - ge::graphStatus CheckSinglePara() const; - ge::graphStatus CheckSingleParaQuery() const; - ge::graphStatus CheckSingleParaOriKv() const; - ge::graphStatus CheckSingleParaCmpKv() const; - ge::graphStatus CheckSingleParaCuSeqLensQ() const; - ge::graphStatus CheckSingleParaCuSeqLensOriKv() const; - ge::graphStatus CheckSingleParaCuSeqLensCmpKv() const; - ge::graphStatus CheckSingleParaCmpResidualKv() const; - ge::graphStatus CheckSingleParaTopkLength() const; - ge::graphStatus CheckSingleParaNumHeads() const; - ge::graphStatus CheckSingleParaKvHeadNums() const; - ge::graphStatus CheckSingleParaOriSparseIndices() const; - ge::graphStatus CheckSingleParaCmpSparseIndices() const; - ge::graphStatus CheckSingleParaSinks() const; - ge::graphStatus CheckSingleParaMetadata() const; - ge::graphStatus CheckSingleParaCmpRatio() const; - ge::graphStatus CheckSingleParaOriMaskMode() const; - ge::graphStatus CheckSingleParaCmpMaskMode() const; - ge::graphStatus CheckSingleParaOriKvStride0() const; // A2/A3 - ge::graphStatus CheckSingleParaCmpKvStride0() const; // A2/A3 - ge::graphStatus CheckSingleParaOriWinLeft() const; - ge::graphStatus CheckSingleParaOriWinRight() const; - ge::graphStatus CheckSingleParaOriBlockTable() const; - ge::graphStatus CheckSingleParaCmpBlockTable() const; - - ge::graphStatus CheckParaExistence() const; - ge::graphStatus CheckExists(const void* pointer, - const std::string& name) const; - ge::graphStatus CheckNotExists(const void* pointer, - const std::string& name) const; - ge::graphStatus CheckExistsByMap( - const std::map& paramMap) const; - ge::graphStatus CheckNotExistsByMap( - const std::map& paramMap) const; - ge::graphStatus CheckExistenceByMap( - std::map& existMap, - std::map& notExistMap) const; - - ge::graphStatus CheckFeature() const; - ge::graphStatus CheckFeatureShape() const; - ge::graphStatus CheckFeatureLayout() const; - ge::graphStatus CheckFeatureDtype() const; - ge::graphStatus CheckFeaturePa() const; - - ge::graphStatus CheckMultiParaConsistency() const; - ge::graphStatus CheckDTypeConsistency(const ge::DataType& actualDtype, - const ge::DataType& expectDtype, - const std::string& name) const; - ge::graphStatus CheckOriAndCmpKv() const; - ge::graphStatus CheckAttenOut() const; - ge::graphStatus CheckActualSeqLensQ() const; - ge::graphStatus CheckActualSeqLens() const; - - const char* opName_; - fe::PlatFormInfos* platformInfo_; - SMLAParaInfo opParamInfo_; - const SMLATilingInfo& smlaInfo_; - - int64_t bSize_ = 0; - int64_t n1Size_ = 0; - int64_t n2Size_ = 0; - int64_t gSize_ = 0; - int64_t s1Size_ = 0; - int64_t s2Size_ = 0; - int64_t cmpS2Size_ = 0; // A5 - int64_t qHeadDim_ = 0; - int64_t oriKvHeadDim_ = 0; - int64_t cmpKvHeadDim_ = 0; - - int64_t qTSize_ = 0; // 仅TND时生效 - int64_t cmpRatio_ = 1; - int64_t oriWinLeft_ = 0; - int64_t oriWinRight_ = 0; - bool hasOriSparseIndices_ = false; - int64_t oriSparseIndexWidth_ = 0; - - int64_t topkValueMode_; - - SMLALayout qLayout_ = SMLALayout::TND; - SMLALayout cmpSparseIndicesLayout_ = SMLALayout::TND; - SMLALayout oriSparseIndicesLayout_ = SMLALayout::TND; - SMLALayout outLayout_ = SMLALayout::TND; - SMLALayout kvLayout_ = SMLALayout::PA_BBND; - - int64_t oriBlockSize_ = 0; - int64_t cmpBlockSize_ = 0; - - NpuArch npuArch_ = NpuArch::DAV_2201; - - ge::DataType qType_ = ge::DT_FLOAT16; - ge::DataType oriKvType_ = ge::DT_FLOAT16; - ge::DataType cmpKvType_ = ge::DT_FLOAT16; - ge::DataType outputType_ = ge::DT_FLOAT16; -}; - -template -inline T Align(T num, T rnd) { - return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd) * (rnd))); -} - -class SMLAInfoParser { - public: - explicit SMLAInfoParser(gert::TilingContext* context) : context_(context) {} - ~SMLAInfoParser() = default; - - ge::graphStatus CheckRequiredInOutExistence() const; - ge::graphStatus CheckRequiredAttrExistence() const; - ge::graphStatus CheckRequiredParaExistence() const; - ge::graphStatus CheckUnrequiredParaExistence() const; - - ge::graphStatus GetActualSeqLenSize(int64_t& size, - const gert::Tensor* tensor, - SMLALayout& layout, - const std::string& name) const; - ge::graphStatus GetActualSeqLenQSize(int64_t& size); - ge::graphStatus GetOpName(); - ge::graphStatus GetNpuInfo(); - void GetOptionalInputParaInfo(); - void GetInputParaInfo(); - void GetOutputParaInfo(); - ge::graphStatus GetAttrParaInfo(); - ge::graphStatus GetOpParaInfo(); - - ge::graphStatus GetInOutDataType(); - ge::graphStatus GetQueryAndOutLayout(); - ge::graphStatus GetKvLayout(); - ge::graphStatus GetSMLATemplateMode(); - ge::graphStatus SetSMLAShape(); - ge::graphStatus GetN1Size(); - ge::graphStatus GetN2Size(); - ge::graphStatus GetGSize(); - ge::graphStatus GetBatchSize(); - ge::graphStatus GetQTSize(); - ge::graphStatus GetS1Size(); - ge::graphStatus GetS2SizeForPageAttention(); - ge::graphStatus GetS2SizeForTND(); // A2/A3 - ge::graphStatus GetS2Size(); - ge::graphStatus GetMaxBlockNumPerBatch(); - ge::graphStatus GetBlockSize(); - ge::graphStatus SmlaGetMagicPM(); - ge::graphStatus GetQHeadDim(); - ge::graphStatus GetValueHeadDim(); - ge::graphStatus GetSparseBlockCount(); - ge::graphStatus GetActualseqInfo(); - ge::graphStatus GetSinks(); - uint64_t GetOptionalInputStride0(uint32_t inputIndex) const; - void GenerateInfo(SMLATilingInfo& smlaInfo); - ge::graphStatus Parse(SMLATilingInfo& smlaInfo); - std::vector GetKvstride(const gert::Shape& shape, - const SMLALayout& layout) const; - ge::graphStatus CheckContiguous() const; // A5 - - gert::TilingContext* context_ = nullptr; - const char* opName_; - fe::PlatFormInfos* platformInfo_; - SMLAParaInfo opParamInfo_; - - bool HasAxis(const SMLAAxis& axis, - const SMLALayout& layout, - const gert::Shape& shape) const; - size_t GetAxisIdx(const SMLAAxis& axis, const SMLALayout& layout) const; - int64_t GetAxisNum(const gert::Shape& shape, - const SMLAAxis& axis, - const SMLALayout& layout) const; - static constexpr int64_t invalidDimValue_ = - std::numeric_limits::min(); - - // BaseParams - int64_t bSize_ = 0; - int64_t n1Size_ = 0; - int64_t n2Size_ = 0; - int64_t gSize_ = 0; - int64_t s1Size_ = 0; - int64_t s2Size_ = 0; - int64_t cmpS2Size_ = 0; // A5 - int64_t qTSize_ = 0; - int64_t qHeadDim_ = 0; - int64_t oriKvHeadDim_ = 0; - int64_t cmpKvHeadDim_ = 0; - int64_t sparseBlockSize_ = 0; - int64_t oriSparseBlockCount_ = 0; // A5 - int64_t cmpSparseBlockCount_ = 0; // A5 - int64_t oriWinLeft_ = 0; - int64_t oriWinRight_ = 0; - bool hasOriSparseIndices_ = false; - int64_t oriSparseIndexWidth_ = 0; - int64_t topkValueMode_ = 0; - int64_t actualLenDimsKV_ = 0; - int64_t actualLenDimsQ_ = 0; - bool batchConsistency_ = false; - - uint32_t actualLenDimsOriKV_ = 0; - uint32_t actualLenDimsCmpKV_ = 0; - uint32_t cmpResidualKVSize_ = 0; - - std::vector oriKeyStridesVec_; // A5 - std::vector cmpKeyStridesVec_; // A5 - - uint32_t aicNum_ = 0; - uint32_t aivNum_ = 0; - // Layout - SMLALayout qLayout_ = SMLALayout::TND; - SMLALayout cmpSparseIndicesLayout_ = SMLALayout::TND; - SMLALayout oriSparseIndicesLayout_ = SMLALayout::TND; - SMLALayout outLayout_ = SMLALayout::BSND; - SMLALayout kvLayout_ = SMLALayout::PA_BBND; - // PageAttention - uint32_t oriMaxBlockNumPerBatch_ = 0; - uint32_t cmpMaxBlockNumPerBatch_ = 0; - int64_t oriBlockSize_ = 0; - int64_t cmpBlockSize_ = 0; - uint32_t oriP_ = 0; - uint32_t oriMLow_ = 0; - uint32_t oriMHigh_ = 0; - uint32_t cmpP_ = 0; - uint32_t cmpMLow_ = 0; - uint32_t cmpMHigh_ = 0; - - // template mode - SMLATemplateMode perfMode_ = SMLATemplateMode::SWA_TEMPLATE_MODE; - - NpuArch npuArch_ = NpuArch::DAV_2201; - ge::DataType qType_ = ge::DT_FLOAT16; - ge::DataType oriKvType_ = ge::DT_FLOAT16; - ge::DataType cmpKvType_ = ge::DT_FLOAT16; - ge::DataType cmpSparseIndicesType_ = ge::DT_INT32; - ge::DataType oriBlockTableType_ = ge::DT_INT32; - ge::DataType cmpBlockTableType_ = ge::DT_INT32; - ge::DataType cuSeqLensQType_ = ge::DT_INT32; - ge::DataType seqsedKvType_ = ge::DT_INT32; - ge::DataType sinksType_ = ge::DT_INT32; - ge::DataType metadataType_ = ge::DT_INT32; - ge::DataType outputType_ = ge::DT_FLOAT16; - - gert::Shape qShape_{}; - gert::Shape oriKvShape_{}; - gert::Shape cmpKvShape_{}; - gert::Shape oriSparseIndicesShape_{}; - gert::Shape cmpSparseIndicesShape_{}; -}; - -// ---------------算子Tiling类--------------- -class SparseFlashMlaTiling { - public: - explicit SparseFlashMlaTiling(gert::TilingContext* context) - : context_(context) {}; - ge::graphStatus DoOpTiling(SMLATilingInfo* tilingInfo); - - private: - void SplitBalanced(SMLATilingInfo* tilingInfo); - void CalcUbBmm(const SMLATilingInfo* tilingInfo); - uint32_t CalcFdLogicalSlotCount(const SMLATilingInfo* tilingInfo, - uint32_t aicNum) const; - uint64_t CalcFdStagingWorkspaceSize(const SMLATilingInfo* tilingInfo, - uint32_t aicNum) const; - uint64_t CalcVectorizeKvPhyAddrWorkspaceSize(const SMLATilingInfo* tilingInfo, - uint32_t& vectorizeFlag) const; - gert::TilingContext* context_ = nullptr; - SMLATemplateMode perfMode_ = SMLATemplateMode::SWA_TEMPLATE_MODE; - SparseFlashMlaTilingData tilingData_; - uint32_t blockDim_{0}; - uint64_t workspaceSize_{0}; - uint64_t tilingKey_{0}; - - SMLATilingInfo* smlaInfo_ = nullptr; - - size_t mmResUbSize_ = 0; - size_t bmm2ResUbSize_ = 0; - uint32_t sInnerLoopTimes_ = 0; - uint32_t sInnerSize_ = 512; // s2固定切分512 - uint32_t sInnerSizeAlign_ = 0; - uint32_t usedCoreNum_ = 0; - - uint32_t headDimAlign_ = 0; - uint32_t mBaseSize_ = 64; -}; - -} // namespace optiling -#endif diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_arch22_metadata.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_arch22_metadata.h deleted file mode 100644 index 6ac2600998..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_arch22_metadata.h +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file sparse_flash_mla_arch22_metadata.h - * \brief - */ - -#ifndef SPARSE_FLASH_MLA_ARCH22_METADATA_H -#define SPARSE_FLASH_MLA_ARCH22_METADATA_H - -#include - -namespace optiling { - -// Constants -constexpr uint32_t AIC_CORE_NUM = 80; -constexpr uint32_t AIV_CORE_NUM = 80; -constexpr uint32_t SMLA_META_SIZE = 2048; -using SMLA_METADATA_T = int32_t; - -constexpr uint32_t FA_METADATA_SIZE = 9; -constexpr uint32_t FD_METADATA_SIZE = 8; - -// FA Metadata Index Definitions -constexpr uint32_t FA_CORE_ENABLE_INDEX = 0; -constexpr uint32_t FA_BN2_START_INDEX = 1; -constexpr uint32_t FA_M_START_INDEX = 2; -constexpr uint32_t FA_S2_START_INDEX = 3; -constexpr uint32_t FA_BN2_END_INDEX = 4; -constexpr uint32_t FA_M_END_INDEX = 5; -constexpr uint32_t FA_S2_END_INDEX = 6; -constexpr uint32_t FA_FIRST_FD_DATA_WORKSPACE_IDX_INDEX = 7; -constexpr uint32_t FA_S2_MAX_NUM = 8; - -// FD Metadata Index Definitions -constexpr uint32_t FD_CORE_ENABLE_INDEX = 0; -constexpr uint32_t FD_BN2_IDX_INDEX = 1; -constexpr uint32_t FD_M_IDX_INDEX = 2; -constexpr uint32_t FD_WORKSPACE_IDX_INDEX = 3; -constexpr uint32_t FD_WORKSPACE_NUM_INDEX = 4; -constexpr uint32_t FD_M_START_INDEX = 5; -constexpr uint32_t FD_M_NUM_INDEX = 6; - -/** - * @brief 获取属性的绝对索引 - * @param coreIdx 核索引 - * @param metaIdx 元数据索引 - * @param isAIV 是否为AIV数据,默认为false - * @return 返回属性的绝对索引 - */ -#ifdef __CCE_AICORE__ -__aicore__ inline uint32_t GetAttrAbsIndex(uint32_t coreIdx, - uint32_t metaIdx, - bool isAIV = false) { - if (isAIV) { - return FA_METADATA_SIZE * AIC_CORE_NUM + FD_METADATA_SIZE * coreIdx + - metaIdx; - } else { - return FA_METADATA_SIZE * coreIdx + metaIdx; - } -} -#endif - -namespace detail { -struct SasMetadata { - uint32_t faMetadata[AIC_CORE_NUM][FA_METADATA_SIZE]; - uint32_t fdMetadata[AIV_CORE_NUM][FD_METADATA_SIZE]; -}; -} // namespace detail - -static_assert(SMLA_META_SIZE * sizeof(SMLA_METADATA_T) >= - sizeof(detail::SasMetadata)); -} // namespace optiling - -#endif // SPARSE_FLASH_MLA_ARCH22_METADATA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_common_arch22.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_common_arch22.h deleted file mode 100644 index c2d4085ddf..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_common_arch22.h +++ /dev/null @@ -1,408 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file sparse_flash_mla_common_arch22.h - * \brief - */ - -#ifndef SPARSE_FLASH_MLA_COMMON_ARCH22_H -#define SPARSE_FLASH_MLA_COMMON_ARCH22_H - -#include "kernel_operator.h" -#include "lib/matmul_intf.h" -#include "lib/matrix/matmul/tiling.h" - -namespace SMLAKernel { -using namespace AscendC; -// 将isCheckTiling设置为false, 输入输出的max&sum&exp的shape为(m, 1) -constexpr SoftmaxConfig SMLA_SOFTMAX_FLASHV2_CFG_WITHOUT_BRC = { - false, - 0, - 0, - SoftmaxMode::SOFTMAX_OUTPUT_WITHOUT_BRC}; - -enum class SMLA_RUN_MODE { - SWA_MODE = 0, - CSA_MODE = 1, - HCA_MODE = 2, -}; - -enum class SMLA_LAYOUT { BSND = 0, TND = 1, PA_BBND = 2 }; - -template -struct SMLAType { - using queryType = Q_T; - using kvType = KV_T; - using outputType = OUT_T; - static constexpr bool flashDecode = FLASH_DECODE; - static constexpr SMLA_LAYOUT layout = LAYOUT_T; - static constexpr SMLA_LAYOUT kvLayout = KV_LAYOUT_T; - static constexpr bool pageAttention = (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND); - static constexpr int templateMode = TEMPLATE_MODE; - static constexpr bool headRatioOne = HEAD_RATIO_ONE; - static constexpr bool isDspark = IS_DSPARK; -}; - -// ================================Util -// functions================================== -template -__aicore__ inline T1 SMLAAlign(T1 num, T2 rnd) { - return (rnd == 0) ? 0 : ((num + rnd - 1) / rnd * rnd); -} - -template -__aicore__ inline T1 CeilDiv(T1 num, T2 rnd) { - return (rnd == 0) ? 0 : ((num + rnd - 1) / rnd); -} - -template -__aicore__ inline T1 Min(T1 a, T2 b) { - return (a > b) ? b : a; -} - -template -__aicore__ inline T1 Max(T1 a, T2 b) { - return (a > b) ? a : b; -} - -template -__aicore__ inline size_t BlockAlign(size_t s) { - if constexpr (IsSameType::value) { - return (s + 63) / 64 * 64; - } - size_t n = (32 / sizeof(T)); - return (s + n - 1) / n * n; -} - -struct PAShape { - uint32_t blockSize; - uint32_t headNum; // 一般为kv的head num,对应n2 - uint32_t headDim; // 512 对应d - uint32_t kvStride; - uint32_t maxblockNumPerBatch; // block table 每一行的最大个数 - uint32_t actHeadDim; // 实际拷贝col大小,考虑到N切块 s*d, 对应d - uint32_t copyRowNum; // 总共要拷贝的行数 - uint32_t copyRowNumAlign; -}; - -struct Position { - uint32_t bIdx; - uint32_t n2Idx; - uint32_t s2Idx; - uint32_t dIdx; -}; - -// 场景:query、key、value GM to L1 -// GM按ND格式存储 -// L1按NZ格式存储 -// GM的行、列、列的stride -template -__aicore__ inline void DataCopyGmNDToL1(LocalTensor& l1Tensor, - GlobalTensor& gmTensor, - uint32_t rowAct, - uint32_t rowAlign, - uint32_t col, // D - uint32_t colStride) // D or N*D -{ - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = rowAct; // nd矩阵的行数 - // T为int4场景下,dValue = col / 2,srcDValue = colStride / 2 - nd2nzPara.dValue = col; // nd矩阵的列数 - nd2nzPara.srcDValue = colStride; // 同一nd矩阵相邻行起始地址间的偏移 - nd2nzPara.dstNzC0Stride = rowAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - DataCopy(l1Tensor, gmTensor, nd2nzPara); -} - -/* - 适用PA数据从GM拷贝到L1,支持ND、NZ数据; - PA的layout分 BBND(blockNum,N,blockSize,D) BBH(blockNum,blockSize,N*D - BSH\BSND\TND 为BBH - shape.copyRowNumAlign 需要16字节对齐,如拷贝k矩阵,一次拷贝128*512,遇到尾块 - 10*512 需对齐到16*512 -*/ -template -__aicore__ inline void DataCopyPA( - LocalTensor& dstTensor, // l1 - GlobalTensor& srcTensor, // gm - GlobalTensor& blockTableGm, - const PAShape& shape, // blockSize, headNum, headDim - const Position& startPos) // bacthIdx nIdx curSeqIdx -{ - uint32_t copyFinishRowCnt = 0; - uint64_t blockTableBaseOffset = startPos.bIdx * shape.maxblockNumPerBatch; - uint32_t curS2Idx = startPos.s2Idx; - uint32_t blockElementCnt = 32 / sizeof(T); - while (copyFinishRowCnt < shape.copyRowNum) { - uint64_t blockIdOffset = - curS2Idx / shape.blockSize; // 获取block table上的索引 - uint64_t reaminRowCnt = - curS2Idx % shape.blockSize; // 获取在单个块上超出的行数 - uint64_t idInBlockTable = blockTableGm.GetValue( - blockTableBaseOffset + blockIdOffset); // 从block table上的获取编号 - uint32_t copyRowCnt = - shape.blockSize - reaminRowCnt; // 一次只能处理一个Block - if (copyFinishRowCnt + copyRowCnt > shape.copyRowNum) { - copyRowCnt = shape.copyRowNum - copyFinishRowCnt; // 一个block未拷满 - } - uint64_t offset = idInBlockTable * shape.kvStride; // PA的偏移 - uint64_t dStride = shape.headDim; - if constexpr (SRC_LAYOUT == SMLA_LAYOUT::BSND || - SRC_LAYOUT == SMLA_LAYOUT::TND) { - offset += (uint64_t)(startPos.n2Idx * shape.headDim) + - reaminRowCnt * shape.headDim * shape.headNum + startPos.dIdx; - dStride = shape.headDim * shape.headNum; - } else { - offset += (uint64_t)(startPos.n2Idx * shape.headDim * shape.blockSize) + - reaminRowCnt * shape.headDim + startPos.dIdx; - } - - uint32_t dValue = shape.actHeadDim; - uint32_t srcDValue = dStride; - LocalTensor tmpDstTensor = dstTensor[copyFinishRowCnt * blockElementCnt]; - GlobalTensor tmpSrcTensor = srcTensor[offset]; - - DataCopyGmNDToL1(tmpDstTensor, - tmpSrcTensor, - copyRowCnt, - shape.copyRowNumAlign, - dValue, - srcDValue); - copyFinishRowCnt += copyRowCnt; - curS2Idx += copyRowCnt; - } -} - -template -__aicore__ inline void DataCopyPABySlots(LocalTensor& dstTensor, - GlobalTensor& srcTensor, - GlobalTensor& blockTableGm, - GlobalTensor& sparseIndicesGm, - const PAShape& shape, - const Position& startPos, - uint64_t sparseIndexBaseOffset, - uint32_t sparseIndexStart) { - uint32_t blockElementCnt = 32 / sizeof(T); - uint64_t blockTableBaseOffset = startPos.bIdx * shape.maxblockNumPerBatch; - for (uint32_t row = 0; row < shape.copyRowNum; ++row) { - int32_t logicalIdx = sparseIndicesGm.GetValue(sparseIndexBaseOffset + - sparseIndexStart + row); - if (logicalIdx < 0) { - continue; - } - uint64_t blockTableIdx = - static_cast(logicalIdx) / shape.blockSize; - uint64_t inBlockIdx = static_cast(logicalIdx) % shape.blockSize; - uint64_t idInBlockTable = - blockTableGm.GetValue(blockTableBaseOffset + blockTableIdx); - uint64_t offset = idInBlockTable * shape.kvStride; - offset += static_cast(startPos.n2Idx * shape.headDim * - shape.blockSize) + - inBlockIdx * shape.headDim + startPos.dIdx; - - LocalTensor tmpDstTensor = dstTensor[row * blockElementCnt]; - GlobalTensor tmpSrcTensor = srcTensor[offset]; - DataCopyGmNDToL1(tmpDstTensor, - tmpSrcTensor, - 1, - shape.copyRowNumAlign, - shape.actHeadDim, - shape.headDim); - } -} - -struct RunInfo { - uint32_t loop = 0; - uint32_t cmpLoop = 0; // 用于判断取 用于merge的4块GM 中的哪一块 - uint32_t bIdx = 0; - uint32_t gIdx = 0; - uint32_t s1Idx = 0; - uint32_t s2Idx = 0; - uint32_t n2IdxReal = 0; - uint32_t relativeS2Idx = 0; - uint32_t bn2IdxInCurCore = 0; - uint32_t curSInnerLoopTimes = 0; - uint64_t tndBIdxOffsetForQ = 0; - uint64_t tndBIdxOffsetForKV = 0; - uint64_t tensorCmpBOffset = 0; - uint64_t tensorAOffset = 0; - uint64_t tensorBOffset = 0; - uint64_t attenOutOffset = 0; - uint64_t qTokenOffset = 0; - uint64_t attenMaskOffset = 0; - uint64_t topKBaseOffset = 0; - uint32_t actualSingleProcessSInnerSize = 0; - uint32_t actualSingleProcessSInnerSizeAlign = 0; - uint32_t actualSingleProcessSInnerOriSize = 0; - uint32_t actualSingleProcessSInnerOriAlignSize = 0; - uint32_t actualSingleProcessSInnerCmpSize = 0; - uint32_t actualSingleProcessSInnerCmpAlignSize = 0; - uint32_t s2BatchOffset = 0; - uint32_t gSize = 0; - uint32_t s1Size = 0; - uint32_t s2Size = 0; - uint32_t mSize = 0; - uint32_t mSizeV = 0; - uint32_t mSizeVStart = 0; - uint32_t tndIsS2SplitCore = 0; - uint32_t tndCoreStartKVSplitPos = 0; - bool isFirstSInnerLoop = false; - bool isBmm2Output = false; - bool isValid = false; - bool isLastS2Loop = 0; - int64_t inValidRowCount = 0; - - uint64_t actS1Size = 1; - uint64_t actS2SizeOri = 0ULL; - static constexpr uint32_t n2Idx = 0; - uint32_t gS1Idx = 0; - uint64_t actS2Size = 1; - uint64_t actOriS2Size = 1; - uint32_t actMBaseSize = 0; - int32_t nextTokensPerBatch = 0; - int64_t threshold = 0; - uint64_t curOffsetInSparseBlock = 0; - uint32_t curTopKIdx = 0; - bool isOriOnly = true; // 判断当前块是在Ori部分还是Cmp部分 - bool isOriCmpMix = false; - uint8_t resv[2]; - uint64_t s2StartPoint = 0; - int64_t cmpS2IdStart = 0; - int64_t cmpS2IdLimit = 0; - int32_t v0S2DealSize = 0; - int32_t v0S2Start = 0; - uint32_t oriDealSize = 0; - int32_t cmpMaskRight = 0; -}; - -struct ConstInfo { - // CUBE与VEC核间同步的模式 - static constexpr uint32_t SMLA_SYNC_MODE2 = 2; - // BUFFER的字节数 - static constexpr uint32_t BUFFER_SIZE_BYTE_32B = 32; - static constexpr uint32_t BUFFER_SIZE_BYTE_64B = 64; - static constexpr uint32_t BUFFER_SIZE_BYTE_256B = 256; - static constexpr uint32_t BUFFER_SIZE_BYTE_512B = 512; - static constexpr uint32_t BUFFER_SIZE_BYTE_1K = 1024; - static constexpr uint32_t BUFFER_SIZE_BYTE_2K = 2048; - static constexpr uint32_t BUFFER_SIZE_BYTE_4K = 4096; - static constexpr uint32_t BUFFER_SIZE_BYTE_8K = 8192; - static constexpr uint32_t BUFFER_SIZE_BYTE_16K = 16384; - static constexpr uint32_t BUFFER_SIZE_BYTE_32K = 32768; - // FP32的0值和极大值 - static constexpr float FLOAT_ZERO = 0; - static constexpr float FLOAT_MAX = 3.402823466e+38F; - - // preLoad的总次数 - uint32_t preLoadNum = 0U; - uint32_t nBufferMBaseSize = 0U; - // CUBE和VEC的核间同步EventID - uint32_t syncV0C1 = 0U; - uint32_t syncC1V1 = 0U; - uint32_t syncV1C2 = 0U; - uint32_t syncC2V2 = 0U; - - uint32_t mmResUbSize = 0U; // Matmul1输出结果GM上的大小 - uint32_t vec1ResUbSize = 0U; // Vector1输出结果GM上的大小 - uint32_t bmm2ResUbSize = 0U; // Matmul2输出结果GM上的大小 - uint32_t usedCoreNum = 0U; - uint64_t batchSize = 0ULL; - uint64_t gSize = 0ULL; - uint64_t qHeadNum = 0ULL; - uint64_t kvHeadNum = 0; - uint64_t headDim = 0; - uint64_t kvSeqSize = 0ULL; // kv最大S长度 - uint64_t qSeqSize = 1ULL; // q最大S长度 - int64_t kvCacheBlockSize = 0; // PA场景的block size - uint64_t paCmpBlockSize = 0; - uint64_t paOriBlockSize = 0; - int64_t orikvCacheBlockSize = 0; - int64_t cmpkvCacheBlockSize = 0; - uint32_t oriMaxBlockNumPerBatch = 0; // PA场景的最大单batch block number - uint32_t cmpMaxBlockNumPerBatch = 0; - uint32_t splitKVNum = 0U; // S2核间切分的切分份数 - SMLA_LAYOUT outputLayout; // 输出的Transpose格式 - uint32_t oriMaskMode = 0; - uint32_t cmpMaskMode = 0; - uint64_t oriKvStride0 = 0; - uint64_t cmpKvStride0 = 0; - bool needInit = false; - uint32_t templateMode = 0; - - // FlashDecoding - uint32_t actualCombineLoopSize = - 0U; // FlashDecoding场景, S2在核间切分的最大份数 - uint64_t combineLseOffset = 0ULL; - uint64_t combineAccumOutOffset = 0ULL; - - uint32_t actualLenDimsQ = 0U; // query的actualSeqLength 的维度 - uint32_t actualLenDimsKV = 0U; // KV 的actualSeqLength 的维度 - - uint32_t actualLenDimsCmpKV = 0U; - uint32_t cmpResidualKVSize = 0U; - - // TND - uint32_t s2Start = 0U; // TND场景下,S2的起始位置 - uint32_t s2End = 0U; // 单核TND场景下S2循环index上限 - - uint32_t bN2Start = 0U; - uint32_t bN2End = 0U; - uint32_t gS1Start = 0U; - uint32_t gS1End = 0U; - - uint32_t tndFDCoreArrLen = 0U; // TNDFlashDecoding相关分核信息array的长度 - uint32_t coreStartKVSplitPos = 0U; // TNDFlashDecoding kv起始位置 - - uint32_t mBaseSize = 1ULL; - uint32_t s2BaseSize = 1ULL; - - // sparse attr - int64_t sparseBlockSize = 0; - uint32_t sparseBlockCount = 0; - bool hasOriSparseIndices = false; - bool hasOriTopkLength = false; - uint32_t oriSparseIndexWidth = 0; - - // cmp attr - int64_t cmpRatio = 0; - - uint64_t cmpSeqSize = 0ULL; - - // win - int32_t oriWinRight = 0; - int32_t oriWinLeft = 128; - - bool returnSoftmaxLse = false; -}; - -struct MSplitInfo { - uint32_t nBufferIdx = 0U; - uint32_t nBufferStartM = 0U; - uint32_t nBufferDealM = 0U; - uint32_t vecStartM = 0U; - uint32_t vecDealM = 0U; -}; -} // namespace SMLAKernel -#endif // SPARSE_FLASH_MLA_COMMON_ARCH22_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_block_cube.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_block_cube.h deleted file mode 100644 index d379cba1d5..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_block_cube.h +++ /dev/null @@ -1,1013 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file sparse_flash_mla_csa_block_cube.h - * \brief use 7 buffer for matmul l1, better pipeline - */ -#ifndef SPARSE_FLASH_MLA_CSA_BLOCK_CUBE_H -#define SPARSE_FLASH_MLA_CSA_BLOCK_CUBE_H - -#include "kernel_operator.h" -#include "kernel_operator_list_tensor_intf.h" -#include "kernel_tiling/kernel_tiling.h" -#include "lib/matmul_intf.h" -#include "lib/matrix/matmul/tiling.h" -#include "sparse_flash_mla_common_arch22.h" - -namespace SMLAKernel { -template -class SMLACubeBlock { - public: - // 中间计算数据类型为float, 高精度模式 - using T = float; - using Q_T = typename SMLAT::queryType; - using KV_T = typename SMLAT::kvType; - using OUT_T = typename SMLAT::outputType; - using MM_OUT_T = T; - - __aicore__ inline SMLACubeBlock(){}; - __aicore__ inline void InitParams(const ConstInfo& constInfo); - __aicore__ inline void InitMm1GlobalTensor(GlobalTensor queryGm, - GlobalTensor oriKvGm, - GlobalTensor cmpKV, - GlobalTensor mm1ResGm); - __aicore__ inline void InitMm2GlobalTensor( - GlobalTensor vec1ResGm, - GlobalTensor mm2ResGm, - GlobalTensor attentionOutGm); - __aicore__ inline void InitPageAttentionInfo( - GlobalTensor oriKvGm, - const GlobalTensor& kvMergeGm, - GlobalTensor oriBlockTableGm, - GlobalTensor cmpBlockTableGm); - __aicore__ inline void InitBuffers(TPipe* pipe); - - __aicore__ inline void AllocEventID(); - __aicore__ inline void FreeEventID(); - __aicore__ inline void ComputeMm1(const RunInfo& info, - const MSplitInfo mSplitInfo); - __aicore__ inline void ComputeMm2(const RunInfo& info, - const MSplitInfo mSplitInfo); - - private: - static constexpr bool PAGE_ATTENTION = SMLAT::pageAttention; - static constexpr int TEMPLATE_MODE = SMLAT::templateMode; - static constexpr bool FLASH_DECODE = SMLAT::flashDecode; - static constexpr SMLA_LAYOUT LAYOUT_T = SMLAT::layout; - static constexpr SMLA_LAYOUT KV_LAYOUT_T = SMLAT::kvLayout; - - static constexpr uint32_t MERGE_CACHE_GM_BUF_NUM = 3; - static constexpr uint32_t M_SPLIT_SIZE = 128; // m方向切分 - static constexpr uint32_t N_SPLIT_SIZE = 128; // n方向切分 - static constexpr uint32_t K_L0_SPLIT_SIZE = 128; // k方向L0切分 - static constexpr uint32_t K_L1_SPLIT_SIZE = 256; // k方向L1切分 - static constexpr uint32_t N_WORKSPACE_SIZE = 512; // n方向切分 - static constexpr uint32_t D_SPLIT_SIZE = 256; // d轴切分 - - static constexpr uint32_t L1_BLOCK_SIZE = (64 * 512 * sizeof(Q_T)); - static constexpr uint32_t L1_BLOCK_OFFSET = 64 * 512; - - static constexpr uint32_t L0A_PP_SIZE = (32 * 1024); - static constexpr uint32_t L0B_PP_SIZE = (32 * 1024); - static constexpr uint32_t L0C_PP_SIZE = (64 * 1024); - - // mte2 <> mte1 EventID - // L1 3buf, 使用3个eventId - static constexpr uint32_t L1_EVENT0 = EVENT_ID2; - static constexpr uint32_t L1_EVENT1 = EVENT_ID3; - static constexpr uint32_t L1_EVENT2 = EVENT_ID4; - static constexpr uint32_t L1_EVENT3 = EVENT_ID5; - static constexpr uint32_t L1_EVENT4 = EVENT_ID6; - static constexpr uint32_t L1_EVENT5 = EVENT_ID7; - static constexpr uint32_t L1_EVENT6 = EVENT_ID1; - - // m <> mte1 EventID - static constexpr uint32_t L0AB_EVENT0 = EVENT_ID3; - static constexpr uint32_t L0AB_EVENT1 = EVENT_ID4; - - static constexpr IsResetLoad3dConfig LOAD3DV2_CONFIG = { - true, - true}; // isSetFMatrix isSetPadding - static constexpr uint32_t mte21QPIds[4] = {L1_EVENT0, - L1_EVENT1, - L1_EVENT2, - L1_EVENT3}; // mte12复用 - static constexpr uint32_t mte21KVIds[3] = {L1_EVENT4, L1_EVENT5, L1_EVENT6}; - - ConstInfo constInfo{}; - - // L1分成3块buf, 用于记录 - uint32_t qpL1BufIter = 0; - uint32_t kvL1BufIter = -1; - uint32_t abL0BufIter = 0; - uint32_t cL0BufIter = 0; - - // mm1 - GlobalTensor queryGm; - GlobalTensor keyGm; - GlobalTensor mm1ResGm; - GlobalTensor oriKvGm; - GlobalTensor kvMergeGm_; - GlobalTensor cmpKvGm; - - // mm2 - GlobalTensor vec1ResGm; - GlobalTensor valueGm; - GlobalTensor mm2ResGm; - GlobalTensor attentionOutGm; - - // block_table - GlobalTensor oriBlockTableGm; - GlobalTensor cmpBlockTableGm; - - TBuf bufQPL1; - TBuf bufKVL1; - TBuf tmpBufL0A; - TBuf tmpBufL0B; - TBuf tmpBufL0C; - - LocalTensor l1QPTensor; - LocalTensor l1KVTensor; - LocalTensor aL0TensorPingPong; - LocalTensor bL0TensorPingPong; - LocalTensor cL0TensorPingPong; - - // L0AB m <> mte1 EventID - __aicore__ inline uint32_t Mte1MmABEventId(uint32_t idx) { - return (L0AB_EVENT0 + idx); - } - - __aicore__ inline uint32_t GetQPL1RealIdx(uint32_t mIdx, uint32_t k1Idx) { - uint32_t idxMap[] = { - 0, 2}; // 确保0块和1块连在一起, 2和3块连在一起, 来保证同一m块的地址相连 - return idxMap[mIdx % 2] + k1Idx; - } - - __aicore__ inline void CopyGmToL1(LocalTensor& l1Tensor, - GlobalTensor& gmSrcTensor, - uint32_t srcN, - uint32_t srcD, - uint32_t srcDstride); - __aicore__ inline void CopyInMm1AToL1(LocalTensor& aL1Tensor, - const RunInfo& info, - uint32_t mSeqIdx, - uint32_t mSizeAct, - uint32_t headSize, - uint32_t headOffset); - - __aicore__ inline void CopyInMm2AToL1(LocalTensor& aL1Tensor, - const RunInfo& info, - uint32_t mSeqIdx, - uint32_t subMSizeAct, - uint32_t nSize, - uint32_t nOffset); - __aicore__ inline void LoadDataMm1A(LocalTensor& aL0Tensor, - LocalTensor& aL1Tensor, - uint32_t idx, - uint32_t kSplitSize, - uint32_t mSize, - uint32_t kSize); - __aicore__ inline void LoadDataMm1B(LocalTensor& bL0Tensor, - LocalTensor& bL1Tensor, - uint32_t idx, - uint32_t kSplitSize, - uint32_t kSize, - uint32_t nSize); -}; - -template -__aicore__ inline void SMLACubeBlock::InitParams( - const ConstInfo& constInfo) { - this->constInfo = constInfo; -} - -template -__aicore__ inline void SMLACubeBlock::InitMm1GlobalTensor( - GlobalTensor queryGm, - GlobalTensor oriKvGm, - GlobalTensor cmpKvGm, - GlobalTensor mm1ResGm) { - // mm1 - this->queryGm = queryGm; - this->oriKvGm = oriKvGm; - this->cmpKvGm = cmpKvGm; - this->mm1ResGm = mm1ResGm; -} - -template -__aicore__ inline void SMLACubeBlock::InitMm2GlobalTensor( - GlobalTensor vec1ResGm, - GlobalTensor mm2ResGm, - GlobalTensor attentionOutGm) { - // mm2 - this->vec1ResGm = vec1ResGm; - this->mm2ResGm = mm2ResGm; - this->attentionOutGm = attentionOutGm; -} - -template -__aicore__ inline void SMLACubeBlock::InitPageAttentionInfo( - GlobalTensor oriKvGm, - const GlobalTensor& kvMergeGm, - GlobalTensor oriBlockTableGm, - GlobalTensor cmpBlockTableGm) { - this->oriKvGm = oriKvGm; - this->kvMergeGm_ = kvMergeGm; - this->oriBlockTableGm = oriBlockTableGm; - this->cmpBlockTableGm = cmpBlockTableGm; -} - -template -__aicore__ inline void SMLACubeBlock::InitBuffers(TPipe* pipe) { - pipe->InitBuffer(bufQPL1, L1_BLOCK_SIZE * 4); - l1QPTensor = bufQPL1.Get(); - pipe->InitBuffer(bufKVL1, L1_BLOCK_SIZE * 3); - l1KVTensor = bufKVL1.Get(); - - // L0A - pipe->InitBuffer(tmpBufL0A, L0A_PP_SIZE * 2); // 64K - aL0TensorPingPong = tmpBufL0A.Get(); - // L0B - pipe->InitBuffer(tmpBufL0B, L0B_PP_SIZE * 2); // 64K - bL0TensorPingPong = tmpBufL0B.Get(); - // L0C - pipe->InitBuffer(tmpBufL0C, L0C_PP_SIZE * 2); // 128K - cL0TensorPingPong = tmpBufL0C.Get(); -} - -template -__aicore__ inline void SMLACubeBlock::AllocEventID() { - SetFlag(L1_EVENT0); - SetFlag(L1_EVENT1); - SetFlag(L1_EVENT2); - SetFlag(L1_EVENT3); - SetFlag(L1_EVENT4); - SetFlag(L1_EVENT5); - SetFlag(L1_EVENT6); - SetFlag(L0AB_EVENT0); - SetFlag(L0AB_EVENT1); -} - -template -__aicore__ inline void SMLACubeBlock::FreeEventID() { - WaitFlag(L1_EVENT0); - WaitFlag(L1_EVENT1); - WaitFlag(L1_EVENT2); - WaitFlag(L1_EVENT3); - WaitFlag(L1_EVENT4); - WaitFlag(L1_EVENT5); - WaitFlag(L1_EVENT6); - WaitFlag(L0AB_EVENT0); - WaitFlag(L0AB_EVENT1); -} - -template -__aicore__ inline void SMLACubeBlock::CopyGmToL1( - LocalTensor& l1Tensor, - GlobalTensor& gmSrcTensor, - uint32_t srcN, - uint32_t srcD, - uint32_t srcDstride) { - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = srcN; // 行数 - nd2nzPara.dValue = srcD; - nd2nzPara.srcDValue = srcDstride; - nd2nzPara.dstNzC0Stride = (srcN + 15) / 16 * 16; // 对齐到16 单位block - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - DataCopy(l1Tensor, gmSrcTensor, nd2nzPara); -} - -template -__aicore__ inline void SMLACubeBlock::CopyInMm1AToL1( - LocalTensor& l1Tensor, - const RunInfo& info, - uint32_t mSeqIdx, - uint32_t mSizeAct, - uint32_t headSize, - uint32_t headOffset) { - auto srcGm = - queryGm[info.tensorAOffset + mSeqIdx * constInfo.headDim + headOffset]; - CopyGmToL1(l1Tensor, srcGm, mSizeAct, headSize, constInfo.headDim); -} - -template -__aicore__ inline void SMLACubeBlock::LoadDataMm1A( - LocalTensor& aL0Tensor, - LocalTensor& aL1Tensor, - uint32_t idx, - uint32_t kSplitSize, - uint32_t mSize, - uint32_t kSize) { - LocalTensor srcTensor = aL1Tensor[mSize * kSplitSize * idx]; - LoadData3DParamsV2 loadData3DParams; - // SetFmatrixParams - loadData3DParams.l1H = mSize / 16; // Hin=M1=8 - loadData3DParams.l1W = 16; // Win=M0 - loadData3DParams.padList[0] = 0; - loadData3DParams.padList[1] = 0; - loadData3DParams.padList[2] = 0; - loadData3DParams.padList[3] = 255; // 尾部数据不影响滑窗的结果 - - // SetLoadToA0Params - loadData3DParams.mExtension = mSize; // M - loadData3DParams.kExtension = kSize; // K - loadData3DParams.mStartPt = 0; - loadData3DParams.kStartPt = 0; - loadData3DParams.strideW = 1; - loadData3DParams.strideH = 1; - loadData3DParams.filterW = 1; - loadData3DParams.filterSizeW = (1 >> 8) & 255; - loadData3DParams.filterH = 1; - loadData3DParams.filterSizeH = (1 >> 8) & 255; - loadData3DParams.dilationFilterW = 1; - loadData3DParams.dilationFilterH = 1; - loadData3DParams.enTranspose = 0; - loadData3DParams.fMatrixCtrl = 0; - loadData3DParams.channelSize = kSize; // Cin=K - LoadData(aL0Tensor, srcTensor, loadData3DParams); -} - -template -__aicore__ inline void SMLACubeBlock::LoadDataMm1B( - LocalTensor& l0Tensor, - LocalTensor& l1Tensor, - uint32_t idx, - uint32_t kSplitSize, - uint32_t kSize, - uint32_t nSize) { - // N 方向全载 - LocalTensor srcTensor = l1Tensor[nSize * kSplitSize * idx]; - - LoadData2DParams loadData2DParams; - loadData2DParams.startIndex = 0; - loadData2DParams.repeatTimes = - (nSize + 15) / 16 * kSize / (32 / sizeof(KV_T)); - loadData2DParams.srcStride = 1; - loadData2DParams.dstGap = 0; - loadData2DParams.ifTranspose = false; - LoadData(l0Tensor, srcTensor, loadData2DParams); -} - -template -__aicore__ inline void SMLACubeBlock::CopyInMm2AToL1( - LocalTensor& aL1Tensor, - const RunInfo& info, - uint32_t mSeqIdx, - uint32_t subMSizeAct, - uint32_t nSize, - uint32_t nOffset) { - auto srcGm = - vec1ResGm[(info.loop % constInfo.preLoadNum) * constInfo.mmResUbSize + - mSeqIdx * info.actualSingleProcessSInnerSizeAlign + nOffset]; - CopyGmToL1(aL1Tensor, - srcGm, - subMSizeAct, - nSize, - info.actualSingleProcessSInnerSizeAlign); -} - -template -__aicore__ inline void SMLACubeBlock::ComputeMm1( - const RunInfo& info, - const MSplitInfo mSplitInfo) { - uint32_t mSize = mSplitInfo.nBufferDealM; - uint32_t mL1Size = M_SPLIT_SIZE; - uint32_t mL1SizeAlign = SMLAAlign(M_SPLIT_SIZE, 16); - uint32_t mL1Loops = CeilDiv(mSize, M_SPLIT_SIZE); - - uint32_t nSize = info.actualSingleProcessSInnerSize; - uint32_t nL1Size = N_SPLIT_SIZE; - uint32_t nL1SizeAlign = SMLAAlign(N_SPLIT_SIZE, 16); - uint32_t nL1Loops = CeilDiv(nSize, N_SPLIT_SIZE); - - uint32_t kSize = 512; - uint32_t kL1Size = 256; - uint32_t kL1Loops = 2; - uint32_t kL0Size = 128; - uint32_t kL0Loops = CeilDiv(kL1Size, kL0Size); - - LocalTensor bL1Tensor; - uint32_t ka = 0, kb = 0; - - // L1 切n切k - for (uint32_t nL1 = 0; nL1 < nL1Loops; nL1++) { - if (nL1 == (nL1Loops - 1)) { - // 尾块重新计算size - nL1Size = nSize - (nL1Loops - 1) * N_SPLIT_SIZE; - nL1SizeAlign = SMLAAlign(nL1Size, 16); - } - - for (uint32_t kL1 = 0; kL1 < kL1Loops; kL1++) { - kvL1BufIter++; - uint32_t kb = kvL1BufIter % 3; - WaitFlag(mte21KVIds[kb]); - // 从k当中取当前的块 - bL1Tensor = l1KVTensor[kb * L1_BLOCK_OFFSET]; - uint32_t curSeqIdx = info.s2BatchOffset + nL1 * N_SPLIT_SIZE; - if (info.isOriOnly) { - if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { - uint32_t curS2Offset = - info.s2Idx * constInfo.s2BaseSize + info.s2StartPoint; - uint32_t copyFinishRowCnt = 0; - LocalTensor kTensor; - uint32_t copyRowCnt = 0; - - while (copyFinishRowCnt < nL1Size) { - // 由于ori_left的存在, 即使第一块搬运也可能并非是pa_block的零点位 - copyRowCnt = constInfo.paOriBlockSize - - curS2Offset % constInfo.paOriBlockSize; - if (copyFinishRowCnt + copyRowCnt > nL1Size) { - copyRowCnt = nL1Size - copyFinishRowCnt; - } - PAShape shape; - shape.blockSize = constInfo.paOriBlockSize; - shape.headNum = constInfo.kvHeadNum; - shape.headDim = constInfo.headDim; - shape.kvStride = constInfo.oriKvStride0; - shape.actHeadDim = D_SPLIT_SIZE; - shape.maxblockNumPerBatch = constInfo.oriMaxBlockNumPerBatch; - shape.copyRowNum = copyRowCnt; - shape.copyRowNumAlign = nL1SizeAlign; - kTensor = bL1Tensor[copyFinishRowCnt * 16]; - - Position startPos; - startPos.bIdx = info.bIdx; - startPos.n2Idx = info.n2Idx; - startPos.s2Idx = curS2Offset; - startPos.dIdx = - kL1 * D_SPLIT_SIZE; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 - // 右矩阵, s2为k轴, d轴切分 - DataCopyPA( - kTensor, oriKvGm, oriBlockTableGm, shape, startPos); - - // 更新循环变量 - copyFinishRowCnt += copyRowCnt; - curS2Offset += copyRowCnt; - } - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = nL1Size; // 行数 - nd2nzPara.dValue = D_SPLIT_SIZE; // 256 - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = nL1SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - - uint32_t headStride = constInfo.headDim; - uint32_t seqStride = constInfo.kvHeadNum * constInfo.headDim; - uint64_t batchStride = - (constInfo.oriKvStride0 == 0) - ? static_cast(constInfo.kvSeqSize) * seqStride - : constInfo.oriKvStride0; - - uint32_t curS2 = - info.s2Idx * constInfo.s2BaseSize + info.s2StartPoint; - uint64_t offset = - (uint64_t)info.bIdx * batchStride + (uint64_t)curS2 * seqStride + - (uint64_t)info.n2Idx * headStride + kL1 * D_SPLIT_SIZE; - DataCopy(bL1Tensor, oriKvGm[offset], nd2nzPara); - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { - uint32_t curS2Offset = - info.s2Idx * constInfo.s2BaseSize + info.s2StartPoint; - if (kL1 == 0) { - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = nL1Size; - nd2nzPara.dValue = constInfo.headDim >> 1; - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = nL1SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - DataCopy( - bL1Tensor, - oriKvGm[info.tensorBOffset + curS2Offset * constInfo.headDim + - nL1 * N_SPLIT_SIZE * constInfo.headDim], - nd2nzPara); - } else { - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = nL1Size; - nd2nzPara.dValue = constInfo.headDim >> 1; - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = nL1SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - DataCopy( - bL1Tensor, - oriKvGm[info.tensorBOffset + curS2Offset * constInfo.headDim + - (constInfo.headDim >> 1) + - nL1 * N_SPLIT_SIZE * constInfo.headDim], - nd2nzPara); - } - } - } else { - if (kL1 == 0) { - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = nL1Size; - nd2nzPara.dValue = constInfo.headDim >> 1; - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = nL1SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - DataCopy(bL1Tensor, - kvMergeGm_[info.cmpLoop % MERGE_CACHE_GM_BUF_NUM * - N_WORKSPACE_SIZE * kSize + - nL1 * N_SPLIT_SIZE * constInfo.headDim], - nd2nzPara); - } else { - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = nL1Size; - nd2nzPara.dValue = constInfo.headDim >> 1; - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = nL1SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - DataCopy(bL1Tensor, - kvMergeGm_[info.cmpLoop % MERGE_CACHE_GM_BUF_NUM * - N_WORKSPACE_SIZE * kSize + - (constInfo.headDim >> 1) + - nL1 * N_SPLIT_SIZE * constInfo.headDim], - nd2nzPara); - } - } - SetFlag(mte21KVIds[kb]); - WaitFlag(mte21KVIds[kb]); - mL1Size = M_SPLIT_SIZE; - mL1SizeAlign = SMLAAlign(M_SPLIT_SIZE, 16U); - for (uint32_t mL1 = 0; mL1 < mL1Loops; mL1++) { - uint32_t aL1PaddingSize = - 0; // 用于使左矩阵对齐到尾部, 以保证两块32K内存连续 - if (mL1 == (mL1Loops - 1)) { - mL1Size = mSize - (mL1Loops - 1) * M_SPLIT_SIZE; - mL1SizeAlign = SMLAAlign(mL1Size, 16U); - aL1PaddingSize = (M_SPLIT_SIZE - mL1SizeAlign) * 256; - } - uint32_t mIdx = qpL1BufIter + mL1; - ka = GetQPL1RealIdx(mIdx, kL1); - LocalTensor aL1Tensor = - l1QPTensor[ka * L1_BLOCK_OFFSET + (1 - kL1) * aL1PaddingSize]; - if (nL1 == 0) { - if (kL1 == 0) { - WaitFlag(mte21QPIds[ka]); - WaitFlag(mte21QPIds[ka + 1]); - CopyInMm1AToL1(aL1Tensor, - info, - mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, - mL1Size, - 256, - 0); - } else { - LocalTensor qTmpTensor = aL1Tensor; - CopyInMm1AToL1(qTmpTensor, - info, - mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, - mL1Size, - 256, - 256); - } - SetFlag(mte21QPIds[ka]); - WaitFlag(mte21QPIds[ka]); - } - // 使用unitflag同步 - LocalTensor cL0Tensor = cL0TensorPingPong - [(cL0BufIter % 2) * - (L0C_PP_SIZE / - sizeof(MM_OUT_T))]; // 需要保证cL0BufIter和m步调一致 - for (uint32_t kL0 = 0; kL0 < kL0Loops; kL0++) { - WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); - LocalTensor aL0Tensor = - aL0TensorPingPong[(abL0BufIter % 2) * - (L0A_PP_SIZE / sizeof(KV_T))]; - LoadDataMm1A( - aL0Tensor, aL1Tensor, kL0, kL0Size, mL1SizeAlign, kL0Size); - LocalTensor bL0Tensor = - bL0TensorPingPong[(abL0BufIter % 2) * - (L0B_PP_SIZE / sizeof(KV_T))]; - LoadDataMm1B( - bL0Tensor, bL1Tensor, kL0, kL0Size, kL0Size, nL1SizeAlign); - SetFlag(Mte1MmABEventId(abL0BufIter % 2)); - WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); - - MmadParams mmadParams; - mmadParams.m = mL1SizeAlign; - mmadParams.n = nL1SizeAlign; - mmadParams.k = kL0Size; - mmadParams.cmatrixInitVal = (kL1 == 0 && kL0 == 0); - mmadParams.cmatrixSource = false; - mmadParams.unitFlag = - (kL1 == 1 && kL0 == (kL0Loops - 1)) - ? 0b11 - : 0b10; // 累加最后一次翻转flag, 表示可以搬出 - Mmad(cL0Tensor, aL0Tensor, bL0Tensor, mmadParams); - if ((mmadParams.m / 16) * (mmadParams.n / 16) < 10) { - PipeBarrier(); - } - SetFlag(Mte1MmABEventId(abL0BufIter % 2)); - abL0BufIter++; - } - - if (nL1 == (nL1Loops - 1)) { - SetFlag( - mte21QPIds[ka]); // 反向同步, 表示L1中的A已经被mte1消费完 - } - - if (kL1 == 1) { // 最后一轮kL1循环 - FixpipeParamsV220 fixParams; - fixParams.nSize = nL1SizeAlign; - fixParams.mSize = mL1SizeAlign; - fixParams.srcStride = mL1SizeAlign; - // 改成nSizeAlign - fixParams.dstStride = - info.actualSingleProcessSInnerSizeAlign; // mm1ResGm两行之间的间隔 - fixParams.unitFlag = 0b11; - fixParams.ndNum = 1; // 输出ND - - Fixpipe(mm1ResGm[(info.loop % (constInfo.preLoadNum)) * - constInfo.mmResUbSize + - nL1 * N_SPLIT_SIZE + - (mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE) * - info.actualSingleProcessSInnerSizeAlign], - cL0Tensor, - fixParams); - } - if (mL1Loops == 2) { - cL0BufIter++; - } - } - - SetFlag( - mte21KVIds[kb]); // 反向同步, 表示L1已经被mte1消费完 - } - if (mL1Loops == 1) { - cL0BufIter++; - } - } - qpL1BufIter += mL1Loops; -} - -template -__aicore__ inline void SMLACubeBlock::ComputeMm2( - const RunInfo& info, - const MSplitInfo mSplitInfo) { - uint32_t mSize = mSplitInfo.nBufferDealM; - uint32_t mSizeAlign = (mSize + 16 - 1) / 16; - uint32_t mL1Loops = (mSize + M_SPLIT_SIZE - 1) / M_SPLIT_SIZE; - uint32_t mL1SizeAlign = M_SPLIT_SIZE; // 16对齐 - uint32_t mL1Size = M_SPLIT_SIZE; // m的实际大小 - - uint32_t nSize = BlockAlign(constInfo.headDim); - uint32_t nL1Loops = (nSize + N_SPLIT_SIZE - 1) / N_SPLIT_SIZE; - uint32_t nL1SizeAlign = N_SPLIT_SIZE; // 16对齐 - uint32_t nL1Size = N_SPLIT_SIZE; // n的实际大小 - - uint32_t kSize = info.actualSingleProcessSInnerSize; - uint32_t kL1Size = 256; - uint32_t kL1SizeAlign = SMLAAlign(kL1Size, 16U); - uint32_t kL1Loops = (kSize + kL1Size - 1) / kL1Size; - uint32_t kL0Size = 128; - uint32_t kL0Loops = (kL1Size + kL0Size - 1) / kL0Size; - uint32_t kL0SizeAlign = kL0Size; - LocalTensor bL1Tensor; - LocalTensor subvTensor; - - // ka表示左矩阵4buf选择哪一块buf, kb表示右矩阵3buf选择哪一块buf - uint32_t ka = 0, kb = 0; - uint32_t mBaseIdx = qpL1BufIter; - for (uint32_t nL1 = 0; nL1 < nL1Loops; nL1++) { // n切L1 -> D - if (nL1 == (nL1Loops - 1)) { - // 尾块 - nL1Size = nSize - (nL1Loops - 1) * N_SPLIT_SIZE; - nL1SizeAlign = SMLAAlign(nL1Size, 16U); - } - // k l1写成一个循环, 和mm1保持一致 - kL1Size = 256; - kL1SizeAlign = SMLAAlign(kL1Size, 16U); - uint32_t copyRowCnt = 0; - - for (uint32_t k1 = 0; k1 < kL1Loops; - k1++) { // k切L1, 这里套了一层l0来操作 -> S2,每次256 - if (k1 == (kL1Loops - 1)) { - // 尾块 - kL1Size = kSize - (kL1Loops - 1) * 256; - kL1SizeAlign = SMLAAlign(kL1Size, 16U); - } - kvL1BufIter++; - uint32_t kb = kvL1BufIter % 3; - WaitFlag(mte21KVIds[kb]); - bL1Tensor = l1KVTensor[kb * L1_BLOCK_OFFSET]; - uint32_t kOffset = k1 * kL0Loops; - kL0Size = 128; - // 此处必须先初始化kL0Size, 再求kL0Loops, 否则由于循环会改变kL0Size大小, - // 导致kL0Loops错误 - kL0Loops = (kL1Size + kL0Size - 1) / kL0Size; - kL0SizeAlign = kL0Size; - for (uint32_t kL1 = kOffset; kL1 < kL0Loops + kOffset; - kL1++) { // 128 循环搬pa,每次128 - if (kL1 == kOffset + kL0Loops - 1) { - // 尾块 - kL0Size = kL1Size - (kL0Loops - 1) * kL0Size; - kL0SizeAlign = SMLAAlign(kL0Size, 16U); - } - - uint32_t curSeqIdx = - info.s2BatchOffset + (kL1 - kOffset) * 128 + k1 * 256; - if (info.isOriOnly) { - if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { - uint32_t copyFinishRowCnt = 0; - uint32_t curS2Offset = - info.s2Idx * constInfo.s2BaseSize + info.s2StartPoint; - while (copyFinishRowCnt < kL0Size) { - copyRowCnt = constInfo.paOriBlockSize - - curS2Offset % constInfo.paOriBlockSize; - if (copyFinishRowCnt + copyRowCnt > kL0Size) { - copyRowCnt = kL0Size - copyFinishRowCnt; - } - Position startPos; - startPos.bIdx = info.bIdx; - startPos.n2Idx = info.n2Idx; - startPos.s2Idx = curS2Offset; - startPos.dIdx = - nL1 * N_SPLIT_SIZE; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 - // 右矩阵, s2为k轴, d轴切分 - PAShape shape; - shape.blockSize = constInfo.paOriBlockSize; - shape.headNum = constInfo.kvHeadNum; - shape.headDim = constInfo.headDim; - shape.kvStride = constInfo.oriKvStride0; - shape.actHeadDim = nL1Size; - shape.maxblockNumPerBatch = constInfo.oriMaxBlockNumPerBatch; - shape.copyRowNum = copyRowCnt; - shape.copyRowNumAlign = kL0SizeAlign; - subvTensor = bL1Tensor[(kL1 - kOffset) * 128 * N_SPLIT_SIZE + - copyFinishRowCnt * 16]; - - DataCopyPA( - subvTensor, oriKvGm, oriBlockTableGm, shape, startPos); - - // 更新循环变量 - copyFinishRowCnt += copyRowCnt; - curS2Offset += copyRowCnt; - } - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = kL0Size; // 行数 - nd2nzPara.dValue = N_SPLIT_SIZE; // constInfo.headDim; - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = kL0SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - - uint32_t headStride = constInfo.headDim; - uint32_t seqStride = constInfo.kvHeadNum * constInfo.headDim; - uint64_t batchStride = - (constInfo.oriKvStride0 == 0) - ? static_cast(constInfo.kvSeqSize) * seqStride - : constInfo.oriKvStride0; - - uint32_t curS2 = - info.s2Idx * constInfo.s2BaseSize + info.s2StartPoint; - uint64_t offset = (uint64_t)info.bIdx * batchStride + - (uint64_t)curS2 * seqStride + - (uint64_t)info.n2Idx * headStride + - nL1 * N_SPLIT_SIZE; - subvTensor = bL1Tensor[(kL1 - kOffset) * 128 * N_SPLIT_SIZE]; - DataCopy(subvTensor, oriKvGm[offset], nd2nzPara); - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { - uint32_t curS2Offset = - info.s2Idx * constInfo.s2BaseSize + info.s2StartPoint; - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = kL0Size; // 行数 - nd2nzPara.dValue = N_SPLIT_SIZE; // constInfo.headDim; - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = kL0SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - DataCopy( - bL1Tensor[(kL1 - kOffset) * 128 * N_SPLIT_SIZE], - oriKvGm[info.tensorBOffset + curS2Offset * constInfo.headDim + - kL1 * 128 * constInfo.headDim + nL1 * N_SPLIT_SIZE], - nd2nzPara); - } - } else { - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = kL0Size; // 行数 - nd2nzPara.dValue = N_SPLIT_SIZE; // constInfo.headDim; - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = kL0SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - DataCopy( - bL1Tensor[(kL1 - kOffset) * 128 * N_SPLIT_SIZE], - kvMergeGm_[info.cmpLoop % MERGE_CACHE_GM_BUF_NUM * - N_WORKSPACE_SIZE * 512 + - kL1 * 128 * constInfo.headDim + nL1 * N_SPLIT_SIZE], - nd2nzPara); - } - } - SetFlag(mte21KVIds[kb]); - WaitFlag(mte21KVIds[kb]); - mL1SizeAlign = M_SPLIT_SIZE; - mL1Size = M_SPLIT_SIZE; // m的实际大小 - for (uint32_t mL1 = 0; mL1 < mL1Loops; mL1++) { - if (mL1 == (mL1Loops - 1)) { - // 尾块 - mL1Size = mSize - (mL1Loops - 1) * M_SPLIT_SIZE; - mL1SizeAlign = SMLAAlign(mL1Size, 16U); - } - - uint32_t mIdx = mBaseIdx + mL1; - ka = GetQPL1RealIdx(mIdx, k1); - LocalTensor aL1Tensor = l1QPTensor[ka * L1_BLOCK_OFFSET]; - if (nL1 == 0) { - WaitFlag(mte21QPIds[ka]); - CopyInMm2AToL1(aL1Tensor, - info, - mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, - mL1Size, - kL1Size, - 256 * k1); - SetFlag(mte21QPIds[ka]); - WaitFlag(mte21QPIds[ka]); - } - - LocalTensor cL0Tensor = cL0TensorPingPong - [(cL0BufIter % 2) * - (L0C_PP_SIZE / - sizeof(MM_OUT_T))]; // 需要保证cL0BufIter和m步调一致 - uint32_t baseK = 128; - uint32_t baseN = 128; - kL0Size = 128; - kL0SizeAlign = kL0Size; - for (uint32_t kL0 = 0; kL0 < kL0Loops; kL0++) { - if (kL0 + 1 == kL0Loops) { - kL0Size = kL1Size - (kL0Loops - 1) * kL0Size; - kL0SizeAlign = SMLAAlign(kL0Size, 16U); - } - WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); - LocalTensor bL0Tensor = - bL0TensorPingPong[(abL0BufIter % 2) * - (L0B_PP_SIZE / sizeof(KV_T))]; - LoadData3DParamsV2 loadData3DParamsForB; - loadData3DParamsForB.l1H = kL0SizeAlign / 16; // 源操作数height - loadData3DParamsForB.l1W = - 16; // 源操作数weight=16,目的height=l1H*L1W - loadData3DParamsForB.padList[0] = 0; - loadData3DParamsForB.padList[1] = 0; - loadData3DParamsForB.padList[2] = 0; - loadData3DParamsForB.padList[3] = 255; // 尾部数据不影响滑窗的结果 - - loadData3DParamsForB.mExtension = - kL0SizeAlign; // 在目的操作数height维度的传输长度 - loadData3DParamsForB.kExtension = - nL1SizeAlign; // 在目的操作数width维度的传输长度 - loadData3DParamsForB.mStartPt = - 0; // 卷积核在目的操作数width维度的起点 - loadData3DParamsForB.kStartPt = - 0; // 卷积核在目的操作数height维度的起点 - loadData3DParamsForB.strideW = 1; - loadData3DParamsForB.strideH = 1; - loadData3DParamsForB.filterW = 1; - loadData3DParamsForB.filterSizeW = - false; // 是否在filterW的基础上将卷积核width增加256个元素 - loadData3DParamsForB.filterH = 1; - loadData3DParamsForB.filterSizeH = - false; // 是否在filterH的基础上将卷积核height增加256个元素 - loadData3DParamsForB.dilationFilterW = 1; // 卷积核width膨胀系数 - loadData3DParamsForB.dilationFilterH = 1; // 卷积核height膨胀系数 - loadData3DParamsForB.enTranspose = 1; // 是否启用转置功能 - loadData3DParamsForB.fMatrixCtrl = - 0; // 使用FMATRIX_LEFT还是使用FMATRIX_RIGHT,=0使用FMATRIX_LEFT,=1使用FMATRIX_RIGHT - // 1 - loadData3DParamsForB.channelSize = - nL1SizeAlign; // 源操作数的通道数。膨胀系数为1时,目的weight为filterW*filterH*channelSize - LoadData( - bL0Tensor, bL1Tensor[kL0 * baseK * baseN], loadData3DParamsForB); - - LocalTensor aL0Tensor = - aL0TensorPingPong[(abL0BufIter % 2) * - (L0A_PP_SIZE / sizeof(KV_T))]; - LoadData3DParamsV2 loadData3DParamsForA; - loadData3DParamsForA.l1H = mL1SizeAlign / 16; // 源操作数height - loadData3DParamsForA.l1W = 16; // 源操作数weight - loadData3DParamsForA.padList[0] = 0; - loadData3DParamsForA.padList[1] = 0; - loadData3DParamsForA.padList[2] = 0; - loadData3DParamsForA.padList[3] = 255; // 尾部数据不影响滑窗的结果 - - loadData3DParamsForA.mExtension = - mL1SizeAlign; // 在目的操作数height维度的传输长度 - loadData3DParamsForA.kExtension = - kL0SizeAlign; // 在目的操作数width维度的传输长度 - loadData3DParamsForA.mStartPt = - 0; // 卷积核在目的操作数width维度的起点 - loadData3DParamsForA.kStartPt = - 0; // 卷积核在目的操作数height维度的起点 - loadData3DParamsForA.strideW = - 1; // 卷积核在源操作数width维度滑动的步长 - loadData3DParamsForA.strideH = - 1; // 卷积核在源操作数height维度滑动的步长 - loadData3DParamsForA.filterW = 1; // 卷积核width - loadData3DParamsForA.filterSizeW = - false; // 是否在filterW的基础上将卷积核width增加256个元素 - loadData3DParamsForA.filterH = 1; // 卷积核height - loadData3DParamsForA.filterSizeH = - false; // 是否在filterH的基础上将卷积核height增加256个元素 - loadData3DParamsForA.dilationFilterW = 1; // 卷积核width膨胀系数 - loadData3DParamsForA.dilationFilterH = 1; // 卷积核height膨胀系数 - loadData3DParamsForA.enTranspose = - 0; // 是否启用转置功能,对整个目标矩阵进行转置 - loadData3DParamsForA.fMatrixCtrl = 0; - loadData3DParamsForA.channelSize = - kL0SizeAlign; // 源操作数的通道数。膨胀系数为1时,目的weight为filterW*filterH*channelSize - LoadData(aL0Tensor, - aL1Tensor[kL0 * baseK * mL1SizeAlign], - loadData3DParamsForA); - SetFlag(Mte1MmABEventId(abL0BufIter % 2)); - WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); - - MmadParams mmadParams; - mmadParams.m = mL1SizeAlign; - mmadParams.n = nL1SizeAlign; - mmadParams.k = kL0Size; - mmadParams.cmatrixInitVal = (kL0 == 0 && k1 == 0); - mmadParams.cmatrixSource = false; - mmadParams.unitFlag = - ((k1 == (kL1Loops - 1)) && (kL0 == (kL0Loops - 1))) ? 0b11 : 0b10; - - Mmad(cL0Tensor, aL0Tensor, bL0Tensor, mmadParams); - if ((mmadParams.m / 16) * (mmadParams.n / 16) < 10) { - PipeBarrier(); - } - SetFlag(Mte1MmABEventId(abL0BufIter % 2)); - abL0BufIter++; - } - - if (nL1 == (nL1Loops - - 1)) { // nL1最后一轮, 需要将B驻留在L1中, 用于下一轮的计算? - SetFlag( - mte21QPIds[ka]); // 反向同步, 表示L1中的A已经被mte1消费完 - } - - if (k1 == (kL1Loops - 1)) { - // ND - FixpipeParamsV220 fixParams; - fixParams.nSize = nL1SizeAlign; - fixParams.mSize = mL1SizeAlign; - fixParams.srcStride = mL1SizeAlign; - fixParams.dstStride = nSize; // mm2ResGm两行之间的间隔 - fixParams.ndNum = 1; // 输出ND - fixParams.unitFlag = 0b11; - - uint64_t mm2Offset = - (mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE) * nSize + - nL1 * N_SPLIT_SIZE; - Fixpipe(mm2ResGm[(info.loop % (constInfo.preLoadNum)) * - constInfo.bmm2ResUbSize + - mm2Offset], - cL0Tensor, - fixParams); - } - - if (mL1Loops == 2) { - cL0BufIter++; - } - } - SetFlag( - mte21KVIds[kb]); // 反向同步, 表示L1已经被mte1消费完 - } - // cL0BufIter已经不在使用 - if (mL1Loops == 1) { - cL0BufIter++; - } - } - qpL1BufIter += mL1Loops; -} -} // namespace SMLAKernel -#endif // SPARSE_FLASH_MLA_CSA_BLOCK_CUBE_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_block_vector.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_block_vector.h deleted file mode 100644 index 5008f01198..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_block_vector.h +++ /dev/null @@ -1,1517 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file sparse_flash_mla_csa_block_vector.h - * \brief - */ -#ifndef SPARSE_FLASH_MLA_CSA_BLOCK_VECTOR_H -#define SPARSE_FLASH_MLA_CSA_BLOCK_VECTOR_H - -#include "kernel_operator.h" -#include "kernel_operator_list_tensor_intf.h" -#include "kernel_tiling/kernel_tiling.h" -#include "lib/matmul_intf.h" -#include "lib/matrix/matmul/tiling.h" -#include "sparse_flash_mla_common_arch22.h" - -namespace SMLAKernel { -using AscendC::CrossCoreSetFlag; -using AscendC::CrossCoreWaitFlag; - -template -class SMLAVectorBlock { - public: - // 中间计算数据类型为float,高精度模式 - using T = float; - using KV_T = typename SMLAT::kvType; - using OUT_T = typename SMLAT::outputType; - using UPDATE_T = T; - using SINKS_T = T; - using MM1_OUT_T = float; - using MM2_OUT_T = float; - - __aicore__ inline SMLAVectorBlock(){}; - __aicore__ inline void ProcessVec0L(const RunInfo& runInfo); - __aicore__ inline void ProcessVec1L(const RunInfo& info); - __aicore__ inline void ProcessVec2L(const RunInfo& info); - __aicore__ inline void InitBuffers(TPipe* pipe); - __aicore__ inline void InitParams( - const struct ConstInfo& constInfo, - const SparseFlashMlaTilingData* __restrict tilingData); - __aicore__ inline void InitVec0GlobalTensor( - const GlobalTensor& kvMergeGm, - const GlobalTensor& oriKvGm, - const GlobalTensor& cmpKvGm, - const GlobalTensor& oriBlockTableGm, - const GlobalTensor& cmpBlockTableGm); - __aicore__ inline void InitVec1GlobalTensor( - GlobalTensor mm1ResGm, - GlobalTensor vec1ResGm, - GlobalTensor actualSeqLengthsQGm, - GlobalTensor actualSeqLengthsKVGm, - GlobalTensor topKGm, - GlobalTensor sinksGm, - GlobalTensor softmaxLseGm); - __aicore__ inline void InitVec2GlobalTensor( - GlobalTensor accumOutGm, - GlobalTensor vec2ResGm, - GlobalTensor mm2ResGm, - GlobalTensor attentionOutGm); - __aicore__ inline void AllocEventID(); - __aicore__ inline void FreeEventID(); - __aicore__ inline void CopySinksIn(); - __aicore__ inline void SliceAndContactSinksValue(uint32_t nIdx, - uint32_t dealRowCount); - __aicore__ inline void InitSoftmaxDefaultBuffer(); - // ================================Base - // Vector========================================== - __aicore__ inline void RowDivs(LocalTensor dstUb, - LocalTensor src0Ub, - LocalTensor src1Ub, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount); - __aicore__ inline void RowMuls(LocalTensor dstUb, - LocalTensor src0Ub, - LocalTensor src1Ub, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount); - // ================================Vector0========================================== - __aicore__ inline int64_t GetKeyGmOffset(int64_t realS2Idx, - const RunInfo& runInfo, - int64_t s2IdLimit); - __aicore__ inline void GetRealS2Idx(int64_t s2GmOffset, - int64_t& realS2Idx, - int64_t topkGmBaseOffset, - const RunInfo& runInfo); - __aicore__ inline void CopyInKv(int64_t& mte2Size, - int64_t mte3Size, - int64_t mergeMte3Idx, - int64_t realS2Idx1, - int64_t realS2Idx2, - const RunInfo& runInfo); - __aicore__ inline void CopyOutMrgeResult(int64_t mte2Size, - int64_t mte3Size, - int64_t s2StartGmOffset, - int64_t mergeMte3Idx, - const RunInfo& runInfo); - __aicore__ inline void CopyInSingleKv(int64_t& mte2Size, - int64_t mte3Size, - int64_t mergeMte3Idx, - int64_t realS2Idx, - int64_t keyBNBOffset, - int64_t s2IdLimit, - const RunInfo& runInfo); - // ================================Vector1========================================== - __aicore__ inline void ProcessVec1SingleBuf(const RunInfo& info, - const MSplitInfo& mSplitInfo); - __aicore__ inline void DealBmm1ResBaseBlock(const RunInfo& info, - const MSplitInfo& mSplitInfo, - uint32_t startRow, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t loopId); - __aicore__ inline void SoftmaxFlashV2Compute( - const RunInfo& info, - const MSplitInfo& mSplitInfo, - LocalTensor& mmResUb, - LocalTensor& softmaxTmpUb, - uint32_t startRow, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount); - - __aicore__ inline void ElewiseCompute(const RunInfo& info, - const LocalTensor& mmResUb, - uint32_t dealRowCount, - uint32_t columnCount); - __aicore__ inline void ProcessLse(const RunInfo& info, - const MSplitInfo& mSplitInfo); - // ================================Vecotr2========================================== - __aicore__ inline void ProcessVec2SingleBuf(const RunInfo& info, - const MSplitInfo& mSplitInfo); - __aicore__ inline void DealBmm2ResBaseBlock(const RunInfo& info, - const MSplitInfo& mSplitInfo, - uint32_t startRow, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount); - __aicore__ inline void ProcessVec2Inner(const RunInfo& info, - const MSplitInfo& mSplitInfo, - uint32_t mStartRow, - uint32_t mDealSize); - __aicore__ inline void Bmm2DataCopyOutTrans(const RunInfo& info, - LocalTensor& attenOutUb, - uint32_t wsMStart, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount); - __aicore__ inline void Bmm2ResCopyOut(const RunInfo& info, - LocalTensor& bmm2ResUb, - uint32_t wsMStart, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount); - __aicore__ inline void Bmm2CastAndCopyOut(const RunInfo& info, - LocalTensor& bmm2ResUb, - uint32_t wsMStart, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount); - __aicore__ inline void Bmm2FDDataCopyOut(const RunInfo& info, - LocalTensor& bmm2ResUb, - uint32_t wsMStart, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount); - __aicore__ inline uint64_t CalcAccumOffset(uint32_t bN2Idx, uint32_t gS1Idx); - - // BLOCK和REPEAT的字节数 - static constexpr uint64_t BYTE_BLOCK = 32UL; - static constexpr uint32_t REPEAT_BLOCK_BYTE = 256U; - // BLOCK和REPEAT的FP32元素数 - static constexpr uint32_t FP32_BLOCK_ELEMENT_NUM = BYTE_BLOCK / sizeof(float); - static constexpr uint32_t FP32_REPEAT_ELEMENT_NUM = - REPEAT_BLOCK_BYTE / sizeof(float); - // repeat stride不能超过256 - static constexpr uint32_t REPEATE_STRIDE_UP_BOUND = 256; - - private: - static constexpr bool PAGE_ATTENTION = SMLAT::pageAttention; - static constexpr int TEMPLATE_MODE = SMLAT::templateMode; - static constexpr bool FLASH_DECODE = SMLAT::flashDecode; - static constexpr SMLA_LAYOUT LAYOUT_T = SMLAT::layout; - static constexpr SMLA_LAYOUT KV_LAYOUT_T = SMLAT::kvLayout; - static constexpr bool HEAD_RATIO_ONE = SMLAT::headRatioOne; - - static constexpr uint64_t MERGE_CACHE_GM_BUF_NUM = 3; - static constexpr uint64_t SYNC_INPUT_BUF1_FLAG = 2; - static constexpr uint64_t SYNC_INPUT_BUF1_PONG_FLAG = 3; - static constexpr uint64_t SYNC_INPUT_BUF2_FLAG = 4; - static constexpr uint64_t SYNC_INPUT_BUF2_PONG_FLAG = 5; - static constexpr uint64_t SYNC_OUTPUT_BUF1_FLAG = 4; - static constexpr uint64_t SYNC_OUTPUT_BUF2_FLAG = 5; - static constexpr uint64_t SYNC_SINKS_BUF_FLAG = 6; - static constexpr uint64_t SYNC_INPUT_V0BUF_FLAG = 7; - static constexpr uint32_t INPUT1_BUFFER_OFFSET = - ConstInfo::BUFFER_SIZE_BYTE_32K; - static constexpr uint32_t INPUT2_BUFFER_OFFSET = - ConstInfo::BUFFER_SIZE_BYTE_16K; - static constexpr uint32_t SOFTMAX_TMP_BUFFER_OFFSET = - ConstInfo::BUFFER_SIZE_BYTE_1K; - static constexpr uint32_t BASE_BLOCK_MAX_ELEMENT_NUM = - ConstInfo::BUFFER_SIZE_BYTE_32K / sizeof(T); - static constexpr uint32_t BLOCK_ELEMENT_NUM = BYTE_BLOCK / sizeof(T); - static constexpr uint32_t MAX_N1_SIZE = 128U; - static constexpr T SOFTMAX_MIN_NUM = -2e38; - static constexpr SINKS_T R0 = 1.0f; - - const SparseFlashMlaTilingData* __restrict tilingData; - - uint32_t pingpongFlag = 0U; - ConstInfo constInfo = {}; - - GlobalTensor mm1ResGm; - GlobalTensor vec1ResGm; - GlobalTensor softmaxMaxGm; - GlobalTensor softmaxSumGm; - GlobalTensor sinksGm; - - GlobalTensor actualSeqLengthsQGm; - GlobalTensor actualSeqLengthsKVGm; - GlobalTensor vec2ResGm; - GlobalTensor mm2ResGm; - GlobalTensor accumOutGm; - GlobalTensor attentionOutGm; - GlobalTensor softmaxLseGm; - - GlobalTensor blkTableGm_; - GlobalTensor kvMergeGm_; - GlobalTensor keyGm_; - GlobalTensor topkGm_; - GlobalTensor oriKvGm_; - GlobalTensor cmpKvGm_; - GlobalTensor oriBlockTableGm_; - GlobalTensor cmpBlockTableGm_; - - // ================================Local - // Buffer区==================================== - TBuf<> inputBuff1; // 32K - TBuf<> inputBuff2; // 16K - TBuf<> outputBuff1; // 32K - TBuf<> outputBuff2; // 32K - - TBuf<> tmpBuff1; // 32K - TBuf<> v0ValidSizeBuff; // 8K - - TBuf<> sinksBuff; // 1K - TBuf<> sinksBrcbBuff; // 12K - - TBuf<> softmaxMaxBuff; // PRE_LOAD_NUM * 2K - TBuf<> softmaxExpBuff; // PRE_LOAD_NUM * 2K - TBuf<> softmaxSumBuff; // PRE_LOAD_NUM * 2K - TBuf<> softmaxMaxDefaultBuff; // 2K - TBuf<> softmaxSumDefaultBuff; // 2K - - LocalTensor softmaxMaxDefaultUb; - LocalTensor softmaxSumDefaultUb; - - LocalTensor softmaxMaxUb; - LocalTensor softmaxSumUb; - LocalTensor softmaxExpUb; - LocalTensor kvMergUb_; - LocalTensor v0ValidSizeUb_; - LocalTensor sinksUb; - LocalTensor sinksBrcbUb; - - uint32_t mergeMte3Idx = 0; -}; - -template -__aicore__ inline void SMLAVectorBlock::InitBuffers(TPipe* pipe) { - pipe->InitBuffer(inputBuff1, - ConstInfo::BUFFER_SIZE_BYTE_32K * 2); // 2:pingpong - pipe->InitBuffer(inputBuff2, - ConstInfo::BUFFER_SIZE_BYTE_16K * 2); // 2:pingpong - pipe->InitBuffer(outputBuff1, ConstInfo::BUFFER_SIZE_BYTE_32K); - if (constInfo.returnSoftmaxLse) { - pipe->InitBuffer(outputBuff2, ConstInfo::BUFFER_SIZE_BYTE_1K); - } - - pipe->InitBuffer(tmpBuff1, ConstInfo::BUFFER_SIZE_BYTE_32K); - pipe->InitBuffer(v0ValidSizeBuff, ConstInfo::BUFFER_SIZE_BYTE_8K); - - // M_MAX = 512/2vector = 256, 256 * sizeof(T) * N_Buffer - - pipe->InitBuffer(softmaxMaxBuff, - ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); - pipe->InitBuffer(softmaxExpBuff, - ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); - pipe->InitBuffer(softmaxSumBuff, - ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); - - pipe->InitBuffer(softmaxMaxDefaultBuff, ConstInfo::BUFFER_SIZE_BYTE_1K); - pipe->InitBuffer(softmaxSumDefaultBuff, ConstInfo::BUFFER_SIZE_BYTE_1K); - - pipe->InitBuffer(sinksBuff, MAX_N1_SIZE * sizeof(SINKS_T)); - // 分配256+N1大小内存,其中256是m轴VEC最大切块 - pipe->InitBuffer(sinksBrcbBuff, - MAX_N1_SIZE * sizeof(SINKS_T) * BLOCK_ELEMENT_NUM * 3U); - - softmaxMaxUb = softmaxMaxBuff.Get(); - softmaxSumUb = softmaxSumBuff.Get(); - softmaxExpUb = softmaxExpBuff.Get(); - - softmaxMaxDefaultUb = softmaxMaxDefaultBuff.Get(); - softmaxSumDefaultUb = softmaxSumDefaultBuff.Get(); - - kvMergUb_ = inputBuff2.Get(); - - v0ValidSizeUb_ = v0ValidSizeBuff.Get(); - - sinksUb = sinksBuff.Get(); - sinksBrcbUb = sinksBrcbBuff.Get(); -} - -template -__aicore__ inline void SMLAVectorBlock::InitParams( - const struct ConstInfo& constInfo, - const SparseFlashMlaTilingData* __restrict tilingData) { - this->constInfo = constInfo; - this->tilingData = tilingData; -} - -template -__aicore__ inline void SMLAVectorBlock::InitVec0GlobalTensor( - const GlobalTensor& kvMergeGm, - const GlobalTensor& oriKvGm, - const GlobalTensor& cmpKvGm, - const GlobalTensor& oriBlockTableGm, - const GlobalTensor& cmpBlockTableGm) { - this->kvMergeGm_ = kvMergeGm; - this->oriKvGm_ = oriKvGm; - this->cmpKvGm_ = cmpKvGm; - this->oriBlockTableGm_ = oriBlockTableGm; - this->cmpBlockTableGm_ = cmpBlockTableGm; -} - -template -__aicore__ inline void SMLAVectorBlock::InitVec1GlobalTensor( - GlobalTensor mm1ResGm, - GlobalTensor vec1ResGm, - GlobalTensor actualSeqLengthsQGm, - GlobalTensor actualSeqLengthsKVGm, - GlobalTensor topKGm, - GlobalTensor sinksGm, - GlobalTensor softmaxLseGm) { - this->mm1ResGm = mm1ResGm; - this->vec1ResGm = vec1ResGm; - this->actualSeqLengthsQGm = actualSeqLengthsQGm; - this->actualSeqLengthsKVGm = actualSeqLengthsKVGm; - this->topkGm_ = topKGm; - this->sinksGm = sinksGm; - this->softmaxLseGm = softmaxLseGm; -} - -template -__aicore__ inline void SMLAVectorBlock::InitVec2GlobalTensor( - GlobalTensor accumOutGm, - GlobalTensor vec2ResGm, - GlobalTensor mm2ResGm, - GlobalTensor attentionOutGm) { - this->accumOutGm = accumOutGm; - this->vec2ResGm = vec2ResGm; - this->mm2ResGm = mm2ResGm; - this->attentionOutGm = attentionOutGm; -} - -template -__aicore__ inline void SMLAVectorBlock::AllocEventID() { - SetFlag(SYNC_INPUT_BUF1_FLAG); - SetFlag(SYNC_INPUT_BUF1_PONG_FLAG); - SetFlag(SYNC_INPUT_BUF2_FLAG); - SetFlag(SYNC_INPUT_BUF2_PONG_FLAG); - SetFlag(SYNC_OUTPUT_BUF1_FLAG); - SetFlag(SYNC_OUTPUT_BUF2_FLAG); -} - -template -__aicore__ inline void SMLAVectorBlock::FreeEventID() { - WaitFlag(SYNC_INPUT_BUF1_FLAG); - WaitFlag(SYNC_INPUT_BUF1_PONG_FLAG); - WaitFlag(SYNC_INPUT_BUF2_FLAG); - WaitFlag(SYNC_INPUT_BUF2_PONG_FLAG); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - WaitFlag(SYNC_OUTPUT_BUF2_FLAG); -} - -template -__aicore__ inline void SMLAVectorBlock::CopySinksIn() { - DataCopyExtParams dataCopyParams; - dataCopyParams.blockCount = 1U; - dataCopyParams.blockLen = constInfo.qHeadNum * sizeof(T); - dataCopyParams.srcStride = 0U; - dataCopyParams.dstStride = 0U; - DataCopyPadExtParams padParams; - DataCopyPad(sinksUb, sinksGm, dataCopyParams, padParams); - SetFlag(SYNC_SINKS_BUF_FLAG); - WaitFlag(SYNC_SINKS_BUF_FLAG); - uint32_t repeatTimes = - (constInfo.qHeadNum + BLOCK_ELEMENT_NUM - 1U) / BLOCK_ELEMENT_NUM; - Brcb(sinksBrcbUb, sinksUb, repeatTimes, {1, BLOCK_ELEMENT_NUM}); - PipeBarrier(); - - DataCopyParams repeatParams; - repeatParams.blockCount = - 1; // 搬到有一个块超过单个vec核减分核M轴大小即可,核间切分每个vec256 - repeatParams.blockLen = constInfo.qHeadNum; - repeatParams.srcStride = 0U; - repeatParams.dstStride = 0U; - for (uint32_t i = 1U; i <= 256U / constInfo.qHeadNum; i++) { - DataCopy(sinksBrcbUb[constInfo.qHeadNum * BLOCK_ELEMENT_NUM * i], - sinksBrcbUb, - repeatParams); - } - PipeBarrier(); -} - -template -__aicore__ inline void SMLAVectorBlock::SliceAndContactSinksValue( - uint32_t nIdx, - uint32_t dealRowCount) { - // WholeReduceMax接口中repeatTimes支持范围(0,255),因此需要分多次调用WholeReduceMax,每次repeatTime=128 - uint32_t repeatTimesOnce = 128; - uint32_t loopTimes = (dealRowCount + repeatTimesOnce - 1) / repeatTimesOnce; - uint32_t repeatTimes = repeatTimesOnce; - - for (uint32_t loop = 0; loop < loopTimes; ++loop) { - if (loop == loopTimes - 1) { - repeatTimes = dealRowCount - loop * repeatTimesOnce; - } - WholeReduceMax( - softmaxMaxDefaultUb[loop * repeatTimesOnce], - sinksBrcbUb[(nIdx + loop * repeatTimesOnce) * BLOCK_ELEMENT_NUM], - BLOCK_ELEMENT_NUM * BLOCK_ELEMENT_NUM, - repeatTimes, - 1, - 0, - 1, - ReduceOrder::ORDER_ONLY_VALUE); - PipeBarrier(); - } -} - -template -__aicore__ inline void SMLAVectorBlock::InitSoftmaxDefaultBuffer() { - CopySinksIn(); - Duplicate(softmaxMaxDefaultUb, - SOFTMAX_MIN_NUM, - SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)); - Duplicate(softmaxSumDefaultUb, R0, SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)); -} - -template -__aicore__ inline void SMLAVectorBlock::ElewiseCompute( - const RunInfo& info, - const LocalTensor& mmResUb, - uint32_t dealRowCount, - uint32_t columnCount) { - Muls(mmResUb, - mmResUb, - static_cast(tilingData->baseParams.softmaxScale), - dealRowCount * columnCount); -} - -template -__aicore__ inline void SMLAVectorBlock::ProcessLse( - const RunInfo& info, - const MSplitInfo& mSplitInfo) { - if (mSplitInfo.vecDealM == 0) { - return; - } - uint64_t lseOffset; - if (constInfo.outputLayout == SMLA_LAYOUT::TND) { - uint32_t tBase = actualSeqLengthsQGm.GetValue(info.bIdx); - lseOffset = - (tBase + info.s1Idx) * constInfo.gSize + // T轴、s1轴偏移 - info.n2IdxReal * constInfo.qSeqSize * constInfo.gSize; // N2轴偏移 - } else if (constInfo.outputLayout == SMLA_LAYOUT::BSND) { - lseOffset = - info.bIdx * constInfo.qSeqSize * constInfo.kvHeadNum * - constInfo.gSize + // B轴偏移 - info.n2IdxReal * constInfo.qSeqSize * constInfo.gSize + // N2轴偏移 - info.s1Idx * constInfo.gSize; // S1轴偏移 - } - lseOffset = lseOffset + mSplitInfo.nBufferStartM + mSplitInfo.vecStartM; - uint32_t baseOffset = mSplitInfo.nBufferStartM / 2; - uint32_t outIdx = info.loop % (constInfo.preLoadNum); - uint32_t softmaxOffset = - outIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset; - auto sumTensor = softmaxSumUb[softmaxOffset]; - auto maxTensor = softmaxMaxUb[softmaxOffset]; - auto outLSETensor = outputBuff2.Get(); - DataCopyExtParams dataCopyParams; - dataCopyParams.blockCount = 1; - dataCopyParams.blockLen = mSplitInfo.vecDealM * sizeof(T); - dataCopyParams.srcStride = 0; - dataCopyParams.dstStride = 0; - - WaitFlag(SYNC_OUTPUT_BUF2_FLAG); - PipeBarrier(); - Log(outLSETensor, sumTensor, mSplitInfo.vecDealM); - PipeBarrier(); - Add(outLSETensor, outLSETensor, maxTensor, mSplitInfo.vecDealM); - SetFlag(SYNC_OUTPUT_BUF2_FLAG); - WaitFlag(SYNC_OUTPUT_BUF2_FLAG); - - DataCopyPad(softmaxLseGm[lseOffset], outLSETensor, dataCopyParams); - SetFlag(SYNC_OUTPUT_BUF2_FLAG); -} - -template -__aicore__ inline void SMLAVectorBlock::SoftmaxFlashV2Compute( - const RunInfo& info, - const MSplitInfo& mSplitInfo, - LocalTensor& mmResUb, - LocalTensor& softmaxTmpUb, - uint32_t startRow, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount) { - LocalTensor inSumTensor; - LocalTensor inMaxTensor; - uint32_t baseOffset = mSplitInfo.nBufferStartM / 2 + startRow; - uint32_t outIdx = info.loop % (constInfo.preLoadNum); - uint32_t softmaxOutOffset = - outIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset; - if (info.isFirstSInnerLoop) { - inMaxTensor = softmaxMaxDefaultUb[startRow]; - inSumTensor = softmaxSumDefaultUb; - } else { - uint32_t inIdx = (info.loop - 1) % (constInfo.preLoadNum); - inMaxTensor = softmaxMaxUb[inIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + - baseOffset]; - inSumTensor = softmaxSumUb[inIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + - baseOffset]; - } - if (actualColumnCount != 0) { - SoftMaxShapeInfo srcShape{ - dealRowCount, columnCount, dealRowCount, actualColumnCount}; - SoftMaxTiling newTiling = SoftMaxFlashV2TilingFunc( - srcShape, sizeof(T), sizeof(T), softmaxTmpUb.GetSize(), true, false); - SoftmaxFlashV2( - mmResUb, - softmaxSumUb[softmaxOutOffset], - softmaxMaxUb[softmaxOutOffset], - mmResUb, - softmaxExpUb[softmaxOutOffset], - inSumTensor, - inMaxTensor, - softmaxTmpUb, - newTiling, - srcShape); - } else { - uint32_t dealRowCountAlign = - SMLAAlign(dealRowCount, FP32_BLOCK_ELEMENT_NUM); - DataCopy(softmaxSumUb[softmaxOutOffset], inSumTensor, dealRowCountAlign); - PipeBarrier(); - DataCopy(softmaxMaxUb[softmaxOutOffset], inMaxTensor, dealRowCountAlign); - } -} - -template -__aicore__ inline void SMLAVectorBlock::DealBmm1ResBaseBlock( - const RunInfo& info, - const MSplitInfo& mSplitInfo, - uint32_t startRow, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t loopId) { - uint32_t computeSize = dealRowCount * columnCount; - uint64_t inOutGmOffset = - (info.loop % constInfo.preLoadNum) * constInfo.mmResUbSize + - (mSplitInfo.nBufferStartM + mSplitInfo.vecStartM + startRow) * - columnCount; - LocalTensor mmResUb = inputBuff1.Get(); - mmResUb = mmResUb[pingpongFlag * INPUT1_BUFFER_OFFSET / sizeof(MM1_OUT_T)]; - WaitFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); - - DataCopy(mmResUb, mm1ResGm[inOutGmOffset], computeSize); - SetFlag(SYNC_INPUT_BUF1_FLAG); - WaitFlag(SYNC_INPUT_BUF1_FLAG); - - ElewiseCompute(info, mmResUb, dealRowCount, columnCount); - - PipeBarrier(); - LocalTensor tmpAFloorUb = tmpBuff1.Get(); - LocalTensor softmaxTmpUb = - tmpAFloorUb.template ReinterpretCast(); - - SoftmaxFlashV2Compute(info, - mSplitInfo, - mmResUb, - softmaxTmpUb, - startRow, - dealRowCount, - columnCount, - info.actualSingleProcessSInnerSize); - - PipeBarrier(); - LocalTensor tmpMMResCastTensor = outputBuff1.Get(); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - - Cast( - tmpMMResCastTensor, mmResUb, AscendC::RoundMode::CAST_ROUND, computeSize); - SetFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); - pingpongFlag ^= 1; // pingpong 0 1 切换 - - SetFlag(SYNC_OUTPUT_BUF1_FLAG); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - DataCopy(vec1ResGm[inOutGmOffset], tmpMMResCastTensor, computeSize); - SetFlag(SYNC_OUTPUT_BUF1_FLAG); -} - -template -__aicore__ inline void SMLAVectorBlock::ProcessVec1SingleBuf( - const RunInfo& info, - const MSplitInfo& mSplitInfo) { - if (mSplitInfo.vecDealM == 0) { - return; - } - uint32_t mSplitSize = info.actualSingleProcessSInnerSize == 0 - ? 16 - : BASE_BLOCK_MAX_ELEMENT_NUM / - info.actualSingleProcessSInnerSizeAlign; - // 1. 向下8对齐是因为UB操作至少32B - // 2. info.actualSingleProcessSInnerSizeAlign最大512, - // mSplitSize可以确保最小为16 - mSplitSize = mSplitSize / 8 * 8; - - if (mSplitSize > mSplitInfo.vecDealM) { - mSplitSize = mSplitInfo.vecDealM; - } - uint32_t loopCount = (mSplitInfo.vecDealM + mSplitSize - 1) / mSplitSize; - uint32_t tailSplitSize = mSplitInfo.vecDealM - (loopCount - 1) * mSplitSize; - - uint32_t sinkHeadIdx = (info.n2IdxReal * constInfo.gSize + - mSplitInfo.nBufferStartM + mSplitInfo.vecStartM) % - constInfo.qHeadNum; - SliceAndContactSinksValue(sinkHeadIdx, mSplitInfo.vecDealM); - - for (uint32_t i = 0, dealSize = mSplitSize; i < loopCount; i++) { - if (i == (loopCount - 1)) { - dealSize = tailSplitSize; - } - DealBmm1ResBaseBlock(info, - mSplitInfo, - i * mSplitSize, - dealSize, - info.actualSingleProcessSInnerSizeAlign, - i); - } -} - -template -__aicore__ inline void SMLAVectorBlock::GetRealS2Idx( - int64_t s2GmOffset, - int64_t& realS2Idx, - int64_t topkGmBaseOffset, - const RunInfo& runInfo) { - int64_t cmpS2Offset = s2GmOffset; - int64_t topkGmIdx = cmpS2Offset / constInfo.sparseBlockSize; - if (unlikely(topkGmIdx >= constInfo.sparseBlockCount || - s2GmOffset >= runInfo.v0S2DealSize)) { - realS2Idx = -1; - return; - } - realS2Idx = topkGm_.GetValue(topkGmBaseOffset + topkGmIdx) * - static_cast(constInfo.sparseBlockSize) + - static_cast(cmpS2Offset % constInfo.sparseBlockSize); -} - -template -__aicore__ inline int64_t SMLAVectorBlock::GetKeyGmOffset( - int64_t realS2Idx, - const RunInfo& runInfo, - int64_t s2IdLimit) { - if (realS2Idx < 0 || realS2Idx >= s2IdLimit) { - return -1; - } - int64_t realKeyGmOffset = 0; - if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { - int64_t blkTableIdx = realS2Idx / constInfo.paCmpBlockSize; - int64_t blkTableOffset = realS2Idx % constInfo.paCmpBlockSize; - realKeyGmOffset = - cmpBlockTableGm_.GetValue( - runInfo.bIdx * constInfo.cmpMaxBlockNumPerBatch + blkTableIdx) * - static_cast(constInfo.cmpKvStride0) + - blkTableOffset * static_cast(constInfo.kvHeadNum) * - static_cast(constInfo.headDim); - - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { - int64_t batchStride = (constInfo.cmpKvStride0 == 0) - ? static_cast(constInfo.cmpSeqSize) * - static_cast(constInfo.kvHeadNum) * - static_cast(constInfo.headDim) - : static_cast(constInfo.cmpKvStride0); - realKeyGmOffset = static_cast(runInfo.bIdx) * batchStride + - realS2Idx * static_cast(constInfo.kvHeadNum) * - static_cast(constInfo.headDim) + - static_cast(runInfo.n2Idx) * - static_cast(constInfo.headDim); - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { - realKeyGmOffset = runInfo.tensorCmpBOffset + - realS2Idx * static_cast(constInfo.kvHeadNum) * - static_cast(constInfo.headDim) + - static_cast(runInfo.n2Idx) * - static_cast(constInfo.headDim); - } - return realKeyGmOffset; -} - -template -__aicore__ inline void SMLAVectorBlock::CopyInSingleKv( - int64_t& mte2Size, - int64_t mte3Size, - int64_t mergeMte3Idx, - int64_t realS2Idx, - int64_t keyBNBOffset, - int64_t s2IdLimit, - const RunInfo& runInfo) { - if (keyBNBOffset < 0) { - return; - } - int64_t validS2Count = (realS2Idx + constInfo.sparseBlockSize > s2IdLimit - ? s2IdLimit - realS2Idx - : constInfo.sparseBlockSize); - DataCopyExtParams intriParams; - intriParams.blockLen = validS2Count * constInfo.headDim * sizeof(KV_T); - intriParams.blockCount = 1; - intriParams.dstStride = 0; - intriParams.srcStride = 0; - DataCopyPadExtParams padParams{false, 0, 0, 0}; - DataCopyPad(kvMergUb_[mergeMte3Idx % 2 * INPUT2_BUFFER_OFFSET / sizeof(KV_T) + - (mte2Size - mte3Size) * constInfo.headDim], - cmpKvGm_[keyBNBOffset], - intriParams, - padParams); - mte2Size += validS2Count; -} - -template -__aicore__ inline void SMLAVectorBlock::CopyInKv( - int64_t& mte2Size, - int64_t mte3Size, - int64_t mergeMte3Idx, - int64_t realS2Idx1, - int64_t realS2Idx2, - const RunInfo& runInfo) { - int64_t s2IdLimit = runInfo.cmpS2IdLimit; - - int64_t keyOffset1 = GetKeyGmOffset(realS2Idx1, runInfo, s2IdLimit); - int64_t keyOffset2 = GetKeyGmOffset(realS2Idx2, runInfo, s2IdLimit); - if (unlikely(keyOffset1 < 0 && keyOffset2 < 0)) { - return; - } - - int64_t keySrcStride = 0; - keySrcStride = ((keyOffset1 > keyOffset2 ? (keyOffset1 - keyOffset2) - : (keyOffset2 - keyOffset1)) - - constInfo.sparseBlockSize * constInfo.headDim) * - sizeof(KV_T); - if (unlikely(keySrcStride >= INT32_MAX || keySrcStride < 0 || - realS2Idx1 + constInfo.sparseBlockSize >= s2IdLimit || - realS2Idx2 + constInfo.sparseBlockSize >= s2IdLimit)) { - // stride溢出、stride为负数、s2超长等异常场景,还原成2条搬运指令 - // 因为需要拷贝两块 - CopyInSingleKv(mte2Size, - mte3Size, - mergeMte3Idx, - realS2Idx1, - keyOffset1, - s2IdLimit, - runInfo); - CopyInSingleKv(mte2Size, - mte3Size, - mergeMte3Idx, - realS2Idx2, - keyOffset2, - s2IdLimit, - runInfo); - } else { - DataCopyExtParams intriParams; - intriParams.blockLen = - constInfo.sparseBlockSize * constInfo.headDim * sizeof(KV_T); - intriParams.blockCount = (keyOffset1 >= 0) + (keyOffset2 >= 0); - intriParams.dstStride = 0; - intriParams.srcStride = keySrcStride; - DataCopyPadExtParams padParams{false, 0, 0, 0}; - - int64_t startGmOffset = keyOffset1 > -1 ? keyOffset1 : keyOffset2; - if (keyOffset2 > -1 && keyOffset2 < keyOffset1) { - startGmOffset = keyOffset2; - } - DataCopyPad( - kvMergUb_[mergeMte3Idx % 2 * INPUT2_BUFFER_OFFSET / sizeof(KV_T) + - (mte2Size - mte3Size) * constInfo.headDim], - cmpKvGm_[startGmOffset], - intriParams, - padParams); - mte2Size += - ((keyOffset1 > -1) + (keyOffset2 > -1)) * constInfo.sparseBlockSize; - } -} - -template -__aicore__ inline void SMLAVectorBlock::CopyOutMrgeResult( - int64_t mte2Size, - int64_t mte3Size, - int64_t s2GmStartOffset, - int64_t mergeMte3Idx, - const RunInfo& runInfo) { - if (mte2Size <= mte3Size) { - return; - } - SetFlag(mergeMte3Idx % 2 + - SYNC_INPUT_BUF2_FLAG); - WaitFlag(mergeMte3Idx % 2 + - SYNC_INPUT_BUF2_FLAG); - - DataCopyExtParams dataCopyParams; - dataCopyParams.blockCount = mte2Size - mte3Size; - dataCopyParams.blockLen = constInfo.headDim * sizeof(KV_T); - dataCopyParams.srcStride = 0; - dataCopyParams.dstStride = 0; - - DataCopyPad(kvMergeGm_[runInfo.cmpLoop % MERGE_CACHE_GM_BUF_NUM * 512 * 512 + - (s2GmStartOffset + mte3Size) * constInfo.headDim], - kvMergUb_[mergeMte3Idx % 2 * INPUT2_BUFFER_OFFSET / sizeof(KV_T)], - dataCopyParams); -} - -// b s1 k -template -__aicore__ inline void SMLAVectorBlock::ProcessVec0L( - const RunInfo& runInfo) { - int64_t s2ProcessSize = runInfo.v0S2DealSize; - int64_t s2Pair = CeilDiv(s2ProcessSize, 2 * constInfo.sparseBlockSize); - int64_t topkGmBaseOffset = runInfo.topKBaseOffset + runInfo.v0S2Start; - int64_t mte2Size = 0; - int64_t mte3Size = 0; - int64_t s2IdxArray0 = -1; - int64_t s2IdxArray1 = -1; - bool needWaitMte3ToMte2 = true; - int64_t s2SplitPoint = SMLAAlign(s2Pair, 2) * constInfo.sparseBlockSize; - int64_t s2GmStartOffset = GetSubBlockIdx() == 0 ? 0 : s2SplitPoint; - int64_t s2GmLimit = GetSubBlockIdx() == 0 ? s2SplitPoint : s2ProcessSize; - if (s2GmLimit > s2ProcessSize) { - s2GmLimit = s2ProcessSize; - } - // 处理两个基本块 - for (int64_t s2GmOffsetArray = s2GmStartOffset; s2GmOffsetArray < s2GmLimit; - s2GmOffsetArray += 2 * constInfo.sparseBlockSize) { - if (needWaitMte3ToMte2) { - WaitFlag(mergeMte3Idx % 2 + - SYNC_INPUT_BUF2_FLAG); - needWaitMte3ToMte2 = false; - } - GetRealS2Idx(s2GmOffsetArray, s2IdxArray0, topkGmBaseOffset, runInfo); - if (unlikely(s2IdxArray0 < 0)) { - CopyOutMrgeResult( - mte2Size, mte3Size, s2GmStartOffset, mergeMte3Idx, runInfo); - SetFlag(mergeMte3Idx % 2 + - SYNC_INPUT_BUF2_FLAG); - mergeMte3Idx++; - break; - } - GetRealS2Idx(s2GmOffsetArray + constInfo.sparseBlockSize, - s2IdxArray1, - topkGmBaseOffset, - runInfo); - CopyInKv( - mte2Size, mte3Size, mergeMte3Idx, s2IdxArray0, s2IdxArray1, runInfo); - if ((mte2Size - mte3Size + 2 * constInfo.sparseBlockSize > 16) || - s2GmOffsetArray + 2 * constInfo.sparseBlockSize >= s2GmLimit) { - CopyOutMrgeResult( - mte2Size, mte3Size, s2GmStartOffset, mergeMte3Idx, runInfo); - mte3Size = mte2Size; - SetFlag(mergeMte3Idx % 2 + - SYNC_INPUT_BUF2_FLAG); - mergeMte3Idx++; - needWaitMte3ToMte2 = true; - } - } - return; -} - -template -__aicore__ inline void SMLAVectorBlock::ProcessVec1L( - const RunInfo& info) { - uint32_t nBufferLoopTimes = - (info.actMBaseSize + constInfo.nBufferMBaseSize - 1) / - constInfo.nBufferMBaseSize; - uint32_t nBufferTail = - info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; - for (uint32_t i = 0; i < nBufferLoopTimes; i++) { - MSplitInfo mSplitInfo; - mSplitInfo.nBufferIdx = i; - mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; - mSplitInfo.nBufferDealM = - (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; - - mSplitInfo.vecDealM = - (mSplitInfo.nBufferDealM <= 16) - ? mSplitInfo.nBufferDealM - : (((mSplitInfo.nBufferDealM + 15) / 16 + 1) / 2 * 16); - mSplitInfo.vecStartM = 0; - if (GetBlockIdx() % 2 == 1) { - mSplitInfo.vecStartM = mSplitInfo.vecDealM; - mSplitInfo.vecDealM = mSplitInfo.nBufferDealM - mSplitInfo.vecDealM; - } - - if constexpr (HEAD_RATIO_ONE) { - CrossCoreWaitFlag( - constInfo.syncC1V1); - } else { - CrossCoreWaitFlag(constInfo.syncC1V1); - } - // vec1 compute - ProcessVec1SingleBuf(info, mSplitInfo); - CrossCoreSetFlag(constInfo.syncV1C2); - - // move lse for flash decode or FA - if (constInfo.returnSoftmaxLse && - info.s2Idx == info.curSInnerLoopTimes - 1) { - ProcessLse(info, mSplitInfo); - } - } -} - -template -__aicore__ inline uint64_t SMLAVectorBlock::CalcAccumOffset( - uint32_t bN2Idx, - uint32_t gS1Idx) { - return 0; -} - -template -__aicore__ inline void SMLAVectorBlock::ProcessVec2SingleBuf( - const RunInfo& info, - const MSplitInfo& mSplitInfo) { - if (mSplitInfo.vecDealM == 0) { - return; - } - - ProcessVec2Inner(info, mSplitInfo, 0, mSplitInfo.vecDealM); -} - -template -__aicore__ inline void SMLAVectorBlock::ProcessVec2L( - const RunInfo& info) { - uint32_t nBufferLoopTimes = - (info.actMBaseSize + constInfo.nBufferMBaseSize - 1) / - constInfo.nBufferMBaseSize; - uint32_t nBufferTail = - info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; - for (uint32_t i = 0; i < nBufferLoopTimes; i++) { - MSplitInfo mSplitInfo; - mSplitInfo.nBufferIdx = i; - mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; - mSplitInfo.nBufferDealM = - (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; - - mSplitInfo.vecDealM = - (mSplitInfo.nBufferDealM <= 16) - ? mSplitInfo.nBufferDealM - : (((mSplitInfo.nBufferDealM + 15) / 16 + 1) / 2 * 16); - mSplitInfo.vecStartM = 0; - if (GetBlockIdx() % 2 == 1) { - mSplitInfo.vecStartM = mSplitInfo.vecDealM; - mSplitInfo.vecDealM = mSplitInfo.nBufferDealM - mSplitInfo.vecDealM; - } - if constexpr (HEAD_RATIO_ONE) { - CrossCoreWaitFlag( - constInfo.syncC2V2); - } else { - CrossCoreWaitFlag(constInfo.syncC2V2); - } - ProcessVec2SingleBuf(info, mSplitInfo); - } -} - -template -__aicore__ inline void SMLAVectorBlock::ProcessVec2Inner( - const RunInfo& info, - const MSplitInfo& mSplitInfo, - uint32_t mStartRow, - uint32_t mDealSize) { - uint32_t mSplitSize = BASE_BLOCK_MAX_ELEMENT_NUM / constInfo.headDim; - if (mSplitSize > mDealSize) { - mSplitSize = mDealSize; - } - - uint32_t loopCount = (mDealSize + mSplitSize - 1) / mSplitSize; - uint32_t tailSplitSize = mDealSize - (loopCount - 1) * mSplitSize; - for (uint32_t i = 0, dealSize = mSplitSize; i < loopCount; i++) { - if (i == (loopCount - 1)) { - dealSize = tailSplitSize; - } - DealBmm2ResBaseBlock(info, - mSplitInfo, - i * mSplitSize + mStartRow, - dealSize, - constInfo.headDim, - constInfo.headDim); - } -} - -template -__aicore__ inline void SMLAVectorBlock::Bmm2FDDataCopyOut( - const RunInfo& info, - LocalTensor& bmm2ResUb, - uint32_t wsMStart, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount) { - LocalTensor tmp = outputBuff1.Get(); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - DataCopy(tmp, bmm2ResUb, columnCount * dealRowCount); - SetFlag(SYNC_OUTPUT_BUF1_FLAG); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - uint64_t accumTmpOutNum = CalcAccumOffset(info.bIdx, info.gS1Idx); - uint64_t offset = accumTmpOutNum * constInfo.kvHeadNum * constInfo.mBaseSize * - constInfo.headDim + // taskoffset - info.tndCoreStartKVSplitPos * constInfo.kvHeadNum * - constInfo.mBaseSize * constInfo.headDim + // 份数offset - wsMStart * actualColumnCount; // m轴offset - GlobalTensor dst = accumOutGm[offset]; - if (info.actualSingleProcessSInnerSize == 0) { - DataCopyExtParams dataCopyParams; - dataCopyParams.blockCount = dealRowCount; - dataCopyParams.blockLen = actualColumnCount * sizeof(T); - dataCopyParams.srcStride = - (columnCount - actualColumnCount) / (BYTE_BLOCK / sizeof(T)); - dataCopyParams.dstStride = 0; - DataCopyPad(dst, tmp, dataCopyParams); - } else { - matmul::InitOutput( - dst, dealRowCount * actualColumnCount, ConstInfo::FLOAT_ZERO); - } - SetFlag(SYNC_OUTPUT_BUF1_FLAG); -} - -template -__aicore__ inline void SMLAVectorBlock::Bmm2DataCopyOutTrans( - const RunInfo& info, - LocalTensor& attenOutUb, - uint32_t wsMStart, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount) { - DataCopyExtParams dataCopyParams; - dataCopyParams.blockCount = dealRowCount; - dataCopyParams.blockLen = actualColumnCount * sizeof(OUT_T); - dataCopyParams.srcStride = - (columnCount - actualColumnCount) / (BYTE_BLOCK / sizeof(OUT_T)); - dataCopyParams.dstStride = 0; - DataCopyPad( - attentionOutGm[info.attenOutOffset + wsMStart * actualColumnCount], - attenOutUb, - dataCopyParams); - return; -} - -template -__aicore__ inline void SMLAVectorBlock::Bmm2CastAndCopyOut( - const RunInfo& info, - LocalTensor& bmm2ResUb, - uint32_t wsMStart, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount) { - LocalTensor tmpBmm2ResCastTensor = outputBuff1.Get(); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - if constexpr (IsSameType::value) { // bf16 采取四舍六入五成双模式 - Cast(tmpBmm2ResCastTensor, - bmm2ResUb, - AscendC::RoundMode::CAST_RINT, - dealRowCount * columnCount); - } else { - Cast(tmpBmm2ResCastTensor, - bmm2ResUb, - AscendC::RoundMode::CAST_ROUND, - dealRowCount * columnCount); - } - - SetFlag(SYNC_OUTPUT_BUF1_FLAG); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - Bmm2DataCopyOutTrans(info, - tmpBmm2ResCastTensor, - wsMStart, - dealRowCount, - columnCount, - actualColumnCount); - SetFlag(SYNC_OUTPUT_BUF1_FLAG); -} - -template -__aicore__ inline void SMLAVectorBlock::Bmm2ResCopyOut( - const RunInfo& info, - LocalTensor& bmm2ResUb, - uint32_t wsMStart, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount) { - if constexpr (FLASH_DECODE) { - if (info.tndIsS2SplitCore) { - Bmm2FDDataCopyOut(info, - bmm2ResUb, - wsMStart, - dealRowCount, - columnCount, - actualColumnCount); - } else { - Bmm2CastAndCopyOut(info, - bmm2ResUb, - wsMStart, - dealRowCount, - columnCount, - actualColumnCount); - } - } else { - Bmm2CastAndCopyOut(info, - bmm2ResUb, - wsMStart, - dealRowCount, - columnCount, - actualColumnCount); - } -} - -template -__aicore__ inline void SMLAVectorBlock::DealBmm2ResBaseBlock( - const RunInfo& info, - const MSplitInfo& mSplitInfo, - uint32_t startRow, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount) { - uint32_t vec2ComputeSize = dealRowCount * columnCount; - uint32_t mStart = mSplitInfo.nBufferStartM + mSplitInfo.vecStartM + startRow; - uint64_t srcGmOffset = - (info.loop % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + - mStart * columnCount; - LocalTensor tmpBmm2ResUb = inputBuff1.Get(); - tmpBmm2ResUb = - tmpBmm2ResUb[pingpongFlag * INPUT1_BUFFER_OFFSET / sizeof(MM2_OUT_T)]; - WaitFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); - DataCopy(tmpBmm2ResUb, mm2ResGm[srcGmOffset], vec2ComputeSize); - - SetFlag(SYNC_INPUT_BUF1_FLAG); - WaitFlag(SYNC_INPUT_BUF1_FLAG); - - LocalTensor bmm2ResUb = tmpBuff1.Get(); - bmm2ResUb.SetSize(vec2ComputeSize); - DataCopy(bmm2ResUb, tmpBmm2ResUb, vec2ComputeSize); - SetFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); - pingpongFlag ^= 1; // pingpong 0 1切换 - - uint32_t inOutBaseOffset = mStart * columnCount; - uint32_t baseOffset = mSplitInfo.nBufferStartM / 2 + startRow; - - if constexpr (!HEAD_RATIO_ONE) { - if (!info.isFirstSInnerLoop) { - event_t eventIdMte2WaitMte3 = static_cast( - GetTPipePtr()->FetchEventID(HardEvent::MTE3_MTE2)); - SetFlag(eventIdMte2WaitMte3); - WaitFlag(eventIdMte2WaitMte3); - - LocalTensor bmm2ResPreUb = inputBuff1.Get(); - bmm2ResPreUb = - bmm2ResPreUb[pingpongFlag * INPUT1_BUFFER_OFFSET / sizeof(MM2_OUT_T)]; - WaitFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); - - uint64_t vec2ResGmOffset = - ((info.loop - 1) % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + - inOutBaseOffset; - DataCopy(bmm2ResPreUb, vec2ResGm[vec2ResGmOffset], vec2ComputeSize); - - SetFlag(SYNC_INPUT_BUF1_FLAG); - WaitFlag(SYNC_INPUT_BUF1_FLAG); - - uint32_t idx = info.loop % (constInfo.preLoadNum); - LocalTensor expUb = v0ValidSizeBuff.Get()[384]; - Brcb(expUb, - softmaxExpUb[idx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + - baseOffset], - (dealRowCount + 7) / 8, - {1, 8}); - PipeBarrier(); - - RowMuls(bmm2ResPreUb, - bmm2ResPreUb, - expUb, - dealRowCount, - columnCount, - actualColumnCount); - AscendC::PipeBarrier(); - Add(bmm2ResUb, bmm2ResUb, bmm2ResPreUb, vec2ComputeSize); - AscendC::PipeBarrier(); - - SetFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); - pingpongFlag ^= 1; - } - - if (info.isLastS2Loop) { - uint32_t idx = info.loop % (constInfo.preLoadNum); - LocalTensor tmpSumUb = v0ValidSizeBuff.Get()[384]; - Brcb(tmpSumUb, - softmaxSumUb[idx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + - baseOffset], - (dealRowCount + 7) / 8, - {1, 8}); - PipeBarrier(); - RowDivs(bmm2ResUb, - bmm2ResUb, - tmpSumUb, - dealRowCount, - columnCount, - actualColumnCount); - PipeBarrier(); - Bmm2ResCopyOut(info, - bmm2ResUb, - mStart, - dealRowCount, - columnCount, - actualColumnCount); - } else { - LocalTensor outUb = outputBuff1.Get(); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - DataCopy(outUb, bmm2ResUb, dealRowCount * columnCount); - SetFlag(SYNC_OUTPUT_BUF1_FLAG); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - uint64_t vec2ResGmOffset = - (info.loop % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + - inOutBaseOffset; - DataCopy(vec2ResGm[vec2ResGmOffset], outUb, vec2ComputeSize); - SetFlag(SYNC_OUTPUT_BUF1_FLAG); - } - } else { - // 除第一个循环外,均需要更新中间计算结果 - if (!info.isFirstSInnerLoop) { - event_t eventIdMte2WaitMte3 = static_cast( - GetTPipePtr()->FetchEventID(HardEvent::MTE3_MTE2)); - SetFlag(eventIdMte2WaitMte3); - WaitFlag(eventIdMte2WaitMte3); - - LocalTensor bmm2ResPreUb = inputBuff1.Get(); - bmm2ResPreUb = - bmm2ResPreUb[pingpongFlag * INPUT1_BUFFER_OFFSET / sizeof(MM2_OUT_T)]; - WaitFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); - - uint64_t accumGmOffset = - ((info.loop - 1) % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + - inOutBaseOffset; - DataCopy(bmm2ResPreUb, mm2ResGm[accumGmOffset], vec2ComputeSize); - - SetFlag(SYNC_INPUT_BUF1_FLAG); - WaitFlag(SYNC_INPUT_BUF1_FLAG); - - uint32_t idx = info.loop % (constInfo.preLoadNum); - LocalTensor expUb = - v0ValidSizeBuff.Get()[384]; // sumUb用临时内存 16 * 32B = 512B - Brcb(expUb, - softmaxExpUb[idx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + - baseOffset], - (dealRowCount + 7) / 8, - {1, 8}); - PipeBarrier(); - - RowMuls(bmm2ResPreUb, - bmm2ResPreUb, - expUb, - dealRowCount, - columnCount, - actualColumnCount); - AscendC::PipeBarrier(); - Add(bmm2ResUb, bmm2ResUb, bmm2ResPreUb, vec2ComputeSize); - AscendC::PipeBarrier(); - - SetFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); - pingpongFlag ^= 1; // pingpong 0 1 切换 - } - - // 最后一次输出计算结果,否则将中间结果暂存至workspace - if (info.isLastS2Loop) { - uint32_t idx = info.loop % (constInfo.preLoadNum); - LocalTensor tmpSumUb = - v0ValidSizeBuff.Get()[384]; // sumUb用临时内存 16 * 32B = 512B - Brcb(tmpSumUb, - softmaxSumUb[idx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + - baseOffset], - (dealRowCount + 7) / 8, - {1, 8}); - PipeBarrier(); - RowDivs(bmm2ResUb, - bmm2ResUb, - tmpSumUb, - dealRowCount, - columnCount, - actualColumnCount); - PipeBarrier(); - Bmm2ResCopyOut(info, - bmm2ResUb, - mStart, - dealRowCount, - columnCount, - actualColumnCount); - } else if (!info.isFirstSInnerLoop) { - LocalTensor outUb = outputBuff1.Get(); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - DataCopy(outUb, bmm2ResUb, dealRowCount * columnCount); - SetFlag(SYNC_OUTPUT_BUF1_FLAG); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - uint64_t accumGmOffset = - (info.loop % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + - inOutBaseOffset; - DataCopy(mm2ResGm[accumGmOffset], outUb, vec2ComputeSize); - SetFlag(SYNC_OUTPUT_BUF1_FLAG); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - SetFlag(SYNC_OUTPUT_BUF1_FLAG); - } - } -} - -template -__aicore__ inline void SMLAVectorBlock::RowDivs( - LocalTensor dstUb, - LocalTensor src0Ub, - LocalTensor src1Ub, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount) { - // divs by row, 每行的元素除以相同的元素 - // dstUb[i, (j * 8) : (j * 8 + 7)] = src0Ub[i, (j * 8) : (j * 8 + 7)] / - // src1Ub[i, 0 : 7] src0Ub:[dealRowCount, columnCount], src1Ub:[dealRowCount, - // FP32_BLOCK_ELEMENT_NUM] dstUb:[dealRowCount, columnCount] - uint32_t dtypeMask = FP32_REPEAT_ELEMENT_NUM; - uint32_t dLoop = actualColumnCount / dtypeMask; - uint32_t dRemain = actualColumnCount % dtypeMask; - - BinaryRepeatParams repeatParamsDiv; - repeatParamsDiv.src0BlkStride = 1; - repeatParamsDiv.src1BlkStride = 0; - repeatParamsDiv.dstBlkStride = 1; - repeatParamsDiv.src0RepStride = columnCount / FP32_BLOCK_ELEMENT_NUM; - repeatParamsDiv.src1RepStride = 1; - repeatParamsDiv.dstRepStride = columnCount / FP32_BLOCK_ELEMENT_NUM; - uint32_t columnRepeatCount = dLoop; - if (columnRepeatCount <= dealRowCount) { - uint32_t offset = 0; - for (uint32_t i = 0; i < dLoop; i++) { - Div(dstUb[offset], - src0Ub[offset], - src1Ub, - dtypeMask, - dealRowCount, - repeatParamsDiv); - offset += dtypeMask; - } - } else { - BinaryRepeatParams columnRepeatParams; - columnRepeatParams.src0BlkStride = 1; - columnRepeatParams.src1BlkStride = 0; - columnRepeatParams.dstBlkStride = 1; - columnRepeatParams.src0RepStride = - 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block - columnRepeatParams.src1RepStride = 0; - columnRepeatParams.dstRepStride = - 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block - uint32_t offset = 0; - for (uint32_t i = 0; i < dealRowCount; i++) { - Div(dstUb[offset], - src0Ub[offset], - src1Ub[i * FP32_BLOCK_ELEMENT_NUM], - dtypeMask, - columnRepeatCount, - columnRepeatParams); - offset += columnCount; - } - } - if (dRemain > 0) { - Div(dstUb[dLoop * dtypeMask], - src0Ub[dLoop * dtypeMask], - src1Ub, - dRemain, - dealRowCount, - repeatParamsDiv); - } -} - -template -__aicore__ inline void SMLAVectorBlock::RowMuls( - LocalTensor dstUb, - LocalTensor src0Ub, - LocalTensor src1Ub, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount) { - // muls by row, 每行的元素乘以相同的元素 - // dstUb[i, (j * 8) : (j * 8 + 7)] = src0Ub[i, (j * 8) : (j * 8 + 7)] * - // src1Ub[i, 0 : 7] src0Ub:[dealRowCount, columnCount] src1Ub:[dealRowCount, - // FP32_BLOCK_ELEMENT_NUM] dstUb:[dealRowCount, columnCount] dealRowCount is - // repeat times, must be less 256 - uint32_t repeatElementNum = FP32_REPEAT_ELEMENT_NUM; - uint32_t blockElementNum = FP32_BLOCK_ELEMENT_NUM; - - if constexpr (std::is_same::value) { - // 此限制由于每个repeat至多连续读取256B数据 - repeatElementNum = FP32_REPEAT_ELEMENT_NUM * 2; // 256/4 * 2=128 - blockElementNum = FP32_BLOCK_ELEMENT_NUM * 2; // 32/4 * 2 = 16 - } - - // 每次只能连续读取256B的数据进行计算,故每次只能处理256B/sizeof(dType)= - // 列方向分dLoop次,每次处理8列数据 - uint32_t dLoop = actualColumnCount / repeatElementNum; - uint32_t dRemain = actualColumnCount % repeatElementNum; - // REPEATE_STRIDE_UP_BOUND=256, - // 此限制由于src0RepStride数据类型为uint8之多256个datablock间距 - if (columnCount < REPEATE_STRIDE_UP_BOUND * blockElementNum) { - BinaryRepeatParams repeatParams; - repeatParams.src0BlkStride = 1; - repeatParams.src1BlkStride = 0; - repeatParams.dstBlkStride = 1; - repeatParams.src0RepStride = columnCount / blockElementNum; - repeatParams.src1RepStride = 1; - repeatParams.dstRepStride = columnCount / blockElementNum; - - // 如果以列为repeat所处理的次数小于行处理次数,则以列方式处理。反之则以行进行repeat处理 - if (dLoop <= dealRowCount) { - uint32_t offset = 0; - for (uint32_t i = 0; i < dLoop; i++) { - Mul(dstUb[offset], - src0Ub[offset], - src1Ub, - repeatElementNum, - dealRowCount, - repeatParams); - offset += repeatElementNum; - } - } else { - BinaryRepeatParams columnRepeatParams; - columnRepeatParams.src0BlkStride = 1; - columnRepeatParams.src1BlkStride = 0; - columnRepeatParams.dstBlkStride = 1; - columnRepeatParams.src0RepStride = - 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block - columnRepeatParams.src1RepStride = 0; - columnRepeatParams.dstRepStride = - 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block - for (uint32_t i = 0; i < dealRowCount; i++) { - Mul(dstUb[i * columnCount], - src0Ub[i * columnCount], - src1Ub[i * blockElementNum], - repeatElementNum, - dLoop, - columnRepeatParams); - } - } - - // 最后一次完成[dealRowCount, dRemain] * [dealRowCount, blockElementNum] - // 只计算有效部分 - if (dRemain > 0) { - Mul(dstUb[dLoop * repeatElementNum], - src0Ub[dLoop * repeatElementNum], - src1Ub, - dRemain, - dealRowCount, - repeatParams); - } - } else { - BinaryRepeatParams repeatParams; - repeatParams.src0RepStride = 8; // 每个repeat为256B数据,正好8个datablock - repeatParams.src0BlkStride = 1; - repeatParams.src1RepStride = 0; - repeatParams.src1BlkStride = 0; - repeatParams.dstRepStride = 8; - repeatParams.dstBlkStride = 1; - // 每次计算一行,共计算dealRowCount行 - for (uint32_t i = 0; i < dealRowCount; i++) { - // 计算一行中的dLoop个repeat, 每个repeat计算256/block_size 个data_block - Mul(dstUb[i * columnCount], - src0Ub[i * columnCount], - src1Ub[i * blockElementNum], - repeatElementNum, - dLoop, - repeatParams); - // 计算一行中的尾块 - if (dRemain > 0) { - Mul(dstUb[i * columnCount + dLoop * repeatElementNum], - src0Ub[i * columnCount + dLoop * repeatElementNum], - src1Ub[i * blockElementNum], - dRemain, - 1, - repeatParams); - } - } - } -} -} // namespace SMLAKernel -#endif // SPARSE_FLASH_MLA_CSA_BLOCK_VECTOR_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_kernel.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_kernel.h deleted file mode 100644 index 7b450273df..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_csa_kernel.h +++ /dev/null @@ -1,1123 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file sparse_flash_mla_csa_kernel.h - * \brief - */ - -#ifndef SPARSE_FLASH_MLA_CSA_KERNEL_H -#define SPARSE_FLASH_MLA_CSA_KERNEL_H - -#include "kernel_operator.h" -#include "kernel_operator_list_tensor_intf.h" -#include "kernel_tiling/kernel_tiling.h" -#include "lib/matmul_intf.h" -#include "lib/matrix/matmul/tiling.h" -#include "sparse_flash_mla_arch22_metadata.h" -#include "sparse_flash_mla_common_arch22.h" -#include "sparse_flash_mla_csa_block_cube.h" -#include "sparse_flash_mla_csa_block_vector.h" - -namespace SMLAKernel { -using namespace matmul; -using namespace optiling; -using AscendC::CrossCoreSetFlag; -using AscendC::CrossCoreWaitFlag; - -// 由于S2循环前,RunInfo还没有赋值,使用Bngs1Param临时存放B、N、S1轴相关的信息;同时减少重复计算 -struct TempLoopInfo { - uint32_t bn2IdxInCurCore = 0; - uint32_t bIdx = 0U; - uint32_t n2Idx = 0U; - uint64_t s2BasicSizeTail = 0U; // S2方向循环的尾基本块大小 - uint32_t s2LoopTimes = - 0U; // S2方向循环的总次数,无论TND还是BXXD都是等于实际次数,不用减1 - - int32_t actS1Size = 0; // TND场景下当前Batch循环处理的S1轴的大小 - int32_t actOriS2Size = 0; - int32_t actCmpS2Size = 0; - - bool curActSeqLenIsZero = false; - - uint32_t tndCoreStartKVSplitPos = 0; - bool tndIsS2SplitCore = false; - uint32_t gS1Idx = 0U; - uint32_t s1StartIdx = 0; - uint32_t s1EndIdx = 0; - uint64_t mBasicSizeTail = 0U; // gS1方向循环的尾基本块大小 - uint32_t cmpLoopTimes = 0; - uint32_t oriLoopTimes = 0; - uint32_t v0OriSize = 0; - uint32_t v0CmpSize = 0; - - // sparsemode = 4 - int32_t oriMaskRight = 0; - int32_t oriMaskLeft = 0; - - // sparsemode = 3 - int32_t cmpMaskRight = 0; - - uint64_t actualSeqQPrefixSum = 0; - uint64_t actualSeqKVPrefixSum = 0; - uint64_t actualSeqCmpKVPrefixSum = 0; -}; - -template -class SparseFlashMlaCsa { - public: - // 中间计算数据类型为float,高精度模式 - using T = float; - using Q_T = typename SMLAT::queryType; - using KV_T = typename SMLAT::kvType; - using OUT_T = typename SMLAT::outputType; - using SINKS_T = float; - using UPDATE_T = T; - using MM1_OUT_T = T; - using MM2_OUT_T = T; - - __aicore__ inline SparseFlashMlaCsa(){}; - __aicore__ inline void Init(__gm__ uint8_t* query, - __gm__ uint8_t* oriKV, - __gm__ uint8_t* cmpKV, - __gm__ uint8_t* oriSparseIndices, - __gm__ uint8_t* cmpSparseIndices, - __gm__ uint8_t* oriBlockTable, - __gm__ uint8_t* cmpBlockTable, - __gm__ uint8_t* cuSeqlensQ, - __gm__ uint8_t* cuSeqlensKV, - __gm__ uint8_t* cuSeqlensCmpKV, - __gm__ uint8_t* seqUsedQ, - __gm__ uint8_t* seqUsedKV, - __gm__ uint8_t* seqUsedCmpKV, - __gm__ uint8_t* cmpResidualKV, - __gm__ uint8_t* oriTopkLength, - __gm__ uint8_t* cmpTopkLength, - __gm__ uint8_t* sinks, - __gm__ uint8_t* metadata, - __gm__ uint8_t* attentionOut, - __gm__ uint8_t* softmaxLse, - __gm__ uint8_t* workspace, - const SparseFlashMlaTilingData* __restrict tiling, - __gm__ uint8_t* gmTiling, - TPipe* tPipe); - - __aicore__ inline void Process(); - - private: - static constexpr bool PAGE_ATTENTION = SMLAT::pageAttention; - static constexpr bool FLASH_DECODE = SMLAT::flashDecode; - static constexpr SMLA_LAYOUT LAYOUT_T = SMLAT::layout; - static constexpr SMLA_LAYOUT KV_LAYOUT_T = SMLAT::kvLayout; - static constexpr bool HEAD_RATIO_ONE = SMLAT::headRatioOne; - - static constexpr uint32_t PRELOAD_NUM = 2; - static constexpr uint32_t N_BUFFER_M_BASIC_SIZE = 256; - static constexpr uint32_t SMLA_PRELOAD_TASK_CACHE_SIZE = 3; - static constexpr uint32_t MERGE_CACHE_GM_BUF_NUM = 3; - - static constexpr uint32_t SYNC_V0_C1_FLAG = 6; - static constexpr uint32_t SYNC_C1_V1_FLAG = 7; - static constexpr uint32_t SYNC_V1_C2_FLAG = 8; - static constexpr uint32_t SYNC_C2_V2_FLAG = 9; - - static constexpr uint64_t headDim = 512ULL; - - static constexpr uint32_t dbWorkspaceRatio = PRELOAD_NUM; - - const SparseFlashMlaTilingData* __restrict tilingData = nullptr; - - TPipe* pipe = nullptr; - GlobalTensor metadataGm; - uint64_t mSizeVStart = 0ULL; - uint64_t topKBaseOffset = 0ULL; - uint64_t tensorACoreOffset = 0ULL; - uint64_t tensorBCoreOffset = 0ULL; - uint64_t tensorCmpBCoreOffset = 0ULL; - - uint32_t tmpBlockIdx = 0U; - uint32_t aiCoreIdx = 0U; - - ConstInfo constInfo{}; - TempLoopInfo tempLoopInfo{}; - - SMLACubeBlock cubeBlock; - SMLAVectorBlock vectorBlock; - - GlobalTensor queryGm; - GlobalTensor oriKvGm; - GlobalTensor cmpKvGm; - GlobalTensor sinksGm; - - GlobalTensor attentionOutGm; - GlobalTensor softmaxLseGm; - - GlobalTensor oriBlockTableGm; - GlobalTensor cmpBlockTableGm; - GlobalTensor topKGm; - - GlobalTensor actualSeqLengthsQGm; - GlobalTensor actualSeqLengthsKVGm; - GlobalTensor actualSeqLengthsCmpKVGm; - GlobalTensor cmpResidualKVGm; - - // workspace - GlobalTensor mm1ResGm; - GlobalTensor vec1ResGm; - GlobalTensor mm2ResGm; - GlobalTensor kvMergeGm_; - - GlobalTensor vec2ResGm; - - GlobalTensor accumOutGm; - - // ================================Init - // functions================================== - __aicore__ inline void InitTilingData(); - __aicore__ inline void InitCalcParamsEach(); - __aicore__ inline void InitBuffers(); - __aicore__ inline void InitActualSeqLen(__gm__ uint8_t* actualSeqLengthsQ, - __gm__ uint8_t* actualSeqLengthsKV); - __aicore__ inline void InitActualSeqLen( - __gm__ uint8_t* actualSeqLengthsQ, - __gm__ uint8_t* actualSeqLengthsKV, - __gm__ uint8_t* actualSeqLengthsCmpKV); - __aicore__ inline void InitOutputSingleCore(); - // ================================Process - // functions================================ - __aicore__ inline void ProcessBalance(); - __aicore__ inline void PreloadPipeline( - uint32_t loop, - uint32_t cmpLoop, - uint64_t s2Start, - uint64_t s2LoopIdx, - RunInfo extraInfo[SMLA_PRELOAD_TASK_CACHE_SIZE]); - // ================================Offset - // Calc===================================== - __aicore__ inline void GetSparseActualSeqLen(); - __aicore__ inline void UpdateInnerLoopCond(); - __aicore__ inline void CalcParams(uint32_t loop, - uint32_t cmpLoop, - uint64_t s2Start, - uint32_t s2LoopIdx, - RunInfo& info); - __aicore__ inline int32_t GetActualSeqLenQ(uint32_t bIdx); - __aicore__ inline int32_t GetActualSeqLenKV(uint32_t bIdx); - __aicore__ inline int32_t GetActualSeqLenCmpKV(uint32_t bIdx, - int32_t actualOriS2Size); - __aicore__ inline int32_t GetCmpMaskS2Size(uint32_t bIdx, - int32_t actualOriS2Size, - int32_t actualCmpS2Size); - __aicore__ inline void GetBN2Idx(uint32_t bN2Idx, - uint32_t& bIdx, - uint32_t& n2Idx); - // ================================Mm1============================================== - __aicore__ inline void ComputeMm1(const RunInfo& info); - // ================================Mm2============================================== - __aicore__ inline void ComputeMm2(const RunInfo& info); - __aicore__ inline void InitAllZeroOutput(uint32_t bIdx, - uint32_t s1Idx, - uint32_t n2Idx); -}; - -template -__aicore__ inline void SparseFlashMlaCsa::InitTilingData() { - // singleCoreParams - // singleCoreTensorSize - constInfo.mmResUbSize = tilingData->baseParams.mmResUbSize; - constInfo.bmm2ResUbSize = tilingData->baseParams.bmm2ResUbSize; - - // baseParams - constInfo.batchSize = tilingData->baseParams.batchSize; - constInfo.gSize = tilingData->baseParams.nNumOfQInOneGroup; - constInfo.kvHeadNum = (tilingData->baseParams.kvHeadNum == 0) - ? 1 - : tilingData->baseParams.kvHeadNum; - constInfo.qHeadNum = constInfo.gSize * constInfo.kvHeadNum; - constInfo.kvSeqSize = tilingData->baseParams.kvSeqSize; - constInfo.qSeqSize = tilingData->baseParams.qSeqSize; - constInfo.oriMaxBlockNumPerBatch = - tilingData->baseParams.oriMaxBlockNumPerBatch; - constInfo.cmpMaxBlockNumPerBatch = - tilingData->cmpParams.cmpMaxBlockNumPerBatch; - constInfo.kvCacheBlockSize = tilingData->baseParams.paBlockSize; - constInfo.paOriBlockSize = tilingData->baseParams.oriBlockSize; - constInfo.paCmpBlockSize = tilingData->baseParams.cmpBlockSize; - constInfo.outputLayout = - static_cast(tilingData->baseParams.outputLayout); - constInfo.headDim = headDim; - constInfo.oriMaskMode = tilingData->baseParams.oriMaskMode; - constInfo.oriKvStride0 = tilingData->baseParams.oriKvStride0; - constInfo.oriWinLeft = tilingData->baseParams.oriWinLeft; - constInfo.oriWinRight = tilingData->baseParams.oriWinRight; - - constInfo.actualLenDimsQ = tilingData->baseParams.actualLenDimsQ; - constInfo.actualLenDimsKV = tilingData->baseParams.actualLenDimsKV; - constInfo.actualLenDimsCmpKV = tilingData->baseParams.actualLenDimsCmpKV; - constInfo.cmpResidualKVSize = tilingData->baseParams.cmpResidualKVSize; - constInfo.returnSoftmaxLse = tilingData->baseParams.returnSoftmaxLse; - // innerSplitParams - constInfo.mBaseSize = constInfo.gSize; - constInfo.s2BaseSize = tilingData->baseParams.s2BaseSize; - - constInfo.preLoadNum = PRELOAD_NUM; - constInfo.nBufferMBaseSize = N_BUFFER_M_BASIC_SIZE; - constInfo.syncV0C1 = SYNC_V0_C1_FLAG; - constInfo.syncC1V1 = SYNC_C1_V1_FLAG; - constInfo.syncV1C2 = SYNC_V1_C2_FLAG; - constInfo.syncC2V2 = SYNC_C2_V2_FLAG; - - // cmp - constInfo.cmpRatio = tilingData->cmpParams.cmpRatio; - constInfo.sparseBlockCount = tilingData->cmpParams.sparseBlockCount; - constInfo.sparseBlockSize = 1; // sparseBlockSize 固定为1 - constInfo.cmpMaskMode = tilingData->cmpParams.cmpMaskMode; - constInfo.cmpKvStride0 = tilingData->cmpParams.cmpKvStride0; - constInfo.cmpSeqSize = tilingData->cmpParams.cmpKvSeqSize; -} - -template -__aicore__ inline void SparseFlashMlaCsa::InitBuffers() { - if ASCEND_IS_AIV { - vectorBlock.InitBuffers(pipe); - } else { - cubeBlock.InitBuffers(pipe); - } -} - -template -__aicore__ inline void SparseFlashMlaCsa::InitActualSeqLen( - __gm__ uint8_t* actualSeqLengthsQ, - __gm__ uint8_t* actualSeqLengthsKV) { - if (constInfo.actualLenDimsKV != 0) { - actualSeqLengthsKVGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsKV, - constInfo.actualLenDimsKV); - } - if (constInfo.actualLenDimsQ != 0) { - actualSeqLengthsQGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsQ, - constInfo.actualLenDimsQ); - } -} - -template -__aicore__ inline void SparseFlashMlaCsa::InitActualSeqLen( - __gm__ uint8_t* actualSeqLengthsQ, - __gm__ uint8_t* actualSeqLengthsKV, - __gm__ uint8_t* actualSeqLengthsCmpKV) { - if (constInfo.actualLenDimsKV != 0) { - actualSeqLengthsKVGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsKV, - constInfo.actualLenDimsKV); - } - if (constInfo.actualLenDimsCmpKV != 0) { - actualSeqLengthsCmpKVGm.SetGlobalBuffer( - (__gm__ int32_t*)actualSeqLengthsCmpKV, constInfo.actualLenDimsCmpKV); - } - if (constInfo.actualLenDimsQ != 0) { - actualSeqLengthsQGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsQ, - constInfo.actualLenDimsQ); - } -} - -template -__aicore__ inline void SparseFlashMlaCsa::InitAllZeroOutput( - uint32_t bIdx, - uint32_t s1Idx, - uint32_t n2Idx) { - if (constInfo.outputLayout == SMLA_LAYOUT::TND) { - if (tempLoopInfo.actS1Size == 0) { - return; - } - uint32_t tBase = actualSeqLengthsQGm.GetValue(bIdx); - uint32_t s1Count = tempLoopInfo.actS1Size; - - uint64_t attenOutOffset = (tBase + s1Idx) * constInfo.kvHeadNum * - constInfo.gSize * constInfo.headDim + - n2Idx * constInfo.gSize * constInfo.headDim; - uint64_t lseOffset = - (tBase + s1Idx) * constInfo.gSize + // T轴、s1轴偏移 - n2Idx * constInfo.qSeqSize * constInfo.gSize; // N2轴偏移 - matmul::InitOutput( - attentionOutGm[attenOutOffset], constInfo.gSize * constInfo.headDim, 0); - if (constInfo.returnSoftmaxLse) { - matmul::InitOutput(softmaxLseGm[lseOffset], constInfo.gSize, 0); - } - } else if (constInfo.outputLayout == SMLA_LAYOUT::BSND) { - uint64_t attenOutOffset = - bIdx * constInfo.qSeqSize * constInfo.kvHeadNum * constInfo.gSize * - constInfo.headDim + - s1Idx * constInfo.kvHeadNum * constInfo.gSize * constInfo.headDim + - n2Idx * constInfo.gSize * constInfo.headDim; - uint64_t lseOffset = - bIdx * constInfo.qSeqSize * constInfo.kvHeadNum * - constInfo.gSize + // B轴偏移 - n2Idx * constInfo.qSeqSize * constInfo.gSize + // N2轴偏移 - s1Idx * constInfo.gSize; // S1轴偏移 - matmul::InitOutput( - attentionOutGm[attenOutOffset], constInfo.gSize * constInfo.headDim, 0); - if (constInfo.returnSoftmaxLse) { - matmul::InitOutput(softmaxLseGm[lseOffset], constInfo.gSize, 0); - } - } -} - -template -__aicore__ inline void SparseFlashMlaCsa::InitOutputSingleCore() { - uint32_t coreNum = GetBlockNum(); - if (coreNum != 0) { - uint64_t totalOutputSize = constInfo.batchSize * constInfo.qHeadNum * - constInfo.qSeqSize * constInfo.headDim; - uint64_t singleCoreSize = (totalOutputSize + (2 * coreNum) - 1) / - (2 * coreNum); // 2 means c:v = 1:2 - uint64_t tailSize = totalOutputSize - tmpBlockIdx * singleCoreSize; - uint64_t singleInitOutputSize = - tailSize < singleCoreSize ? tailSize : singleCoreSize; - if (singleInitOutputSize > 0) { - matmul::InitOutput(attentionOutGm[tmpBlockIdx * singleCoreSize], - singleInitOutputSize, - 0); - } - SyncAll(); - } -} - -template -__aicore__ inline int32_t SparseFlashMlaCsa::GetActualSeqLenQ( - uint32_t bIdx) { - if constexpr (LAYOUT_T == SMLA_LAYOUT::TND) { - int32_t actualSeqQPrefixSum = actualSeqLengthsQGm.GetValue(bIdx); - int32_t actualSeqQNextSum = actualSeqLengthsQGm.GetValue(bIdx + 1); - tempLoopInfo.actualSeqQPrefixSum = - static_cast(actualSeqQPrefixSum); - return actualSeqQNextSum - actualSeqQPrefixSum; - } else { - tempLoopInfo.actualSeqQPrefixSum = - static_cast(bIdx * constInfo.qSeqSize); - if (constInfo.actualLenDimsQ == 0) { - return static_cast(constInfo.qSeqSize); - } else { - return actualSeqLengthsQGm.GetValue(bIdx); - } - } -} - -template -__aicore__ inline int32_t SparseFlashMlaCsa::GetActualSeqLenKV( - uint32_t bIdx) { - if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { - tempLoopInfo.actualSeqKVPrefixSum = - static_cast(bIdx * constInfo.kvSeqSize); - if (constInfo.actualLenDimsKV == 0) { - return static_cast(constInfo.kvSeqSize); - } - return actualSeqLengthsKVGm.GetValue(bIdx); - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { - tempLoopInfo.actualSeqKVPrefixSum = - static_cast(bIdx * constInfo.kvSeqSize); - if (constInfo.actualLenDimsKV != 0) { - return actualSeqLengthsKVGm.GetValue(bIdx); - } - return static_cast(constInfo.kvSeqSize); - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { - int32_t actualSeqKVPrefixSum = actualSeqLengthsKVGm.GetValue(bIdx); - int32_t actualSeqKVNextSum = actualSeqLengthsKVGm.GetValue(bIdx + 1); - tempLoopInfo.actualSeqKVPrefixSum = actualSeqKVPrefixSum; - return actualSeqKVNextSum - actualSeqKVPrefixSum; - } -} - -template -__aicore__ inline int32_t SparseFlashMlaCsa::GetActualSeqLenCmpKV( - uint32_t bIdx, - int32_t actualOriS2Size) { - (void)actualOriS2Size; - if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { - int32_t actualSeqCmpKVPrefixSum = actualSeqLengthsCmpKVGm.GetValue(bIdx); - int32_t actualSeqCmpKVNextSum = actualSeqLengthsCmpKVGm.GetValue(bIdx + 1); - tempLoopInfo.actualSeqCmpKVPrefixSum = actualSeqCmpKVPrefixSum; - return actualSeqCmpKVNextSum - actualSeqCmpKVPrefixSum; - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { - tempLoopInfo.actualSeqCmpKVPrefixSum = - static_cast(bIdx * constInfo.cmpSeqSize); - if (constInfo.actualLenDimsCmpKV != 0) { - return actualSeqLengthsCmpKVGm.GetValue(bIdx); - } - return static_cast(constInfo.cmpSeqSize); - } else { - tempLoopInfo.actualSeqCmpKVPrefixSum = - static_cast(bIdx * constInfo.cmpSeqSize); - if (constInfo.actualLenDimsCmpKV != 0) { - return actualSeqLengthsCmpKVGm.GetValue(bIdx); - } - return (constInfo.cmpSeqSize != 0) - ? static_cast(constInfo.cmpSeqSize) - : actualOriS2Size / static_cast(constInfo.cmpRatio); - } -} - -template -__aicore__ inline int32_t SparseFlashMlaCsa::GetCmpMaskS2Size( - uint32_t bIdx, - int32_t actualOriS2Size, - int32_t actualCmpS2Size) { - (void)actualOriS2Size; - int32_t residual = 0; - if (constInfo.cmpResidualKVSize != 0) { - residual = cmpResidualKVGm.GetValue(bIdx); - } - return actualCmpS2Size * static_cast(constInfo.cmpRatio) + residual; -} - -template -__aicore__ inline void SparseFlashMlaCsa::GetSparseActualSeqLen() { - // 行无效通过ori部分判断, ori部分如果有行无效那么ori和cmp都有 - if (static_cast(tempLoopInfo.s1EndIdx) < - -(tempLoopInfo.actOriS2Size - tempLoopInfo.actS1Size)) { - tempLoopInfo.actOriS2Size = 0; - tempLoopInfo.actCmpS2Size = 0; - return; - } - - // 对于cmp部分还有top k, tempLoopInfo.actS2Size只针对cmp - int32_t thresHold = (tempLoopInfo.cmpMaskRight + tempLoopInfo.s1EndIdx + 1) / - constInfo.cmpRatio; - tempLoopInfo.actCmpS2Size = - Min(tempLoopInfo.actCmpS2Size, - Min(constInfo.sparseBlockCount * constInfo.sparseBlockSize, - Max(thresHold, 0))); -} - -template -__aicore__ inline void SparseFlashMlaCsa::UpdateInnerLoopCond() { - if ((tempLoopInfo.actCmpS2Size == 0 && tempLoopInfo.actOriS2Size == 0) || - (tempLoopInfo.actS1Size == 0)) { - tempLoopInfo.curActSeqLenIsZero = true; - return; - } - tempLoopInfo.curActSeqLenIsZero = false; - tempLoopInfo.mBasicSizeTail = - (tempLoopInfo.actS1Size * constInfo.gSize) % constInfo.mBaseSize; - tempLoopInfo.mBasicSizeTail = (tempLoopInfo.mBasicSizeTail == 0) - ? constInfo.mBaseSize - : tempLoopInfo.mBasicSizeTail; -} - -template -__aicore__ inline void SparseFlashMlaCsa::Init( - __gm__ uint8_t* query, - __gm__ uint8_t* oriKV, - __gm__ uint8_t* cmpKV, - __gm__ uint8_t* oriSparseIndices, - __gm__ uint8_t* cmpSparseIndices, - __gm__ uint8_t* oriBlockTable, - __gm__ uint8_t* cmpBlockTable, - __gm__ uint8_t* cuSeqlensQ, - __gm__ uint8_t* cuSeqlensKV, - __gm__ uint8_t* cuSeqlensCmpKV, - __gm__ uint8_t* seqUsedQ, - __gm__ uint8_t* seqUsedKV, - __gm__ uint8_t* seqUsedCmpKV, - __gm__ uint8_t* cmpResidualKV, - __gm__ uint8_t* oriTopkLength, - __gm__ uint8_t* cmpTopkLength, - __gm__ uint8_t* sinks, - __gm__ uint8_t* metadata, - __gm__ uint8_t* attentionOut, - __gm__ uint8_t* softmaxLse, - __gm__ uint8_t* workspace, - const SparseFlashMlaTilingData* __restrict tiling, - __gm__ uint8_t* gmTiling, - TPipe* tPipe) { - if ASCEND_IS_AIV { - tmpBlockIdx = GetBlockIdx(); // vec:0-47 - aiCoreIdx = tmpBlockIdx / 2; - } else { - tmpBlockIdx = GetBlockIdx(); // cube:0-23 - aiCoreIdx = tmpBlockIdx; - } - - // init tiling data - tilingData = tiling; - InitTilingData(); - if (KV_LAYOUT_T == SMLA_LAYOUT::TND && LAYOUT_T == SMLA_LAYOUT::TND) { - InitActualSeqLen(cuSeqlensQ, cuSeqlensKV, cuSeqlensCmpKV); - } else if (KV_LAYOUT_T == SMLA_LAYOUT::TND) { - InitActualSeqLen(seqUsedQ, cuSeqlensKV, cuSeqlensCmpKV); - } else if ((KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND || - KV_LAYOUT_T == SMLA_LAYOUT::BSND) && - LAYOUT_T == SMLA_LAYOUT::TND) { - InitActualSeqLen(cuSeqlensQ, seqUsedKV, seqUsedCmpKV); - } else if ((KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND || - KV_LAYOUT_T == SMLA_LAYOUT::BSND)) { - InitActualSeqLen(seqUsedQ, seqUsedKV, seqUsedCmpKV); - } - - metadataGm.SetGlobalBuffer((__gm__ uint32_t*)metadata); - InitCalcParamsEach(); - - pipe = tPipe; - // init global buffer - queryGm.SetGlobalBuffer((__gm__ Q_T*)query); - oriKvGm.SetGlobalBuffer((__gm__ KV_T*)oriKV); - cmpKvGm.SetGlobalBuffer((__gm__ KV_T*)cmpKV); - if (constInfo.cmpResidualKVSize != 0) { - cmpResidualKVGm.SetGlobalBuffer((__gm__ int32_t*)cmpResidualKV, - constInfo.cmpResidualKVSize); - } - - if (sinks != nullptr) { - sinksGm.SetGlobalBuffer((__gm__ SINKS_T*)sinks); - } - - attentionOutGm.SetGlobalBuffer((__gm__ OUT_T*)attentionOut); - softmaxLseGm.SetGlobalBuffer((__gm__ T*)softmaxLse); - - if ASCEND_IS_AIV { - if (LAYOUT_T != SMLA_LAYOUT::TND) { - if (constInfo.needInit) { - InitOutputSingleCore(); - } - } - } - - if constexpr (PAGE_ATTENTION) { - oriBlockTableGm.SetGlobalBuffer((__gm__ int32_t*)oriBlockTable); - cmpBlockTableGm.SetGlobalBuffer((__gm__ int32_t*)cmpBlockTable); - } - topKGm.SetGlobalBuffer((__gm__ int32_t*)cmpSparseIndices); - - // workspace 内存排布 - // |Q--|mm1ResGm|vec1ResGm|mm2ResGm|vec2ResGm - // |Core0_Q1-Core0_Q2-Core1_Q1-Core1_Q2....Core32_Q1-Core32_Q2|Core0_mmRes - uint64_t offset = 0; - mm1ResGm.SetGlobalBuffer( - (__gm__ MM1_OUT_T*)(workspace + offset + - aiCoreIdx * dbWorkspaceRatio * constInfo.mmResUbSize * - sizeof(MM1_OUT_T))); - offset += GetBlockNum() * dbWorkspaceRatio * constInfo.mmResUbSize * - sizeof(MM1_OUT_T); - - vec1ResGm.SetGlobalBuffer( - (__gm__ Q_T*)(workspace + offset + - aiCoreIdx * dbWorkspaceRatio * constInfo.mmResUbSize * - sizeof(KV_T))); - offset += - GetBlockNum() * dbWorkspaceRatio * constInfo.mmResUbSize * sizeof(KV_T); - - mm2ResGm.SetGlobalBuffer((__gm__ MM2_OUT_T*)(workspace + offset + - aiCoreIdx * dbWorkspaceRatio * - constInfo.bmm2ResUbSize * - sizeof(MM2_OUT_T))); - offset += GetBlockNum() * dbWorkspaceRatio * constInfo.bmm2ResUbSize * - sizeof(MM2_OUT_T); - - vec2ResGm.SetGlobalBuffer( - (__gm__ T*)(workspace + offset + - aiCoreIdx * dbWorkspaceRatio * constInfo.bmm2ResUbSize * - sizeof(T))); - offset += - GetBlockNum() * dbWorkspaceRatio * constInfo.bmm2ResUbSize * sizeof(T); - - kvMergeGm_.SetGlobalBuffer( - (__gm__ KV_T*)(workspace + offset + - aiCoreIdx * 512 * 512 * MERGE_CACHE_GM_BUF_NUM * - sizeof(KV_T))); - offset += GetBlockNum() * 512 * 512 * 4 * sizeof(KV_T); - - if ASCEND_IS_AIV { - vectorBlock.InitParams(constInfo, tilingData); - vectorBlock.InitVec0GlobalTensor( - kvMergeGm_, oriKvGm, cmpKvGm, oriBlockTableGm, cmpBlockTableGm); - vectorBlock.InitVec1GlobalTensor(mm1ResGm, - vec1ResGm, - actualSeqLengthsQGm, - actualSeqLengthsKVGm, - topKGm, - sinksGm, - softmaxLseGm); - vectorBlock.InitVec2GlobalTensor( - accumOutGm, vec2ResGm, mm2ResGm, attentionOutGm); - } - - if ASCEND_IS_AIC { - cubeBlock.InitParams(constInfo); - cubeBlock.InitMm1GlobalTensor(queryGm, oriKvGm, cmpKvGm, mm1ResGm); - cubeBlock.InitMm2GlobalTensor(vec1ResGm, mm2ResGm, attentionOutGm); - cubeBlock.InitPageAttentionInfo( - oriKvGm, kvMergeGm_, oriBlockTableGm, cmpBlockTableGm); - } - // 要在InitParams之后执行 - if (pipe != nullptr) { - InitBuffers(); - } -} - -template -__aicore__ inline void SparseFlashMlaCsa::InitCalcParamsEach() { - if (aiCoreIdx != 0) { - constInfo.bN2Start = metadataGm.GetValue( - GetAttrAbsIndex(aiCoreIdx, FA_BN2_START_INDEX, false)); - constInfo.gS1Start = metadataGm.GetValue( - GetAttrAbsIndex(aiCoreIdx, FA_M_START_INDEX, false)); - constInfo.s2Start = metadataGm.GetValue( - GetAttrAbsIndex(aiCoreIdx, FA_S2_START_INDEX, false)); - } - constInfo.bN2End = - metadataGm.GetValue(GetAttrAbsIndex(aiCoreIdx, FA_BN2_END_INDEX, false)); - constInfo.gS1End = - metadataGm.GetValue(GetAttrAbsIndex(aiCoreIdx, FA_M_END_INDEX, false)); - constInfo.s2End = - metadataGm.GetValue(GetAttrAbsIndex(aiCoreIdx, FA_S2_END_INDEX, false)); -} - -template -__aicore__ inline void SparseFlashMlaCsa::CalcParams(uint32_t loop, - uint32_t cmpLoop, - uint64_t s2Start, - uint32_t s2LoopIdx, - RunInfo& info) { - info.isValid = s2LoopIdx < tempLoopInfo.s2LoopTimes; - info.loop = loop; - info.cmpLoop = cmpLoop; - info.bIdx = tempLoopInfo.bIdx; - info.n2IdxReal = tempLoopInfo.n2Idx; - - info.gS1Idx = tempLoopInfo.gS1Idx; - info.s1Idx = tempLoopInfo.gS1Idx / constInfo.gSize; - info.s2Idx = s2LoopIdx; - info.curSInnerLoopTimes = tempLoopInfo.s2LoopTimes; - info.tndIsS2SplitCore = tempLoopInfo.tndIsS2SplitCore; - info.tndCoreStartKVSplitPos = tempLoopInfo.tndCoreStartKVSplitPos; - info.isBmm2Output = false; - info.actS1Size = tempLoopInfo.actS1Size; - - // M方向的尾块 - info.actMBaseSize = tempLoopInfo.mBasicSizeTail; - - if ASCEND_IS_AIV { - info.mSize = info.actMBaseSize; - info.mSizeV = (info.mSize <= 16) ? info.mSize - : ((CeilDiv(info.mSize, 16) + 1) / 2 * 16); - info.mSizeVStart = 0; - if (tmpBlockIdx % 2 == 1) { - info.mSizeVStart = info.mSizeV; - info.mSizeV = info.mSize - info.mSizeV; - } - } - - info.isFirstSInnerLoop = s2LoopIdx == s2Start; - if (info.isFirstSInnerLoop) { - tempLoopInfo.bn2IdxInCurCore++; - } - info.isLastS2Loop = (s2LoopIdx == (tempLoopInfo.s2LoopTimes - 1)); - info.bn2IdxInCurCore = tempLoopInfo.bn2IdxInCurCore - 1; - - uint64_t tndBIdxOffsetForQ = - tempLoopInfo.actualSeqQPrefixSum * constInfo.qHeadNum * constInfo.headDim; - uint64_t tndBIdxOffsetForKV = tempLoopInfo.actualSeqKVPrefixSum * - constInfo.kvHeadNum * constInfo.headDim; - uint64_t tndBIdxOffsetForCmpKV = tempLoopInfo.actualSeqCmpKVPrefixSum * - constInfo.kvHeadNum * constInfo.headDim; - - if (info.isFirstSInnerLoop) { - uint64_t s1HeadOffset = - (info.gS1Idx / constInfo.gSize) * constInfo.qHeadNum; - uint64_t qHeadOffset = - info.n2Idx * constInfo.gSize + info.gS1Idx % constInfo.gSize; - tensorACoreOffset = - tndBIdxOffsetForQ + (s1HeadOffset + qHeadOffset) * constInfo.headDim; - tensorBCoreOffset = - tndBIdxOffsetForKV + - info.n2Idx * constInfo.headDim; // 当前为PA场景,该变量失效 - tensorCmpBCoreOffset = - tndBIdxOffsetForCmpKV + info.n2Idx * constInfo.headDim; - if constexpr (LAYOUT_T == SMLA_LAYOUT::BSND) { // B,S1,N2 K - topKBaseOffset = - (info.bIdx * constInfo.qSeqSize + tempLoopInfo.s1StartIdx) * - constInfo.kvHeadNum * constInfo.sparseBlockCount + - info.n2Idx * constInfo.sparseBlockCount; - } else if (LAYOUT_T == SMLA_LAYOUT::TND) { // T N2 K - topKBaseOffset = - (tempLoopInfo.actualSeqQPrefixSum + tempLoopInfo.s1StartIdx) * - constInfo.kvHeadNum * constInfo.sparseBlockCount + - info.n2Idx * constInfo.sparseBlockCount; - } - } - info.tensorAOffset = tensorACoreOffset; - info.tensorBOffset = tensorBCoreOffset; - info.tensorCmpBOffset = tensorCmpBCoreOffset; - info.attenOutOffset = tensorACoreOffset; - info.topKBaseOffset = topKBaseOffset; - - if (s2LoopIdx < tempLoopInfo.oriLoopTimes) { - // S2首次循环只能在ori_kv - info.isOriOnly = true; - info.relativeS2Idx = 0; - uint64_t s2Offset = info.s2Idx * constInfo.s2BaseSize; - if (s2LoopIdx + 1 == tempLoopInfo.oriLoopTimes) { - info.actualSingleProcessSInnerSize = - (tempLoopInfo.oriMaskRight - tempLoopInfo.oriMaskLeft + 1) - s2Offset; - } else { - info.actualSingleProcessSInnerSize = constInfo.s2BaseSize; - } - info.s2StartPoint = tempLoopInfo.oriMaskLeft; - info.cmpS2IdLimit = - (tempLoopInfo.cmpMaskRight + tempLoopInfo.s1EndIdx + 1) / - constInfo.cmpRatio; - } else { - info.isOriOnly = false; - info.relativeS2Idx = info.s2Idx - tempLoopInfo.oriLoopTimes; - uint64_t s2Offset = - (info.s2Idx - tempLoopInfo.oriLoopTimes) * constInfo.s2BaseSize; - if (s2LoopIdx + 1 == tempLoopInfo.s2LoopTimes) { - info.actualSingleProcessSInnerSize = tempLoopInfo.actCmpS2Size - s2Offset; - } else { - info.actualSingleProcessSInnerSize = constInfo.s2BaseSize; - } - info.s2StartPoint = 0; - info.cmpS2IdLimit = - (tempLoopInfo.cmpMaskRight + tempLoopInfo.s1EndIdx + 1) / - constInfo.cmpRatio; - // Each compressed block reads its own slice, including a partial final - // block. - info.v0S2Start = static_cast(s2Offset); - info.v0S2DealSize = - static_cast(info.actualSingleProcessSInnerSize); - } - - info.actualSingleProcessSInnerSizeAlign = SMLAAlign( - info.actualSingleProcessSInnerSize, SMLAVectorBlock::BYTE_BLOCK); - if (info.isOriOnly) { - info.v0S2Start = 0; - info.v0S2DealSize = 0; - } -} - -template -__aicore__ inline void SparseFlashMlaCsa::ComputeMm1( - const RunInfo& info) { - uint32_t nBufferLoopTimes = - CeilDiv(info.actMBaseSize, constInfo.nBufferMBaseSize); - uint32_t nBufferTail = - info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; - for (uint32_t i = 0; i < nBufferLoopTimes; i++) { - MSplitInfo mSplitInfo; - mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; - mSplitInfo.nBufferDealM = - (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; - cubeBlock.ComputeMm1(info, mSplitInfo); - if constexpr (HEAD_RATIO_ONE) { - event_t eventIdFixWait = - static_cast(GetTPipePtr()->FetchEventID(HardEvent::FIX_M)); - SetFlag(eventIdFixWait); - WaitFlag(eventIdFixWait); - } - CrossCoreSetFlag(constInfo.syncC1V1); - } -} - -template -__aicore__ inline void SparseFlashMlaCsa::ComputeMm2( - const RunInfo& info) { - uint32_t nBufferLoopTimes = - (info.actMBaseSize + constInfo.nBufferMBaseSize - 1) / - constInfo.nBufferMBaseSize; - uint32_t nBufferTail = - info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; - for (uint32_t i = 0; i < nBufferLoopTimes; i++) { - MSplitInfo mSplitInfo; - mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; - mSplitInfo.nBufferDealM = - (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; - if constexpr (HEAD_RATIO_ONE) { - CrossCoreWaitFlag( - constInfo.syncV1C2); - } else { - CrossCoreWaitFlag(constInfo.syncV1C2); - } - cubeBlock.ComputeMm2(info, mSplitInfo); - if constexpr (HEAD_RATIO_ONE) { - event_t eventIdFixWait = - static_cast(GetTPipePtr()->FetchEventID(HardEvent::FIX_M)); - SetFlag(eventIdFixWait); - WaitFlag(eventIdFixWait); - } - CrossCoreSetFlag(constInfo.syncC2V2); - } -} - -template -__aicore__ inline void SparseFlashMlaCsa::Process() { - uint32_t hasLoad = metadataGm.GetValue( - GetAttrAbsIndex(aiCoreIdx, FA_CORE_ENABLE_INDEX, false)); - if (hasLoad == 0) { - return; - } - if ASCEND_IS_AIV { - vectorBlock.AllocEventID(); - vectorBlock.InitSoftmaxDefaultBuffer(); - } else { - cubeBlock.AllocEventID(); - } - ProcessBalance(); - if ASCEND_IS_AIV { - vectorBlock.FreeEventID(); - } else { - cubeBlock.FreeEventID(); - } -} - -template -__aicore__ inline void SparseFlashMlaCsa::GetBN2Idx(uint32_t bN2Idx, - uint32_t& bIdx, - uint32_t& n2Idx) { - bIdx = bN2Idx / constInfo.kvHeadNum; - n2Idx = bN2Idx % constInfo.kvHeadNum; -} - -template -__aicore__ inline void SparseFlashMlaCsa::ProcessBalance() { - RunInfo extraInfo[SMLA_PRELOAD_TASK_CACHE_SIZE]; - uint32_t gloop = 0; - uint32_t cmpLoop = 0; - uint32_t gS1LoopEnd = 0; - bool globalLoopStart = true; - - if ASCEND_IS_AIC { - CrossCoreSetFlag(3); - CrossCoreSetFlag(3); - CrossCoreSetFlag(3); - CrossCoreSetFlag(3); - } - - // 适配左闭右开 - if (constInfo.bN2Start == constInfo.bN2End) { - if (constInfo.gS1Start != constInfo.gS1End || - constInfo.s2Start != constInfo.s2End) { - constInfo.bN2End += 1; - } - } else if ((constInfo.gS1End != 0) || (constInfo.s2End != 0)) { - constInfo.bN2End += 1; - } - - for (uint32_t bN2LoopIdx = constInfo.bN2Start; bN2LoopIdx < constInfo.bN2End; - bN2LoopIdx++) { - GetBN2Idx(bN2LoopIdx, tempLoopInfo.bIdx, tempLoopInfo.n2Idx); - tempLoopInfo.actS1Size = - GetActualSeqLenQ(tempLoopInfo.bIdx); // 获取actualSeqLength - bool isS1ZeroAndLastBatch = - (tempLoopInfo.actS1Size == 0) && - ((constInfo.outputLayout == SMLA_LAYOUT::BSND) || - (bN2LoopIdx + 1 == constInfo.bN2End)); - uint32_t gS1SplitNum = - CeilDiv(tempLoopInfo.actS1Size * constInfo.gSize, constInfo.mBaseSize); - - // 当处于最后一个BN2时, 且gS1End为0时, 说明当前BN2里的所有数据都在当前核处理 - gS1LoopEnd = (bN2LoopIdx + 1 == constInfo.bN2End && constInfo.gS1End != 0) - ? constInfo.gS1End - : gS1SplitNum; - // 当处于最后一个BN2且当前S1为0时,需要进入循环计算preload导致的未完成的部分 - gS1LoopEnd = isS1ZeroAndLastBatch ? gS1LoopEnd + 1 : gS1LoopEnd; - for (uint32_t gS1LoopIdx = constInfo.gS1Start; gS1LoopIdx < gS1LoopEnd; - gS1LoopIdx++) { - tempLoopInfo.actOriS2Size = GetActualSeqLenKV(tempLoopInfo.bIdx); - tempLoopInfo.actCmpS2Size = - GetActualSeqLenCmpKV(tempLoopInfo.bIdx, tempLoopInfo.actOriS2Size); - // 计算需要的数据, 避免重复计算 - tempLoopInfo.gS1Idx = gS1LoopIdx * constInfo.mBaseSize; - tempLoopInfo.s1StartIdx = tempLoopInfo.gS1Idx / constInfo.gSize; - tempLoopInfo.s1EndIdx = Min( - (tempLoopInfo.s1StartIdx + constInfo.mBaseSize / constInfo.gSize - 1), - tempLoopInfo.actS1Size - 1); - - // 此处均为闭区间 - tempLoopInfo.oriMaskRight = - tempLoopInfo.actOriS2Size - tempLoopInfo.actS1Size + - static_cast(tempLoopInfo.s1EndIdx) + constInfo.oriWinRight; - tempLoopInfo.oriMaskLeft = - Max(tempLoopInfo.actOriS2Size - tempLoopInfo.actS1Size + - static_cast(tempLoopInfo.s1EndIdx) - - constInfo.oriWinLeft, - 0); - int32_t cmpMaskS2Size = GetCmpMaskS2Size(tempLoopInfo.bIdx, - tempLoopInfo.actOriS2Size, - tempLoopInfo.actCmpS2Size); - tempLoopInfo.cmpMaskRight = cmpMaskS2Size - tempLoopInfo.actS1Size; - GetSparseActualSeqLen(); - UpdateInnerLoopCond(); - - uint32_t oriS2Size = - tempLoopInfo.oriMaskRight - tempLoopInfo.oriMaskLeft + 1; - uint32_t oriSplitNum = 0; - uint32_t cmpSplitNum = 0; - uint32_t cmpS2Size = 0; - bool isEnd = (bN2LoopIdx + 1 == constInfo.bN2End) && - (gS1LoopIdx + 1 == gS1LoopEnd); - if (tempLoopInfo.curActSeqLenIsZero) { - if ASCEND_IS_AIV { - InitAllZeroOutput( - tempLoopInfo.bIdx, tempLoopInfo.s1StartIdx, tempLoopInfo.n2Idx); - } - if (!isEnd) { - continue; - } - } else { - oriSplitNum = CeilDiv(oriS2Size, constInfo.s2BaseSize); - cmpS2Size = tempLoopInfo.actCmpS2Size; - cmpSplitNum = CeilDiv(cmpS2Size, constInfo.s2BaseSize); - } - - uint32_t s2SplitNum = oriSplitNum + cmpSplitNum; - constexpr uint32_t V0_SPLIT = 32; // align to 32 - uint32_t v0OriSize = - CeilDiv(oriS2Size * cmpS2Size, oriS2Size + cmpS2Size); - if (cmpS2Size > V0_SPLIT * oriSplitNum) { - v0OriSize = SMLAAlign(v0OriSize, V0_SPLIT * oriSplitNum); - } - uint32_t v0CmpSize = cmpS2Size - v0OriSize; - - tempLoopInfo.oriLoopTimes = oriSplitNum; - tempLoopInfo.cmpLoopTimes = cmpSplitNum; - tempLoopInfo.s2LoopTimes = s2SplitNum; - tempLoopInfo.v0OriSize = v0OriSize; - tempLoopInfo.v0CmpSize = v0CmpSize; - - uint32_t s2LoopEnd = (isEnd && constInfo.s2End != 0) - ? constInfo.s2End - : tempLoopInfo.s2LoopTimes; - tempLoopInfo.s2LoopTimes = s2LoopEnd; - // 分核修改后需要打开 - // 当前s2是否被切,决定了输出是否要写到attenOut上 - tempLoopInfo.tndIsS2SplitCore = - ((constInfo.s2Start == 0) && (s2LoopEnd == s2SplitNum)) ? false - : true; - tempLoopInfo.tndCoreStartKVSplitPos = - globalLoopStart ? constInfo.coreStartKVSplitPos : 0; - uint32_t extraLoop = isEnd ? 2 : 0; - uint32_t curTopKIdx = 0; - for (uint32_t s2LoopIdx = constInfo.s2Start; - s2LoopIdx < (s2LoopEnd + extraLoop); - s2LoopIdx++) { - PreloadPipeline( - gloop, cmpLoop, constInfo.s2Start, s2LoopIdx, extraInfo); - ++gloop; - if (s2LoopIdx >= tempLoopInfo.oriLoopTimes && - s2LoopIdx < s2LoopEnd) { // 用于判断v0使用的循环GM的id - ++cmpLoop; - } - } - globalLoopStart = false; - constInfo.s2Start = 0; - } - constInfo.gS1Start = 0; - } - if ASCEND_IS_AIV { - CrossCoreWaitFlag(3); - CrossCoreWaitFlag(3); - CrossCoreWaitFlag(3); - CrossCoreWaitFlag(3); - } -} - -template -__aicore__ inline void SparseFlashMlaCsa::PreloadPipeline( - uint32_t loop, - uint32_t cmpLoop, - uint64_t s2Start, - uint64_t s2LoopIdx, - RunInfo extraInfo[SMLA_PRELOAD_TASK_CACHE_SIZE]) { - RunInfo& extraInfo0 = - extraInfo[loop % SMLA_PRELOAD_TASK_CACHE_SIZE]; // 本轮任务 - RunInfo& extraInfo2 = - extraInfo[(loop + 2) % SMLA_PRELOAD_TASK_CACHE_SIZE]; // 上一轮任务 - RunInfo& extraInfo1 = - extraInfo[(loop + 1) % SMLA_PRELOAD_TASK_CACHE_SIZE]; // 上两轮任务 - - CalcParams(loop, cmpLoop, s2Start, s2LoopIdx, extraInfo0); - if constexpr (!HEAD_RATIO_ONE) { - if (extraInfo0.isValid) { - if ASCEND_IS_AIC { - if (!extraInfo0.isOriOnly) { - CrossCoreWaitFlag(constInfo.syncV0C1); - } - ComputeMm1(extraInfo0); - } else { - if (extraInfo0.isFirstSInnerLoop) { - CrossCoreWaitFlag(3); - } - vectorBlock.ProcessVec0L(extraInfo0); - if (!extraInfo0.isOriOnly) { - CrossCoreSetFlag( - constInfo.syncV0C1); - } - } - } - if (extraInfo2.isValid) { - if ASCEND_IS_AIV { - vectorBlock.ProcessVec1L(extraInfo2); - } - if ASCEND_IS_AIC { - ComputeMm2(extraInfo2); - if (extraInfo2.isLastS2Loop) { - CrossCoreSetFlag(3); - } - } - } - if (extraInfo1.isValid) { - if ASCEND_IS_AIV { - vectorBlock.ProcessVec2L(extraInfo1); - } - extraInfo1.isValid = false; - } - } else { - if (extraInfo0.isValid) { - if ASCEND_IS_AIV { - if (extraInfo0.isFirstSInnerLoop) { - CrossCoreWaitFlag(3); - } - vectorBlock.ProcessVec0L(extraInfo0); - if (!extraInfo0.isOriOnly) { - CrossCoreSetFlag( - constInfo.syncV0C1); - } - } - } - if (extraInfo2.isValid) { - if ASCEND_IS_AIV { - vectorBlock.ProcessVec1L(extraInfo2); - } - if ASCEND_IS_AIC { - ComputeMm2(extraInfo2); - if (extraInfo2.isLastS2Loop) { - CrossCoreSetFlag(3); - } - } - } - if (extraInfo1.isValid) { - if ASCEND_IS_AIV { - vectorBlock.ProcessVec2L(extraInfo1); - } - extraInfo1.isValid = false; - } - if (extraInfo0.isValid) { - if ASCEND_IS_AIC { - if (!extraInfo0.isOriOnly) { - CrossCoreWaitFlag( - constInfo.syncV0C1); - } - ComputeMm1(extraInfo0); - } - } - } -} - -} // namespace SMLAKernel -#endif // SPARSE_FLASH_MLA_CSA_KERNEL_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_block_cube.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_block_cube.h deleted file mode 100644 index cf92f16c83..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_block_cube.h +++ /dev/null @@ -1,1539 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file sparse_flash_mla_swa_block_cube.h - * \brief use 7 buffer for matmul l1, better pipeline - */ -#ifndef SPARSE_FLASH_MLA_SWA_BLOCK_CUBE_H -#define SPARSE_FLASH_MLA_SWA_BLOCK_CUBE_H - -#include "kernel_operator.h" -#include "kernel_operator_list_tensor_intf.h" -#include "kernel_tiling/kernel_tiling.h" -#include "lib/matmul_intf.h" -#include "lib/matrix/matmul/tiling.h" -#include "sparse_flash_mla_common_arch22.h" - -namespace SMLAKernel { -template -class SWACubeBlock { - public: - // 中间计算数据类型为float, 高精度模式 - using T = float; - using Q_T = typename SMLAT::queryType; - using KV_T = typename SMLAT::kvType; - using OUT_T = typename SMLAT::outputType; - using MM_OUT_T = T; - - __aicore__ inline SWACubeBlock(){}; - __aicore__ inline void InitParams(const ConstInfo& constInfo); - __aicore__ inline void InitMm1GlobalTensor(GlobalTensor queryGm, - GlobalTensor oriKvGm, - GlobalTensor cmpKV, - GlobalTensor mm1ResGm); - __aicore__ inline void InitMm2GlobalTensor( - GlobalTensor vec1ResGm, - GlobalTensor mm2ResGm, - GlobalTensor attentionOutGm); - __aicore__ inline void InitPageAttentionInfo( - GlobalTensor oriKvGm, - GlobalTensor oriBlockTableGm, - GlobalTensor cmpBlockTableGm); - __aicore__ inline void InitDsparkKvMerge(GlobalTensor kvMergeGm); - __aicore__ inline void InitBuffers(TPipe* pipe); - - __aicore__ inline void AllocEventID(); - __aicore__ inline void FreeEventID(); - __aicore__ inline void ComputeMm1(const RunInfo& info, - const MSplitInfo mSplitInfo); - __aicore__ inline void ComputeMm2(const RunInfo& info, - const MSplitInfo mSplitInfo); - - private: - static constexpr bool PAGE_ATTENTION = SMLAT::pageAttention; - static constexpr int TEMPLATE_MODE = SMLAT::templateMode; - static constexpr bool FLASH_DECODE = SMLAT::flashDecode; - static constexpr SMLA_LAYOUT LAYOUT_T = SMLAT::layout; - static constexpr SMLA_LAYOUT KV_LAYOUT_T = SMLAT::kvLayout; - static constexpr bool IS_DSPARK = SMLAT::isDspark; - - static constexpr uint32_t M_SPLIT_SIZE = 128; // m方向切分 - static constexpr uint32_t N_SPLIT_SIZE = 128; // n方向切分 - static constexpr uint32_t K_L0_SPLIT_SIZE = 128; // k方向L0切分 - static constexpr uint32_t K_L1_SPLIT_SIZE = 256; // k方向L1切分 - static constexpr uint32_t N_WORKSPACE_SIZE = 512; // n方向切分 - static constexpr uint32_t MERGE_CACHE_GM_BUF_NUM = 3; - static constexpr uint32_t D_SPLIT_SIZE = 256; // d轴切分 - - static constexpr uint32_t L1_BLOCK_SIZE = (64 * 512 * sizeof(Q_T)); - static constexpr uint32_t L1_BLOCK_OFFSET = 64 * 512; - - static constexpr uint32_t L0A_PP_SIZE = (32 * 1024); - static constexpr uint32_t L0B_PP_SIZE = (32 * 1024); - static constexpr uint32_t L0C_PP_SIZE = (64 * 1024); - - // mte2 <> mte1 EventID - // L1 3buf, 使用3个eventId - static constexpr uint32_t L1_EVENT0 = EVENT_ID2; - static constexpr uint32_t L1_EVENT1 = EVENT_ID3; - static constexpr uint32_t L1_EVENT2 = EVENT_ID4; - static constexpr uint32_t L1_EVENT3 = EVENT_ID5; - static constexpr uint32_t L1_EVENT4 = EVENT_ID6; - static constexpr uint32_t L1_EVENT5 = EVENT_ID7; - static constexpr uint32_t L1_EVENT6 = EVENT_ID1; - - // m <> mte1 EventID - static constexpr uint32_t L0AB_EVENT0 = EVENT_ID3; - static constexpr uint32_t L0AB_EVENT1 = EVENT_ID4; - - static constexpr IsResetLoad3dConfig LOAD3DV2_CONFIG = { - true, - true}; // isSetFMatrix isSetPadding; - static constexpr uint32_t mte21QPIds[4] = {L1_EVENT0, - L1_EVENT1, - L1_EVENT2, - L1_EVENT3}; // mte12复用 - static constexpr uint32_t mte21KVIds[3] = {L1_EVENT4, L1_EVENT5, L1_EVENT6}; - - ConstInfo constInfo{}; - - // L1分成3块buf, 用于记录 - uint32_t qpL1BufIter = 0; - uint32_t kvL1BufIter = -1; - uint32_t abL0BufIter = 0; - uint32_t cL0BufIter = 0; - - // mm1 - GlobalTensor queryGm; - GlobalTensor keyGm; - GlobalTensor mm1ResGm; - GlobalTensor kvMergeGm_; - GlobalTensor oriKvGm; - GlobalTensor cmpKvGm; - - // mm2 - GlobalTensor vec1ResGm; - GlobalTensor valueGm; - GlobalTensor mm2ResGm; - GlobalTensor attentionOutGm; - - // block_table - GlobalTensor oriBlockTableGm; - GlobalTensor cmpBlockTableGm; - - TBuf bufQPL1; - TBuf bufKVL1; - TBuf tmpBufL0A; - TBuf tmpBufL0B; - TBuf tmpBufL0C; - - LocalTensor l1QPTensor; - LocalTensor l1KVTensor; - LocalTensor aL0TensorPingPong; - LocalTensor bL0TensorPingPong; - LocalTensor cL0TensorPingPong; - - // L0AB m <> mte1 EventID - __aicore__ inline uint32_t Mte1MmABEventId(uint32_t idx) { - return (L0AB_EVENT0 + idx); - } - - __aicore__ inline uint32_t GetQPL1RealIdx(uint32_t mIdx, uint32_t k1Idx) { - uint32_t idxMap[] = { - 0, 2}; // 确保0块和1块连在一起, 2和3块连在一起, 来保证同一m块的地址相连 - return idxMap[mIdx % 2] + k1Idx; - } - - __aicore__ inline void CopyGmToL1(LocalTensor& l1Tensor, - GlobalTensor& gmSrcTensor, - uint32_t srcN, - uint32_t srcD, - uint32_t srcDstride); - __aicore__ inline void CopyInMm1AToL1(LocalTensor& aL1Tensor, - const RunInfo& info, - uint32_t mSeqIdx, - uint32_t mSizeAct, - uint32_t headSize, - uint32_t headOffset); - __aicore__ inline void CopyInMm2AToL1(LocalTensor& aL1Tensor, - const RunInfo& info, - uint32_t mSeqIdx, - uint32_t subMSizeAct, - uint32_t nSize, - uint32_t nOffset); - __aicore__ inline void LoadDataMm1A(LocalTensor& aL0Tensor, - LocalTensor& aL1Tensor, - uint32_t idx, - uint32_t kSplitSize, - uint32_t mSize, - uint32_t kSize); - __aicore__ inline void LoadDataMm1B(LocalTensor& bL0Tensor, - LocalTensor& bL1Tensor, - uint32_t idx, - uint32_t kSplitSize, - uint32_t kSize, - uint32_t nSize); -}; - -template -__aicore__ inline void SWACubeBlock::InitParams( - const ConstInfo& constInfo) { - this->constInfo = constInfo; -} - -template -__aicore__ inline void SWACubeBlock::InitMm1GlobalTensor( - GlobalTensor queryGm, - GlobalTensor oriKvGm, - GlobalTensor cmpKvGm, - GlobalTensor mm1ResGm) { - // mm1 - this->queryGm = queryGm; - this->oriKvGm = oriKvGm; - if constexpr (TEMPLATE_MODE == HCA_TEMPLATE) { - this->cmpKvGm = cmpKvGm; - } - this->mm1ResGm = mm1ResGm; -} - -template -__aicore__ inline void SWACubeBlock::InitMm2GlobalTensor( - GlobalTensor vec1ResGm, - GlobalTensor mm2ResGm, - GlobalTensor attentionOutGm) { - // mm2 - this->vec1ResGm = vec1ResGm; - this->mm2ResGm = mm2ResGm; - this->attentionOutGm = attentionOutGm; -} - -template -__aicore__ inline void SWACubeBlock::InitPageAttentionInfo( - GlobalTensor oriKvGm, - GlobalTensor oriBlockTableGm, - GlobalTensor cmpBlockTableGm) { - this->oriKvGm = oriKvGm; - this->oriBlockTableGm = oriBlockTableGm; - if constexpr (TEMPLATE_MODE == HCA_TEMPLATE) { - this->cmpBlockTableGm = cmpBlockTableGm; - } -} - -template -__aicore__ inline void SWACubeBlock::InitDsparkKvMerge( - GlobalTensor kvMergeGm) { - this->kvMergeGm_ = kvMergeGm; -} - -template -__aicore__ inline void SWACubeBlock::InitBuffers(TPipe* pipe) { - pipe->InitBuffer(bufQPL1, L1_BLOCK_SIZE * 4); - l1QPTensor = bufQPL1.Get(); - pipe->InitBuffer(bufKVL1, L1_BLOCK_SIZE * 3); - l1KVTensor = bufKVL1.Get(); - // L0A - pipe->InitBuffer(tmpBufL0A, L0A_PP_SIZE * 2); // 64K - aL0TensorPingPong = tmpBufL0A.Get(); - // L0B - pipe->InitBuffer(tmpBufL0B, L0B_PP_SIZE * 2); // 64K - bL0TensorPingPong = tmpBufL0B.Get(); - // L0C - pipe->InitBuffer(tmpBufL0C, L0C_PP_SIZE * 2); // 128K - cL0TensorPingPong = tmpBufL0C.Get(); -} - -template -__aicore__ inline void SWACubeBlock::AllocEventID() { - SetFlag(L1_EVENT0); - SetFlag(L1_EVENT1); - SetFlag(L1_EVENT2); - SetFlag(L1_EVENT3); - SetFlag(L1_EVENT4); - SetFlag(L1_EVENT5); - SetFlag(L1_EVENT6); - SetFlag(L0AB_EVENT0); - SetFlag(L0AB_EVENT1); -} - -template -__aicore__ inline void SWACubeBlock::FreeEventID() { - WaitFlag(L1_EVENT0); - WaitFlag(L1_EVENT1); - WaitFlag(L1_EVENT2); - WaitFlag(L1_EVENT3); - WaitFlag(L1_EVENT4); - WaitFlag(L1_EVENT5); - WaitFlag(L1_EVENT6); - WaitFlag(L0AB_EVENT0); - WaitFlag(L0AB_EVENT1); -} - -template -__aicore__ inline void SWACubeBlock::CopyGmToL1( - LocalTensor& l1Tensor, - GlobalTensor& gmSrcTensor, - uint32_t srcN, - uint32_t srcD, - uint32_t srcDstride) { - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = srcN; // 行数 - nd2nzPara.dValue = srcD; - nd2nzPara.srcDValue = srcDstride; - nd2nzPara.dstNzC0Stride = (srcN + 15) / 16 * 16; // 对齐到16 单位block - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - DataCopy(l1Tensor, gmSrcTensor, nd2nzPara); -} - -template -__aicore__ inline void SWACubeBlock::CopyInMm1AToL1( - LocalTensor& l1Tensor, - const RunInfo& info, - uint32_t mSeqIdx, - uint32_t mSizeAct, - uint32_t headSize, - uint32_t headOffset) { - auto srcGm = - queryGm[info.tensorAOffset + mSeqIdx * constInfo.headDim + headOffset]; - CopyGmToL1(l1Tensor, srcGm, mSizeAct, headSize, constInfo.headDim); -} - -template -__aicore__ inline void SWACubeBlock::LoadDataMm1A( - LocalTensor& aL0Tensor, - LocalTensor& aL1Tensor, - uint32_t idx, - uint32_t kSplitSize, - uint32_t mSize, - uint32_t kSize) { - LocalTensor srcTensor = aL1Tensor[mSize * kSplitSize * idx]; - LoadData3DParamsV2 loadData3DParams; - // SetFmatrixParams - loadData3DParams.l1H = mSize / 16; // Hin=M1=8 - loadData3DParams.l1W = 16; // Win=M0 - loadData3DParams.padList[0] = 0; - loadData3DParams.padList[1] = 0; - loadData3DParams.padList[2] = 0; - loadData3DParams.padList[3] = 255; // 尾部数据不影响滑窗的结果 - - // SetLoadToA0Params - loadData3DParams.mExtension = mSize; // M - loadData3DParams.kExtension = kSize; // K - loadData3DParams.mStartPt = 0; - loadData3DParams.kStartPt = 0; - loadData3DParams.strideW = 1; - loadData3DParams.strideH = 1; - loadData3DParams.filterW = 1; - loadData3DParams.filterSizeW = (1 >> 8) & 255; - loadData3DParams.filterH = 1; - loadData3DParams.filterSizeH = (1 >> 8) & 255; - loadData3DParams.dilationFilterW = 1; - loadData3DParams.dilationFilterH = 1; - loadData3DParams.enTranspose = 0; - loadData3DParams.fMatrixCtrl = 0; - loadData3DParams.channelSize = kSize; // Cin=K - LoadData(aL0Tensor, srcTensor, loadData3DParams); -} - -template -__aicore__ inline void SWACubeBlock::LoadDataMm1B( - LocalTensor& l0Tensor, - LocalTensor& l1Tensor, - uint32_t idx, - uint32_t kSplitSize, - uint32_t kSize, - uint32_t nSize) { - // N 方向全载 - LocalTensor srcTensor = l1Tensor[nSize * kSplitSize * idx]; - LoadData2DParams loadData2DParams; - loadData2DParams.startIndex = 0; - loadData2DParams.repeatTimes = - (nSize + 15) / 16 * kSize / (32 / sizeof(KV_T)); - loadData2DParams.srcStride = 1; - loadData2DParams.dstGap = 0; - loadData2DParams.ifTranspose = false; - LoadData(l0Tensor, srcTensor, loadData2DParams); -} - -template -__aicore__ inline void SWACubeBlock::CopyInMm2AToL1( - LocalTensor& aL1Tensor, - const RunInfo& info, - uint32_t mSeqIdx, - uint32_t subMSizeAct, - uint32_t nSize, - uint32_t nOffset) { - auto srcGm = - vec1ResGm[(info.loop % constInfo.preLoadNum) * constInfo.mmResUbSize + - mSeqIdx * info.actualSingleProcessSInnerSizeAlign + nOffset]; - CopyGmToL1(aL1Tensor, - srcGm, - subMSizeAct, - nSize, - info.actualSingleProcessSInnerSizeAlign); -} - -template -__aicore__ inline void SWACubeBlock::ComputeMm1( - const RunInfo& info, - const MSplitInfo mSplitInfo) { - uint32_t mSize = mSplitInfo.nBufferDealM; - uint32_t mL1Size = M_SPLIT_SIZE; - uint32_t mL1SizeAlign = SMLAAlign(M_SPLIT_SIZE, 16); - uint32_t mL1Loops = CeilDiv(mSize, M_SPLIT_SIZE); - - uint32_t nSize = info.actualSingleProcessSInnerSize; - uint32_t nL1Size = N_SPLIT_SIZE; - uint32_t nL1SizeAlign = SMLAAlign(N_SPLIT_SIZE, 16); - uint32_t nL1Loops = CeilDiv(nSize, N_SPLIT_SIZE); - - uint32_t kSize = 512; - uint32_t kL1Size = 256; - uint32_t kL1Loops = 2; - uint32_t kL0Size = 128; - uint32_t kL0Loops = CeilDiv(kL1Size, kL0Size); - - LocalTensor bL1Tensor; - LocalTensor kTensor; - uint32_t ka = 0, kb = 0; - uint32_t copyRowCnt = 0; - uint32_t copyRowCntTmp = 0; - // L1 切n切k - for (uint32_t nL1 = 0; nL1 < nL1Loops; nL1++) { // L1切n, 512/128=4 - if (nL1 == (nL1Loops - 1)) { - // 尾块重新计算size - nL1Size = nSize - (nL1Loops - 1) * N_SPLIT_SIZE; - nL1SizeAlign = SMLAAlign(nL1Size, 16); - } - - for (uint32_t kL1 = 0; kL1 < kL1Loops; kL1++) { - kvL1BufIter++; - uint32_t kb = kvL1BufIter % 3; - WaitFlag(mte21KVIds[kb]); - // 从k当中取当前的块 - bL1Tensor = l1KVTensor[kb * L1_BLOCK_OFFSET]; - uint32_t copyFinishRowCnt = 0; - - if (info.isOriOnly) { - if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { - uint64_t curS2Offset = - static_cast(info.s2Idx) * constInfo.s2BaseSize + - info.s2StartPoint + nL1 * N_SPLIT_SIZE; - uint32_t copyFinishRowCnt = 0; - LocalTensor kTensor; - uint32_t copyRowCnt = 0; - - if constexpr (IS_DSPARK) { - uint64_t mergeBase = - static_cast(info.cmpLoop % MERGE_CACHE_GM_BUF_NUM) * - N_WORKSPACE_SIZE * constInfo.headDim; - uint32_t blockElementCnt = 32U / sizeof(KV_T); - for (uint32_t row = 0; row < nL1Size; ++row) { - uint64_t mergeOffset = - mergeBase + - static_cast(nL1 * N_SPLIT_SIZE + row) * - constInfo.headDim + - kL1 * D_SPLIT_SIZE; - GlobalTensor mergeSrcGm = kvMergeGm_[mergeOffset]; - kTensor = bL1Tensor[row * blockElementCnt]; - DataCopyGmNDToL1(kTensor, - mergeSrcGm, - 1, - nL1SizeAlign, - D_SPLIT_SIZE, - constInfo.headDim); - } - } else - while (copyFinishRowCnt < nL1Size) { - // 由于ori_left的存在, 即使第一块搬运也可能并非是pa_block的零点位 - copyRowCnt = constInfo.paOriBlockSize - - curS2Offset % constInfo.paOriBlockSize; - if (copyFinishRowCnt + copyRowCnt > nL1Size) { - copyRowCnt = nL1Size - copyFinishRowCnt; - } - Position startPos; - startPos.bIdx = info.bIdx; - startPos.n2Idx = info.n2Idx; - startPos.s2Idx = curS2Offset; - // 256、32等待7buf命名更改 - startPos.dIdx = kL1 * 256; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 - // 右矩阵, s2为k轴, d轴切分 - PAShape shape; - shape.blockSize = constInfo.paOriBlockSize; - shape.headNum = constInfo.kvHeadNum; - shape.headDim = constInfo.headDim; - shape.kvStride = constInfo.oriKvStride0; - shape.actHeadDim = 256; - shape.maxblockNumPerBatch = constInfo.oriMaxBlockNumPerBatch; - shape.copyRowNum = copyRowCnt; - shape.copyRowNumAlign = nL1SizeAlign; - kTensor = bL1Tensor[copyFinishRowCnt * 16]; - DataCopyPA( - kTensor, oriKvGm, oriBlockTableGm, shape, startPos); - // 更新循环变量 - copyFinishRowCnt += copyRowCnt; - curS2Offset += copyRowCnt; - } - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = nL1Size; // 行数 - nd2nzPara.dValue = D_SPLIT_SIZE; // 256 - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = nL1SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - - uint32_t headStride = constInfo.headDim; - uint32_t seqStride = constInfo.kvHeadNum * constInfo.headDim; - uint64_t batchStride = - (constInfo.oriKvStride0 == 0) - ? static_cast(constInfo.kvSeqSize) * seqStride - : constInfo.oriKvStride0; - - uint64_t curS2 = info.s2StartPoint + nL1 * N_SPLIT_SIZE; - uint64_t offset = - (uint64_t)info.bIdx * batchStride + (uint64_t)curS2 * seqStride + - (uint64_t)info.n2Idx * headStride + kL1 * D_SPLIT_SIZE; - DataCopy(bL1Tensor, oriKvGm[offset], nd2nzPara); - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { - uint64_t curS2Offset = - static_cast(info.s2Idx) * - static_cast(constInfo.s2BaseSize) + - info.s2StartPoint + nL1 * N_SPLIT_SIZE; - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = nL1Size; - nd2nzPara.dValue = constInfo.headDim >> 1; - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = nL1SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - DataCopy( - bL1Tensor, - oriKvGm[info.tensorBOffset + curS2Offset * constInfo.headDim + - kL1 * D_SPLIT_SIZE], - nd2nzPara); - } - } else if (info.isOriCmpMix) { - uint32_t cumNl1LoopSize = nL1 * N_SPLIT_SIZE; - uint32_t oriSizeCur = - (info.actualSingleProcessSInnerOriSize < cumNl1LoopSize) - ? 0 - : (info.actualSingleProcessSInnerOriSize - cumNl1LoopSize); - oriSizeCur = (oriSizeCur > nL1Size) ? nL1Size : oriSizeCur; - uint32_t cmpSizeCur = nL1Size - oriSizeCur; - cmpSizeCur = (cmpSizeCur < info.actualSingleProcessSInnerCmpSize) - ? cmpSizeCur - : info.actualSingleProcessSInnerCmpSize; - if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { - LocalTensor kTensor; - uint32_t copyRowCnt = 0; - - if (oriSizeCur > 0) { - uint32_t copyFinishRowCnt = 0; - uint64_t curS2Offset = info.s2StartPoint + nL1 * N_SPLIT_SIZE; - while (copyFinishRowCnt < oriSizeCur) { - // 由于ori_left的存在, 即使第一块搬运也可能并非是pa_block的零点位 - copyRowCnt = constInfo.paOriBlockSize - - curS2Offset % constInfo.paOriBlockSize; - if (copyFinishRowCnt + copyRowCnt > oriSizeCur) { - copyRowCnt = oriSizeCur - copyFinishRowCnt; - } - Position startPos; - startPos.bIdx = info.bIdx; - startPos.n2Idx = info.n2Idx; - startPos.s2Idx = curS2Offset; - // 256、32等待7buf命名更改 - startPos.dIdx = kL1 * 256; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 - // 右矩阵, s2为k轴, d轴切分 - PAShape shape; - shape.blockSize = constInfo.paOriBlockSize; - shape.headNum = constInfo.kvHeadNum; - shape.headDim = constInfo.headDim; - shape.kvStride = constInfo.oriKvStride0; - shape.actHeadDim = 256; - shape.maxblockNumPerBatch = constInfo.oriMaxBlockNumPerBatch; - shape.copyRowNum = copyRowCnt; - shape.copyRowNumAlign = nL1SizeAlign; - kTensor = bL1Tensor[copyFinishRowCnt * 16]; - DataCopyPA( - kTensor, oriKvGm, oriBlockTableGm, shape, startPos); - // 更新循环变量 - copyFinishRowCnt += copyRowCnt; - curS2Offset += copyRowCnt; - } - } - if (cmpSizeCur > 0) { - uint32_t cmpMixsizeCur = - N_SPLIT_SIZE - - info.actualSingleProcessSInnerOriSize % N_SPLIT_SIZE; - uint32_t oriOnlyLoopTimes = - info.actualSingleProcessSInnerOriSize / N_SPLIT_SIZE; - uint32_t cmpLoopTimes = nL1 - oriOnlyLoopTimes; - uint64_t curS2Offset = - (cmpLoopTimes == 0) - ? 0 - : (cmpMixsizeCur + - static_cast(cmpLoopTimes - 1) * N_SPLIT_SIZE); - uint32_t copyFinishRowCnt = 0; - while (copyFinishRowCnt < cmpSizeCur) { - // 由于ori_left的存在, 即使第一块搬运也可能并非是pa_block的零点位 - copyRowCnt = constInfo.paCmpBlockSize - - curS2Offset % constInfo.paCmpBlockSize; - if (copyFinishRowCnt + copyRowCnt > cmpSizeCur) { - copyRowCnt = cmpSizeCur - copyFinishRowCnt; - } - Position startPos; - startPos.bIdx = info.bIdx; - startPos.n2Idx = info.n2Idx; - startPos.s2Idx = curS2Offset; - // 256、32等待7buf命名更改 - startPos.dIdx = kL1 * 256; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 - // 右矩阵, s2为k轴, d轴切分 - PAShape shape; - shape.blockSize = constInfo.paCmpBlockSize; - shape.headNum = constInfo.kvHeadNum; - shape.headDim = constInfo.headDim; - shape.kvStride = constInfo.cmpKvStride0; - shape.actHeadDim = 256; - shape.maxblockNumPerBatch = constInfo.cmpMaxBlockNumPerBatch; - shape.copyRowNum = copyRowCnt; - shape.copyRowNumAlign = nL1SizeAlign; - kTensor = bL1Tensor[copyFinishRowCnt * 16 + oriSizeCur * 16]; - DataCopyPA( - kTensor, cmpKvGm, cmpBlockTableGm, shape, startPos); - // 更新循环变量 - copyFinishRowCnt += copyRowCnt; - curS2Offset += copyRowCnt; - } - } - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = nL1Size; // 行数 - nd2nzPara.dValue = D_SPLIT_SIZE; // 256 - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = nL1SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - - uint32_t headStride = constInfo.headDim; - uint32_t seqStride = constInfo.kvHeadNum * constInfo.headDim; - if (oriSizeCur > 0) { - nd2nzPara.nValue = oriSizeCur; - uint64_t batchStride = - (constInfo.oriKvStride0 == 0) - ? static_cast(constInfo.kvSeqSize) * seqStride - : constInfo.oriKvStride0; - uint64_t curS2 = info.s2StartPoint + nL1 * N_SPLIT_SIZE; - uint64_t offset = (uint64_t)info.bIdx * batchStride + - (uint64_t)curS2 * seqStride + - (uint64_t)info.n2Idx * headStride + - kL1 * D_SPLIT_SIZE; - DataCopy(bL1Tensor, oriKvGm[offset], nd2nzPara); - } - if (cmpSizeCur > 0) { - nd2nzPara.nValue = cmpSizeCur; - uint64_t batchStride = - (constInfo.cmpKvStride0 == 0) - ? static_cast(constInfo.cmpSeqSize) * seqStride - : constInfo.cmpKvStride0; - uint32_t cmpMixsizeCur = - N_SPLIT_SIZE - - info.actualSingleProcessSInnerOriSize % N_SPLIT_SIZE; - uint32_t oriOnlyLoopTimes = - info.actualSingleProcessSInnerOriSize / N_SPLIT_SIZE; - uint32_t cmpLoopTimes = nL1 - oriOnlyLoopTimes; - uint64_t curS2 = - (cmpLoopTimes == 0) - ? 0 - : (cmpMixsizeCur + (cmpLoopTimes - 1) * N_SPLIT_SIZE); - uint64_t offset = - (uint64_t)info.bIdx * batchStride + curS2 * seqStride + - (uint64_t)info.n2Idx * headStride + kL1 * D_SPLIT_SIZE; - DataCopy(bL1Tensor[oriSizeCur * 16], cmpKvGm[offset], nd2nzPara); - } - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = nL1Size; - nd2nzPara.dValue = constInfo.headDim >> 1; - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = nL1SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - - if (oriSizeCur > 0) { - nd2nzPara.nValue = oriSizeCur; - uint64_t curS2Offset = info.s2StartPoint + nL1 * N_SPLIT_SIZE; - DataCopy( - bL1Tensor, - oriKvGm[info.tensorBOffset + curS2Offset * constInfo.headDim + - kL1 * D_SPLIT_SIZE], - nd2nzPara); - } - if (cmpSizeCur > 0) { - nd2nzPara.nValue = cmpSizeCur; - uint32_t cmpMixsizeCur = - N_SPLIT_SIZE - - info.actualSingleProcessSInnerOriSize % N_SPLIT_SIZE; - uint32_t oriOnlyLoopTimes = - info.actualSingleProcessSInnerOriSize / N_SPLIT_SIZE; - uint32_t cmpLoopTimes = nL1 - oriOnlyLoopTimes; - uint64_t curS2Offset = - (cmpLoopTimes == 0) - ? 0 - : (cmpMixsizeCur + - static_cast(cmpLoopTimes - 1) * N_SPLIT_SIZE); - DataCopy( - bL1Tensor[oriSizeCur * 16], - cmpKvGm[info.tensorCmpBOffset + - curS2Offset * constInfo.headDim + kL1 * D_SPLIT_SIZE], - nd2nzPara); - } - } - } else { - if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { - uint64_t curS2Offset = - static_cast(info.relativeS2Idx) * constInfo.s2BaseSize + - info.s2StartPoint + nL1 * N_SPLIT_SIZE; - while (copyFinishRowCnt < nL1Size) { - // 由于ori_left的存在, 即使第一块搬运也可能并非是pa_block的零点位 - copyRowCnt = constInfo.paCmpBlockSize - - curS2Offset % constInfo.paCmpBlockSize; - if (copyFinishRowCnt + copyRowCnt > nL1Size) { - copyRowCnt = nL1Size - copyFinishRowCnt; - } - - Position startPos; - startPos.bIdx = info.bIdx; - startPos.n2Idx = info.n2Idx; - startPos.s2Idx = curS2Offset; - // 256、32等待7buf命名更改 - startPos.dIdx = kL1 * 256; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 - // 右矩阵, s2为k轴, d轴切分 - - PAShape shape; - shape.blockSize = constInfo.paCmpBlockSize; - shape.headNum = constInfo.kvHeadNum; - shape.headDim = constInfo.headDim; - shape.kvStride = constInfo.cmpKvStride0; - shape.actHeadDim = 256; - shape.maxblockNumPerBatch = constInfo.cmpMaxBlockNumPerBatch; - shape.copyRowNum = copyRowCnt; - shape.copyRowNumAlign = nL1SizeAlign; - kTensor = bL1Tensor[copyFinishRowCnt * 16]; - DataCopyPA( - kTensor, cmpKvGm, cmpBlockTableGm, shape, startPos); - // 更新循环变量 - copyFinishRowCnt += copyRowCnt; - curS2Offset += copyRowCnt; - } - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = nL1Size; // 行数 - nd2nzPara.dValue = D_SPLIT_SIZE; // 256 - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = nL1SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - - uint32_t headStride = constInfo.headDim; - uint32_t seqStride = constInfo.kvHeadNum * constInfo.headDim; - uint64_t batchStride = - (constInfo.cmpKvStride0 == 0) - ? static_cast(constInfo.cmpSeqSize) * seqStride - : constInfo.cmpKvStride0; - - uint64_t curS2 = - static_cast(info.relativeS2Idx) * constInfo.s2BaseSize + - info.s2StartPoint + nL1 * N_SPLIT_SIZE; - uint64_t offset = - (uint64_t)info.bIdx * batchStride + (uint64_t)curS2 * seqStride + - (uint64_t)info.n2Idx * headStride + kL1 * D_SPLIT_SIZE; - DataCopy(bL1Tensor, cmpKvGm[offset], nd2nzPara); - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { - uint64_t curS2Offset = - static_cast(info.relativeS2Idx) * constInfo.s2BaseSize + - info.s2StartPoint + nL1 * N_SPLIT_SIZE; - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = nL1Size; - nd2nzPara.dValue = constInfo.headDim >> 1; - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = nL1SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - DataCopy( - bL1Tensor, - cmpKvGm[info.tensorCmpBOffset + curS2Offset * constInfo.headDim + - +kL1 * D_SPLIT_SIZE], - nd2nzPara); - } - } - - SetFlag(mte21KVIds[kb]); - WaitFlag(mte21KVIds[kb]); - mL1Size = M_SPLIT_SIZE; - mL1SizeAlign = SMLAAlign(M_SPLIT_SIZE, 16U); - for (uint32_t mL1 = 0; mL1 < mL1Loops; mL1++) { - uint32_t aL1PaddingSize = - 0; // 用于使左矩阵对齐到尾部, 以保证两块32K内存连续 - if (mL1 == (mL1Loops - 1)) { - mL1Size = mSize - (mL1Loops - 1) * M_SPLIT_SIZE; - mL1SizeAlign = SMLAAlign(mL1Size, 16U); - aL1PaddingSize = (M_SPLIT_SIZE - mL1SizeAlign) * 256; - } - uint32_t mIdx = qpL1BufIter + mL1; - ka = GetQPL1RealIdx(mIdx, kL1); - LocalTensor aL1Tensor = - l1QPTensor[ka * L1_BLOCK_OFFSET + (1 - kL1) * aL1PaddingSize]; - if (nL1 == 0) { - if (kL1 == 0) { - WaitFlag(mte21QPIds[ka]); - WaitFlag(mte21QPIds[ka + 1]); - CopyInMm1AToL1(aL1Tensor, - info, - mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, - mL1Size, - 256, - 0); - } else { - LocalTensor qTmpTensor = aL1Tensor; - CopyInMm1AToL1(qTmpTensor, - info, - mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, - mL1Size, - 256, - 256); - } - SetFlag(mte21QPIds[ka]); - WaitFlag(mte21QPIds[ka]); - } - // 使用unitflag同步 - LocalTensor cL0Tensor = cL0TensorPingPong - [(cL0BufIter % 2) * - (L0C_PP_SIZE / - sizeof(MM_OUT_T))]; // 需要保证cL0BufIter和m步调一致 - for (uint32_t kL0 = 0; kL0 < kL0Loops; kL0++) { - WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); - LocalTensor aL0Tensor = - aL0TensorPingPong[(abL0BufIter % 2) * - (L0A_PP_SIZE / sizeof(KV_T))]; - LoadDataMm1A( - aL0Tensor, aL1Tensor, kL0, kL0Size, mL1SizeAlign, kL0Size); - LocalTensor bL0Tensor = - bL0TensorPingPong[(abL0BufIter % 2) * - (L0B_PP_SIZE / sizeof(KV_T))]; - if (mL1 == 0) { - LoadDataMm1B( - bL0Tensor, bL1Tensor, kL0, kL0Size, kL0Size, nL1SizeAlign); - } - SetFlag(Mte1MmABEventId(abL0BufIter % 2)); - WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); - - MmadParams mmadParams; - mmadParams.m = mL1SizeAlign; - mmadParams.n = nL1SizeAlign; - mmadParams.k = kL0Size; - mmadParams.cmatrixInitVal = (kL1 == 0 && kL0 == 0); - mmadParams.cmatrixSource = false; - mmadParams.unitFlag = - (kL1 == 1 && kL0 == (kL0Loops - 1)) - ? 0b11 - : 0b10; // 累加最后一次翻转flag, 表示可以搬出 - Mmad(cL0Tensor, aL0Tensor, bL0Tensor, mmadParams); - if ((mmadParams.m / 16) * (mmadParams.n / 16) < 10) { - PipeBarrier(); - } - SetFlag(Mte1MmABEventId(abL0BufIter % 2)); - abL0BufIter++; - } - - if (nL1 == (nL1Loops - 1)) { - SetFlag( - mte21QPIds[ka]); // 反向同步, 表示L1中的A已经被mte1消费完 - } - - if (kL1 == 1) { // 最后一轮kL1循环 - FixpipeParamsV220 fixParams; - fixParams.nSize = nL1SizeAlign; - fixParams.mSize = mL1SizeAlign; - fixParams.srcStride = mL1SizeAlign; - // 改成nSizeAlign - fixParams.dstStride = - info.actualSingleProcessSInnerSizeAlign; // mm1ResGm两行之间的间隔 - fixParams.unitFlag = 0b11; - fixParams.ndNum = 1; // 输出ND - - Fixpipe(mm1ResGm[(info.loop % (constInfo.preLoadNum)) * - constInfo.mmResUbSize + - nL1 * N_SPLIT_SIZE + - (mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE) * - info.actualSingleProcessSInnerSizeAlign], - cL0Tensor, - fixParams); - } - if (mL1Loops == 2) { - cL0BufIter++; - } - } - - SetFlag( - mte21KVIds[kb]); // 反向同步, 表示L1已经被mte1消费完 - } - if (mL1Loops == 1) { - cL0BufIter++; - } - } - qpL1BufIter += mL1Loops; -} - -template -__aicore__ inline void SWACubeBlock::ComputeMm2( - const RunInfo& info, - const MSplitInfo mSplitInfo) { - uint32_t mSize = mSplitInfo.nBufferDealM; - uint32_t mSizeAlign = (mSize + 16 - 1) / 16; - uint32_t mL1Loops = (mSize + M_SPLIT_SIZE - 1) / M_SPLIT_SIZE; - uint32_t mL1SizeAlign = M_SPLIT_SIZE; // 16对齐 - uint32_t mL1Size = M_SPLIT_SIZE; // m的实际大小 - - uint32_t nSize = BlockAlign(constInfo.headDim); - uint32_t nL1Loops = (nSize + N_SPLIT_SIZE - 1) / N_SPLIT_SIZE; - uint32_t nL1SizeAlign = N_SPLIT_SIZE; // 16对齐 - uint32_t nL1Size = N_SPLIT_SIZE; // n的实际大小 - - uint32_t kSize = info.actualSingleProcessSInnerSize; - uint32_t kL1Size = K_L1_SPLIT_SIZE; - uint32_t kL1SizeAlign = SMLAAlign(kL1Size, 16U); - uint32_t kL1Loops = (kSize + kL1Size - 1) / kL1Size; - uint32_t kL0Size = K_L0_SPLIT_SIZE; - uint32_t kL0Loops = (kL1Size + kL0Size - 1) / kL0Size; - uint32_t kL0SizeAlign = kL0Size; - LocalTensor bL1Tensor; - LocalTensor subvTensor; - // ka表示左矩阵4buf选择哪一块buf, kb表示右矩阵3buf选择哪一块buf - uint32_t ka = 0, kb = 0; - uint32_t mBaseIdx = qpL1BufIter; - for (uint32_t nL1 = 0; nL1 < nL1Loops; nL1++) { // n切L1 - if (nL1 == (nL1Loops - 1)) { - // 尾块 - nL1Size = nSize - (nL1Loops - 1) * N_SPLIT_SIZE; - nL1SizeAlign = SMLAAlign(nL1Size, 16U); - } - // k l1写成一个循环, 和mm1保持一致 - kL1Size = K_L1_SPLIT_SIZE; - kL1SizeAlign = SMLAAlign(kL1Size, 16U); - uint32_t copyRowCnt = 0; - for (uint32_t k1 = 0; k1 < kL1Loops; k1++) { // k切L1, 这里套了一层l0来操作 - if (k1 == (kL1Loops - 1)) { - // 尾块 - kL1Size = kSize - (kL1Loops - 1) * K_L1_SPLIT_SIZE; - kL1SizeAlign = SMLAAlign(kL1Size, 16U); - } - kvL1BufIter++; - uint32_t kb = kvL1BufIter % 3; - WaitFlag(mte21KVIds[kb]); - bL1Tensor = l1KVTensor[kb * L1_BLOCK_OFFSET]; - uint32_t kOffset = k1 * kL0Loops; - kL0Size = K_L0_SPLIT_SIZE; - // 此处必须先初始化kL0Size, 再求kL0Loops, 否则由于循环会改变kL0Size大小, - // 导致kL0Loops错误 - kL0Loops = (kL1Size + kL0Size - 1) / kL0Size; - kL0SizeAlign = kL0Size; - for (uint32_t kL1 = kOffset; kL1 < kL0Loops + kOffset; - kL1++) { // 128 循环搬pa - if (kL1 == kOffset + kL0Loops - 1) { - // 尾块 - kL0Size = kL1Size - (kL0Loops - 1) * kL0Size; - kL0SizeAlign = SMLAAlign(kL0Size, 16U); - } - - uint32_t copyFinishRowCnt = 0; - if (info.isOriOnly) { - if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { - uint64_t curS2Offset = - static_cast(info.s2Idx) * constInfo.s2BaseSize + - info.s2StartPoint + kL1 * K_L0_SPLIT_SIZE; - if constexpr (IS_DSPARK) { - uint64_t mergeBase = - static_cast(info.cmpLoop % MERGE_CACHE_GM_BUF_NUM) * - N_WORKSPACE_SIZE * constInfo.headDim; - uint32_t blockElementCnt = 32U / sizeof(KV_T); - subvTensor = - bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE]; - for (uint32_t row = 0; row < kL0Size; ++row) { - uint64_t mergeOffset = - mergeBase + - static_cast(kL1 * K_L0_SPLIT_SIZE + row) * - constInfo.headDim + - nL1 * N_SPLIT_SIZE; - GlobalTensor mergeSrcGm = kvMergeGm_[mergeOffset]; - LocalTensor dstTensor = subvTensor[row * blockElementCnt]; - DataCopyGmNDToL1(dstTensor, - mergeSrcGm, - 1, - kL0SizeAlign, - nL1Size, - constInfo.headDim); - } - } else - while (copyFinishRowCnt < kL0Size) { - copyRowCnt = constInfo.paOriBlockSize - - curS2Offset % constInfo.paOriBlockSize; - if (copyFinishRowCnt + copyRowCnt > kL0Size) { - copyRowCnt = kL0Size - copyFinishRowCnt; - } - Position startPos; - startPos.bIdx = info.bIdx; - startPos.n2Idx = info.n2Idx; - startPos.s2Idx = curS2Offset; - startPos.dIdx = - nL1 * N_SPLIT_SIZE; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 - // 右矩阵, s2为k轴, d轴切分 - PAShape shape; - shape.blockSize = constInfo.paOriBlockSize; - shape.headNum = constInfo.kvHeadNum; - shape.headDim = constInfo.headDim; - shape.kvStride = constInfo.oriKvStride0; - shape.actHeadDim = nL1Size; - shape.maxblockNumPerBatch = constInfo.oriMaxBlockNumPerBatch; - shape.copyRowNum = copyRowCnt; - shape.copyRowNumAlign = kL0SizeAlign; - subvTensor = - bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE + - copyFinishRowCnt * 16]; - DataCopyPA( - subvTensor, oriKvGm, oriBlockTableGm, shape, startPos); - - // 更新循环变量 - copyFinishRowCnt += copyRowCnt; - curS2Offset += copyRowCnt; - } - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { - subvTensor = - bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE]; - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = kL0Size; // 行数 - nd2nzPara.dValue = nL1Size; // 256 - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = kL0SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - - uint32_t headStride = constInfo.headDim; - uint32_t seqStride = constInfo.kvHeadNum * constInfo.headDim; - uint64_t batchStride = - (constInfo.oriKvStride0 == 0) - ? static_cast(constInfo.kvSeqSize) * seqStride - : constInfo.oriKvStride0; - - uint64_t curS2 = info.s2StartPoint + kL1 * K_L0_SPLIT_SIZE; - uint64_t offset = (uint64_t)info.bIdx * batchStride + - (uint64_t)curS2 * seqStride + - (uint64_t)info.n2Idx * headStride + - nL1 * N_SPLIT_SIZE; - DataCopy(subvTensor, oriKvGm[offset], nd2nzPara); - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { - uint64_t curS2Offset = - static_cast(info.s2Idx) * constInfo.s2BaseSize + - info.s2StartPoint + kL1 * K_L0_SPLIT_SIZE; - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = kL0Size; // 行数 - nd2nzPara.dValue = N_SPLIT_SIZE; // constInfo.headDim; - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = kL0SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - DataCopy( - bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE], - oriKvGm[info.tensorBOffset + curS2Offset * constInfo.headDim + - nL1 * N_SPLIT_SIZE], - nd2nzPara); - } - } else if (info.isOriCmpMix) { - uint32_t cumKl0LoopSize = kL1 * K_L0_SPLIT_SIZE; - uint32_t oriSizeCur = - (info.actualSingleProcessSInnerOriSize < cumKl0LoopSize) - ? 0 - : (info.actualSingleProcessSInnerOriSize - cumKl0LoopSize); - oriSizeCur = (oriSizeCur > kL0Size) ? kL0Size : oriSizeCur; - uint32_t cmpSizeCur = kL0Size - oriSizeCur; - cmpSizeCur = (cmpSizeCur < info.actualSingleProcessSInnerCmpSize) - ? cmpSizeCur - : info.actualSingleProcessSInnerCmpSize; - if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { - if (oriSizeCur > 0) { - copyFinishRowCnt = 0; - uint64_t curS2Offset = info.s2StartPoint + kL1 * K_L0_SPLIT_SIZE; - while (copyFinishRowCnt < oriSizeCur) { - copyRowCnt = constInfo.paOriBlockSize - - curS2Offset % constInfo.paOriBlockSize; - if (copyFinishRowCnt + copyRowCnt > oriSizeCur) { - copyRowCnt = oriSizeCur - copyFinishRowCnt; - } - Position startPos; - startPos.bIdx = info.bIdx; - startPos.n2Idx = info.n2Idx; - startPos.s2Idx = curS2Offset; - startPos.dIdx = - nL1 * N_SPLIT_SIZE; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 - // 右矩阵, s2为k轴, d轴切分 - PAShape shape; - shape.blockSize = constInfo.paOriBlockSize; - shape.headNum = constInfo.kvHeadNum; - shape.headDim = constInfo.headDim; - shape.kvStride = constInfo.oriKvStride0; - shape.actHeadDim = nL1Size; - shape.maxblockNumPerBatch = constInfo.oriMaxBlockNumPerBatch; - shape.copyRowNum = copyRowCnt; - shape.copyRowNumAlign = kL0SizeAlign; - subvTensor = - bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE + - copyFinishRowCnt * 16]; - DataCopyPA( - subvTensor, oriKvGm, oriBlockTableGm, shape, startPos); - - // 更新循环变量 - copyFinishRowCnt += copyRowCnt; - curS2Offset += copyRowCnt; - } - } - if (cmpSizeCur > 0) { - copyFinishRowCnt = 0; - uint32_t cmpMixsizeCur = - K_L0_SPLIT_SIZE - - info.actualSingleProcessSInnerOriSize % K_L0_SPLIT_SIZE; - uint32_t oriOnlyLoopTimes = - info.actualSingleProcessSInnerOriSize / K_L0_SPLIT_SIZE; - uint32_t cmpLoopTimes = kL1 - oriOnlyLoopTimes; - uint64_t curS2Offset = - (cmpLoopTimes == 0) - ? 0 - : (cmpMixsizeCur + - static_cast(cmpLoopTimes - 1) * - K_L0_SPLIT_SIZE); - while (copyFinishRowCnt < cmpSizeCur) { - copyRowCnt = constInfo.paCmpBlockSize - - curS2Offset % constInfo.paCmpBlockSize; - if (copyFinishRowCnt + copyRowCnt > cmpSizeCur) { - copyRowCnt = cmpSizeCur - copyFinishRowCnt; - } - - Position startPos; - startPos.bIdx = info.bIdx; - startPos.n2Idx = info.n2Idx; - startPos.s2Idx = curS2Offset; - // 256、32等待7buf命名更改 - startPos.dIdx = - nL1 * N_SPLIT_SIZE; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 - // 右矩阵, s2为k轴, d轴切分 - - PAShape shape; - shape.blockSize = constInfo.paCmpBlockSize; - shape.headNum = constInfo.kvHeadNum; - shape.headDim = constInfo.headDim; - shape.kvStride = constInfo.cmpKvStride0; - shape.actHeadDim = nL1Size; - shape.maxblockNumPerBatch = constInfo.cmpMaxBlockNumPerBatch; - shape.copyRowNum = copyRowCnt; - shape.copyRowNumAlign = kL0SizeAlign; - subvTensor = - bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE + - oriSizeCur * 16 + copyFinishRowCnt * 16]; - DataCopyPA( - subvTensor, cmpKvGm, cmpBlockTableGm, shape, startPos); - // 更新循环变量 - copyFinishRowCnt += copyRowCnt; - curS2Offset += copyRowCnt; - } - } - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = kL0Size; // 行数 - nd2nzPara.dValue = nL1Size; // 256 - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = kL0SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - - uint32_t headStride = constInfo.headDim; - uint32_t seqStride = constInfo.kvHeadNum * constInfo.headDim; - if (oriSizeCur > 0) { - subvTensor = - bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE]; - nd2nzPara.nValue = oriSizeCur; - uint64_t batchStride = - (constInfo.oriKvStride0 == 0) - ? static_cast(constInfo.kvSeqSize) * seqStride - : constInfo.oriKvStride0; - uint64_t curS2 = info.s2StartPoint + kL1 * K_L0_SPLIT_SIZE; - uint64_t offset = (uint64_t)info.bIdx * batchStride + - (uint64_t)curS2 * seqStride + - (uint64_t)info.n2Idx * headStride + - nL1 * N_SPLIT_SIZE; - DataCopy(subvTensor, oriKvGm[offset], nd2nzPara); - } - if (cmpSizeCur > 0) { - nd2nzPara.nValue = cmpSizeCur; - subvTensor = - bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE + - oriSizeCur * 16]; - uint64_t batchStride = - (constInfo.cmpKvStride0 == 0) - ? static_cast(constInfo.cmpSeqSize) * seqStride - : constInfo.cmpKvStride0; - uint32_t cmpMixsizeCur = - K_L0_SPLIT_SIZE - - info.actualSingleProcessSInnerOriSize % K_L0_SPLIT_SIZE; - uint32_t oriOnlyLoopTimes = - info.actualSingleProcessSInnerOriSize / K_L0_SPLIT_SIZE; - uint32_t cmpLoopTimes = kL1 - oriOnlyLoopTimes; - uint64_t curS2 = (cmpLoopTimes == 0) - ? 0 - : (cmpMixsizeCur + - static_cast(cmpLoopTimes - 1) * - K_L0_SPLIT_SIZE); - uint64_t offset = (uint64_t)info.bIdx * batchStride + - (uint64_t)curS2 * seqStride + - (uint64_t)info.n2Idx * headStride + - nL1 * N_SPLIT_SIZE; - DataCopy(subvTensor, cmpKvGm[offset], nd2nzPara); - } - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = kL0Size; // 行数 - nd2nzPara.dValue = N_SPLIT_SIZE; // constInfo.headDim; - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = kL0SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - - if (oriSizeCur > 0) { - nd2nzPara.nValue = oriSizeCur; - uint64_t curS2Offset = info.s2StartPoint + kL1 * K_L0_SPLIT_SIZE; - DataCopy( - bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE], - oriKvGm[info.tensorBOffset + curS2Offset * constInfo.headDim + - nL1 * N_SPLIT_SIZE], - nd2nzPara); - } - if (cmpSizeCur > 0) { - nd2nzPara.nValue = cmpSizeCur; - uint32_t cmpMixsizeCur = - K_L0_SPLIT_SIZE - - info.actualSingleProcessSInnerOriSize % K_L0_SPLIT_SIZE; - uint32_t oriOnlyLoopTimes = - info.actualSingleProcessSInnerOriSize / K_L0_SPLIT_SIZE; - uint32_t cmpLoopTimes = kL1 - oriOnlyLoopTimes; - uint64_t curS2Offset = - (cmpLoopTimes == 0) - ? 0 - : (cmpMixsizeCur + - static_cast(cmpLoopTimes - 1) * - K_L0_SPLIT_SIZE); - DataCopy( - bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE + - oriSizeCur * 16], - cmpKvGm[info.tensorCmpBOffset + - curS2Offset * constInfo.headDim + nL1 * N_SPLIT_SIZE], - nd2nzPara); - } - } - } else { - if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { - uint64_t curS2Offset = static_cast(info.relativeS2Idx) * - constInfo.s2BaseSize + - info.s2StartPoint + K_L0_SPLIT_SIZE * kL1; - while (copyFinishRowCnt < kL0Size) { - copyRowCnt = constInfo.paCmpBlockSize - - curS2Offset % constInfo.paCmpBlockSize; - if (copyFinishRowCnt + copyRowCnt > kL0Size) { - copyRowCnt = kL0Size - copyFinishRowCnt; - } - - Position startPos; - startPos.bIdx = info.bIdx; - startPos.n2Idx = info.n2Idx; - startPos.s2Idx = curS2Offset; - // 256、32等待7buf命名更改 - startPos.dIdx = - nL1 * N_SPLIT_SIZE; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 - // 右矩阵, s2为k轴, d轴切分 - - PAShape shape; - shape.blockSize = constInfo.paCmpBlockSize; - shape.headNum = constInfo.kvHeadNum; - shape.headDim = constInfo.headDim; - shape.kvStride = constInfo.cmpKvStride0; - shape.actHeadDim = nL1Size; - shape.maxblockNumPerBatch = constInfo.cmpMaxBlockNumPerBatch; - shape.copyRowNum = copyRowCnt; - shape.copyRowNumAlign = kL0SizeAlign; - subvTensor = - bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE + - copyFinishRowCnt * 16]; - DataCopyPA( - subvTensor, cmpKvGm, cmpBlockTableGm, shape, startPos); - // 更新循环变量 - copyFinishRowCnt += copyRowCnt; - curS2Offset += copyRowCnt; - } - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { - subvTensor = - bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE]; - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = kL0Size; // 行数 - nd2nzPara.dValue = nL1Size; // 256 - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = kL0SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - - uint32_t headStride = constInfo.headDim; - uint32_t seqStride = constInfo.kvHeadNum * constInfo.headDim; - uint64_t batchStride = - (constInfo.cmpKvStride0 == 0) - ? static_cast(constInfo.cmpSeqSize) * seqStride - : constInfo.cmpKvStride0; - - uint64_t curS2 = - (uint64_t)info.relativeS2Idx * constInfo.s2BaseSize + - info.s2StartPoint + K_L0_SPLIT_SIZE * kL1; - uint64_t offset = (uint64_t)info.bIdx * batchStride + - (uint64_t)curS2 * seqStride + - (uint64_t)info.n2Idx * headStride + - nL1 * N_SPLIT_SIZE; - DataCopy(subvTensor, cmpKvGm[offset], nd2nzPara); - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { - uint64_t curS2Offset = static_cast(info.relativeS2Idx) * - constInfo.s2BaseSize + - info.s2StartPoint + K_L0_SPLIT_SIZE * kL1; - Nd2NzParams nd2nzPara; - nd2nzPara.ndNum = 1; - nd2nzPara.nValue = kL0Size; // 行数 - nd2nzPara.dValue = N_SPLIT_SIZE; // constInfo.headDim; - nd2nzPara.srcDValue = constInfo.headDim; - nd2nzPara.dstNzC0Stride = kL0SizeAlign; - nd2nzPara.dstNzNStride = 1; - nd2nzPara.srcNdMatrixStride = 0; - nd2nzPara.dstNzMatrixStride = 0; - DataCopy( - bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE], - cmpKvGm[info.tensorCmpBOffset + - curS2Offset * constInfo.headDim + nL1 * N_SPLIT_SIZE], - nd2nzPara); - } - } - } - SetFlag(mte21KVIds[kb]); - WaitFlag(mte21KVIds[kb]); - mL1SizeAlign = M_SPLIT_SIZE; - mL1Size = M_SPLIT_SIZE; // m的实际大小 - for (uint32_t mL1 = 0; mL1 < mL1Loops; mL1++) { - if (mL1 == (mL1Loops - 1)) { - // 尾块 - mL1Size = mSize - (mL1Loops - 1) * M_SPLIT_SIZE; - mL1SizeAlign = SMLAAlign(mL1Size, 16U); - } - - uint32_t mIdx = mBaseIdx + mL1; - ka = GetQPL1RealIdx(mIdx, k1); - LocalTensor aL1Tensor = l1QPTensor[ka * L1_BLOCK_OFFSET]; - if (nL1 == 0) { - WaitFlag(mte21QPIds[ka]); - CopyInMm2AToL1(aL1Tensor, - info, - mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, - mL1Size, - kL1Size, - 256 * k1); - SetFlag(mte21QPIds[ka]); - WaitFlag(mte21QPIds[ka]); - } - - LocalTensor cL0Tensor = cL0TensorPingPong - [(cL0BufIter % 2) * - (L0C_PP_SIZE / - sizeof(MM_OUT_T))]; // 需要保证cL0BufIter和m步调一致 - uint32_t baseK = 128; - uint32_t baseN = 128; - kL0Size = 128; - kL0SizeAlign = kL0Size; - for (uint32_t kL0 = 0; kL0 < kL0Loops; kL0++) { - if (kL0 + 1 == kL0Loops) { - kL0Size = kL1Size - (kL0Loops - 1) * kL0Size; - kL0SizeAlign = SMLAAlign(kL0Size, 16U); - } - WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); - LocalTensor bL0Tensor = - bL0TensorPingPong[(abL0BufIter % 2) * - (L0B_PP_SIZE / sizeof(KV_T))]; - LoadData3DParamsV2 loadData3DParamsForB; - loadData3DParamsForB.l1H = kL0SizeAlign / 16; // 源操作数height - loadData3DParamsForB.l1W = - 16; // 源操作数weight=16,目的height=l1H*L1W - loadData3DParamsForB.padList[0] = 0; - loadData3DParamsForB.padList[1] = 0; - loadData3DParamsForB.padList[2] = 0; - loadData3DParamsForB.padList[3] = 255; // 尾部数据不影响滑窗的结果 - - loadData3DParamsForB.mExtension = - kL0SizeAlign; // 在目的操作数height维度的传输长度 - loadData3DParamsForB.kExtension = - nL1SizeAlign; // 在目的操作数width维度的传输长度 - loadData3DParamsForB.mStartPt = - 0; // 卷积核在目的操作数width维度的起点 - loadData3DParamsForB.kStartPt = - 0; // 卷积核在目的操作数height维度的起点 - loadData3DParamsForB.strideW = 1; - loadData3DParamsForB.strideH = 1; - loadData3DParamsForB.filterW = 1; - loadData3DParamsForB.filterSizeW = - false; // 是否在filterW的基础上将卷积核width增加256个元素 - loadData3DParamsForB.filterH = 1; - loadData3DParamsForB.filterSizeH = - false; // 是否在filterH的基础上将卷积核height增加256个元素 - loadData3DParamsForB.dilationFilterW = 1; // 卷积核width膨胀系数 - loadData3DParamsForB.dilationFilterH = 1; // 卷积核height膨胀系数 - loadData3DParamsForB.enTranspose = 1; // 是否启用转置功能 - loadData3DParamsForB.fMatrixCtrl = - 0; // 使用FMATRIX_LEFT还是使用FMATRIX_RIGHT,=0使用FMATRIX_LEFT,=1使用FMATRIX_RIGHT - // 1 - loadData3DParamsForB.channelSize = - nL1SizeAlign; // 源操作数的通道数。膨胀系数为1时,目的weight为filterW*filterH*channelSize - LoadData( - bL0Tensor, bL1Tensor[kL0 * baseK * baseN], loadData3DParamsForB); - - LocalTensor aL0Tensor = - aL0TensorPingPong[(abL0BufIter % 2) * - (L0A_PP_SIZE / sizeof(KV_T))]; - LoadData3DParamsV2 loadData3DParamsForA; - loadData3DParamsForA.l1H = mL1SizeAlign / 16; // 源操作数height - loadData3DParamsForA.l1W = 16; // 源操作数weight - loadData3DParamsForA.padList[0] = 0; - loadData3DParamsForA.padList[1] = 0; - loadData3DParamsForA.padList[2] = 0; - loadData3DParamsForA.padList[3] = 255; // 尾部数据不影响滑窗的结果 - - loadData3DParamsForA.mExtension = - mL1SizeAlign; // 在目的操作数height维度的传输长度 - loadData3DParamsForA.kExtension = - kL0SizeAlign; // 在目的操作数width维度的传输长度 - loadData3DParamsForA.mStartPt = - 0; // 卷积核在目的操作数width维度的起点 - loadData3DParamsForA.kStartPt = - 0; // 卷积核在目的操作数height维度的起点 - loadData3DParamsForA.strideW = - 1; // 卷积核在源操作数width维度滑动的步长 - loadData3DParamsForA.strideH = - 1; // 卷积核在源操作数height维度滑动的步长 - loadData3DParamsForA.filterW = 1; // 卷积核width - loadData3DParamsForA.filterSizeW = - false; // 是否在filterW的基础上将卷积核width增加256个元素 - loadData3DParamsForA.filterH = 1; // 卷积核height - loadData3DParamsForA.filterSizeH = - false; // 是否在filterH的基础上将卷积核height增加256个元素 - loadData3DParamsForA.dilationFilterW = 1; // 卷积核width膨胀系数 - loadData3DParamsForA.dilationFilterH = 1; // 卷积核height膨胀系数 - loadData3DParamsForA.enTranspose = - 0; // 是否启用转置功能,对整个目标矩阵进行转置 - loadData3DParamsForA.fMatrixCtrl = 0; - loadData3DParamsForA.channelSize = - kL0SizeAlign; // 源操作数的通道数。膨胀系数为1时,目的weight为filterW*filterH*channelSize - LoadData(aL0Tensor, - aL1Tensor[kL0 * baseK * mL1SizeAlign], - loadData3DParamsForA); - SetFlag(Mte1MmABEventId(abL0BufIter % 2)); - WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); - - MmadParams mmadParams; - mmadParams.m = mL1SizeAlign; - mmadParams.n = nL1SizeAlign; - mmadParams.k = kL0Size; - mmadParams.cmatrixInitVal = (kL0 == 0 && k1 == 0); - mmadParams.cmatrixSource = false; - mmadParams.unitFlag = - ((k1 == (kL1Loops - 1)) && (kL0 == (kL0Loops - 1))) ? 0b11 : 0b10; - - Mmad(cL0Tensor, aL0Tensor, bL0Tensor, mmadParams); - if ((mmadParams.m / 16) * (mmadParams.n / 16) < 10) { - PipeBarrier(); - } - SetFlag(Mte1MmABEventId(abL0BufIter % 2)); - abL0BufIter++; - } - - if (nL1 == (nL1Loops - - 1)) { // nL1最后一轮, 需要将B驻留在L1中, 用于下一轮的计算? - SetFlag( - mte21QPIds[ka]); // 反向同步, 表示L1中的A已经被mte1消费完 - } - - if (k1 == (kL1Loops - 1)) { - // ND - FixpipeParamsV220 fixParams; - fixParams.nSize = nL1SizeAlign; - fixParams.mSize = mL1SizeAlign; - fixParams.srcStride = mL1SizeAlign; - fixParams.dstStride = nSize; // mm2ResGm两行之间的间隔 - fixParams.ndNum = 1; // 输出ND - fixParams.unitFlag = 0b11; - - uint64_t mm2Offset = - (mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE) * nSize + - nL1 * N_SPLIT_SIZE; - Fixpipe(mm2ResGm[(info.loop % (constInfo.preLoadNum)) * - constInfo.bmm2ResUbSize + - mm2Offset], - cL0Tensor, - fixParams); - } - - if (mL1Loops == 2) { - cL0BufIter++; - } - } - SetFlag( - mte21KVIds[kb]); // 反向同步, 表示L1已经被mte1消费完 - } - // cL0BufIter已经不在使用 - if (mL1Loops == 1) { - cL0BufIter++; - } - } - qpL1BufIter += mL1Loops; -} -} // namespace SMLAKernel -#endif diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_block_vector.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_block_vector.h deleted file mode 100644 index 0f21d91480..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_block_vector.h +++ /dev/null @@ -1,1688 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file sparse_flash_mla_swa_block_vector.h - * \brief - */ -#ifndef SPARSE_FLASH_MLA_SWA_BLOCK_VECTOR_H -#define SPARSE_FLASH_MLA_SWA_BLOCK_VECTOR_H - -#include "kernel_operator.h" -#include "kernel_operator_list_tensor_intf.h" -#include "kernel_tiling/kernel_tiling.h" -#include "lib/matmul_intf.h" -#include "lib/matrix/matmul/tiling.h" -#include "sparse_flash_mla_common_arch22.h" - -namespace SMLAKernel { -using AscendC::CrossCoreSetFlag; -using AscendC::CrossCoreWaitFlag; - -template -class SWAVectorBlock { - public: - // 中间计算数据类型为float,高精度模式 - using T = float; - using KV_T = typename SMLAT::kvType; - using OUT_T = typename SMLAT::outputType; - using UPDATE_T = T; - using SINKS_T = T; - using MM1_OUT_T = float; - using MM2_OUT_T = float; - - __aicore__ inline SWAVectorBlock(){}; - __aicore__ inline void ProcessVec0L(const RunInfo& runInfo); - __aicore__ inline void ProcessVec1L(const RunInfo& info); - __aicore__ inline void ProcessVec2L(const RunInfo& info); - __aicore__ inline void InitBuffers(TPipe* pipe); - __aicore__ inline void InitParams( - const struct ConstInfo& constInfo, - const SparseFlashMlaTilingData* __restrict tilingData); - __aicore__ inline void InitVec0GlobalTensor( - GlobalTensor kvMergeGm, - GlobalTensor oriKvGm, - GlobalTensor oriBlockTableGm, - GlobalTensor oriSparseIndicesGm, - GlobalTensor oriTopkLengthGm); - __aicore__ inline void InitVec1GlobalTensor( - GlobalTensor mm1ResGm, - GlobalTensor vec1ResGm, - GlobalTensor actualSeqLengthsQGm, - GlobalTensor actualSeqLengthsKVGm, - GlobalTensor sinksGm, - GlobalTensor softmaxLseGm); - __aicore__ inline void InitVec2GlobalTensor( - GlobalTensor accumOutGm, - GlobalTensor vec2ResGm, - GlobalTensor mm2ResGm, - GlobalTensor attentionOutGm); - __aicore__ inline void AllocEventID(); - __aicore__ inline void FreeEventID(); - __aicore__ inline void CopySinksIn(); - __aicore__ inline void SliceAndContactSinksValue(uint32_t nIdx, - uint32_t dealRowCount); - __aicore__ inline void InitSoftmaxDefaultBuffer(); - // ================================Base - // Vector========================================== - __aicore__ inline void RowDivs(LocalTensor dstUb, - LocalTensor src0Ub, - LocalTensor src1Ub, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount); - __aicore__ inline void RowMuls(LocalTensor dstUb, - LocalTensor src0Ub, - LocalTensor src1Ub, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount); - // ================================Vector1========================================== - __aicore__ inline void ProcessVec1SingleBuf(const RunInfo& info, - const MSplitInfo& mSplitInfo); - __aicore__ inline void DealBmm1ResBaseBlock(const RunInfo& info, - const MSplitInfo& mSplitInfo, - uint32_t startRow, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t loopId); - __aicore__ inline void SoftmaxFlashV2Compute( - const RunInfo& info, - const MSplitInfo& mSplitInfo, - LocalTensor& mmResUb, - LocalTensor& softmaxTmpUb, - uint32_t startRow, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount); - __aicore__ inline void ElewiseCompute(const RunInfo& info, - const MSplitInfo& mSplitInfo, - const LocalTensor& mmResUb, - uint32_t dealRowCount, - uint32_t startRow, - uint32_t columnCount); - __aicore__ inline void ProcessLse(const RunInfo& info, - const MSplitInfo& mSplitInfo); - // ================================Vecotr2========================================== - __aicore__ inline void ProcessVec2SingleBuf(const RunInfo& info, - const MSplitInfo& mSplitInfo); - __aicore__ inline void DealBmm2ResBaseBlock(const RunInfo& info, - const MSplitInfo& mSplitInfo, - uint32_t startRow, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount); - __aicore__ inline void ProcessVec2Inner(const RunInfo& info, - const MSplitInfo& mSplitInfo, - uint32_t mStartRow, - uint32_t mDealSize); - __aicore__ inline void Bmm2DataCopyOutTrans(const RunInfo& info, - LocalTensor& attenOutUb, - uint32_t wsMStart, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount); - __aicore__ inline void Bmm2ResCopyOut(const RunInfo& info, - LocalTensor& bmm2ResUb, - uint32_t wsMStart, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount); - __aicore__ inline void Bmm2CastAndCopyOut(const RunInfo& info, - LocalTensor& bmm2ResUb, - uint32_t wsMStart, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount); - __aicore__ inline void Bmm2FDDataCopyOut(const RunInfo& info, - LocalTensor& bmm2ResUb, - uint32_t wsMStart, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount); - __aicore__ inline uint64_t CalcAccumOffset(uint32_t bN2Idx, uint32_t gS1Idx); - __aicore__ inline void SetInfInBlk(const LocalTensor& mmResUb, - uint32_t dealRowCount, - uint32_t columnCount, - int64_t startId, - int64_t endId); - - // BLOCK和REPEAT的字节数 - static constexpr uint64_t BYTE_BLOCK = 32UL; - static constexpr uint32_t REPEAT_BLOCK_BYTE = 256U; - // BLOCK和REPEAT的FP32元素数 - static constexpr uint32_t FP32_BLOCK_ELEMENT_NUM = BYTE_BLOCK / sizeof(float); - static constexpr uint32_t FP32_REPEAT_ELEMENT_NUM = - REPEAT_BLOCK_BYTE / sizeof(float); - // repeat stride不能超过256 - static constexpr uint32_t REPEATE_STRIDE_UP_BOUND = 256; - static constexpr uint64_t MERGE_CACHE_GM_BUF_NUM = 3; - static constexpr uint64_t MERGE_WORKSPACE_ROW_NUM = 512; - - private: - __aicore__ inline int64_t GetOriSparseKeyGmOffset(int32_t logicalIdx, - const RunInfo& runInfo); - __aicore__ inline void CopyInSingleOriSparseRow(int64_t& mte2Size, - int64_t mte3Size, - int64_t mergeMte3Idx, - int32_t logicalIdx, - const RunInfo& runInfo); - __aicore__ inline void CopyInOriSparseKv(int64_t& mte2Size, - int64_t mte3Size, - int64_t mergeMte3Idx, - int32_t logicalIdx0, - int32_t logicalIdx1, - const RunInfo& runInfo); - __aicore__ inline void CopyOutOriSparseMerge(int64_t mte2Size, - int64_t mte3Size, - int64_t s2GmStartOffset, - int64_t mergeMte3Idx, - const RunInfo& runInfo); - __aicore__ inline int32_t AlignOriSparseIndexLoadCount(int32_t loadCount); - __aicore__ inline void LoadOriSparseIndicesGmToUb( - uint64_t qTokenOffset, - uint32_t n2Idx, - uint32_t gmColStart, - int32_t loadCount, - const LocalTensor& dstUb); - static constexpr bool PAGE_ATTENTION = SMLAT::pageAttention; - static constexpr bool FLASH_DECODE = SMLAT::flashDecode; - static constexpr SMLA_LAYOUT LAYOUT_T = SMLAT::layout; - static constexpr SMLA_LAYOUT KV_LAYOUT_T = SMLAT::kvLayout; - static constexpr bool IS_DSPARK = SMLAT::isDspark; - - static constexpr uint64_t SYNC_INPUT_BUF1_FLAG = 2; - static constexpr uint64_t SYNC_INPUT_BUF1_PONG_FLAG = 3; - static constexpr uint64_t SYNC_INPUT_BUF2_FLAG = 4; - static constexpr uint64_t SYNC_INPUT_BUF2_PONG_FLAG = 5; - static constexpr uint64_t SYNC_OUTPUT_BUF1_FLAG = 4; - static constexpr uint64_t SYNC_OUTPUT_BUF2_FLAG = 5; - static constexpr uint64_t SYNC_SINKS_BUF_FLAG = 6; - static constexpr uint32_t INPUT1_BUFFER_OFFSET = - ConstInfo::BUFFER_SIZE_BYTE_32K; - static constexpr uint32_t SOFTMAX_TMP_BUFFER_OFFSET = - ConstInfo::BUFFER_SIZE_BYTE_1K; - static constexpr uint32_t BASE_BLOCK_MAX_ELEMENT_NUM = - ConstInfo::BUFFER_SIZE_BYTE_32K / sizeof(T); - static constexpr uint32_t BLOCK_ELEMENT_NUM = BYTE_BLOCK / sizeof(T); - static constexpr uint32_t MAX_N1_SIZE = 128U; - static constexpr T SOFTMAX_MIN_NUM = -2e38; - static constexpr SINKS_T R0 = 1.0f; - - const SparseFlashMlaTilingData* __restrict tilingData; - - uint32_t pingpongFlag = 0U; - ConstInfo constInfo = {}; - - GlobalTensor mm1ResGm; - GlobalTensor vec1ResGm; - GlobalTensor softmaxMaxGm; - GlobalTensor softmaxSumGm; - GlobalTensor sinksGm; - - GlobalTensor actualSeqLengthsQGm; - GlobalTensor actualSeqLengthsKVGm; - GlobalTensor oriSparseIndicesGm; - GlobalTensor oriTopkLengthGm; - GlobalTensor vec2ResGm; - GlobalTensor mm2ResGm; - GlobalTensor accumOutGm; - GlobalTensor attentionOutGm; - GlobalTensor blkTableGm_; - GlobalTensor keyGm_; - GlobalTensor kvValidSizeGm_; - GlobalTensor oriKvGm_; - GlobalTensor cmpKvGm_; - GlobalTensor oriBlockTableGm_; - GlobalTensor cmpBlockTableGm_; - GlobalTensor kvMergeGm_; - GlobalTensor softmaxLseGm; - - // ================================Local - // Buffer区==================================== - TBuf<> inputBuff1; // 32K - TBuf<> inputBuff2; // 8K - TBuf<> outputBuff1; // 32K - TBuf<> outputBuff2; // 4K - - TBuf<> tmpBuff1; // 32K - TBuf<> v0ValidSizeBuff; // 8K - TBuf<> sinksBuff; // 1K - TBuf<> sinksBrcbBuff; // 12K - - TBuf<> softmaxMaxBuff; // PRE_LOAD_NUM * 2K - TBuf<> softmaxExpBuff; // PRE_LOAD_NUM * 2K - TBuf<> softmaxSumBuff; // PRE_LOAD_NUM * 2K - TBuf<> softmaxMaxDefaultBuff; // 2K - TBuf<> softmaxSumDefaultBuff; // 2K - - LocalTensor softmaxMaxDefaultUb; - LocalTensor softmaxSumDefaultUb; - - LocalTensor softmaxMaxUb; - LocalTensor softmaxSumUb; - LocalTensor softmaxExpUb; - LocalTensor sinksUb; - LocalTensor sinksBrcbUb; - LocalTensor kvMergUb_; - uint32_t mergeMte3Idx = 0; -}; - -// ============================== init -// ============================================== -template -__aicore__ inline void SWAVectorBlock::InitBuffers(TPipe* pipe) { - pipe->InitBuffer(inputBuff1, - ConstInfo::BUFFER_SIZE_BYTE_32K * 2); // 2:pingpong - pipe->InitBuffer(inputBuff2, - ConstInfo::BUFFER_SIZE_BYTE_8K * 2); // 2:pingpong - pipe->InitBuffer(outputBuff1, ConstInfo::BUFFER_SIZE_BYTE_32K); - pipe->InitBuffer(outputBuff2, ConstInfo::BUFFER_SIZE_BYTE_4K); - - pipe->InitBuffer(tmpBuff1, ConstInfo::BUFFER_SIZE_BYTE_32K); - pipe->InitBuffer(v0ValidSizeBuff, ConstInfo::BUFFER_SIZE_BYTE_8K); - // M_MAX = 512/2vector = 256, 256 * sizeof(T) * N_Buffer - pipe->InitBuffer(softmaxMaxBuff, - ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); - pipe->InitBuffer(softmaxExpBuff, - ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); - pipe->InitBuffer(softmaxSumBuff, - ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); - - pipe->InitBuffer(softmaxMaxDefaultBuff, ConstInfo::BUFFER_SIZE_BYTE_1K); - pipe->InitBuffer(softmaxSumDefaultBuff, ConstInfo::BUFFER_SIZE_BYTE_1K); - - pipe->InitBuffer(sinksBuff, MAX_N1_SIZE * sizeof(SINKS_T)); - // 分配256+N1大小内存,其中256是m轴VEC最大切块 - pipe->InitBuffer(sinksBrcbBuff, - MAX_N1_SIZE * sizeof(SINKS_T) * BLOCK_ELEMENT_NUM * 3U); - - softmaxMaxUb = softmaxMaxBuff.Get(); - softmaxSumUb = softmaxSumBuff.Get(); - softmaxExpUb = softmaxExpBuff.Get(); - - softmaxMaxDefaultUb = softmaxMaxDefaultBuff.Get(); - softmaxSumDefaultUb = softmaxSumDefaultBuff.Get(); - - sinksUb = sinksBuff.Get(); - sinksBrcbUb = sinksBrcbBuff.Get(); - if constexpr (IS_DSPARK) { - kvMergUb_ = inputBuff1.Get(); - } -} - -template -__aicore__ inline void SWAVectorBlock::InitParams( - const struct ConstInfo& constInfo, - const SparseFlashMlaTilingData* __restrict tilingData) { - this->constInfo = constInfo; - this->tilingData = tilingData; -} - -template -__aicore__ inline void SWAVectorBlock::InitVec0GlobalTensor( - GlobalTensor kvMergeGm, - GlobalTensor oriKvGm, - GlobalTensor oriBlockTableGm, - GlobalTensor oriSparseIndicesGm, - GlobalTensor oriTopkLengthGm) { - this->kvMergeGm_ = kvMergeGm; - this->oriKvGm_ = oriKvGm; - this->oriBlockTableGm_ = oriBlockTableGm; - this->oriSparseIndicesGm = oriSparseIndicesGm; - this->oriTopkLengthGm = oriTopkLengthGm; -} - -template -__aicore__ inline int64_t SWAVectorBlock::GetOriSparseKeyGmOffset( - int32_t logicalIdx, - const RunInfo& runInfo) { - if (logicalIdx < 0) { - return -1; - } - int32_t oriLenLimit = actualSeqLengthsKVGm.GetValue(runInfo.bIdx); - if (logicalIdx >= oriLenLimit) { - return -1; - } - uint64_t blockTableIdx = - static_cast(logicalIdx) / constInfo.paOriBlockSize; - uint64_t inBlockIdx = - static_cast(logicalIdx) % constInfo.paOriBlockSize; - uint64_t idInBlockTable = oriBlockTableGm_.GetValue( - runInfo.bIdx * constInfo.oriMaxBlockNumPerBatch + blockTableIdx); - return static_cast(idInBlockTable * constInfo.oriKvStride0 + - static_cast(runInfo.n2IdxReal) * - constInfo.headDim * constInfo.paOriBlockSize + - inBlockIdx * constInfo.headDim); -} - -template -__aicore__ inline void SWAVectorBlock::CopyInSingleOriSparseRow( - int64_t& mte2Size, - int64_t mte3Size, - int64_t mergeMte3Idx, - int32_t logicalIdx, - const RunInfo& runInfo) { - int64_t keyOffset = GetOriSparseKeyGmOffset(logicalIdx, runInfo); - if (keyOffset >= 0) { - int64_t ubRowOffset = - mergeMte3Idx % 2 * INPUT1_BUFFER_OFFSET / sizeof(KV_T) + - (mte2Size - mte3Size) * constInfo.headDim; - DataCopyExtParams copyInParams; - copyInParams.blockCount = 1; - copyInParams.blockLen = constInfo.headDim * sizeof(KV_T); - copyInParams.srcStride = 0; - copyInParams.dstStride = 0; - DataCopyPadExtParams padInParams{false, 0, 0, 0}; - DataCopyPad( - kvMergUb_[ubRowOffset], oriKvGm_[keyOffset], copyInParams, padInParams); - } - mte2Size += constInfo.sparseBlockSize; -} - -template -__aicore__ inline void SWAVectorBlock::CopyInOriSparseKv( - int64_t& mte2Size, - int64_t mte3Size, - int64_t mergeMte3Idx, - int32_t logicalIdx0, - int32_t logicalIdx1, - const RunInfo& runInfo) { - int64_t keyOffset1 = GetOriSparseKeyGmOffset(logicalIdx0, runInfo); - int64_t keyOffset2 = GetOriSparseKeyGmOffset(logicalIdx1, runInfo); - if (logicalIdx1 < 0) { - CopyInSingleOriSparseRow( - mte2Size, mte3Size, mergeMte3Idx, logicalIdx0, runInfo); - return; - } - if (unlikely(keyOffset1 < 0 && keyOffset2 < 0)) { - // invalid 行仅占 merge 行位,不搬 KV;V1 按索引刷 -inf,值无关 - mte2Size += 2 * constInfo.sparseBlockSize; - return; - } - - int64_t keySrcStride = - ((keyOffset1 > keyOffset2 ? (keyOffset1 - keyOffset2) - : (keyOffset2 - keyOffset1)) - - constInfo.sparseBlockSize * constInfo.headDim) * - static_cast(sizeof(KV_T)); - if (unlikely(keySrcStride >= INT32_MAX || keySrcStride < 0 || - keyOffset1 < 0 || keyOffset2 < 0)) { - CopyInSingleOriSparseRow( - mte2Size, mte3Size, mergeMte3Idx, logicalIdx0, runInfo); - CopyInSingleOriSparseRow( - mte2Size, mte3Size, mergeMte3Idx, logicalIdx1, runInfo); - } else { - DataCopyExtParams intriParams; - intriParams.blockLen = - constInfo.sparseBlockSize * constInfo.headDim * sizeof(KV_T); - intriParams.blockCount = (keyOffset1 >= 0) + (keyOffset2 >= 0); - intriParams.dstStride = 0; - intriParams.srcStride = keySrcStride; - DataCopyPadExtParams padParams{false, 0, 0, 0}; - int64_t startGmOffset = keyOffset1 > -1 ? keyOffset1 : keyOffset2; - if (keyOffset2 > -1 && keyOffset2 < keyOffset1) { - startGmOffset = keyOffset2; - } - DataCopyPad( - kvMergUb_[mergeMte3Idx % 2 * INPUT1_BUFFER_OFFSET / sizeof(KV_T) + - (mte2Size - mte3Size) * constInfo.headDim], - oriKvGm_[startGmOffset], - intriParams, - padParams); - mte2Size += 2 * constInfo.sparseBlockSize; - } -} - -template -__aicore__ inline void SWAVectorBlock::CopyOutOriSparseMerge( - int64_t mte2Size, - int64_t mte3Size, - int64_t s2GmStartOffset, - int64_t mergeMte3Idx, - const RunInfo& runInfo) { - if (mte2Size <= mte3Size) { - return; - } - SetFlag(mergeMte3Idx % 2 + - SYNC_INPUT_BUF2_FLAG); - WaitFlag(mergeMte3Idx % 2 + - SYNC_INPUT_BUF2_FLAG); - - DataCopyExtParams dataCopyParams; - dataCopyParams.blockCount = static_cast(mte2Size - mte3Size); - dataCopyParams.blockLen = constInfo.headDim * sizeof(KV_T); - dataCopyParams.srcStride = 0; - dataCopyParams.dstStride = 0; - DataCopyPad(kvMergeGm_[runInfo.cmpLoop % MERGE_CACHE_GM_BUF_NUM * - MERGE_WORKSPACE_ROW_NUM * constInfo.headDim + - (s2GmStartOffset + mte3Size) * constInfo.headDim], - kvMergUb_[mergeMte3Idx % 2 * INPUT1_BUFFER_OFFSET / sizeof(KV_T)], - dataCopyParams); - SetFlag(mergeMte3Idx % 2 + - SYNC_INPUT_BUF2_FLAG); - WaitFlag(mergeMte3Idx % 2 + - SYNC_INPUT_BUF2_FLAG); -} - -template -__aicore__ inline int32_t SWAVectorBlock::AlignOriSparseIndexLoadCount( - int32_t loadCount) { - if (loadCount <= 0) { - return 0; - } - // MTE blockLen must be 32B-aligned; int32 slot count aligns to 8 elements. - return ((loadCount + 7) / 8) * 8; -} - -template -__aicore__ inline void SWAVectorBlock::LoadOriSparseIndicesGmToUb( - uint64_t qTokenOffset, - uint32_t n2Idx, - uint32_t gmColStart, - int32_t loadCount, - const LocalTensor& dstUb) { - if (loadCount <= 0 || constInfo.oriSparseIndexWidth == 0) { - return; - } - int32_t remain = static_cast(constInfo.oriSparseIndexWidth) - - static_cast(gmColStart); - int32_t validCount = (remain < loadCount) ? remain : loadCount; - if (validCount <= 0) { - return; - } - int32_t alignedCount = AlignOriSparseIndexLoadCount(loadCount); - uint64_t gmOffset = (qTokenOffset * constInfo.kvHeadNum + n2Idx) * - constInfo.oriSparseIndexWidth + - gmColStart; - - // dstUb来自tmpBuff1,需要上一轮的getvalue(S)结束再开始搬入 - event_t sToMte2 = - static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_MTE2)); - SetFlag(sToMte2); - WaitFlag(sToMte2); - - DataCopyExtParams copyParams; - copyParams.blockCount = 1; - copyParams.blockLen = static_cast(validCount) * sizeof(int32_t); - copyParams.srcStride = 0; - copyParams.dstStride = 0; - DataCopyPadExtParams padParams; - padParams.isPad = true; - padParams.leftPadding = 0; - padParams.rightPadding = static_cast(alignedCount - validCount); - padParams.paddingValue = -1; - DataCopyPad(dstUb, oriSparseIndicesGm[gmOffset], copyParams, padParams); - event_t mte2ToS = - static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_S)); - SetFlag(mte2ToS); - WaitFlag(mte2ToS); -} - -template -__aicore__ inline void SWAVectorBlock::ProcessVec0L( - const RunInfo& runInfo) { - int64_t s2ProcessSize = runInfo.v0S2DealSize; - if (s2ProcessSize <= 0) { - return; - } - uint32_t sparseColStart = runInfo.s2Idx * constInfo.s2BaseSize + - static_cast(runInfo.v0S2Start); - int64_t s2Pair = CeilDiv(s2ProcessSize, 2 * constInfo.sparseBlockSize); - int64_t s2SplitPoint = SMLAAlign(s2Pair, 2) * constInfo.sparseBlockSize; - int64_t s2GmStartOffset = GetSubBlockIdx() == 0 ? 0 : s2SplitPoint; - int64_t s2GmLimit = GetSubBlockIdx() == 0 ? s2SplitPoint : s2ProcessSize; - if (s2GmLimit > s2ProcessSize) { - s2GmLimit = s2ProcessSize; - } - if (s2GmStartOffset >= s2GmLimit) { - return; - } - // V0 reuses both inputBuff1 halves after V1/V2 release their MTE2 access. - WaitFlag(SYNC_INPUT_BUF1_FLAG); - WaitFlag(SYNC_INPUT_BUF1_PONG_FLAG); - - LocalTensor sliceUb = v0ValidSizeBuff.Get(); - LoadOriSparseIndicesGmToUb( - runInfo.qTokenOffset, - runInfo.n2IdxReal, - sparseColStart + static_cast(s2GmStartOffset), - static_cast(s2GmLimit - s2GmStartOffset), - sliceUb); - - int64_t s2LocalSize = s2GmLimit - s2GmStartOffset; - int64_t mte2Size = 0; - int64_t mte3Size = 0; - bool needWaitMte3ToMte2 = true; - for (int64_t s2GmOffsetArray = 0; s2GmOffsetArray < s2LocalSize; - s2GmOffsetArray += 2 * constInfo.sparseBlockSize) { - if (needWaitMte3ToMte2) { - WaitFlag(mergeMte3Idx % 2 + - SYNC_INPUT_BUF2_FLAG); - needWaitMte3ToMte2 = false; - } - int32_t logicalIdx0 = - sliceUb.GetValue(static_cast(s2GmOffsetArray)); - int32_t logicalIdx1 = -1; - if (s2GmOffsetArray + constInfo.sparseBlockSize < s2LocalSize) { - logicalIdx1 = sliceUb.GetValue( - static_cast(s2GmOffsetArray + constInfo.sparseBlockSize)); - } - CopyInOriSparseKv( - mte2Size, mte3Size, mergeMte3Idx, logicalIdx0, logicalIdx1, runInfo); - if ((mte2Size - mte3Size + 2 * constInfo.sparseBlockSize > 16) || - s2GmOffsetArray + 2 * constInfo.sparseBlockSize >= s2LocalSize) { - CopyOutOriSparseMerge( - mte2Size, mte3Size, s2GmStartOffset, mergeMte3Idx, runInfo); - mte3Size = mte2Size; - SetFlag(mergeMte3Idx % 2 + - SYNC_INPUT_BUF2_FLAG); - mergeMte3Idx++; - needWaitMte3ToMte2 = true; - } - } - // CopyOutOriSparseMerge drains V0's MTE3 read before V1/V2 reuse inputBuff1. - SetFlag(SYNC_INPUT_BUF1_FLAG); - SetFlag(SYNC_INPUT_BUF1_PONG_FLAG); -} - -template -__aicore__ inline void SWAVectorBlock::InitVec1GlobalTensor( - GlobalTensor mm1ResGm, - GlobalTensor vec1ResGm, - GlobalTensor actualSeqLengthsQGm, - GlobalTensor actualSeqLengthsKVGm, - GlobalTensor sinksGm, - GlobalTensor softmaxLseGm) { - this->mm1ResGm = mm1ResGm; - this->vec1ResGm = vec1ResGm; - this->actualSeqLengthsQGm = actualSeqLengthsQGm; - this->actualSeqLengthsKVGm = actualSeqLengthsKVGm; - this->sinksGm = sinksGm; - this->softmaxLseGm = softmaxLseGm; -} - -template -__aicore__ inline void SWAVectorBlock::InitVec2GlobalTensor( - GlobalTensor accumOutGm, - GlobalTensor vec2ResGm, - GlobalTensor mm2ResGm, - GlobalTensor attentionOutGm) { - this->accumOutGm = accumOutGm; - this->vec2ResGm = vec2ResGm; - this->mm2ResGm = mm2ResGm; - this->attentionOutGm = attentionOutGm; -} - -template -__aicore__ inline void SWAVectorBlock::AllocEventID() { - SetFlag(SYNC_INPUT_BUF1_FLAG); - SetFlag(SYNC_INPUT_BUF1_PONG_FLAG); - SetFlag(SYNC_INPUT_BUF2_FLAG); - SetFlag(SYNC_INPUT_BUF2_PONG_FLAG); - if constexpr (IS_DSPARK) { - SetFlag(SYNC_INPUT_BUF2_FLAG); - SetFlag(SYNC_INPUT_BUF2_PONG_FLAG); - } - SetFlag(SYNC_OUTPUT_BUF1_FLAG); - SetFlag(SYNC_OUTPUT_BUF2_FLAG); -} - -template -__aicore__ inline void SWAVectorBlock::FreeEventID() { - WaitFlag(SYNC_INPUT_BUF1_FLAG); - WaitFlag(SYNC_INPUT_BUF1_PONG_FLAG); - WaitFlag(SYNC_INPUT_BUF2_FLAG); - WaitFlag(SYNC_INPUT_BUF2_PONG_FLAG); - if constexpr (IS_DSPARK) { - WaitFlag(SYNC_INPUT_BUF2_FLAG); - WaitFlag(SYNC_INPUT_BUF2_PONG_FLAG); - } - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - WaitFlag(SYNC_OUTPUT_BUF2_FLAG); -} - -template -__aicore__ inline void SWAVectorBlock::CopySinksIn() { - DataCopyExtParams dataCopyParams; - dataCopyParams.blockCount = 1U; - dataCopyParams.blockLen = constInfo.qHeadNum * sizeof(T); - dataCopyParams.srcStride = 0U; - dataCopyParams.dstStride = 0U; - DataCopyPadExtParams padParams; - DataCopyPad(sinksUb, sinksGm, dataCopyParams, padParams); - SetFlag(SYNC_SINKS_BUF_FLAG); - WaitFlag(SYNC_SINKS_BUF_FLAG); - uint32_t repeatTimes = - (constInfo.qHeadNum + BLOCK_ELEMENT_NUM - 1U) / BLOCK_ELEMENT_NUM; - Brcb(sinksBrcbUb, sinksUb, repeatTimes, {1, BLOCK_ELEMENT_NUM}); - PipeBarrier(); - - DataCopyParams repeatParams; - repeatParams.blockCount = - 1; // 搬到有一个块超过单个vec核减分核M轴大小即可,核间切分每个vec256 - repeatParams.blockLen = constInfo.qHeadNum; - repeatParams.srcStride = 0U; - repeatParams.dstStride = 0U; - for (uint32_t i = 1U; i <= 256U / constInfo.qHeadNum; i++) { - DataCopy(sinksBrcbUb[constInfo.qHeadNum * BLOCK_ELEMENT_NUM * i], - sinksBrcbUb, - repeatParams); - } - PipeBarrier(); -} - -template -__aicore__ inline void SWAVectorBlock::SliceAndContactSinksValue( - uint32_t nIdx, - uint32_t dealRowCount) { - // 由于WholeReduceMax接口中repeatTimes支持范围(0,255),因此需要分多次调用WholeReduceMax,这里就使用每次repeatTime=128 - uint32_t repeatTimesOnce = 128; - uint32_t loopTimes = (dealRowCount + repeatTimesOnce - 1) / repeatTimesOnce; - uint32_t repeatTimes = repeatTimesOnce; - - for (uint32_t loop = 0; loop < loopTimes; ++loop) { - if (loop == loopTimes - 1) { - repeatTimes = dealRowCount - loop * repeatTimesOnce; - } - WholeReduceMax( - softmaxMaxDefaultUb[loop * repeatTimesOnce], - sinksBrcbUb[(nIdx + loop * repeatTimesOnce) * BLOCK_ELEMENT_NUM], - BLOCK_ELEMENT_NUM * BLOCK_ELEMENT_NUM, - repeatTimes, - 1, - 0, - 1, - ReduceOrder::ORDER_ONLY_VALUE); - PipeBarrier(); - } -} - -template -__aicore__ inline void SWAVectorBlock::InitSoftmaxDefaultBuffer() { - CopySinksIn(); - Duplicate(softmaxMaxDefaultUb, - SOFTMAX_MIN_NUM, - SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)); - Duplicate(softmaxSumDefaultUb, R0, SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)); -} - -template -__aicore__ inline void SWAVectorBlock::ElewiseCompute( - const RunInfo& info, - const MSplitInfo& mSplitInfo, - const LocalTensor& mmResUb, - uint32_t startRow, - uint32_t dealRowCount, - uint32_t columnCount) { - Muls(mmResUb, - mmResUb, - static_cast(tilingData->baseParams.softmaxScale), - dealRowCount * columnCount); - uint32_t gs1StartIdx = - info.gS1Idx + mSplitInfo.nBufferStartM + mSplitInfo.vecStartM + startRow; - uint32_t gs1EndIdx = gs1StartIdx + dealRowCount; - uint32_t s1StartIdx = gs1StartIdx / constInfo.gSize; - uint32_t s1EndIdx = gs1EndIdx / constInfo.gSize; - uint32_t gStartIdx = gs1StartIdx % constInfo.gSize; - uint32_t gEndIdx = gs1EndIdx % constInfo.gSize; - uint32_t dealTempSize = 0; - uint32_t ubOffset = 0; - if (info.isOriOnly) { - if constexpr (IS_DSPARK) { - int32_t oriLenLimit = actualSeqLengthsKVGm.GetValue(info.bIdx); - uint32_t validCols = Min(info.actualSingleProcessSInnerSize, columnCount); - uint32_t sparseColStart = info.s2Idx * constInfo.s2BaseSize; - for (uint32_t i = s1StartIdx; i <= s1EndIdx; i++) { - dealTempSize = constInfo.gSize - gStartIdx; - if (i == s1EndIdx) { - dealTempSize = gEndIdx - gStartIdx; - } - if (dealTempSize == 0) { - continue; - } - uint64_t qTokenOffsetForS1 = 0; - if constexpr (LAYOUT_T == SMLA_LAYOUT::TND) { - qTokenOffsetForS1 = - static_cast(actualSeqLengthsQGm.GetValue(info.bIdx)) + - static_cast(i); - } else { - qTokenOffsetForS1 = - static_cast(info.bIdx) * constInfo.qSeqSize + - static_cast(i); - } - uint64_t topkLenOffset = - qTokenOffsetForS1 * constInfo.kvHeadNum + info.n2IdxReal; - int32_t rowLen = oriTopkLengthGm.GetValue(topkLenOffset); - if (rowLen <= 0) { - SetInfInBlk(mmResUb[ubOffset], - dealTempSize, - columnCount, - 0, - static_cast(columnCount - 1)); - ubOffset += dealTempSize * columnCount; - gStartIdx = 0; - continue; - } - uint32_t colEnd = 0; - uint32_t tailStart = 0; - if (static_cast(rowLen) > sparseColStart) { - colEnd = - Min(validCols, static_cast(rowLen) - sparseColStart); - tailStart = static_cast(rowLen) - sparseColStart; - } - if (colEnd > 0) { - LocalTensor rowIndexUb = tmpBuff1.Get(); - event_t vToMte2 = static_cast( - GetTPipePtr()->FetchEventID(HardEvent::V_MTE2)); - SetFlag(vToMte2); - WaitFlag(vToMte2); - LoadOriSparseIndicesGmToUb(qTokenOffsetForS1, - info.n2IdxReal, - sparseColStart, - static_cast(colEnd), - rowIndexUb); - for (uint32_t k = 0; k < colEnd; ++k) { - int32_t logicalIdx = rowIndexUb.GetValue(k); - if (logicalIdx < 0 || logicalIdx >= oriLenLimit) { - SetInfInBlk(mmResUb[ubOffset], - dealTempSize, - columnCount, - static_cast(k), - static_cast(k)); - } - } - } - if (tailStart < validCols) { - SetInfInBlk(mmResUb[ubOffset], - dealTempSize, - columnCount, - static_cast(tailStart), - static_cast(validCols - 1)); - } - if (info.actualSingleProcessSInnerSize < columnCount) { - SetInfInBlk(mmResUb[ubOffset], - dealTempSize, - columnCount, - static_cast(info.actualSingleProcessSInnerSize), - static_cast(columnCount - 1)); - } - ubOffset += dealTempSize * columnCount; - gStartIdx = 0; - } - // rowIndexUb来自tmpBuff1,后续的softmaxTmpUb(V)处理需要等此处getvalue(S)结束 - event_t sToV = - static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); - SetFlag(sToV); - WaitFlag(sToV); - - } else { - int32_t right = - info.oriDealSize + s1StartIdx - info.gS1Idx / constInfo.gSize; - int32_t left = Max(0, - static_cast(right) - constInfo.oriWinLeft + - constInfo.oriWinRight); - for (uint32_t i = s1StartIdx; i <= s1EndIdx; i++) { - dealTempSize = constInfo.gSize - gStartIdx; - if (i == s1EndIdx) { - dealTempSize = gEndIdx - gStartIdx; - } - if (dealTempSize == 0) { - continue; - } - SetInfInBlk(mmResUb[ubOffset], dealTempSize, columnCount, 0, left - 1); - SetInfInBlk(mmResUb[ubOffset], - dealTempSize, - columnCount, - right + 1, - columnCount - 1); - right = Min(right + 1, columnCount - 1); - left = Max(0, - static_cast(right) - constInfo.oriWinLeft + - constInfo.oriWinRight); - ubOffset += dealTempSize * columnCount; - gStartIdx = 0; - } - } - } else if (info.isOriCmpMix) { - int32_t oriRight = - info.oriDealSize + s1StartIdx - info.gS1Idx / constInfo.gSize; - int32_t oriLeft = Max(0, - static_cast(oriRight) - - constInfo.oriWinLeft + constInfo.oriWinRight); - int32_t noMaskCmpSize = info.cmpMaskRight + s1StartIdx + 1; - int32_t actNoMaskCmpSize = 0; - int32_t cmpRight = 0; - for (uint32_t i = s1StartIdx; i <= s1EndIdx; i++) { - dealTempSize = constInfo.gSize - gStartIdx; - if (i == s1EndIdx) { - dealTempSize = gEndIdx - gStartIdx; - } - if (dealTempSize == 0) { - continue; - } - actNoMaskCmpSize = noMaskCmpSize / constInfo.cmpRatio; - if (actNoMaskCmpSize <= 0) { - cmpRight = 0; - } else { - cmpRight = - Min(actNoMaskCmpSize, - constInfo.s2BaseSize - info.actualSingleProcessSInnerOriSize); - } - SetInfInBlk(mmResUb[ubOffset], dealTempSize, columnCount, 0, oriLeft - 1); - SetInfInBlk(mmResUb[ubOffset], - dealTempSize, - columnCount, - oriRight + 1, - info.actualSingleProcessSInnerOriSize - 1); - oriRight = Min(oriRight + 1, info.actualSingleProcessSInnerOriSize); - oriLeft = Max(0, - static_cast(oriRight) - constInfo.oriWinLeft + - constInfo.oriWinRight); - SetInfInBlk(mmResUb[ubOffset], - dealTempSize, - columnCount, - cmpRight + info.actualSingleProcessSInnerOriSize, - columnCount - 1); - noMaskCmpSize += 1; - ubOffset += dealTempSize * columnCount; - gStartIdx = 0; - } - } else { - int32_t noMaskCmpSize = info.cmpMaskRight + s1StartIdx + 1; - int32_t actNoMaskCmpSize = 0; - int32_t right = 0; - // relativeS2Idx is the cmp tile index relative to the current batch. - // s2Idx may include the global task index. - int64_t cmpTileStart = - static_cast(info.relativeS2Idx) * constInfo.s2BaseSize + - static_cast(info.s2StartPoint); - for (uint32_t i = s1StartIdx; i <= s1EndIdx; i++) { - actNoMaskCmpSize = noMaskCmpSize / constInfo.cmpRatio; - if (actNoMaskCmpSize <= 0) { - right = 0; - } else { - right = actNoMaskCmpSize - cmpTileStart; - } - dealTempSize = constInfo.gSize - gStartIdx; - if (i == s1EndIdx) { - dealTempSize = gEndIdx - gStartIdx; - } - if (dealTempSize == 0) { - continue; - } - SetInfInBlk( - mmResUb[ubOffset], dealTempSize, columnCount, right, columnCount - 1); - noMaskCmpSize += 1; - ubOffset += dealTempSize * columnCount; - gStartIdx = 0; - } - } -} - -template -__aicore__ inline void SWAVectorBlock::SetInfInBlk( - const LocalTensor& mmResUb, - uint32_t dealRowCount, - uint32_t columnCount, - int64_t startId, - int64_t endId) { - // startId endId - // x x x 0 0 0 x x x - // 从startId到endId部分置-inf, endId、startId为endId一个blk内部的下标 - // 左闭右闭 - if (startId > endId) { - return; - } - int64_t start = startId < 0 ? 0 : startId; - int64_t end = endId >= static_cast(columnCount) - ? static_cast(columnCount) - 1 - : endId; - if (start > end) { - return; - } - - uint64_t curStart = static_cast(start); - uint64_t curEnd = static_cast(end); - while (curStart <= curEnd) { - uint64_t blockStart = curStart / BLOCK_ELEMENT_NUM * BLOCK_ELEMENT_NUM; - uint64_t blockEnd = blockStart + BLOCK_ELEMENT_NUM - 1; - blockEnd = blockEnd > curEnd ? curEnd : blockEnd; - - uint64_t preMask = (1llu << (curStart - blockStart)) - 1; - uint64_t postMask = ~((1llu << (blockEnd - blockStart + 1)) - 1); - uint64_t mask[1] = {~(preMask | postMask)}; - Duplicate(mmResUb[blockStart], - SOFTMAX_MIN_NUM, - mask, - dealRowCount, - 1, - columnCount / BLOCK_ELEMENT_NUM); - if constexpr (IS_DSPARK) { - PipeBarrier(); - } - curStart = blockEnd + 1; - } -} - -template -__aicore__ inline void SWAVectorBlock::SoftmaxFlashV2Compute( - const RunInfo& info, - const MSplitInfo& mSplitInfo, - LocalTensor& mmResUb, - LocalTensor& softmaxTmpUb, - uint32_t startRow, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount) { - LocalTensor inSumTensor; - LocalTensor inMaxTensor; - uint32_t baseOffset = mSplitInfo.nBufferStartM / 2 + startRow; - uint32_t outIdx = info.loop % (constInfo.preLoadNum); - uint32_t softmaxOutOffset = - outIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset; - if (info.isFirstSInnerLoop) { - inMaxTensor = softmaxMaxDefaultUb[startRow]; - inSumTensor = softmaxSumDefaultUb; - } else { - uint32_t inIdx = (info.loop - 1) % (constInfo.preLoadNum); - inMaxTensor = softmaxMaxUb[inIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + - baseOffset]; - inSumTensor = softmaxSumUb[inIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + - baseOffset]; - } - if (actualColumnCount != 0) { - SoftMaxShapeInfo srcShape{ - dealRowCount, columnCount, dealRowCount, actualColumnCount}; - SoftMaxTiling newTiling = SoftMaxFlashV2TilingFunc( - srcShape, sizeof(T), sizeof(T), softmaxTmpUb.GetSize(), true, false); - SoftmaxFlashV2( - mmResUb, - softmaxSumUb[softmaxOutOffset], - softmaxMaxUb[softmaxOutOffset], - mmResUb, - softmaxExpUb[softmaxOutOffset], - inSumTensor, - inMaxTensor, - softmaxTmpUb, - newTiling, - srcShape); - } else { - uint32_t dealRowCountAlign = - SMLAAlign(dealRowCount, FP32_BLOCK_ELEMENT_NUM); - DataCopy(softmaxSumUb[softmaxOutOffset], inSumTensor, dealRowCountAlign); - PipeBarrier(); - DataCopy(softmaxMaxUb[softmaxOutOffset], inMaxTensor, dealRowCountAlign); - } -} - -template -__aicore__ inline void SWAVectorBlock::ProcessLse( - const RunInfo& info, - const MSplitInfo& mSplitInfo) { - if (mSplitInfo.vecDealM == 0) { - return; - } - uint64_t lseOffset; - if (constInfo.outputLayout == SMLA_LAYOUT::TND) { - uint32_t tBase = actualSeqLengthsQGm.GetValue(info.bIdx); - lseOffset = (tBase + info.s1Idx) * constInfo.gSize + - info.n2IdxReal * constInfo.qSeqSize * constInfo.gSize; - } else if (constInfo.outputLayout == SMLA_LAYOUT::BSND) { - lseOffset = - info.bIdx * constInfo.qSeqSize * constInfo.kvHeadNum * constInfo.gSize + - info.n2IdxReal * constInfo.qSeqSize * constInfo.gSize + - info.s1Idx * constInfo.gSize; - } - lseOffset = lseOffset + mSplitInfo.nBufferStartM + mSplitInfo.vecStartM; - uint32_t baseOffset = mSplitInfo.nBufferStartM / 2; - uint32_t outIdx = info.loop % (constInfo.preLoadNum); - uint32_t softmaxOffset = - outIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset; - auto sumTensor = softmaxSumUb[softmaxOffset]; - auto maxTensor = softmaxMaxUb[softmaxOffset]; - auto outLSETensor = outputBuff2.Get(); - DataCopyExtParams dataCopyParams; - dataCopyParams.blockCount = 1; - dataCopyParams.blockLen = mSplitInfo.vecDealM * sizeof(T); - dataCopyParams.srcStride = 0; - dataCopyParams.dstStride = 0; - - WaitFlag(SYNC_OUTPUT_BUF2_FLAG); - PipeBarrier(); - Log(outLSETensor, sumTensor, mSplitInfo.vecDealM); - PipeBarrier(); - Add(outLSETensor, outLSETensor, maxTensor, mSplitInfo.vecDealM); - SetFlag(SYNC_OUTPUT_BUF2_FLAG); - WaitFlag(SYNC_OUTPUT_BUF2_FLAG); - - DataCopyPad(softmaxLseGm[lseOffset], outLSETensor, dataCopyParams); - SetFlag(SYNC_OUTPUT_BUF2_FLAG); -} - -template -__aicore__ inline void SWAVectorBlock::DealBmm1ResBaseBlock( - const RunInfo& info, - const MSplitInfo& mSplitInfo, - uint32_t startRow, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t loopId) { - uint32_t computeSize = dealRowCount * columnCount; - uint64_t inOutGmOffset = - (info.loop % constInfo.preLoadNum) * constInfo.mmResUbSize + - (mSplitInfo.nBufferStartM + mSplitInfo.vecStartM + startRow) * - columnCount; - LocalTensor mmResUb = inputBuff1.Get(); - mmResUb = mmResUb[pingpongFlag * INPUT1_BUFFER_OFFSET / sizeof(MM1_OUT_T)]; - WaitFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); - - DataCopy(mmResUb, mm1ResGm[inOutGmOffset], computeSize); - SetFlag(SYNC_INPUT_BUF1_FLAG); - WaitFlag(SYNC_INPUT_BUF1_FLAG); - - ElewiseCompute( - info, mSplitInfo, mmResUb, startRow, dealRowCount, columnCount); - - PipeBarrier(); - LocalTensor tmpAFloorUb = tmpBuff1.Get(); - LocalTensor softmaxTmpUb = - tmpAFloorUb.template ReinterpretCast(); - - SoftmaxFlashV2Compute(info, - mSplitInfo, - mmResUb, - softmaxTmpUb, - startRow, - dealRowCount, - columnCount, - info.actualSingleProcessSInnerSize); - PipeBarrier(); - LocalTensor tmpMMResCastTensor = outputBuff1.Get(); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - - Cast( - tmpMMResCastTensor, mmResUb, AscendC::RoundMode::CAST_ROUND, computeSize); - SetFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); - - SetFlag(SYNC_OUTPUT_BUF1_FLAG); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - DataCopy(vec1ResGm[inOutGmOffset], tmpMMResCastTensor, computeSize); - SetFlag(SYNC_OUTPUT_BUF1_FLAG); -} - -template -__aicore__ inline void SWAVectorBlock::ProcessVec1SingleBuf( - const RunInfo& info, - const MSplitInfo& mSplitInfo) { - if (mSplitInfo.vecDealM == 0) { - return; - } - uint32_t mSplitSize = info.actualSingleProcessSInnerSize == 0 - ? 16 - : BASE_BLOCK_MAX_ELEMENT_NUM / - info.actualSingleProcessSInnerSizeAlign; - // 1. 向下8对齐是因为UB操作至少32B - // 2. info.actualSingleProcessSInnerSizeAlign最大512, - // mSplitSize可以确保最小为16 - mSplitSize = mSplitSize / 8 * 8; - - if (mSplitSize > mSplitInfo.vecDealM) { - mSplitSize = mSplitInfo.vecDealM; - } - uint32_t loopCount = (mSplitInfo.vecDealM + mSplitSize - 1) / mSplitSize; - uint32_t tailSplitSize = mSplitInfo.vecDealM - (loopCount - 1) * mSplitSize; - - uint32_t sinkHeadIdx = (info.n2IdxReal * constInfo.gSize + - mSplitInfo.nBufferStartM + mSplitInfo.vecStartM) % - constInfo.qHeadNum; - SliceAndContactSinksValue(sinkHeadIdx, mSplitInfo.vecDealM); - - for (uint32_t i = 0, dealSize = mSplitSize; i < loopCount; i++) { - if (i == (loopCount - 1)) { - dealSize = tailSplitSize; - } - DealBmm1ResBaseBlock(info, - mSplitInfo, - i * mSplitSize, - dealSize, - info.actualSingleProcessSInnerSizeAlign, - i); - pingpongFlag ^= 1; // pingpong 0 1切换 - } -} - -// =======================vec1============================= - -template -__aicore__ inline void SWAVectorBlock::ProcessVec1L( - const RunInfo& info) { - uint32_t nBufferLoopTimes = - (info.actMBaseSize + constInfo.nBufferMBaseSize - 1) / - constInfo.nBufferMBaseSize; - uint32_t nBufferTail = - info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; - for (uint32_t i = 0; i < nBufferLoopTimes; i++) { - MSplitInfo mSplitInfo; - mSplitInfo.nBufferIdx = i; - mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; - mSplitInfo.nBufferDealM = - (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; - - mSplitInfo.vecDealM = - (mSplitInfo.nBufferDealM <= 16) - ? mSplitInfo.nBufferDealM - : (((mSplitInfo.nBufferDealM + 15) / 16 + 1) / 2 * 16); - mSplitInfo.vecStartM = 0; - if (GetBlockIdx() % 2 == 1) { - mSplitInfo.vecStartM = mSplitInfo.vecDealM; - mSplitInfo.vecDealM = mSplitInfo.nBufferDealM - mSplitInfo.vecDealM; - } - - CrossCoreWaitFlag(constInfo.syncC1V1); - // vec1 compute - ProcessVec1SingleBuf(info, mSplitInfo); - CrossCoreSetFlag(constInfo.syncV1C2); - - // move lse for flash decode or FA - if (constInfo.returnSoftmaxLse && - info.s2Idx == info.curSInnerLoopTimes - 1) { - ProcessLse(info, mSplitInfo); - } - } -} - -// =======================vec2============================= - -template -__aicore__ inline uint64_t SWAVectorBlock::CalcAccumOffset( - uint32_t bN2Idx, - uint32_t gS1Idx) { - return 0; -} - -template -__aicore__ inline void SWAVectorBlock::ProcessVec2SingleBuf( - const RunInfo& info, - const MSplitInfo& mSplitInfo) { - if (mSplitInfo.vecDealM == 0) { - return; - } - - ProcessVec2Inner(info, mSplitInfo, 0, mSplitInfo.vecDealM); -} - -template -__aicore__ inline void SWAVectorBlock::ProcessVec2L( - const RunInfo& info) { - uint32_t nBufferLoopTimes = - (info.actMBaseSize + constInfo.nBufferMBaseSize - 1) / - constInfo.nBufferMBaseSize; - uint32_t nBufferTail = - info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; - for (uint32_t i = 0; i < nBufferLoopTimes; i++) { - MSplitInfo mSplitInfo; - mSplitInfo.nBufferIdx = i; - mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; - mSplitInfo.nBufferDealM = - (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; - - mSplitInfo.vecDealM = - (mSplitInfo.nBufferDealM <= 16) - ? mSplitInfo.nBufferDealM - : (((mSplitInfo.nBufferDealM + 15) / 16 + 1) / 2 * 16); - mSplitInfo.vecStartM = 0; - if (GetBlockIdx() % 2 == 1) { - mSplitInfo.vecStartM = mSplitInfo.vecDealM; - mSplitInfo.vecDealM = mSplitInfo.nBufferDealM - mSplitInfo.vecDealM; - } - CrossCoreWaitFlag(constInfo.syncC2V2); - ProcessVec2SingleBuf(info, mSplitInfo); - } -} - -template -__aicore__ inline void SWAVectorBlock::ProcessVec2Inner( - const RunInfo& info, - const MSplitInfo& mSplitInfo, - uint32_t mStartRow, - uint32_t mDealSize) { - uint32_t mSplitSize = BASE_BLOCK_MAX_ELEMENT_NUM / constInfo.headDim; - if (mSplitSize > mDealSize) { - mSplitSize = mDealSize; - } - - uint32_t loopCount = (mDealSize + mSplitSize - 1) / mSplitSize; - uint32_t tailSplitSize = mDealSize - (loopCount - 1) * mSplitSize; - for (uint32_t i = 0, dealSize = mSplitSize; i < loopCount; i++) { - if (i == (loopCount - 1)) { - dealSize = tailSplitSize; - } - DealBmm2ResBaseBlock(info, - mSplitInfo, - i * mSplitSize + mStartRow, - dealSize, - constInfo.headDim, - constInfo.headDim); - pingpongFlag ^= 1; // pingpong 0 1切换 - } -} - -template -__aicore__ inline void SWAVectorBlock::Bmm2FDDataCopyOut( - const RunInfo& info, - LocalTensor& bmm2ResUb, - uint32_t wsMStart, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount) { - LocalTensor tmp = outputBuff1.Get(); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - DataCopy(tmp, bmm2ResUb, columnCount * dealRowCount); - SetFlag(SYNC_OUTPUT_BUF1_FLAG); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - uint64_t accumTmpOutNum = CalcAccumOffset(info.bIdx, info.gS1Idx); - uint64_t offset = accumTmpOutNum * constInfo.kvHeadNum * constInfo.mBaseSize * - constInfo.headDim + // taskoffset - info.tndCoreStartKVSplitPos * constInfo.kvHeadNum * - constInfo.mBaseSize * constInfo.headDim + // 份数offset - wsMStart * actualColumnCount; // m轴offset - GlobalTensor dst = accumOutGm[offset]; - if (info.actualSingleProcessSInnerSize == 0) { - DataCopyExtParams dataCopyParams; - dataCopyParams.blockCount = dealRowCount; - dataCopyParams.blockLen = actualColumnCount * sizeof(T); - dataCopyParams.srcStride = - (columnCount - actualColumnCount) / (BYTE_BLOCK / sizeof(T)); - dataCopyParams.dstStride = 0; - DataCopyPad(dst, tmp, dataCopyParams); - } else { - matmul::InitOutput( - dst, dealRowCount * actualColumnCount, ConstInfo::FLOAT_ZERO); - } - SetFlag(SYNC_OUTPUT_BUF1_FLAG); -} - -template -__aicore__ inline void SWAVectorBlock::Bmm2DataCopyOutTrans( - const RunInfo& info, - LocalTensor& attenOutUb, - uint32_t wsMStart, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount) { - DataCopyExtParams dataCopyParams; - dataCopyParams.blockCount = dealRowCount; - dataCopyParams.blockLen = actualColumnCount * sizeof(OUT_T); - dataCopyParams.srcStride = - (columnCount - actualColumnCount) / (BYTE_BLOCK / sizeof(OUT_T)); - dataCopyParams.dstStride = 0; - DataCopyPad( - attentionOutGm[info.attenOutOffset + wsMStart * actualColumnCount], - attenOutUb, - dataCopyParams); - return; -} - -template -__aicore__ inline void SWAVectorBlock::Bmm2CastAndCopyOut( - const RunInfo& info, - LocalTensor& bmm2ResUb, - uint32_t wsMStart, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount) { - LocalTensor tmpBmm2ResCastTensor = outputBuff1.Get(); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - if constexpr (IsSameType::value) { // bf16 采取四舍六入五成双模式 - Cast(tmpBmm2ResCastTensor, - bmm2ResUb, - AscendC::RoundMode::CAST_RINT, - dealRowCount * columnCount); - } else { - Cast(tmpBmm2ResCastTensor, - bmm2ResUb, - AscendC::RoundMode::CAST_ROUND, - dealRowCount * columnCount); - } - - SetFlag(SYNC_OUTPUT_BUF1_FLAG); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - Bmm2DataCopyOutTrans(info, - tmpBmm2ResCastTensor, - wsMStart, - dealRowCount, - columnCount, - actualColumnCount); - SetFlag(SYNC_OUTPUT_BUF1_FLAG); -} - -template -__aicore__ inline void SWAVectorBlock::Bmm2ResCopyOut( - const RunInfo& info, - LocalTensor& bmm2ResUb, - uint32_t wsMStart, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount) { - if constexpr (FLASH_DECODE) { - if (info.tndIsS2SplitCore) { - Bmm2FDDataCopyOut(info, - bmm2ResUb, - wsMStart, - dealRowCount, - columnCount, - actualColumnCount); - } else { - Bmm2CastAndCopyOut(info, - bmm2ResUb, - wsMStart, - dealRowCount, - columnCount, - actualColumnCount); - } - } else { - Bmm2CastAndCopyOut(info, - bmm2ResUb, - wsMStart, - dealRowCount, - columnCount, - actualColumnCount); - } -} - -template -__aicore__ inline void SWAVectorBlock::DealBmm2ResBaseBlock( - const RunInfo& info, - const MSplitInfo& mSplitInfo, - uint32_t startRow, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount) { - uint32_t vec2ComputeSize = dealRowCount * columnCount; - uint32_t mStart = mSplitInfo.nBufferStartM + mSplitInfo.vecStartM + startRow; - uint64_t srcGmOffset = - (info.loop % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + - mStart * columnCount; - LocalTensor tmpBmm2ResUb = inputBuff1.Get(); - tmpBmm2ResUb = - tmpBmm2ResUb[pingpongFlag * INPUT1_BUFFER_OFFSET / sizeof(MM2_OUT_T)]; - WaitFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); - DataCopy(tmpBmm2ResUb, mm2ResGm[srcGmOffset], vec2ComputeSize); - - SetFlag(SYNC_INPUT_BUF1_FLAG); - WaitFlag(SYNC_INPUT_BUF1_FLAG); - - LocalTensor bmm2ResUb = tmpBuff1.Get(); - bmm2ResUb.SetSize(vec2ComputeSize); - DataCopy(bmm2ResUb, tmpBmm2ResUb, vec2ComputeSize); - SetFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); - - uint32_t inOutBaseOffset = mStart * columnCount; - uint32_t baseOffset = mSplitInfo.nBufferStartM / 2 + startRow; - - // 除第一个循环外,均需要更新中间计算结果 - if (!info.isFirstSInnerLoop) { - event_t eventIdMte2WaitMte3 = - static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE3_MTE2)); - SetFlag(eventIdMte2WaitMte3); - WaitFlag(eventIdMte2WaitMte3); - - LocalTensor bmm2ResPreUb = inputBuff2.Get(); - WaitFlag(SYNC_INPUT_BUF2_FLAG); - - uint64_t vec2ResGmOffset = - ((info.loop - 1) % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + - inOutBaseOffset; - DataCopy(bmm2ResPreUb, vec2ResGm[vec2ResGmOffset], vec2ComputeSize); - - SetFlag(SYNC_INPUT_BUF2_FLAG); - WaitFlag(SYNC_INPUT_BUF2_FLAG); - - uint32_t idx = info.loop % (constInfo.preLoadNum); - LocalTensor expUb = - v0ValidSizeBuff.Get()[384]; // sumUb用临时内存 16 * 32B = 512B - Brcb(expUb, - softmaxExpUb[idx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset], - (dealRowCount + 7) / 8, - {1, 8}); - PipeBarrier(); - - RowMuls(bmm2ResPreUb, - bmm2ResPreUb, - expUb, - dealRowCount, - columnCount, - actualColumnCount); - AscendC::PipeBarrier(); - Add(bmm2ResUb, bmm2ResUb, bmm2ResPreUb, vec2ComputeSize); - AscendC::PipeBarrier(); - - SetFlag(SYNC_INPUT_BUF2_FLAG); - } - - // 最后一次输出计算结果,否则将中间结果暂存至workspace - if (info.isLastS2Loop) { - uint32_t idx = info.loop % (constInfo.preLoadNum); - LocalTensor tmpSumUb = - v0ValidSizeBuff.Get()[384]; // sumUb用临时内存 16 * 32B = 512B - Brcb(tmpSumUb, - softmaxSumUb[idx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset], - (dealRowCount + 7) / 8, - {1, 8}); - PipeBarrier(); - RowDivs(bmm2ResUb, - bmm2ResUb, - tmpSumUb, - dealRowCount, - columnCount, - actualColumnCount); - PipeBarrier(); - Bmm2ResCopyOut( - info, bmm2ResUb, mStart, dealRowCount, columnCount, actualColumnCount); - } else { - LocalTensor outUb = outputBuff1.Get(); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - PipeBarrier(); - DataCopy(outUb, bmm2ResUb, dealRowCount * columnCount); - SetFlag(SYNC_OUTPUT_BUF1_FLAG); - WaitFlag(SYNC_OUTPUT_BUF1_FLAG); - uint64_t vec2ResGmOffset = - (info.loop % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + - inOutBaseOffset; - DataCopy(vec2ResGm[vec2ResGmOffset], outUb, vec2ComputeSize); - SetFlag(SYNC_OUTPUT_BUF1_FLAG); - } -} - -template -__aicore__ inline void SWAVectorBlock::RowDivs( - LocalTensor dstUb, - LocalTensor src0Ub, - LocalTensor src1Ub, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount) { - // divs by row, 每行的元素除以相同的元素 - // dstUb[i, (j * 8) : (j * 8 + 7)] = src0Ub[i, (j * 8) : (j * 8 + 7)] / - // src1Ub[i, 0 : 7] src0Ub:[dealRowCount, columnCount], src1Ub:[dealRowCount, - // FP32_BLOCK_ELEMENT_NUM] dstUb:[dealRowCount, columnCount] - uint32_t dtypeMask = FP32_REPEAT_ELEMENT_NUM; - uint32_t dLoop = actualColumnCount / dtypeMask; - uint32_t dRemain = actualColumnCount % dtypeMask; - - BinaryRepeatParams repeatParamsDiv; - repeatParamsDiv.src0BlkStride = 1; - repeatParamsDiv.src1BlkStride = 0; - repeatParamsDiv.dstBlkStride = 1; - repeatParamsDiv.src0RepStride = columnCount / FP32_BLOCK_ELEMENT_NUM; - repeatParamsDiv.src1RepStride = 1; - repeatParamsDiv.dstRepStride = columnCount / FP32_BLOCK_ELEMENT_NUM; - uint32_t columnRepeatCount = dLoop; - if (columnRepeatCount <= dealRowCount) { - uint32_t offset = 0; - for (uint32_t i = 0; i < dLoop; i++) { - Div(dstUb[offset], - src0Ub[offset], - src1Ub, - dtypeMask, - dealRowCount, - repeatParamsDiv); - offset += dtypeMask; - } - } else { - BinaryRepeatParams columnRepeatParams; - columnRepeatParams.src0BlkStride = 1; - columnRepeatParams.src1BlkStride = 0; - columnRepeatParams.dstBlkStride = 1; - columnRepeatParams.src0RepStride = - 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block - columnRepeatParams.src1RepStride = 0; - columnRepeatParams.dstRepStride = - 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block - uint32_t offset = 0; - for (uint32_t i = 0; i < dealRowCount; i++) { - Div(dstUb[offset], - src0Ub[offset], - src1Ub[i * FP32_BLOCK_ELEMENT_NUM], - dtypeMask, - columnRepeatCount, - columnRepeatParams); - offset += columnCount; - } - } - if (dRemain > 0) { - Div(dstUb[dLoop * dtypeMask], - src0Ub[dLoop * dtypeMask], - src1Ub, - dRemain, - dealRowCount, - repeatParamsDiv); - } -} - -template -__aicore__ inline void SWAVectorBlock::RowMuls( - LocalTensor dstUb, - LocalTensor src0Ub, - LocalTensor src1Ub, - uint32_t dealRowCount, - uint32_t columnCount, - uint32_t actualColumnCount) { - // muls by row, 每行的元素乘以相同的元素 - // dstUb[i, (j * 8) : (j * 8 + 7)] = src0Ub[i, (j * 8) : (j * 8 + 7)] * - // src1Ub[i, 0 : 7] src0Ub:[dealRowCount, columnCount] src1Ub:[dealRowCount, - // FP32_BLOCK_ELEMENT_NUM] dstUb:[dealRowCount, columnCount] dealRowCount is - // repeat times, must be less 256 - uint32_t repeatElementNum = FP32_REPEAT_ELEMENT_NUM; - uint32_t blockElementNum = FP32_BLOCK_ELEMENT_NUM; - - if constexpr (std::is_same::value) { - // 此限制由于每个repeat至多连续读取256B数据 - repeatElementNum = FP32_REPEAT_ELEMENT_NUM * 2; // 256/4 * 2=128 - blockElementNum = FP32_BLOCK_ELEMENT_NUM * 2; // 32/4 * 2 = 16 - } - - // 每次只能连续读取256B的数据进行计算,故每次只能处理256B/sizeof(dType)= - // 列方向分dLoop次,每次处理8列数据 - uint32_t dLoop = actualColumnCount / repeatElementNum; - uint32_t dRemain = actualColumnCount % repeatElementNum; - // REPEATE_STRIDE_UP_BOUND=256, - // 此限制由于src0RepStride数据类型为uint8之多256个datablock间距 - if (columnCount < REPEATE_STRIDE_UP_BOUND * blockElementNum) { - BinaryRepeatParams repeatParams; - repeatParams.src0BlkStride = 1; - repeatParams.src1BlkStride = 0; - repeatParams.dstBlkStride = 1; - repeatParams.src0RepStride = columnCount / blockElementNum; - repeatParams.src1RepStride = 1; - repeatParams.dstRepStride = columnCount / blockElementNum; - - // 如果以列为repeat所处理的次数小于行处理次数,则以列方式处理。反之则以行进行repeat处理 - if (dLoop <= dealRowCount) { - uint32_t offset = 0; - for (uint32_t i = 0; i < dLoop; i++) { - Mul(dstUb[offset], - src0Ub[offset], - src1Ub, - repeatElementNum, - dealRowCount, - repeatParams); - offset += repeatElementNum; - } - } else { - BinaryRepeatParams columnRepeatParams; - columnRepeatParams.src0BlkStride = 1; - columnRepeatParams.src1BlkStride = 0; - columnRepeatParams.dstBlkStride = 1; - columnRepeatParams.src0RepStride = - 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block - columnRepeatParams.src1RepStride = 0; - columnRepeatParams.dstRepStride = - 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block - for (uint32_t i = 0; i < dealRowCount; i++) { - Mul(dstUb[i * columnCount], - src0Ub[i * columnCount], - src1Ub[i * blockElementNum], - repeatElementNum, - dLoop, - columnRepeatParams); - } - } - - // 最后一次完成[dealRowCount, dRemain] * [dealRowCount, blockElementNum] - // 只计算有效部分 - if (dRemain > 0) { - Mul(dstUb[dLoop * repeatElementNum], - src0Ub[dLoop * repeatElementNum], - src1Ub, - dRemain, - dealRowCount, - repeatParams); - } - } else { - BinaryRepeatParams repeatParams; - repeatParams.src0RepStride = 8; // 每个repeat为256B数据,正好8个datablock - repeatParams.src0BlkStride = 1; - repeatParams.src1RepStride = 0; - repeatParams.src1BlkStride = 0; - repeatParams.dstRepStride = 8; - repeatParams.dstBlkStride = 1; - // 每次计算一行,共计算dealRowCount行 - for (uint32_t i = 0; i < dealRowCount; i++) { - // 计算一行中的dLoop个repeat, 每个repeat计算256/block_size 个data_block - Mul(dstUb[i * columnCount], - src0Ub[i * columnCount], - src1Ub[i * blockElementNum], - repeatElementNum, - dLoop, - repeatParams); - // 计算一行中的尾块 - if (dRemain > 0) { - Mul(dstUb[i * columnCount + dLoop * repeatElementNum], - src0Ub[i * columnCount + dLoop * repeatElementNum], - src1Ub[i * blockElementNum], - dRemain, - 1, - repeatParams); - } - } - } -} -} // namespace SMLAKernel -#endif diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_kernel.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_kernel.h deleted file mode 100644 index 55263a7581..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch22/sparse_flash_mla_swa_kernel.h +++ /dev/null @@ -1,1238 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file sparse_flash_mla_swa_kernel.h - * \brief - */ - -#ifndef SPARSE_FLASH_MLA_SWA_KERNEL_H -#define SPARSE_FLASH_MLA_SWA_KERNEL_H - -#include "kernel_operator.h" -#include "kernel_operator_list_tensor_intf.h" -#include "kernel_tiling/kernel_tiling.h" -#include "lib/matmul_intf.h" -#include "lib/matrix/matmul/tiling.h" -#include "sparse_flash_mla_arch22_metadata.h" -#include "sparse_flash_mla_common_arch22.h" -#include "sparse_flash_mla_swa_block_cube.h" -#include "sparse_flash_mla_swa_block_vector.h" - -namespace SMLAKernel { -using namespace matmul; -using namespace optiling; -using AscendC::CrossCoreSetFlag; -using AscendC::CrossCoreWaitFlag; - -// 由于S2循环前,RunInfo还没有赋值,使用Bngs1Param临时存放B、N、S1轴相关的信息;同时减少重复计算 -struct SwaTempLoopInfo { - uint32_t bn2IdxInCurCore = 0; - uint32_t bIdx = 0U; - uint32_t n2Idx = 0U; - uint32_t s2LoopTimes = - 0U; // S2方向循环的总次数,无论TND还是BXXD都是等于实际次数,不用减1 - uint64_t s2BasicSizeTail = 0U; // S2方向循环的尾基本块大小 - - int32_t actS1Size = 0; // TND场景下当前Batch循环处理的S1轴的大小 - int32_t actOriS2Size = 0; - int32_t actCmpS2Size = 0; - - bool curActSeqLenIsZero = false; - bool hasInvalidRow = false; - bool tndIsS2SplitCore = false; - bool resv; - uint32_t tndCoreStartKVSplitPos = 0; - uint32_t gS1Idx = 0U; - uint32_t s1StartIdx = 0; - uint32_t s1EndIdx = 0; - uint64_t mBasicSizeTail = 0U; // gS1方向循环的尾基本块大小 - uint32_t cmpLoopTimes = 0; - uint32_t oriLoopTimes = 0; - uint32_t oriCmpMixLoopTimes = 0; - uint32_t cmpMixSize = 0; - - int32_t oriMaskRight = 0; - int32_t oriMaskLeft = 0; - int32_t cmpMaskRight = 0; - - uint64_t actualSeqQPrefixSum = 0; - uint64_t actualSeqKVPrefixSum = 0; - uint64_t actualSeqCmpKVPrefixSum = 0; -}; - -template -class SparseFlashMlaSwa { - public: - // 中间计算数据类型为float,高精度模式 - using T = float; - using Q_T = typename SMLAT::queryType; - using KV_T = typename SMLAT::kvType; - using OUT_T = typename SMLAT::outputType; - using SINKS_T = float; - using UPDATE_T = T; - using MM1_OUT_T = T; - using MM2_OUT_T = T; - - __aicore__ inline SparseFlashMlaSwa(){}; - __aicore__ inline void Init(__gm__ uint8_t* query, - __gm__ uint8_t* oriKV, - __gm__ uint8_t* cmpKV, - __gm__ uint8_t* oriSparseIndices, - __gm__ uint8_t* cmpSparseIndices, - __gm__ uint8_t* oriBlockTable, - __gm__ uint8_t* cmpBlockTable, - __gm__ uint8_t* cuSeqlensQ, - __gm__ uint8_t* cuSeqlensKV, - __gm__ uint8_t* cuSeqlensCmpKV, - __gm__ uint8_t* seqUsedQ, - __gm__ uint8_t* seqUsedKV, - __gm__ uint8_t* seqUsedCmpKV, - __gm__ uint8_t* cmpResidualKV, - __gm__ uint8_t* oriTopkLength, - __gm__ uint8_t* cmpTopkLength, - __gm__ uint8_t* sinks, - __gm__ uint8_t* metadata, - __gm__ uint8_t* attentionOut, - __gm__ uint8_t* softmaxLse, - __gm__ uint8_t* workspace, - const SparseFlashMlaTilingData* __restrict tiling, - __gm__ uint8_t* gmTiling, - TPipe* tPipe); - - __aicore__ inline void Process(); - - private: - static constexpr bool PAGE_ATTENTION = SMLAT::pageAttention; - static constexpr int TEMPLATE_MODE = SMLAT::templateMode; - static constexpr bool FLASH_DECODE = SMLAT::flashDecode; - static constexpr SMLA_LAYOUT LAYOUT_T = SMLAT::layout; - static constexpr SMLA_LAYOUT KV_LAYOUT_T = SMLAT::kvLayout; - static constexpr bool IS_DSPARK = SMLAT::isDspark; - - static constexpr uint32_t PRELOAD_NUM = 2; - static constexpr uint32_t N_BUFFER_M_BASIC_SIZE = 256; - static constexpr uint32_t SMLA_PRELOAD_TASK_CACHE_SIZE = 3; - - static constexpr uint32_t SYNC_V0_C1_FLAG = 6; - static constexpr uint32_t SYNC_C1_V1_FLAG = 7; - static constexpr uint32_t SYNC_V1_C2_FLAG = 8; - static constexpr uint32_t SYNC_C2_V2_FLAG = 9; - static constexpr uint32_t MERGE_CACHE_GM_BUF_NUM = 3; - - static constexpr uint64_t SYNC_MM2RES_BUF1_FLAG = 10; - static constexpr uint64_t SYNC_MM2RES_BUF2_FLAG = 11; - static constexpr uint64_t SYNC_FDOUTPUT_BUF_FLAG = 12; - - static constexpr uint64_t headDim = 512ULL; - static constexpr uint64_t headDimAlign = 512ULL; - static constexpr uint32_t msdIterNum = 2U; - - static constexpr uint32_t dbWorkspaceRatio = PRELOAD_NUM; - - const SparseFlashMlaTilingData* __restrict tilingData = nullptr; - - TPipe* pipe = nullptr; - GlobalTensor metadataGm; - - uint64_t mSizeVStart = 0ULL; - int64_t threshold = 0; - uint64_t s2BatchBaseOffset = 0; - uint64_t tensorACoreOffset = 0ULL; - uint64_t tensorBCoreOffset = 0ULL; - uint64_t tensorCmpBCoreOffset = 0ULL; - uint64_t attenOutOffset = 0ULL; - - uint32_t tmpBlockIdx = 0U; - uint32_t aiCoreIdx = 0U; - - ConstInfo constInfo{}; - SwaTempLoopInfo tempLoopInfo{}; - - SWACubeBlock cubeBlock; - SWAVectorBlock vectorBlock; - - GlobalTensor queryGm; - GlobalTensor oriKvGm; - GlobalTensor cmpKvGm; - GlobalTensor sinksGm; - - GlobalTensor attentionOutGm; - GlobalTensor softmaxLseGm; - - GlobalTensor oriBlockTableGm; - GlobalTensor cmpBlockTableGm; - GlobalTensor oriSparseIndicesGm; - GlobalTensor oriTopkLengthGm; - - GlobalTensor actualSeqLengthsQGm; - GlobalTensor actualSeqLengthsKVGm; - GlobalTensor actualSeqLengthsCmpKVGm; - GlobalTensor cmpResidualKVGm; - - // workspace - GlobalTensor mm1ResGm; - GlobalTensor vec1ResGm; - GlobalTensor mm2ResGm; - - GlobalTensor vec2ResGm; - - GlobalTensor kvMergeGm_; - GlobalTensor accumOutGm; - // ================================Init - // functions================================== - __aicore__ inline void InitTilingData(); - __aicore__ inline void InitCalcParamsEach(); - __aicore__ inline void InitBuffers(); - __aicore__ inline void InitActualSeqLen(__gm__ uint8_t* actualSeqLengthsQ, - __gm__ uint8_t* actualSeqLengthsKv); - __aicore__ inline void InitActualSeqLen( - __gm__ uint8_t* actualSeqLengthsQ, - __gm__ uint8_t* actualSeqLengthsKV, - __gm__ uint8_t* actualSeqLengthsCmpKV); - __aicore__ inline void InitOutputSingleCore(); - // ================================Process - // functions================================ - __aicore__ inline void ProcessBalance(); - __aicore__ inline void PreloadPipeline( - uint32_t loop, - uint32_t cmpLoop, - uint64_t s2Start, - uint64_t s2LoopIdx, - RunInfo extraInfo[SMLA_PRELOAD_TASK_CACHE_SIZE]); - // ================================Offset - // Calc===================================== - __aicore__ inline void GetSparseActualSeqLen(); - __aicore__ inline void UpdateInnerLoopCond(); - __aicore__ inline void CalcParams(uint32_t loop, - uint32_t cmpLoop, - uint64_t s2Start, - uint32_t s2LoopIdx, - RunInfo& info); - __aicore__ inline int32_t GetActualSeqLenQ(uint32_t bIdx); - __aicore__ inline int32_t GetActualSeqLenKV(uint32_t bIdx); - __aicore__ inline uint32_t GetOriSparseActualSeqLen(); - __aicore__ inline int32_t GetActualSeqLenCmpKV(uint32_t bIdx, - int32_t actualOriS2Size); - __aicore__ inline int32_t GetCmpMaskS2Size(uint32_t bIdx, - int32_t actualOriS2Size, - int32_t actualCmpS2Size); - __aicore__ inline void GetBN2Idx(uint32_t bN2Idx, - uint32_t& bIdx, - uint32_t& n2Idx); - // ================================Mm1============================================== - __aicore__ inline void ComputeMm1(const RunInfo& info); - // ================================Mm2============================================== - __aicore__ inline void ComputeMm2(const RunInfo& info); - __aicore__ inline void InitAllZeroOutput(uint32_t bIdx, - uint32_t inValidRowS1StartIdx, - int32_t inValidRowCount, - uint32_t n2Idx); -}; - -template -__aicore__ inline void SparseFlashMlaSwa::InitTilingData() { - // singleCoreParams - // singleCoreTensorSize - constInfo.mmResUbSize = tilingData->baseParams.mmResUbSize; - constInfo.bmm2ResUbSize = tilingData->baseParams.bmm2ResUbSize; - constInfo.usedCoreNum = tilingData->baseParams.usedCoreNum; - // baseParams - constInfo.batchSize = tilingData->baseParams.batchSize; - constInfo.gSize = tilingData->baseParams.nNumOfQInOneGroup; - constInfo.kvHeadNum = (tilingData->baseParams.kvHeadNum == 0) - ? 1 - : tilingData->baseParams.kvHeadNum; - constInfo.qHeadNum = constInfo.gSize * constInfo.kvHeadNum; - constInfo.kvSeqSize = tilingData->baseParams.kvSeqSize; - constInfo.qSeqSize = tilingData->baseParams.qSeqSize; - constInfo.oriMaxBlockNumPerBatch = - tilingData->baseParams.oriMaxBlockNumPerBatch; - constInfo.kvCacheBlockSize = tilingData->baseParams.paBlockSize; - - constInfo.paOriBlockSize = tilingData->baseParams.oriBlockSize; - constInfo.paCmpBlockSize = tilingData->baseParams.cmpBlockSize; - constInfo.outputLayout = - static_cast(tilingData->baseParams.outputLayout); - constInfo.headDim = headDim; - constInfo.oriMaskMode = tilingData->baseParams.oriMaskMode; - constInfo.oriKvStride0 = tilingData->baseParams.oriKvStride0; - constInfo.oriWinLeft = tilingData->baseParams.oriWinLeft; - constInfo.oriWinRight = tilingData->baseParams.oriWinRight; - constInfo.hasOriSparseIndices = - tilingData->baseParams.hasOriSparseIndices != 0; - constInfo.oriSparseIndexWidth = tilingData->baseParams.oriSparseIndexWidth; - constInfo.returnSoftmaxLse = tilingData->baseParams.returnSoftmaxLse; - - constInfo.actualLenDimsQ = tilingData->baseParams.actualLenDimsQ; - constInfo.actualLenDimsKV = tilingData->baseParams.actualLenDimsKV; - constInfo.actualLenDimsCmpKV = tilingData->baseParams.actualLenDimsCmpKV; - constInfo.cmpResidualKVSize = tilingData->baseParams.cmpResidualKVSize; - - // innerSplitParams - constInfo.mBaseSize = tilingData->baseParams.mBaseSize; - constInfo.s2BaseSize = tilingData->baseParams.s2BaseSize; - constInfo.sparseBlockSize = tilingData->baseParams.sparseBlockSize; - - constInfo.preLoadNum = PRELOAD_NUM; - constInfo.nBufferMBaseSize = N_BUFFER_M_BASIC_SIZE; - constInfo.syncV0C1 = SYNC_V0_C1_FLAG; - constInfo.syncC1V1 = SYNC_C1_V1_FLAG; - constInfo.syncV1C2 = SYNC_V1_C2_FLAG; - constInfo.syncC2V2 = SYNC_C2_V2_FLAG; - constInfo.templateMode = TEMPLATE_MODE; - - // cmp - if constexpr (TEMPLATE_MODE == HCA_TEMPLATE) { - constInfo.cmpRatio = tilingData->cmpParams.cmpRatio; - constInfo.cmpMaskMode = tilingData->cmpParams.cmpMaskMode; - constInfo.cmpKvStride0 = tilingData->cmpParams.cmpKvStride0; - constInfo.cmpMaxBlockNumPerBatch = - tilingData->cmpParams.cmpMaxBlockNumPerBatch; - constInfo.cmpSeqSize = tilingData->cmpParams.cmpKvSeqSize; - } -} - -template -__aicore__ inline void SparseFlashMlaSwa::InitBuffers() { - if ASCEND_IS_AIV { - vectorBlock.InitBuffers(pipe); - } else { - cubeBlock.InitBuffers(pipe); - } -} - -template -__aicore__ inline void SparseFlashMlaSwa::InitActualSeqLen( - __gm__ uint8_t* actualSeqLengthsQ, - __gm__ uint8_t* actualSeqLengthsKv) { - if (constInfo.actualLenDimsKV != 0) { - actualSeqLengthsKVGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsKv, - constInfo.actualLenDimsKV); - } - if (constInfo.actualLenDimsQ != 0) { - actualSeqLengthsQGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsQ, - constInfo.actualLenDimsQ); - } -} - -template -__aicore__ inline void SparseFlashMlaSwa::InitActualSeqLen( - __gm__ uint8_t* actualSeqLengthsQ, - __gm__ uint8_t* actualSeqLengthsKV, - __gm__ uint8_t* actualSeqLengthsCmpKV) { - if (constInfo.actualLenDimsKV != 0) { - actualSeqLengthsKVGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsKV, - constInfo.actualLenDimsKV); - } - if constexpr (TEMPLATE_MODE == HCA_TEMPLATE) { - if (constInfo.actualLenDimsCmpKV != 0) { - actualSeqLengthsCmpKVGm.SetGlobalBuffer( - (__gm__ int32_t*)actualSeqLengthsCmpKV, constInfo.actualLenDimsCmpKV); - } - } - if (constInfo.actualLenDimsQ != 0) { - actualSeqLengthsQGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsQ, - constInfo.actualLenDimsQ); - } -} - -template -__aicore__ inline void SparseFlashMlaSwa::InitAllZeroOutput( - uint32_t bIdx, - uint32_t inValidRowS1StartIdx, - int32_t inValidRowCount, - uint32_t n2Idx) { - if (constInfo.outputLayout == SMLA_LAYOUT::TND) { - if (tempLoopInfo.actS1Size == 0) { - return; - } - uint32_t tBase = actualSeqLengthsQGm.GetValue(bIdx); - uint64_t attenOutOffset = - (tBase + inValidRowS1StartIdx) * constInfo.kvHeadNum * constInfo.gSize * - constInfo.headDim + - n2Idx * constInfo.gSize * constInfo.headDim; // N2轴偏移 - uint64_t lseOffset = - (tBase + inValidRowS1StartIdx) * constInfo.gSize + // T轴、s1轴偏移 - n2Idx * constInfo.qSeqSize * constInfo.gSize; // N2轴偏移 - if (constInfo.kvHeadNum == 1 || inValidRowCount <= 1) { - matmul::InitOutput( - attentionOutGm[attenOutOffset], - inValidRowCount * constInfo.gSize * constInfo.headDim, - 0); - } else { - uint64_t attenOutRowStride = constInfo.qHeadNum * constInfo.headDim; - for (int32_t rowIdx = 0; rowIdx < inValidRowCount; ++rowIdx) { - matmul::InitOutput( - attentionOutGm[attenOutOffset + - static_cast(rowIdx) * attenOutRowStride], - constInfo.gSize * constInfo.headDim, - 0); - } - } - if (constInfo.returnSoftmaxLse) { - matmul::InitOutput( - softmaxLseGm[lseOffset], inValidRowCount * constInfo.gSize, 0); - } - } else if (constInfo.outputLayout == SMLA_LAYOUT::BSND) { - uint64_t attenOutOffset = - bIdx * constInfo.qSeqSize * constInfo.kvHeadNum * constInfo.gSize * - constInfo.headDim + - inValidRowS1StartIdx * constInfo.kvHeadNum * constInfo.gSize * - constInfo.headDim + - n2Idx * constInfo.gSize * constInfo.headDim; // N2轴偏移 - uint64_t lseOffset = - bIdx * constInfo.qSeqSize * constInfo.kvHeadNum * - constInfo.gSize + // B轴偏移 - n2Idx * constInfo.qSeqSize * constInfo.gSize + // N2轴偏移 - inValidRowS1StartIdx * constInfo.gSize; // S1轴偏移 - if (constInfo.kvHeadNum == 1 || inValidRowCount <= 1) { - matmul::InitOutput( - attentionOutGm[attenOutOffset], - inValidRowCount * constInfo.gSize * constInfo.headDim, - 0); - } else { - uint64_t attenOutRowStride = constInfo.qHeadNum * constInfo.headDim; - for (int32_t rowIdx = 0; rowIdx < inValidRowCount; ++rowIdx) { - matmul::InitOutput( - attentionOutGm[attenOutOffset + - static_cast(rowIdx) * attenOutRowStride], - constInfo.gSize * constInfo.headDim, - 0); - } - } - if (constInfo.returnSoftmaxLse) { - matmul::InitOutput( - softmaxLseGm[lseOffset], inValidRowCount * constInfo.gSize, 0); - } - } -} - -template -__aicore__ inline void SparseFlashMlaSwa::InitOutputSingleCore() { - uint32_t coreNum = GetBlockNum(); - if (coreNum != 0) { - uint64_t totalOutputSize = constInfo.batchSize * constInfo.qHeadNum * - constInfo.qSeqSize * constInfo.headDim; - uint64_t singleCoreSize = (totalOutputSize + (2 * coreNum) - 1) / - (2 * coreNum); // 2 means c:v = 1:2 - uint64_t tailSize = totalOutputSize - tmpBlockIdx * singleCoreSize; - uint64_t singleInitOutputSize = - tailSize < singleCoreSize ? tailSize : singleCoreSize; - if (singleInitOutputSize > 0) { - matmul::InitOutput(attentionOutGm[tmpBlockIdx * singleCoreSize], - singleInitOutputSize, - 0); - } - SyncAll(); - } -} - -template -__aicore__ inline int32_t SparseFlashMlaSwa::GetActualSeqLenQ( - uint32_t bIdx) { - if constexpr (LAYOUT_T == SMLA_LAYOUT::TND) { - int32_t actualSeqQPrefixSum = actualSeqLengthsQGm.GetValue(bIdx); - int32_t actualSeqQNextSum = actualSeqLengthsQGm.GetValue(bIdx + 1); - tempLoopInfo.actualSeqQPrefixSum = - static_cast(actualSeqQPrefixSum); - return actualSeqQNextSum - actualSeqQPrefixSum; - } else { - tempLoopInfo.actualSeqQPrefixSum = - static_cast(bIdx * constInfo.qSeqSize); - if (constInfo.actualLenDimsQ == 0) { - return static_cast(constInfo.qSeqSize); - } else { - return actualSeqLengthsQGm.GetValue(bIdx); - } - } -} - -template -__aicore__ inline int32_t SparseFlashMlaSwa::GetActualSeqLenKV( - uint32_t bIdx) { - if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { - tempLoopInfo.actualSeqKVPrefixSum = - static_cast(bIdx * constInfo.kvSeqSize); - if (constInfo.actualLenDimsKV == 0) { - return static_cast(constInfo.kvSeqSize); - } - return actualSeqLengthsKVGm.GetValue(bIdx); - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::BSND) { - tempLoopInfo.actualSeqKVPrefixSum = - static_cast(bIdx * constInfo.kvSeqSize); - if (constInfo.actualLenDimsKV != 0) { - return actualSeqLengthsKVGm.GetValue(bIdx); - } - return static_cast(constInfo.kvSeqSize); - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { - int32_t actualSeqKVPrefixSum = actualSeqLengthsKVGm.GetValue(bIdx); - int32_t actualSeqKVNextSum = actualSeqLengthsKVGm.GetValue(bIdx + 1); - tempLoopInfo.actualSeqKVPrefixSum = actualSeqKVPrefixSum; - return actualSeqKVNextSum - actualSeqKVPrefixSum; - } -} - -template -__aicore__ inline int32_t SparseFlashMlaSwa::GetActualSeqLenCmpKV( - uint32_t bIdx, - int32_t actualOriS2Size) { - (void)actualOriS2Size; - if constexpr (TEMPLATE_MODE != HCA_TEMPLATE) { - return 0; - } - if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::TND) { - int32_t actualSeqCmpKVPrefixSum = actualSeqLengthsCmpKVGm.GetValue(bIdx); - int32_t actualSeqCmpKVNextSum = actualSeqLengthsCmpKVGm.GetValue(bIdx + 1); - tempLoopInfo.actualSeqCmpKVPrefixSum = actualSeqCmpKVPrefixSum; - return actualSeqCmpKVNextSum - actualSeqCmpKVPrefixSum; - } else if constexpr (KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND) { - tempLoopInfo.actualSeqCmpKVPrefixSum = - static_cast(bIdx * constInfo.cmpSeqSize); - if (constInfo.actualLenDimsCmpKV != 0) { - return actualSeqLengthsCmpKVGm.GetValue(bIdx); - } - return static_cast(constInfo.cmpSeqSize); - } else { - tempLoopInfo.actualSeqCmpKVPrefixSum = - static_cast(bIdx * constInfo.cmpSeqSize); - if (constInfo.actualLenDimsCmpKV != 0) { - return actualSeqLengthsCmpKVGm.GetValue(bIdx); - } - return (constInfo.cmpSeqSize != 0) - ? static_cast(constInfo.cmpSeqSize) - : actualOriS2Size / static_cast(constInfo.cmpRatio); - } -} - -template -__aicore__ inline int32_t SparseFlashMlaSwa::GetCmpMaskS2Size( - uint32_t bIdx, - int32_t actualOriS2Size, - int32_t actualCmpS2Size) { - (void)actualOriS2Size; - if constexpr (TEMPLATE_MODE != HCA_TEMPLATE) { - return actualOriS2Size; - } - int32_t residual = 0; - if (constInfo.cmpResidualKVSize != 0) { - residual = cmpResidualKVGm.GetValue(bIdx); - } - return actualCmpS2Size * static_cast(constInfo.cmpRatio) + residual; -} - -template -__aicore__ inline uint32_t -SparseFlashMlaSwa::GetOriSparseActualSeqLen() { - if (constInfo.oriSparseIndexWidth == 0 || tempLoopInfo.actOriS2Size <= 0) { - return 0; - } - uint64_t qTokenOffset = - tempLoopInfo.actualSeqQPrefixSum + tempLoopInfo.s1StartIdx; - uint64_t topkLenOffset = - qTokenOffset * constInfo.kvHeadNum + tempLoopInfo.n2Idx; - if constexpr (IS_DSPARK) { - if (!constInfo.hasOriTopkLength) { - return 0; - } - int32_t topkLen = oriTopkLengthGm.GetValue(topkLenOffset); - if (topkLen <= 0) { - return 0; - } - return Min(static_cast(topkLen), constInfo.oriSparseIndexWidth); - } - return 0; -} - -template -__aicore__ inline void SparseFlashMlaSwa::GetSparseActualSeqLen() { - // 行无效通过ori部分判断, ori部分如果有行无效那么ori和cmp都有 - if (static_cast(tempLoopInfo.s1EndIdx) < - -(tempLoopInfo.actOriS2Size - tempLoopInfo.actS1Size)) { - tempLoopInfo.actOriS2Size = 0; - tempLoopInfo.actCmpS2Size = 0; - return; - } - - // 对于cmp部分还有top k, tempLoopInfo.actS2Size只针对cmp - if constexpr (TEMPLATE_MODE == HCA_TEMPLATE) { - int32_t thresHold = - (tempLoopInfo.cmpMaskRight + tempLoopInfo.s1EndIdx + 1) / - constInfo.cmpRatio; - tempLoopInfo.actCmpS2Size = - Min(tempLoopInfo.actCmpS2Size, Max(thresHold, 0)); - } -} - -template -__aicore__ inline void SparseFlashMlaSwa::UpdateInnerLoopCond() { - if ((tempLoopInfo.actCmpS2Size == 0 && tempLoopInfo.actOriS2Size == 0) || - (tempLoopInfo.actS1Size == 0)) { - tempLoopInfo.curActSeqLenIsZero = true; - return; - } - tempLoopInfo.curActSeqLenIsZero = false; - tempLoopInfo.mBasicSizeTail = - ((tempLoopInfo.s1EndIdx - tempLoopInfo.s1StartIdx + 1) * - constInfo.gSize) % - constInfo.mBaseSize; - tempLoopInfo.mBasicSizeTail = (tempLoopInfo.mBasicSizeTail == 0) - ? constInfo.mBaseSize - : tempLoopInfo.mBasicSizeTail; -} - -template -__aicore__ inline void SparseFlashMlaSwa::Init( - __gm__ uint8_t* query, - __gm__ uint8_t* oriKV, - __gm__ uint8_t* cmpKV, - __gm__ uint8_t* oriSparseIndices, - __gm__ uint8_t* cmpSparseIndices, - __gm__ uint8_t* oriBlockTable, - __gm__ uint8_t* cmpBlockTable, - __gm__ uint8_t* cuSeqlensQ, - __gm__ uint8_t* cuSeqlensKV, - __gm__ uint8_t* cuSeqlensCmpKV, - __gm__ uint8_t* seqUsedQ, - __gm__ uint8_t* seqUsedKV, - __gm__ uint8_t* seqUsedCmpKV, - __gm__ uint8_t* cmpResidualKV, - __gm__ uint8_t* oriTopkLength, - __gm__ uint8_t* cmpTopkLength, - __gm__ uint8_t* sinks, - __gm__ uint8_t* metadata, - __gm__ uint8_t* attentionOut, - __gm__ uint8_t* softmaxLse, - __gm__ uint8_t* workspace, - const SparseFlashMlaTilingData* __restrict tiling, - __gm__ uint8_t* gmTiling, - TPipe* tPipe) { - if ASCEND_IS_AIV { - tmpBlockIdx = GetBlockIdx(); // vec:0-47 - aiCoreIdx = tmpBlockIdx / 2; - } else { - tmpBlockIdx = GetBlockIdx(); // cube:0-23 - aiCoreIdx = tmpBlockIdx; - } - - // init tiling data - tilingData = tiling; - - InitTilingData(); - if constexpr (IS_DSPARK) { - constInfo.hasOriTopkLength = (oriTopkLength != nullptr); - if (constInfo.hasOriTopkLength) { - oriTopkLengthGm.SetGlobalBuffer((__gm__ int32_t*)oriTopkLength); - } - } - (void)cmpTopkLength; - if (KV_LAYOUT_T == SMLA_LAYOUT::TND && LAYOUT_T == SMLA_LAYOUT::TND) { - InitActualSeqLen(cuSeqlensQ, cuSeqlensKV, cuSeqlensCmpKV); - } else if (KV_LAYOUT_T == SMLA_LAYOUT::TND) { - InitActualSeqLen(seqUsedQ, cuSeqlensKV, cuSeqlensCmpKV); - } else if ((KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND || - KV_LAYOUT_T == SMLA_LAYOUT::BSND) && - LAYOUT_T == SMLA_LAYOUT::TND) { - InitActualSeqLen(cuSeqlensQ, seqUsedKV, seqUsedCmpKV); - } else if ((KV_LAYOUT_T == SMLA_LAYOUT::PA_BBND || - KV_LAYOUT_T == SMLA_LAYOUT::BSND)) { - InitActualSeqLen(seqUsedQ, seqUsedKV, seqUsedCmpKV); - } - metadataGm.SetGlobalBuffer((__gm__ uint32_t*)metadata); - InitCalcParamsEach(); - - pipe = tPipe; - // init global buffer - queryGm.SetGlobalBuffer((__gm__ Q_T*)query); - oriKvGm.SetGlobalBuffer((__gm__ KV_T*)oriKV); - if constexpr (TEMPLATE_MODE == HCA_TEMPLATE) { - cmpKvGm.SetGlobalBuffer((__gm__ KV_T*)cmpKV); - if (constInfo.cmpResidualKVSize != 0) { - cmpResidualKVGm.SetGlobalBuffer((__gm__ int32_t*)cmpResidualKV, - constInfo.cmpResidualKVSize); - } - } - - if (sinks != nullptr) { - sinksGm.SetGlobalBuffer((__gm__ SINKS_T*)sinks); - } - - attentionOutGm.SetGlobalBuffer((__gm__ OUT_T*)attentionOut); - softmaxLseGm.SetGlobalBuffer((__gm__ T*)softmaxLse); - - if ASCEND_IS_AIV { - if (LAYOUT_T != SMLA_LAYOUT::TND) { - if (constInfo.needInit) { - InitOutputSingleCore(); - } - } - } - - if constexpr (PAGE_ATTENTION) { - oriBlockTableGm.SetGlobalBuffer((__gm__ int32_t*)oriBlockTable); - if constexpr (IS_DSPARK) { - oriSparseIndicesGm.SetGlobalBuffer((__gm__ int32_t*)oriSparseIndices); - } - if constexpr (TEMPLATE_MODE == HCA_TEMPLATE) { - cmpBlockTableGm.SetGlobalBuffer((__gm__ int32_t*)cmpBlockTable); - } - } - - // workspace 内存排布 - // |Q--|mm1ResGm|vec1ResGm|mm2ResGm|vec2ResGm - // |Core0_Q1-Core0_Q2-Core1_Q1-Core1_Q2....Core32_Q1-Core32_Q2|Core0_mmRes - uint64_t offset = 0; - mm1ResGm.SetGlobalBuffer( - (__gm__ MM1_OUT_T*)(workspace + offset + - aiCoreIdx * dbWorkspaceRatio * constInfo.mmResUbSize * - sizeof(MM1_OUT_T))); - offset += GetBlockNum() * dbWorkspaceRatio * constInfo.mmResUbSize * - sizeof(MM1_OUT_T); - - vec1ResGm.SetGlobalBuffer( - (__gm__ Q_T*)(workspace + offset + - aiCoreIdx * dbWorkspaceRatio * constInfo.mmResUbSize * - sizeof(KV_T))); - offset += - GetBlockNum() * dbWorkspaceRatio * constInfo.mmResUbSize * sizeof(KV_T); - - mm2ResGm.SetGlobalBuffer((__gm__ MM2_OUT_T*)(workspace + offset + - aiCoreIdx * dbWorkspaceRatio * - constInfo.bmm2ResUbSize * - sizeof(MM2_OUT_T))); - offset += GetBlockNum() * dbWorkspaceRatio * constInfo.bmm2ResUbSize * - sizeof(MM2_OUT_T); - - vec2ResGm.SetGlobalBuffer( - (__gm__ T*)(workspace + offset + - aiCoreIdx * dbWorkspaceRatio * constInfo.bmm2ResUbSize * - sizeof(T))); - offset += - GetBlockNum() * dbWorkspaceRatio * constInfo.bmm2ResUbSize * sizeof(T); - - if constexpr (IS_DSPARK) { - kvMergeGm_.SetGlobalBuffer( - (__gm__ KV_T*)(workspace + offset + - aiCoreIdx * 512 * 512 * MERGE_CACHE_GM_BUF_NUM * - sizeof(KV_T))); - offset += static_cast(GetBlockNum()) * 512 * 512 * - MERGE_CACHE_GM_BUF_NUM * sizeof(KV_T); - } - - if ASCEND_IS_AIV { - vectorBlock.InitParams(constInfo, tilingData); - if constexpr (IS_DSPARK) { - vectorBlock.InitVec0GlobalTensor(kvMergeGm_, - oriKvGm, - oriBlockTableGm, - oriSparseIndicesGm, - oriTopkLengthGm); - } - vectorBlock.InitVec1GlobalTensor(mm1ResGm, - vec1ResGm, - actualSeqLengthsQGm, - actualSeqLengthsKVGm, - sinksGm, - softmaxLseGm); - vectorBlock.InitVec2GlobalTensor( - accumOutGm, vec2ResGm, mm2ResGm, attentionOutGm); - } - - if ASCEND_IS_AIC { - cubeBlock.InitParams(constInfo); - cubeBlock.InitMm1GlobalTensor(queryGm, oriKvGm, cmpKvGm, mm1ResGm); - cubeBlock.InitMm2GlobalTensor(vec1ResGm, mm2ResGm, attentionOutGm); - cubeBlock.InitPageAttentionInfo(oriKvGm, oriBlockTableGm, cmpBlockTableGm); - if constexpr (IS_DSPARK) { - cubeBlock.InitDsparkKvMerge(kvMergeGm_); - } - } - // 要在InitParams之后执行 - if (pipe != nullptr) { - InitBuffers(); - } -} - -template -__aicore__ inline void SparseFlashMlaSwa::InitCalcParamsEach() { - if (aiCoreIdx != 0) { - constInfo.bN2Start = metadataGm.GetValue( - GetAttrAbsIndex(aiCoreIdx, FA_BN2_START_INDEX, false)); - constInfo.gS1Start = metadataGm.GetValue( - GetAttrAbsIndex(aiCoreIdx, FA_M_START_INDEX, false)); - constInfo.s2Start = metadataGm.GetValue( - GetAttrAbsIndex(aiCoreIdx, FA_S2_START_INDEX, false)); - } - constInfo.bN2End = - metadataGm.GetValue(GetAttrAbsIndex(aiCoreIdx, FA_BN2_END_INDEX, false)); - constInfo.gS1End = - metadataGm.GetValue(GetAttrAbsIndex(aiCoreIdx, FA_M_END_INDEX, false)); - constInfo.s2End = - metadataGm.GetValue(GetAttrAbsIndex(aiCoreIdx, FA_S2_END_INDEX, false)); -} - -template -__aicore__ inline void SparseFlashMlaSwa::CalcParams(uint32_t loop, - uint32_t cmpLoop, - uint64_t s2Start, - uint32_t s2LoopIdx, - RunInfo& info) { - info.isValid = s2LoopIdx < tempLoopInfo.s2LoopTimes; - info.loop = loop; - info.cmpLoop = cmpLoop; - info.bIdx = tempLoopInfo.bIdx; - info.gS1Idx = tempLoopInfo.gS1Idx; - info.s1Idx = tempLoopInfo.gS1Idx / constInfo.gSize; - info.s2Idx = s2LoopIdx; - info.n2IdxReal = tempLoopInfo.n2Idx; - - info.curSInnerLoopTimes = tempLoopInfo.s2LoopTimes; - info.tndIsS2SplitCore = tempLoopInfo.tndIsS2SplitCore; - info.tndCoreStartKVSplitPos = tempLoopInfo.tndCoreStartKVSplitPos; - info.isBmm2Output = false; - info.actS1Size = tempLoopInfo.actS1Size; - info.oriDealSize = tempLoopInfo.oriMaskRight + tempLoopInfo.s1StartIdx - - tempLoopInfo.oriMaskLeft - tempLoopInfo.s1EndIdx; - info.cmpMaskRight = tempLoopInfo.cmpMaskRight; - - // M方向的尾块 - info.actMBaseSize = tempLoopInfo.mBasicSizeTail; - - if ASCEND_IS_AIV { - info.mSize = info.actMBaseSize; - info.mSizeV = (info.mSize <= 16) ? info.mSize - : ((CeilDiv(info.mSize, 16) + 1) / 2 * 16); - info.mSizeVStart = 0; - if (tmpBlockIdx % 2 == 1) { - info.mSizeVStart = info.mSizeV; - info.mSizeV = info.mSize - info.mSizeV; - } - } - - info.isFirstSInnerLoop = s2LoopIdx == s2Start; - if (info.isFirstSInnerLoop) { - tempLoopInfo.bn2IdxInCurCore++; - } - info.isLastS2Loop = (s2LoopIdx == (tempLoopInfo.s2LoopTimes - 1)); - info.bn2IdxInCurCore = tempLoopInfo.bn2IdxInCurCore - 1; - - uint64_t tndBIdxOffsetForQ = - tempLoopInfo.actualSeqQPrefixSum * constInfo.qHeadNum * constInfo.headDim; - uint64_t tndBIdxOffsetForKV = tempLoopInfo.actualSeqKVPrefixSum * - constInfo.kvHeadNum * constInfo.headDim; - uint64_t tndBIdxOffsetForCmpKV = tempLoopInfo.actualSeqCmpKVPrefixSum * - constInfo.kvHeadNum * constInfo.headDim; - - if (info.isFirstSInnerLoop) { - uint64_t s1HeadOffset = - (info.gS1Idx / constInfo.gSize) * constInfo.qHeadNum; - uint64_t qHeadOffset = - info.n2Idx * constInfo.gSize + info.gS1Idx % constInfo.gSize; - tensorACoreOffset = - tndBIdxOffsetForQ + (s1HeadOffset + qHeadOffset) * constInfo.headDim; - tensorBCoreOffset = tndBIdxOffsetForKV + info.n2Idx * constInfo.headDim; - tensorCmpBCoreOffset = - tndBIdxOffsetForCmpKV + info.n2Idx * constInfo.headDim; - } - info.tensorAOffset = tensorACoreOffset; - info.tensorBOffset = tensorBCoreOffset; - info.tensorCmpBOffset = tensorCmpBCoreOffset; - info.attenOutOffset = tensorACoreOffset; - if constexpr (IS_DSPARK) { - if constexpr (LAYOUT_T == SMLA_LAYOUT::TND) { - info.qTokenOffset = tempLoopInfo.actualSeqQPrefixSum + info.s1Idx; - } else { - info.qTokenOffset = info.bIdx * constInfo.qSeqSize + info.s1Idx; - } - } - - if constexpr (TEMPLATE_MODE == SWA_TEMPLATE) { - // SWA只有ori_kv - info.isOriOnly = true; - info.isOriCmpMix = false; - info.relativeS2Idx = 0; - uint64_t s2Offset = info.s2Idx * constInfo.s2BaseSize; - if (s2LoopIdx + 1 == tempLoopInfo.oriLoopTimes) { - info.actualSingleProcessSInnerOriSize = - (tempLoopInfo.oriMaskRight - tempLoopInfo.oriMaskLeft + 1) - s2Offset; - } else { - info.actualSingleProcessSInnerOriSize = constInfo.s2BaseSize; - } - info.actualSingleProcessSInnerSize = info.actualSingleProcessSInnerOriSize; - if constexpr (IS_DSPARK) { - info.s2StartPoint = 0; - } else { - info.s2StartPoint = tempLoopInfo.oriMaskLeft; - } - info.cmpS2IdLimit = 0; - } else { // HCA_TEMPLATE场景 - if (s2LoopIdx < tempLoopInfo.oriLoopTimes) { - // S2首次循环只能在ori_kv - info.isOriOnly = true; - info.isOriCmpMix = false; - info.relativeS2Idx = 0; - uint64_t s2Offset = info.s2Idx * constInfo.s2BaseSize; - if (s2LoopIdx + 1 == - tempLoopInfo - .oriLoopTimes) { // HCA场景可能处理oriLen / cmpRatio等于0的场景 - info.actualSingleProcessSInnerOriSize = - (tempLoopInfo.oriMaskRight - tempLoopInfo.oriMaskLeft + 1) - - s2Offset; - } else { - info.actualSingleProcessSInnerOriSize = constInfo.s2BaseSize; - } - info.actualSingleProcessSInnerSize = - info.actualSingleProcessSInnerOriSize; - info.s2StartPoint = tempLoopInfo.oriMaskLeft; - info.cmpS2IdLimit = 0; - } else if (s2LoopIdx - tempLoopInfo.oriLoopTimes < - tempLoopInfo.oriCmpMixLoopTimes) { - uint64_t s2Offset = info.s2Idx * constInfo.s2BaseSize; - info.isOriOnly = false; - info.isOriCmpMix = true; - info.relativeS2Idx = info.s2Idx - tempLoopInfo.oriLoopTimes; - info.actualSingleProcessSInnerOriSize = - (tempLoopInfo.oriMaskRight - tempLoopInfo.oriMaskLeft + 1) - s2Offset; - info.s2StartPoint = tempLoopInfo.oriMaskLeft + - tempLoopInfo.oriLoopTimes * constInfo.s2BaseSize; - info.actualSingleProcessSInnerCmpSize = tempLoopInfo.cmpMixSize; - info.cmpS2IdLimit = tempLoopInfo.cmpMixSize; - info.actualSingleProcessSInnerSize = - info.actualSingleProcessSInnerOriSize + - info.actualSingleProcessSInnerCmpSize; - } else { - info.isOriOnly = false; - info.isOriCmpMix = false; - info.relativeS2Idx = info.s2Idx - tempLoopInfo.oriLoopTimes - - tempLoopInfo.oriCmpMixLoopTimes; - uint64_t s2Offset = - info.relativeS2Idx * constInfo.s2BaseSize + tempLoopInfo.cmpMixSize; - if (s2LoopIdx + 1 == tempLoopInfo.s2LoopTimes) { - info.actualSingleProcessSInnerSize = - tempLoopInfo.actCmpS2Size - s2Offset; - } else { - info.actualSingleProcessSInnerSize = constInfo.s2BaseSize; - } - info.s2StartPoint = tempLoopInfo.cmpMixSize; - info.cmpS2IdLimit = - (tempLoopInfo.cmpMaskRight + tempLoopInfo.s1EndIdx + 1) / - constInfo.cmpRatio; - } - } - - info.inValidRowCount = tempLoopInfo.actS1Size - tempLoopInfo.actOriS2Size - - tempLoopInfo.s1StartIdx; - info.actualSingleProcessSInnerSizeAlign = SMLAAlign( - info.actualSingleProcessSInnerSize, SMLAVectorBlock::BYTE_BLOCK); - info.actualSingleProcessSInnerOriAlignSize = - SMLAAlign(info.actualSingleProcessSInnerOriSize, - SMLAVectorBlock::BYTE_BLOCK); - info.actualSingleProcessSInnerCmpAlignSize = - SMLAAlign(info.actualSingleProcessSInnerCmpSize, - SMLAVectorBlock::BYTE_BLOCK); - if constexpr (IS_DSPARK) { - if (info.isValid) { - info.v0S2Start = 0; - info.v0S2DealSize = - static_cast(info.actualSingleProcessSInnerOriSize); - } - } -} - -template -__aicore__ inline void SparseFlashMlaSwa::ComputeMm1( - const RunInfo& info) { - uint32_t nBufferLoopTimes = - CeilDiv(info.actMBaseSize, constInfo.nBufferMBaseSize); - uint32_t nBufferTail = - info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; - for (uint32_t i = 0; i < nBufferLoopTimes; i++) { - MSplitInfo mSplitInfo; - mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; - mSplitInfo.nBufferDealM = - (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; - cubeBlock.ComputeMm1(info, mSplitInfo); - CrossCoreSetFlag(constInfo.syncC1V1); - } -} - -template -__aicore__ inline void SparseFlashMlaSwa::ComputeMm2( - const RunInfo& info) { - uint32_t nBufferLoopTimes = - (info.actMBaseSize + constInfo.nBufferMBaseSize - 1) / - constInfo.nBufferMBaseSize; - uint32_t nBufferTail = - info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; - for (uint32_t i = 0; i < nBufferLoopTimes; i++) { - MSplitInfo mSplitInfo; - mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; - mSplitInfo.nBufferDealM = - (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; - CrossCoreWaitFlag(constInfo.syncV1C2); - cubeBlock.ComputeMm2(info, mSplitInfo); - CrossCoreSetFlag(constInfo.syncC2V2); - } -} - -template -__aicore__ inline void SparseFlashMlaSwa::Process() { - uint32_t hasLoad = metadataGm.GetValue( - GetAttrAbsIndex(aiCoreIdx, FA_CORE_ENABLE_INDEX, false)); - if (hasLoad == 0) { - return; - } - if ASCEND_IS_AIV { - vectorBlock.AllocEventID(); - vectorBlock.InitSoftmaxDefaultBuffer(); - } else { - cubeBlock.AllocEventID(); - } - ProcessBalance(); - if ASCEND_IS_AIV { - vectorBlock.FreeEventID(); - } else { - cubeBlock.FreeEventID(); - } -} - -template -__aicore__ inline void SparseFlashMlaSwa::GetBN2Idx(uint32_t bN2Idx, - uint32_t& bIdx, - uint32_t& n2Idx) { - bIdx = bN2Idx / constInfo.kvHeadNum; - n2Idx = bN2Idx % constInfo.kvHeadNum; -} - -template -__aicore__ inline void SparseFlashMlaSwa::ProcessBalance() { - RunInfo extraInfo[SMLA_PRELOAD_TASK_CACHE_SIZE]; - uint32_t gloop = 0; - uint32_t cmpLoop = 0; - uint32_t gS1LoopEnd = 0; - bool globalLoopStart = true; - // 适配左闭右开 - if (constInfo.bN2Start == constInfo.bN2End) { - if (constInfo.gS1Start != constInfo.gS1End || - constInfo.s2Start != constInfo.s2End) { - constInfo.bN2End += 1; - } - } else if ((constInfo.gS1End != 0) || (constInfo.s2End != 0)) { - constInfo.bN2End += 1; - } - for (uint32_t bN2LoopIdx = constInfo.bN2Start; bN2LoopIdx < constInfo.bN2End; - bN2LoopIdx++) { - GetBN2Idx(bN2LoopIdx, tempLoopInfo.bIdx, tempLoopInfo.n2Idx); - tempLoopInfo.actS1Size = - GetActualSeqLenQ(tempLoopInfo.bIdx); // 获取actualSeqLength - tempLoopInfo.actOriS2Size = - GetActualSeqLenKV(tempLoopInfo.bIdx); // 获取actualSeqLengthKV - // 判断是否存在行无效场景,直接全部刷零(DSpark 走 sparse topk,不做 dense - // 行无效清零) - int32_t inValidRowCount = 0; - int32_t inValidRowS1StartIdx = 0; - if constexpr (!IS_DSPARK) { - if (inValidRowS1StartIdx < - (tempLoopInfo.actS1Size - tempLoopInfo.actOriS2Size)) { - inValidRowCount = tempLoopInfo.actS1Size - tempLoopInfo.actOriS2Size; - tempLoopInfo.hasInvalidRow = true; - if ASCEND_IS_AIV { - InitAllZeroOutput(tempLoopInfo.bIdx, - inValidRowS1StartIdx, - inValidRowCount, - tempLoopInfo.n2Idx); - } - } - } - bool isS1S2ZeroAndLastBatch = - (tempLoopInfo.actS1Size == 0 || tempLoopInfo.actOriS2Size == 0) && - ((constInfo.outputLayout == SMLA_LAYOUT::BSND) || - (bN2LoopIdx + 1 == constInfo.bN2End)); - uint32_t gS1SplitNum = - CeilDiv((tempLoopInfo.actS1Size - inValidRowCount) * constInfo.gSize, - constInfo.mBaseSize); // gS1轴上有效基本块数量 - - // 当处于最后一个BN2时, 且gS1End为0时, 说明当前BN2里的所有数据都在当前核处理 - gS1LoopEnd = (bN2LoopIdx == constInfo.bN2End - 1 && constInfo.gS1End != 0) - ? constInfo.gS1End - : gS1SplitNum; - // 当处于最后一个BN2且当前S1为0时,需要进入循环计算preload导致的未完成的部分 - gS1LoopEnd = isS1S2ZeroAndLastBatch ? gS1LoopEnd + 1 : gS1LoopEnd; - for (uint32_t gS1LoopIdx = constInfo.gS1Start; gS1LoopIdx < gS1LoopEnd; - gS1LoopIdx++) { - tempLoopInfo.actOriS2Size = GetActualSeqLenKV(tempLoopInfo.bIdx); - if constexpr (TEMPLATE_MODE == HCA_TEMPLATE) { - tempLoopInfo.actCmpS2Size = - GetActualSeqLenCmpKV(tempLoopInfo.bIdx, tempLoopInfo.actOriS2Size); - } - // 对于各轴上的真实的idx, 采用左闭右闭的方案 - // 跳过行无效部分,从有效行开始后续计算 - tempLoopInfo.gS1Idx = - inValidRowCount * constInfo.gSize + gS1LoopIdx * constInfo.mBaseSize; - tempLoopInfo.s1StartIdx = tempLoopInfo.gS1Idx / constInfo.gSize; - tempLoopInfo.s1EndIdx = Min( - (tempLoopInfo.s1StartIdx + constInfo.mBaseSize / constInfo.gSize - 1), - tempLoopInfo.actS1Size - 1); - // 此处均为闭区间 - // oriMaskMode 0 (DSpark): effective ori S2 from sparse topk_length, not - // band window. - if constexpr (IS_DSPARK) { - uint32_t sparseOriS2Size = GetOriSparseActualSeqLen(); - tempLoopInfo.oriMaskLeft = 0; - tempLoopInfo.oriMaskRight = - sparseOriS2Size == 0 ? -1 - : static_cast(sparseOriS2Size - 1U); - } else { - // oriMaskMode 4 (Band): sliding window on dense ori_kv. - tempLoopInfo.oriMaskRight = - tempLoopInfo.actOriS2Size - tempLoopInfo.actS1Size + - static_cast(tempLoopInfo.s1EndIdx) + constInfo.oriWinRight; - tempLoopInfo.oriMaskRight = - Min(tempLoopInfo.oriMaskRight, tempLoopInfo.actOriS2Size - 1); - tempLoopInfo.oriMaskLeft = - Max(tempLoopInfo.actOriS2Size - tempLoopInfo.actS1Size + - static_cast(tempLoopInfo.s1StartIdx) - - constInfo.oriWinLeft, - 0); - } - if constexpr (TEMPLATE_MODE == HCA_TEMPLATE) { - int32_t cmpMaskS2Size = GetCmpMaskS2Size(tempLoopInfo.bIdx, - tempLoopInfo.actOriS2Size, - tempLoopInfo.actCmpS2Size); - tempLoopInfo.cmpMaskRight = cmpMaskS2Size - tempLoopInfo.actS1Size; - } - GetSparseActualSeqLen(); - UpdateInnerLoopCond(); - bool isEnd = (bN2LoopIdx + 1 == constInfo.bN2End) && - (gS1LoopIdx + 1 == gS1LoopEnd); - if (tempLoopInfo.curActSeqLenIsZero && !isEnd) { - continue; - } - if constexpr (TEMPLATE_MODE == SWA_TEMPLATE) { - uint32_t oriS2Size = - (tempLoopInfo.oriMaskRight >= tempLoopInfo.oriMaskLeft) - ? static_cast(tempLoopInfo.oriMaskRight - - tempLoopInfo.oriMaskLeft + 1) - : 0U; - tempLoopInfo.oriLoopTimes = CeilDiv(oriS2Size, constInfo.s2BaseSize); - tempLoopInfo.oriCmpMixLoopTimes = 0; - tempLoopInfo.cmpLoopTimes = 0; - tempLoopInfo.s2LoopTimes = tempLoopInfo.oriLoopTimes; - } else { // HCA_TEMPLATE - uint32_t oriLen = - tempLoopInfo.oriMaskRight - tempLoopInfo.oriMaskLeft + 1; - if (tempLoopInfo.actCmpS2Size == 0) { // ori/cmp_ratio长度等于0的场景 - tempLoopInfo.oriLoopTimes = - (oriLen + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize; - tempLoopInfo.oriCmpMixLoopTimes = 0; - tempLoopInfo.cmpLoopTimes = 0; - } else { - tempLoopInfo.oriLoopTimes = oriLen / constInfo.s2BaseSize; - tempLoopInfo.oriCmpMixLoopTimes = - (oriLen % constInfo.s2BaseSize == 0) ? 0 : 1; - if (tempLoopInfo.oriCmpMixLoopTimes == 0) { - tempLoopInfo.cmpMixSize = 0; - } else { - uint32_t cmpLeftSize = - constInfo.s2BaseSize - - (oriLen - tempLoopInfo.oriLoopTimes * constInfo.s2BaseSize); - tempLoopInfo.cmpMixSize = (cmpLeftSize < tempLoopInfo.actCmpS2Size) - ? cmpLeftSize - : tempLoopInfo.actCmpS2Size; - } - tempLoopInfo.cmpLoopTimes = - CeilDiv(tempLoopInfo.actCmpS2Size - tempLoopInfo.cmpMixSize, - constInfo.s2BaseSize); - } - tempLoopInfo.s2LoopTimes = tempLoopInfo.oriLoopTimes + - tempLoopInfo.oriCmpMixLoopTimes + - tempLoopInfo.cmpLoopTimes; - } - - tempLoopInfo.tndIsS2SplitCore = false; // 当前不支持核间切S2 - tempLoopInfo.tndCoreStartKVSplitPos = 0; - uint32_t extraLoop = isEnd ? PRELOAD_NUM : 0; - - for (uint32_t s2LoopIdx = constInfo.s2Start; - s2LoopIdx < (tempLoopInfo.s2LoopTimes + extraLoop); - s2LoopIdx++) { - PreloadPipeline( - gloop, cmpLoop, constInfo.s2Start, s2LoopIdx, extraInfo); - ++gloop; - if constexpr (IS_DSPARK) { - if (s2LoopIdx < tempLoopInfo.s2LoopTimes) { - ++cmpLoop; - } - } - } - globalLoopStart = false; - constInfo.s2Start = 0; - } - constInfo.gS1Start = 0; - tempLoopInfo.hasInvalidRow = false; - } -} - -template -__aicore__ inline void SparseFlashMlaSwa::PreloadPipeline( - uint32_t loop, - uint32_t cmpLoop, - uint64_t s2Start, - uint64_t s2LoopIdx, - RunInfo extraInfo[SMLA_PRELOAD_TASK_CACHE_SIZE]) { - RunInfo& extraInfo0 = - extraInfo[loop % SMLA_PRELOAD_TASK_CACHE_SIZE]; // 本轮任务 - RunInfo& extraInfo2 = - extraInfo[(loop + 2) % SMLA_PRELOAD_TASK_CACHE_SIZE]; // 上一轮任务 - RunInfo& extraInfo1 = - extraInfo[(loop + 1) % SMLA_PRELOAD_TASK_CACHE_SIZE]; // 上两轮任务 - - CalcParams(loop, cmpLoop, s2Start, s2LoopIdx, extraInfo0); - if (extraInfo0.isValid) { - if constexpr (IS_DSPARK) { - if ASCEND_IS_AIV { - vectorBlock.ProcessVec0L(extraInfo0); - CrossCoreSetFlag( - constInfo.syncV0C1); - } - } else { - if ASCEND_IS_AIC { - ComputeMm1(extraInfo0); - } - } - } - if (extraInfo2.isValid) { - if ASCEND_IS_AIV { - vectorBlock.ProcessVec1L(extraInfo2); - } - if ASCEND_IS_AIC { - ComputeMm2(extraInfo2); - } - } - if (extraInfo1.isValid) { - if ASCEND_IS_AIV { - vectorBlock.ProcessVec2L(extraInfo1); - } - extraInfo1.isValid = false; - } - if constexpr (IS_DSPARK) { - if (extraInfo0.isValid) { - if ASCEND_IS_AIC { - CrossCoreWaitFlag( - constInfo.syncV0C1); - ComputeMm1(extraInfo0); - } - } - } -} -} // namespace SMLAKernel -#endif // SPARSE_FLASH_MLA_SWA_KERNEL_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch35/common/smla_metadata_common.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch35/common/smla_metadata_common.h deleted file mode 100644 index c982ad9c33..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/arch35/common/smla_metadata_common.h +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file smla_metadata_common.h - * \brief sparse_flash_mla / mixed_quant_sparse_flash_mla / - * quant_sparse_flash_mla 三个算子共用的 metadata 常量与 GetAttrAbsIndex 定义。 - */ - -#ifndef SMLA_METADATA_COMMON_H -#define SMLA_METADATA_COMMON_H - -#include - -namespace optiling { - -// Constants -constexpr uint32_t AIC_CORE_MAX_NUM = 80; -constexpr uint32_t AIV_CORE_MAX_NUM = 80; - -constexpr uint32_t FA_METADATA_SIZE = 9; -constexpr uint32_t FD_METADATA_SIZE = 8; - -// FA Metadata Index Definitions -constexpr uint32_t FA_CORE_ENABLE_INDEX = 0; -constexpr uint32_t FA_BN2_START_INDEX = 1; -constexpr uint32_t FA_M_START_INDEX = 2; -constexpr uint32_t FA_S2_START_INDEX = 3; -constexpr uint32_t FA_BN2_END_INDEX = 4; -constexpr uint32_t FA_M_END_INDEX = 5; -constexpr uint32_t FA_S2_END_INDEX = 6; -constexpr uint32_t FA_FIRST_FD_DATA_WORKSPACE_IDX_INDEX = 7; -constexpr uint32_t FA_S2_MAX_NUM = 8; - -// FD Metadata Index Definitions -constexpr uint32_t FD_CORE_ENABLE_INDEX = 0; -constexpr uint32_t FD_BN2_IDX_INDEX = 1; -constexpr uint32_t FD_M_IDX_INDEX = 2; -constexpr uint32_t FD_WORKSPACE_IDX_INDEX = 3; -constexpr uint32_t FD_WORKSPACE_NUM_INDEX = 4; -constexpr uint32_t FD_M_START_INDEX = 5; -constexpr uint32_t FD_M_NUM_INDEX = 6; - -/** - * @brief 获取属性的绝对索引 - * @param coreIdx 核索引 - * @param metaIdx 元数据索引 - * @param isAIV 是否为AIV数据,默认为false - * @return 返回属性的绝对索引 - */ -#ifdef __CCE_AICORE__ -__aicore__ inline uint32_t GetAttrAbsIndex(uint32_t coreIdx, - uint32_t metaIdx, - bool isAIV = false) { - if (isAIV) { - return FA_METADATA_SIZE * AIC_CORE_MAX_NUM + FD_METADATA_SIZE * coreIdx + - metaIdx; - } else { - return FA_METADATA_SIZE * coreIdx + metaIdx; - } -} -#endif - -} // namespace optiling - -#endif // SMLA_METADATA_COMMON_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/sparse_flash_mla_kernel_metadata.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/sparse_flash_mla_kernel_metadata.h deleted file mode 100644 index 70d26804a6..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/sparse_flash_mla_kernel_metadata.h +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file sparse_flash_mla_kernel_metadata.h - * \brief - */ - -#ifndef SPARSE_FLASH_MLA_KERNEL_METADATA_H -#define SPARSE_FLASH_MLA_KERNEL_METADATA_H - -#include - -#include "arch35/common/smla_metadata_common.h" - -namespace optiling { - -constexpr uint32_t SMLA_METADATA_TOTAL_SIZE = 2048; - -using SMLA_METADATA_T = int32_t; - -namespace detail { -struct SmlaMetadata { - uint32_t faMetadata[AIC_CORE_MAX_NUM][FA_METADATA_SIZE]; - uint32_t fdMetadata[AIV_CORE_MAX_NUM][FD_METADATA_SIZE]; -}; -}; // namespace detail - -static_assert(SMLA_METADATA_TOTAL_SIZE * sizeof(SMLA_METADATA_T) >= - sizeof(detail::SmlaMetadata)); -}; // namespace optiling - -#endif // SPARSE_FLASH_MLA_KERNEL_METADATA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/sparse_flash_mla_template_tiling_key.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/sparse_flash_mla_template_tiling_key.h deleted file mode 100644 index 63e5ba6e40..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/sparse_flash_mla_template_tiling_key.h +++ /dev/null @@ -1,140 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under -the terms and conditions of  * CANN Open Software License Agreement Version 2.0 -(the "License").  * Please refer to the License for details. You may not use -this file except in compliance with the License.  * THIS SOFTWARE IS PROVIDED ON -AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,  * -INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A -PARTICULAR PURPOSE.  * See LICENSE in the root of the software repository for -the full text of the License.  */ - -/*! - * \file sparse_flash_mla_template_tiling_key.h - * \brief - */ - -#ifndef SPARSE_ATTN_SHARED_TEMPLATE_TILING_KEY_H -#define SPARSE_ATTN_SHARED_TEMPLATE_TILING_KEY_H - -#include "ascendc/host_api/tiling/template_argument.h" - -#define SMLA_LAYOUT_BSND 0 -#define SMLA_LAYOUT_TND 1 -#define SMLA_LAYOUT_PA_BBND 2 - -#define ASCENDC_TPL_4_BW 4 - -#define SWA_TEMPLATE 0 -#define HCA_TEMPLATE 1 -#define CSA_TEMPLATE 2 -#define ORI_SPARSE_TEMPLATE 3 -#define ORI_CMP_SPARSE_TEMPLATE 4 - -#define TOPK_INDEX 1 -#define TOPK_OFFSET 2 - -// Keep the key layout identical across architectures; A2/A3 only builds index -// mode kernels. -#if defined(__CCE_AICORE__) && (__CCE_AICORE__ != 310) -#define SMLA_TOPK_VALUE_MODE_SEL \ - ASCENDC_TPL_UINT_SEL(TOPK_VALUE_MODE, ASCENDC_TPL_UI_LIST, TOPK_INDEX) -#else -#define SMLA_TOPK_VALUE_MODE_SEL \ - ASCENDC_TPL_UINT_SEL( \ - TOPK_VALUE_MODE, ASCENDC_TPL_UI_LIST, TOPK_INDEX, TOPK_OFFSET) -#endif - -// 模板参数支持的范围定义 -ASCENDC_TPL_ARGS_DECL(XllmKernelSparseFlashMla, // 算子OpType - ASCENDC_TPL_BOOL_DECL(FLASH_DECODE, 0, 1), - ASCENDC_TPL_UINT_DECL(LAYOUT_T, - ASCENDC_TPL_4_BW, - ASCENDC_TPL_UI_LIST, - SMLA_LAYOUT_BSND, - SMLA_LAYOUT_TND), - ASCENDC_TPL_UINT_DECL(KV_LAYOUT_T, - ASCENDC_TPL_4_BW, - ASCENDC_TPL_UI_LIST, - SMLA_LAYOUT_BSND, - SMLA_LAYOUT_TND, - SMLA_LAYOUT_PA_BBND), - ASCENDC_TPL_UINT_DECL(TEMPLATE_MODE, - ASCENDC_TPL_4_BW, - ASCENDC_TPL_UI_LIST, - SWA_TEMPLATE, - HCA_TEMPLATE, - CSA_TEMPLATE, - ORI_SPARSE_TEMPLATE, - ORI_CMP_SPARSE_TEMPLATE), - ASCENDC_TPL_BOOL_DECL(SPLIT_G, 0, 1), - ASCENDC_TPL_BOOL_DECL(HEAD_RATIO_ONE, 0, 1), - ASCENDC_TPL_BOOL_DECL(BATCH_CONSISTENCY, 0, 1), - ASCENDC_TPL_BOOL_DECL(IS_VEC_S2PHYADDR, 0, 1), - ASCENDC_TPL_UINT_DECL(TOPK_VALUE_MODE, - ASCENDC_TPL_4_BW, - ASCENDC_TPL_UI_LIST, - TOPK_INDEX, - TOPK_OFFSET), - ASCENDC_TPL_BOOL_DECL(IS_DSPARK, 0, 1)); - -// 支持的模板参数组合 -// 用于调用GET_TPL_TILING_KEY获取TilingKey时,接口内部校验TilingKey是否合法 -ASCENDC_TPL_SEL( - ASCENDC_TPL_ARGS_SEL( - ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), - ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SMLA_LAYOUT_BSND), - ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - SMLA_LAYOUT_BSND, - SMLA_LAYOUT_PA_BBND), - ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, - ASCENDC_TPL_UI_LIST, - SWA_TEMPLATE, - HCA_TEMPLATE, - CSA_TEMPLATE, - ORI_SPARSE_TEMPLATE, - ORI_CMP_SPARSE_TEMPLATE), - ASCENDC_TPL_BOOL_SEL(SPLIT_G, 0, 1), - ASCENDC_TPL_BOOL_SEL(HEAD_RATIO_ONE, 0, 1), - ASCENDC_TPL_BOOL_SEL(BATCH_CONSISTENCY, 0, 1), - ASCENDC_TPL_BOOL_SEL(IS_VEC_S2PHYADDR, 0, 1), - SMLA_TOPK_VALUE_MODE_SEL, - ASCENDC_TPL_BOOL_SEL(IS_DSPARK, 0)), - ASCENDC_TPL_ARGS_SEL( - ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), - ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SMLA_LAYOUT_TND), - ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - SMLA_LAYOUT_TND, - SMLA_LAYOUT_PA_BBND), - ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, - ASCENDC_TPL_UI_LIST, - SWA_TEMPLATE, - HCA_TEMPLATE, - CSA_TEMPLATE, - ORI_SPARSE_TEMPLATE, - ORI_CMP_SPARSE_TEMPLATE), - ASCENDC_TPL_BOOL_SEL(SPLIT_G, 0, 1), - ASCENDC_TPL_BOOL_SEL(HEAD_RATIO_ONE, 0, 1), - ASCENDC_TPL_BOOL_SEL(BATCH_CONSISTENCY, 0, 1), - ASCENDC_TPL_BOOL_SEL(IS_VEC_S2PHYADDR, 0, 1), - SMLA_TOPK_VALUE_MODE_SEL, - ASCENDC_TPL_BOOL_SEL(IS_DSPARK, 0)), - ASCENDC_TPL_ARGS_SEL( - ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), - ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SMLA_LAYOUT_TND), - ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, - ASCENDC_TPL_UI_LIST, - SMLA_LAYOUT_PA_BBND), - ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, SWA_TEMPLATE), - ASCENDC_TPL_BOOL_SEL(SPLIT_G, 0, 1), - ASCENDC_TPL_BOOL_SEL(HEAD_RATIO_ONE, 0, 1), - ASCENDC_TPL_BOOL_SEL(BATCH_CONSISTENCY, 0, 1), - ASCENDC_TPL_BOOL_SEL(IS_VEC_S2PHYADDR, 0, 1), - SMLA_TOPK_VALUE_MODE_SEL, - ASCENDC_TPL_BOOL_SEL(IS_DSPARK, 1))); - -#undef SMLA_TOPK_VALUE_MODE_SEL - -#endif // TEMPLATE_TILING_KEY diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/xllm_kernel_sparse_flash_mla.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/xllm_kernel_sparse_flash_mla.cpp deleted file mode 100644 index 056707e79c..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla/op_kernel/xllm_kernel_sparse_flash_mla.cpp +++ /dev/null @@ -1,155 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file sparse_flash_mla.cpp - * \brief - */ -#include "kernel_operator.h" -#include "lib/matmul_intf.h" -#include "sparse_flash_mla_template_tiling_key.h" - -// The block templates below use the template-mode constants from the tiling -// key. -#include "arch22/sparse_flash_mla_csa_kernel.h" -#include "arch22/sparse_flash_mla_swa_kernel.h" - -using namespace AscendC; -using namespace optiling::detail; -using namespace SMLAKernel; - -#define SMLA_OP_IMPL(templateClass, tilingdataClass, ...) \ - do { \ - templateClass> op; \ - GET_TILING_DATA_WITH_STRUCT(tilingdataClass, tiling_data_in, tiling); \ - const tilingdataClass* __restrict tiling_data = &tiling_data_in; \ - op.Init(query, \ - oriKV, \ - cmpKV, \ - oriSparseIndices, \ - cmpSparseIndices, \ - oriBlockTable, \ - cmpBlockTable, \ - cuSeqlensQ, \ - cuSeqlensOriKv, \ - cuSeqlensCmpKv, \ - seqUsedQ, \ - seqUsedOriKV, \ - seqUsedCmpKV, \ - cmpResidualKV, \ - oriTopkLength, \ - cmpTopkLength, \ - sinks, \ - metadata, \ - attentionOut, \ - softmaxLse, \ - user, \ - tiling_data, \ - tiling, \ - &tPipe); \ - op.Process(); \ - } while (0) - -template -__global__ __aicore__ void xllm_kernel_sparse_flash_mla( - __gm__ uint8_t* query, - __gm__ uint8_t* oriKV, - __gm__ uint8_t* cmpKV, - __gm__ uint8_t* oriSparseIndices, - __gm__ uint8_t* cmpSparseIndices, - __gm__ uint8_t* oriBlockTable, - __gm__ uint8_t* cmpBlockTable, - __gm__ uint8_t* cuSeqlensQ, - __gm__ uint8_t* cuSeqlensOriKv, - __gm__ uint8_t* cuSeqlensCmpKv, - __gm__ uint8_t* seqUsedQ, - __gm__ uint8_t* seqUsedOriKV, - __gm__ uint8_t* seqUsedCmpKV, - __gm__ uint8_t* cmpResidualKV, - __gm__ uint8_t* oriTopkLength, - __gm__ uint8_t* cmpTopkLength, - __gm__ uint8_t* sinks, - __gm__ uint8_t* metadata, - __gm__ uint8_t* attentionOut, - __gm__ uint8_t* softmaxLse, - __gm__ uint8_t* workspace, - __gm__ uint8_t* tiling) { - KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); - __gm__ uint8_t* user = GetUserWorkspace(workspace); - - TPipe tPipe; - if constexpr (ORIG_DTYPE_Q == DT_FLOAT16 && ORIG_DTYPE_ORI_KV == DT_FLOAT16 && - ORIG_DTYPE_ATTN_OUT == DT_FLOAT16) { - if constexpr (TEMPLATE_MODE == CSA_TEMPLATE) { - SMLA_OP_IMPL(SparseFlashMlaCsa, - SparseFlashMlaTilingData, - half, - half, - half, - FLASH_DECODE, - static_cast(LAYOUT_T), - static_cast(KV_LAYOUT_T), - TEMPLATE_MODE, - static_cast(HEAD_RATIO_ONE), - static_cast(IS_DSPARK)); - } else { - SMLA_OP_IMPL(SparseFlashMlaSwa, - SparseFlashMlaTilingData, - half, - half, - half, - FLASH_DECODE, - static_cast(LAYOUT_T), - static_cast(KV_LAYOUT_T), - TEMPLATE_MODE, - static_cast(HEAD_RATIO_ONE), - static_cast(IS_DSPARK)); - } - } - if constexpr (ORIG_DTYPE_Q == DT_BF16 && ORIG_DTYPE_ORI_KV == DT_BF16 && - ORIG_DTYPE_ATTN_OUT == DT_BF16) { - if constexpr (TEMPLATE_MODE == CSA_TEMPLATE) { - SMLA_OP_IMPL(SparseFlashMlaCsa, - SparseFlashMlaTilingData, - bfloat16_t, - bfloat16_t, - bfloat16_t, - FLASH_DECODE, - static_cast(LAYOUT_T), - static_cast(KV_LAYOUT_T), - TEMPLATE_MODE, - static_cast(HEAD_RATIO_ONE), - static_cast(IS_DSPARK)); - } else { - SMLA_OP_IMPL(SparseFlashMlaSwa, - SparseFlashMlaTilingData, - bfloat16_t, - bfloat16_t, - bfloat16_t, - FLASH_DECODE, - static_cast(LAYOUT_T), - static_cast(KV_LAYOUT_T), - TEMPLATE_MODE, - static_cast(HEAD_RATIO_ONE), - static_cast(IS_DSPARK)); - } - } -} diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/SOURCE.txt b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/SOURCE.txt deleted file mode 100644 index ff1e99e8ab..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/SOURCE.txt +++ /dev/null @@ -1,5 +0,0 @@ -Source: https://gitcode.com/cann/ops-transformer, commit 814116886e54f04053f8870a400dfd31c46bf53c -Directory: attention/sparse_flash_mla_metadata -License: CANN Open Software License Agreement Version 2.0 (see CANN_LICENSE.txt). -The xllm-kernel package builds the Ascend A3 implementation with a distinct -operator name. The metadata protocol and kernel inputs follow the upstream ABI. diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_graph/sparse_flash_mla_metadata_proto.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_graph/sparse_flash_mla_metadata_proto.cpp deleted file mode 100644 index 6fb0d3120e..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_graph/sparse_flash_mla_metadata_proto.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file sparse_flash_mla_metadata_proto.cpp - * \brief - */ -#include "graph/operator_reg.h" -#include "graph/types.h" - -namespace ge { - -REG_OP(XllmKernelSparseFlashMlaMetadata) - .OPTIONAL_INPUT(cu_seqlens_q, TensorType({DT_INT32})) - .OPTIONAL_INPUT(cu_seqlens_ori_kv, TensorType({DT_INT32})) - .OPTIONAL_INPUT(cu_seqlens_cmp_kv, TensorType({DT_INT32})) - .OPTIONAL_INPUT(seqused_q, TensorType({DT_INT32})) - .OPTIONAL_INPUT(seqused_ori_kv, TensorType({DT_INT32})) - .OPTIONAL_INPUT(seqused_cmp_kv, TensorType({DT_INT32})) - .OPTIONAL_INPUT(cmp_residual_kv, TensorType({DT_INT32})) - .OPTIONAL_INPUT(ori_topk_length, TensorType({DT_INT32})) - .OPTIONAL_INPUT(cmp_topk_length, TensorType({DT_INT32})) - .OUTPUT(metadata, TensorType({DT_INT32})) - .REQUIRED_ATTR(num_heads_q, Int) - .REQUIRED_ATTR(num_heads_kv, Int) - .REQUIRED_ATTR(head_dim, Int) - .ATTR(batch_size, Int, 0) - .ATTR(max_seqlen_q, Int, 0) - .ATTR(max_seqlen_ori_kv, Int, 0) - .ATTR(max_seqlen_cmp_kv, Int, 0) - .ATTR(ori_topk, Int, 0) - .ATTR(cmp_topk, Int, 0) - .ATTR(cmp_ratio, Int, -1) - .ATTR(ori_mask_mode, Int, 4) - .ATTR(cmp_mask_mode, Int, 3) - .ATTR(ori_win_left, Int, 127) - .ATTR(ori_win_right, Int, 0) - .ATTR(layout_q, String, "BSND") - .ATTR(layout_kv, String, "PA_BBND") - .ATTR(has_ori_kv, Bool, true) - .ATTR(has_cmp_kv, Bool, true) - .REQUIRED_ATTR(soc_version, String) - .REQUIRED_ATTR(aic_core_num, Int) - .REQUIRED_ATTR(aiv_core_num, Int) - .REQUIRED_ATTR(is_batch_consistency, Bool) - .OP_END_FACTORY_REG(XllmKernelSparseFlashMlaMetadata) - -} // namespace ge diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/aclnn_sparse_flash_mla_metadata.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/aclnn_sparse_flash_mla_metadata.cpp deleted file mode 100644 index 816540c415..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/aclnn_sparse_flash_mla_metadata.cpp +++ /dev/null @@ -1,319 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file aclnn_sparse_flash_mla_metadata.cpp - * \brief - */ - -#include "aclnn_sparse_flash_mla_metadata.h" - -#include - -#include "acl/acl_rt.h" -#include "aclnn/aclnn_base.h" -#include "aclnn_kernels/common/op_error_check.h" -#include "aclnn_kernels/contiguous.h" -#include "aclnn_kernels/reshape.h" -#include "opdev/common_types.h" -#include "opdev/data_type_utils.h" -#include "opdev/format_utils.h" -#include "opdev/make_op_executor.h" -#include "opdev/op_dfx.h" -#include "opdev/op_executor.h" -#include "opdev/op_log.h" -#include "opdev/tensor_view_utils.h" -#include "sparse_flash_mla/op_host/common/log.h" -#include "sparse_flash_mla_metadata.h" -#include "sparse_flash_mla_metadata/op_host/sparse_flash_mla_metadata_check.h" - -constexpr int64_t BATCH_CONSISTENCY_LEVEL = 3; - -#ifdef __cplusplus -extern "C" { -#endif - -aclnnStatus aclnnXllmKernelSparseFlashMlaMetadataGetWorkspaceSize( - const aclTensor* cuSeqlensQOptional, - const aclTensor* cuSeqlensOriKvOptional, - const aclTensor* cuSeqlensCmpKvOptional, - const aclTensor* sequsedQOptional, - const aclTensor* sequsedOriKvOptional, - const aclTensor* sequsedCmpKvOptional, - const aclTensor* cmpResidualKvOptional, - const aclTensor* oriTopkLengthOptional, - const aclTensor* cmpTopkLengthOptional, - int64_t numHeadsQ, - int64_t numHeadsKv, - int64_t headDim, - int64_t batchSize, - int64_t maxSeqlenQ, - int64_t maxSeqlenOriKv, - int64_t maxSeqlenCmpKv, - int64_t oriTopk, - int64_t cmpTopk, - int64_t cmpRatio, - int64_t oriMaskMode, - int64_t cmpMaskMode, - int64_t oriWinLeft, - int64_t oriWinRight, - const char* layoutQOptional, - const char* layoutKvOptional, - bool hasOriKv, - bool hasCmpKv, - const aclTensor* metaData, - uint64_t* workspaceSize, - aclOpExecutor** executor) { - if (workspaceSize == nullptr) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - "XllmKernelSparseFlashMlaMetadata", "workspaceSize", "Null input"); - return ACLNN_ERR_INNER_NULLPTR; - } - if (executor == nullptr) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - "XllmKernelSparseFlashMlaMetadata", "executor", "Null input"); - return ACLNN_ERR_INNER_NULLPTR; - } - L2_DFX_PHASE_1(aclnnXllmKernelSparseFlashMlaMetadata, - DFX_IN(cuSeqlensQOptional, - cuSeqlensOriKvOptional, - cuSeqlensCmpKvOptional, - sequsedQOptional, - sequsedOriKvOptional, - sequsedCmpKvOptional, - cmpResidualKvOptional, - oriTopkLengthOptional, - cmpTopkLengthOptional, - numHeadsQ, - numHeadsKv, - headDim, - batchSize, - maxSeqlenQ, - maxSeqlenOriKv, - maxSeqlenCmpKv, - oriTopk, - cmpTopk, - cmpRatio, - oriMaskMode, - cmpMaskMode, - oriWinLeft, - oriWinRight, - layoutQOptional, - layoutKvOptional, - hasOriKv, - hasCmpKv), - DFX_OUT(metaData)); - - auto uniqueExecutor = CREATE_EXECUTOR(); - CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); - - const op::PlatformInfo& npuInfo = op::GetCurrentPlatformInfo(); - uint32_t aicCoreNum = 0; - uint32_t aivCoreNum = 0; - if (aclrtGetResInCurrentThread(ACL_RT_DEV_RES_CUBE_CORE, &aicCoreNum) != - ACL_SUCCESS) { - aicCoreNum = npuInfo.GetCubeCoreNum(); - } - if (aclrtGetResInCurrentThread(ACL_RT_DEV_RES_VECTOR_CORE, &aivCoreNum) != - ACL_SUCCESS) { - aivCoreNum = npuInfo.GetVectorCoreNum(); - } - std::string socVersionStr = npuInfo.GetSocLongVersion(); - const char* socVersion = socVersionStr.c_str(); - - int64_t batchConsistencyLevel = 0; - aclError aclRet = - aclrtGetSysParamOpt(ACL_OPT_DETERMINISTIC, &batchConsistencyLevel); - if (aclRet != ACL_SUCCESS) { - OP_LOGW( - "aclnnXllmKernelSparseFlashMlaMetadata unable to get system param " - "batch consistency level."); - } - OP_LOGD("deterministic_level=%lld", batchConsistencyLevel); - bool isBatchConsistency = (batchConsistencyLevel == BATCH_CONSISTENCY_LEVEL); - auto ret = ParamsCheck(cuSeqlensQOptional, - cuSeqlensOriKvOptional, - cuSeqlensCmpKvOptional, - sequsedQOptional, - sequsedOriKvOptional, - sequsedCmpKvOptional, - cmpResidualKvOptional, - oriTopkLengthOptional, - cmpTopkLengthOptional, - numHeadsQ, - numHeadsKv, - headDim, - batchSize, - maxSeqlenQ, - maxSeqlenOriKv, - maxSeqlenCmpKv, - oriTopk, - cmpTopk, - cmpRatio, - oriMaskMode, - cmpMaskMode, - oriWinLeft, - oriWinRight, - layoutQOptional, - layoutKvOptional, - hasOriKv, - hasCmpKv, - aicCoreNum, - aivCoreNum, - socVersion, - metaData); - CHECK_RET(ret == ACLNN_SUCCESS, ret); - - const aclTensor* cuSeqlensQOptionalContiguous = nullptr; - if (cuSeqlensQOptional != nullptr) { - cuSeqlensQOptionalContiguous = - l0op::Contiguous(cuSeqlensQOptional, uniqueExecutor.get()); - if (cuSeqlensQOptionalContiguous == nullptr) { - OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, - "cu_seqlens_q contiguous is null"); - return ACLNN_ERR_INNER_NULLPTR; - } - } - const aclTensor* cuSeqlensOriKvOptionalContiguous = nullptr; - if (cuSeqlensOriKvOptional != nullptr) { - cuSeqlensOriKvOptionalContiguous = - l0op::Contiguous(cuSeqlensOriKvOptional, uniqueExecutor.get()); - if (cuSeqlensOriKvOptionalContiguous == nullptr) { - OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, - "cu_seqlens_ori_kv contiguous is null"); - return ACLNN_ERR_INNER_NULLPTR; - } - } - const aclTensor* cuSeqlensCmpKvOptionalContiguous = nullptr; - if (cuSeqlensCmpKvOptional != nullptr) { - cuSeqlensCmpKvOptionalContiguous = - l0op::Contiguous(cuSeqlensCmpKvOptional, uniqueExecutor.get()); - if (cuSeqlensCmpKvOptionalContiguous == nullptr) { - OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, - "cu_seqlens_cmp_kv contiguous is null"); - return ACLNN_ERR_INNER_NULLPTR; - } - } - const aclTensor* sequsedQOptionalContiguous = nullptr; - if (sequsedQOptional != nullptr) { - sequsedQOptionalContiguous = - l0op::Contiguous(sequsedQOptional, uniqueExecutor.get()); - if (sequsedQOptionalContiguous == nullptr) { - OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, - "seqused_q contiguous is null"); - return ACLNN_ERR_INNER_NULLPTR; - } - } - const aclTensor* sequsedOriKvOptionalContiguous = nullptr; - if (sequsedOriKvOptional != nullptr) { - sequsedOriKvOptionalContiguous = - l0op::Contiguous(sequsedOriKvOptional, uniqueExecutor.get()); - if (sequsedOriKvOptionalContiguous == nullptr) { - OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, - "seqused_ori_kv contiguous is null"); - return ACLNN_ERR_INNER_NULLPTR; - } - } - const aclTensor* sequsedCmpKvOptionalContiguous = nullptr; - if (sequsedCmpKvOptional != nullptr) { - sequsedCmpKvOptionalContiguous = - l0op::Contiguous(sequsedCmpKvOptional, uniqueExecutor.get()); - if (sequsedCmpKvOptionalContiguous == nullptr) { - OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, - "seqused_cmp_kv contiguous is null"); - return ACLNN_ERR_INNER_NULLPTR; - } - } - const aclTensor* cmpResidualKvOptionalContiguous = nullptr; - if (cmpResidualKvOptional != nullptr) { - cmpResidualKvOptionalContiguous = - l0op::Contiguous(cmpResidualKvOptional, uniqueExecutor.get()); - if (cmpResidualKvOptionalContiguous == nullptr) { - OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, - "cmp_residual_kv contiguous is null"); - return ACLNN_ERR_INNER_NULLPTR; - } - } - const aclTensor* oriTopkLengthOptionalContiguous = nullptr; - if (oriTopkLengthOptional != nullptr) { - oriTopkLengthOptionalContiguous = - l0op::Contiguous(oriTopkLengthOptional, uniqueExecutor.get()); - if (oriTopkLengthOptionalContiguous == nullptr) { - OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, - "ori_topk_length contiguous is null"); - return ACLNN_ERR_INNER_NULLPTR; - } - } - const aclTensor* cmpTopkLengthOptionalContiguous = nullptr; - if (cmpTopkLengthOptional != nullptr) { - cmpTopkLengthOptionalContiguous = - l0op::Contiguous(cmpTopkLengthOptional, uniqueExecutor.get()); - if (cmpTopkLengthOptionalContiguous == nullptr) { - OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, - "cmp_topk_length contiguous is null"); - return ACLNN_ERR_INNER_NULLPTR; - } - } - - auto output = - l0op::XllmKernelSparseFlashMlaMetadata(cuSeqlensQOptionalContiguous, - cuSeqlensOriKvOptionalContiguous, - cuSeqlensCmpKvOptionalContiguous, - sequsedQOptionalContiguous, - sequsedOriKvOptionalContiguous, - sequsedCmpKvOptionalContiguous, - cmpResidualKvOptionalContiguous, - oriTopkLengthOptionalContiguous, - cmpTopkLengthOptionalContiguous, - numHeadsQ, - numHeadsKv, - headDim, - batchSize, - maxSeqlenQ, - maxSeqlenOriKv, - maxSeqlenCmpKv, - oriTopk, - cmpTopk, - cmpRatio, - oriMaskMode, - cmpMaskMode, - oriWinLeft, - oriWinRight, - layoutQOptional, - layoutKvOptional, - hasOriKv, - hasCmpKv, - socVersion, - aicCoreNum, - aivCoreNum, - isBatchConsistency, - metaData, - uniqueExecutor.get()); - CHECK_RET(output != nullptr, ACLNN_ERR_INNER_NULLPTR); - - *workspaceSize = uniqueExecutor->GetWorkspaceSize(); - uniqueExecutor.ReleaseTo(executor); - return ACLNN_SUCCESS; -} - -__attribute__((visibility("default"))) aclnnStatus -aclnnXllmKernelSparseFlashMlaMetadata(void* workspace, - uint64_t workspaceSize, - aclOpExecutor* executor, - aclrtStream stream) { - L2_DFX_PHASE_2(aclnnXllmKernelSparseFlashMlaMetadata); - return CommonOpExecutorRun(workspace, workspaceSize, executor, stream); -} - -#ifdef __cplusplus -} -#endif diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/aclnn_sparse_flash_mla_metadata.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/aclnn_sparse_flash_mla_metadata.h deleted file mode 100644 index 8a522405dc..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/aclnn_sparse_flash_mla_metadata.h +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#ifndef ACLNN_SPARSE_FLASH_MLA_METADATA_H -#define ACLNN_SPARSE_FLASH_MLA_METADATA_H - -#include "aclnn/aclnn_base.h" - -#ifdef __cplusplus -extern "C" { -#endif - -__attribute__((visibility("default"))) aclnnStatus -aclnnXllmKernelSparseFlashMlaMetadataGetWorkspaceSize( - const aclTensor* cuSeqlensQOptional, - const aclTensor* cuSeqlensOriKvOptional, - const aclTensor* cuSeqlensCmpKvOptional, - const aclTensor* sequsedQOptional, - const aclTensor* sequsedOriKvOptional, - const aclTensor* sequsedCmpKvOptional, - const aclTensor* cmpResidualKvOptional, - const aclTensor* oriTopkLengthOptional, - const aclTensor* cmpTopkLengthOptional, - int64_t numHeadsQ, - int64_t numHeadsKv, - int64_t headDim, - int64_t batchSize, - int64_t maxSeqlenQ, - int64_t maxSeqlenOriKv, - int64_t maxSeqlenCmpKv, - int64_t oriTopk, - int64_t cmpTopk, - int64_t cmpRatio, - int64_t oriMaskMode, - int64_t cmpMaskMode, - int64_t oriWinLeft, - int64_t oriWinRight, - const char* layoutQOptional, - const char* layoutKvOptional, - bool hasOriKv, - bool hasCmpKv, - const aclTensor* metaData, - uint64_t* workspaceSize, - aclOpExecutor** executor); - -__attribute__((visibility("default"))) aclnnStatus -aclnnXllmKernelSparseFlashMlaMetadata(void* workspace, - uint64_t workspaceSize, - aclOpExecutor* executor, - aclrtStream stream); - -#ifdef __cplusplus -} -#endif - -#endif // ACLNN_SPARSE_FLASH_MLA_METADATA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/sparse_flash_mla_metadata.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/sparse_flash_mla_metadata.cpp deleted file mode 100644 index a0e766e5c4..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/sparse_flash_mla_metadata.cpp +++ /dev/null @@ -1,156 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file sparse_flash_mla_metadata.cpp - * \brief - */ - -#include "sparse_flash_mla_metadata.h" - -#include - -#include "opdev/aicpu/aicpu_task.h" -#include "opdev/make_op_executor.h" -#include "opdev/op_def.h" -#include "opdev/op_dfx.h" -#include "opdev/op_executor.h" -#include "opdev/op_log.h" -#include "opdev/shape_utils.h" -#include "sparse_flash_mla/op_host/common/log.h" - -using namespace op; -namespace l0op { -OP_TYPE_REGISTER(XllmKernelSparseFlashMlaMetadata); - -const aclTensor* XllmKernelSparseFlashMlaMetadata( - const aclTensor* cuSeqlensQOptional, - const aclTensor* cuSeqlensOriKvOptional, - const aclTensor* cuSeqlensCmpKvOptional, - const aclTensor* sequsedQOptional, - const aclTensor* sequsedOriKvOptional, - const aclTensor* sequsedCmpKvOptional, - const aclTensor* cmpResidualKvOptional, - const aclTensor* oriTopkLengthOptional, - const aclTensor* cmpTopkLengthOptional, - int64_t numHeadsQ, - int64_t numHeadsKv, - int64_t headDim, - int64_t batchSize, - int64_t maxSeqlenQ, - int64_t maxSeqlenOriKv, - int64_t maxSeqlenCmpKv, - int64_t oriTopk, - int64_t cmpTopk, - int64_t cmpRatio, - int64_t oriMaskMode, - int64_t cmpMaskMode, - int64_t oriWinLeft, - int64_t oriWinRight, - const char* layoutQOptional, - const char* layoutKvOptional, - bool hasOriKv, - bool hasCmpKv, - const char* socVersion, - int64_t aicCoreNum, - int64_t aivCoreNum, - bool isBatchConsistency, - const aclTensor* metaData, - aclOpExecutor* executor) { - L0_DFX(XllmKernelSparseFlashMlaMetadata, - cuSeqlensQOptional, - cuSeqlensOriKvOptional, - cuSeqlensCmpKvOptional, - sequsedQOptional, - sequsedOriKvOptional, - sequsedCmpKvOptional, - cmpResidualKvOptional, - oriTopkLengthOptional, - cmpTopkLengthOptional, - numHeadsQ, - numHeadsKv, - headDim, - batchSize, - maxSeqlenQ, - maxSeqlenOriKv, - maxSeqlenCmpKv, - oriTopk, - cmpTopk, - cmpRatio, - oriMaskMode, - cmpMaskMode, - oriWinLeft, - oriWinRight, - layoutQOptional, - layoutKvOptional, - hasOriKv, - hasCmpKv, - socVersion, - aicCoreNum, - aivCoreNum, - isBatchConsistency, - metaData); - - static internal::AicpuTaskSpace space("XllmKernelSparseFlashMlaMetadata"); - - auto ret = ADD_TO_LAUNCHER_LIST_AICPU( - XllmKernelSparseFlashMlaMetadata, - OP_ATTR_NAMES( - {"num_heads_q", "num_heads_kv", "head_dim", - "batch_size", "max_seqlen_q", "max_seqlen_ori_kv", - "max_seqlen_cmp_kv", "ori_topk", "cmp_topk", - "cmp_ratio", "ori_mask_mode", "cmp_mask_mode", - "ori_win_left", "ori_win_right", "layout_q", - "layout_kv", "has_ori_kv", "has_cmp_kv", - "soc_version", "aic_core_num", "aiv_core_num", - "is_batch_consistency"}), - OP_INPUT(cuSeqlensQOptional, - cuSeqlensOriKvOptional, - cuSeqlensCmpKvOptional, - sequsedQOptional, - sequsedOriKvOptional, - sequsedCmpKvOptional, - cmpResidualKvOptional, - oriTopkLengthOptional, - cmpTopkLengthOptional), - OP_OUTPUT(metaData), - OP_ATTR(numHeadsQ, - numHeadsKv, - headDim, - batchSize, - maxSeqlenQ, - maxSeqlenOriKv, - maxSeqlenCmpKv, - oriTopk, - cmpTopk, - cmpRatio, - oriMaskMode, - cmpMaskMode, - oriWinLeft, - oriWinRight, - layoutQOptional, - layoutKvOptional, - hasOriKv, - hasCmpKv, - socVersion, - aicCoreNum, - aivCoreNum, - isBatchConsistency)); - OP_CHECK(ret == ACL_SUCCESS, - OP_LOGE_WITHOUT_REPORT(ACLNN_ERR_INNER_NULLPTR, - "XllmKernelSparseFlashMlaMetadata " - "ADD_TO_LAUNCHER_LIST_AICPU failed."), - return nullptr); - return metaData; -} - -} // namespace l0op diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/sparse_flash_mla_metadata.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/sparse_flash_mla_metadata.h deleted file mode 100644 index f2197b1695..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/op_api/sparse_flash_mla_metadata.h +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -#ifndef L0_SPARSE_FLASH_MLA_METADATA_H -#define L0_SPARSE_FLASH_MLA_METADATA_H - -#include "opdev/op_executor.h" - -namespace l0op { -const aclTensor* XllmKernelSparseFlashMlaMetadata( - const aclTensor* cuSeqlensQOptional, - const aclTensor* cuSeqlensOriKvOptional, - const aclTensor* cuSeqlensCmpKvOptional, - const aclTensor* sequsedQOptional, - const aclTensor* sequsedOriKvOptional, - const aclTensor* sequsedCmpKvOptional, - const aclTensor* cmpResidualKvOptional, - const aclTensor* oriTopkLengthOptional, - const aclTensor* cmpTopkLengthOptional, - int64_t numHeadsQ, - int64_t numHeadsKv, - int64_t headDim, - int64_t batchSize, - int64_t maxSeqlenQ, - int64_t maxSeqlenOriKv, - int64_t maxSeqlenCmpKv, - int64_t oriTopk, - int64_t cmpTopk, - int64_t cmpRatio, - int64_t oriMaskMode, - int64_t cmpMaskMode, - int64_t oriWinLeft, - int64_t oriWinRight, - const char* layoutQOptional, - const char* layoutKvOptional, - bool hasOriKv, - bool hasCmpKv, - const char* socVersion, - int64_t aicCoreNum, - int64_t aivCoreNum, - bool isBatchConsistency, - const aclTensor* metaData, - aclOpExecutor* executor); -} // namespace l0op - -#endif diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/sparse_flash_mla_metadata_check.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/sparse_flash_mla_metadata_check.h deleted file mode 100644 index f6280f450a..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/sparse_flash_mla_metadata_check.h +++ /dev/null @@ -1,1464 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file sparse_flash_mla_metadata_check.h - * \brief - */ - -#include -#include - -#include "opdev/data_type_utils.h" -#include "opdev/format_utils.h" -#include "opdev/tensor_view_utils.h" -#include "sparse_flash_mla/op_host/common/log.h" -#include "sparse_flash_mla/op_kernel/sparse_flash_mla_kernel_metadata.h" - -#ifdef __cplusplus -extern "C" { -#endif - -namespace { - -static constexpr const char* SMLA_ACLNN_OP_NAME = - "aclnnXllmKernelSparseFlashMlaMetadata"; - -enum class SparseModeSmla : uint8_t { - DEFAULT_MASK = 0, - ALL_MASK, - LEFT_UP_CAUSAL, - RIGHT_DOWN_CAUSAL, - BAND, - SPARSE_BUTT, -}; - -inline constexpr int64_t SMLA_CMP_RATIO_LOWER_BOUND = 1; -inline constexpr int64_t SMLA_CMP_RATIO_UPPER_BOUND = 128; -inline constexpr int64_t SMLA_NUM_HEADS_Q_LOWER_BOUND = 1; -inline constexpr int64_t SMLA_NUM_HEADS_Q_UPPER_BOUND = 128; - -inline bool IsPowerOfTwoInRangeSmla(int64_t value, - int64_t minValue, - int64_t maxValue) { - return value >= minValue && value <= maxValue && ((value & (value - 1)) == 0); -} - -inline bool IsA5Smla(const char* socVersion) { - return socVersion != nullptr && (strstr(socVersion, "Ascend950") != nullptr); -} - -inline bool IsA6Smla(const char* socVersion) { - return socVersion != nullptr && - (strstr(socVersion, "Ascend960DT") != nullptr || - strstr(socVersion, "Ascend960PR") != nullptr); -} - -inline bool IsCmpRatioSupportSmla(const char* socVersion, - bool hasCmpKv, - int64_t cmpTopk, - int64_t cmpRatio) { - if (IsA5Smla(socVersion) || IsA6Smla(socVersion)) { - return cmpRatio >= SMLA_CMP_RATIO_LOWER_BOUND && - cmpRatio <= SMLA_CMP_RATIO_UPPER_BOUND; - } - return (cmpTopk > 0) ? (cmpRatio == 1 || cmpRatio == 2 || cmpRatio == 4) - : (cmpRatio == 128); -} - -inline bool IsTensorExistSmla(const aclTensor* tensor) { - return (tensor != nullptr) && (tensor->GetViewShape().GetDimNum() > 0) && - (tensor->GetViewShape().GetDim(0) > 0); -} - -aclnnStatus CheckReservedOptionalTensorSmla(const aclTensor* tensor, - const char* tensorName) { - if (!IsTensorExistSmla(tensor)) { - return ACLNN_SUCCESS; - } - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - SMLA_ACLNN_OP_NAME, - tensorName, - std::string(tensorName) + - " is reserved and does not support " - "non-empty tensor"); - return ACLNN_ERR_PARAM_INVALID; -} - -int64_t GetDimNumSmla(const aclTensor* tensor) { - if (tensor == nullptr) { - return -1; - } - return tensor->GetViewShape().GetDimNum(); -} - -aclDataType GetDataTypeSmla(const aclTensor* tensor) { - aclDataType dataType = aclDataType::ACL_DT_UNDEFINED; - if (tensor == nullptr) { - return dataType; - } - aclGetDataType(tensor, &dataType); - return dataType; -} - -inline bool IsTensorSourceSmla(const std::string& source) { - return source != "batch_size"; -} - -inline int64_t GetRawShapeSizeSmla(const std::string& source, - int64_t batchValue) { - if (source.find("cu_seqlens") != std::string::npos) { - return batchValue + 1; - } - return batchValue; -} - -inline std::string GetSourceDescSmla(const std::string& source) { - if (source == "batch_size") { - return "batch_size"; - } - if (source.find("cu_seqlens") != std::string::npos) { - return "the shape size of " + source + " minus 1"; - } - return "the shape size of " + source; -} - -aclnnStatus CheckSingleParamSmla(int64_t batchSize, - int64_t maxSeqlenQ, - int64_t maxSeqlenOriKv, - int64_t maxSeqlenCmpKv, - int64_t numHeadsQ, - int64_t numHeadsKv, - int64_t headDim, - int64_t oriTopk, - int64_t cmpTopk, - int64_t cmpRatio, - int64_t oriMaskMode, - int64_t cmpMaskMode, - int64_t oriWinLeft, - int64_t oriWinRight, - const char* layoutQOptional, - const char* layoutKvOptional, - bool hasOriKv, - bool hasCmpKv, - uint32_t aicCoreNum, - uint32_t aivCoreNum, - const char* socVersion) { - // batch_size >= 0 - if (batchSize < 0) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "batch_size", - std::to_string(batchSize), - "The value of batch_size must be greater than or equal to 0"); - return ACLNN_ERR_PARAM_INVALID; - } - // max_seqlen_q >= 0 - if (maxSeqlenQ < 0) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "max_seqlen_q", - std::to_string(maxSeqlenQ), - "The value of max_seqlen_q must be greater than or equal to 0"); - return ACLNN_ERR_PARAM_INVALID; - } - // max_seqlen_ori_kv >= 0 - if (maxSeqlenOriKv < 0) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "max_seqlen_ori_kv", - std::to_string(maxSeqlenOriKv), - "The value of max_seqlen_ori_kv must be greater than or equal to 0"); - return ACLNN_ERR_PARAM_INVALID; - } - // max_seqlen_cmp_kv >= 0 - if (maxSeqlenCmpKv < 0) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "max_seqlen_cmp_kv", - std::to_string(maxSeqlenCmpKv), - "The value of max_seqlen_cmp_kv must be greater than or equal to 0"); - return ACLNN_ERR_PARAM_INVALID; - } - // num_heads_q [1, 128] - if (numHeadsQ < SMLA_NUM_HEADS_Q_LOWER_BOUND || - numHeadsQ > SMLA_NUM_HEADS_Q_UPPER_BOUND) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "num_heads_q", - std::to_string(numHeadsQ), - "The current value is not within the valid range. " - "The valid range is [" + - std::to_string(SMLA_NUM_HEADS_Q_LOWER_BOUND) + ", " + - std::to_string(SMLA_NUM_HEADS_Q_UPPER_BOUND) + "]"); - return ACLNN_ERR_PARAM_INVALID; - } - // num_heads_kv: 1 - if (numHeadsKv != 1) { - OP_LOGE_FOR_INVALID_VALUE( - SMLA_ACLNN_OP_NAME, "num_heads_kv", std::to_string(numHeadsKv), "1"); - return ACLNN_ERR_PARAM_INVALID; - } - if (numHeadsQ % numHeadsKv != 0) { - OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "num_heads_q, num_heads_kv", - std::to_string(numHeadsQ) + ", " + std::to_string(numHeadsKv), - "The value of num_heads_q must be divisible by " - "that of num_heads_kv"); - return ACLNN_ERR_PARAM_INVALID; - } - int64_t headRatio = numHeadsQ / numHeadsKv; - if (IsA5Smla(socVersion) || IsA6Smla(socVersion)) { - if (headRatio < SMLA_NUM_HEADS_Q_LOWER_BOUND || - headRatio > SMLA_NUM_HEADS_Q_UPPER_BOUND) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "num_heads_q / num_heads_kv", - std::to_string(headRatio), - "The current value is not within the valid range. " - "The valid range is [" + - std::to_string(SMLA_NUM_HEADS_Q_LOWER_BOUND) + ", " + - std::to_string(SMLA_NUM_HEADS_Q_UPPER_BOUND) + "]"); - return ACLNN_ERR_PARAM_INVALID; - } - } else if (!IsPowerOfTwoInRangeSmla(headRatio, - SMLA_NUM_HEADS_Q_LOWER_BOUND, - SMLA_NUM_HEADS_Q_UPPER_BOUND)) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "num_heads_q / num_heads_kv", - std::to_string(headRatio), - "The current value is not within the valid range. " - "The valid range is power of two in [" + - std::to_string(SMLA_NUM_HEADS_Q_LOWER_BOUND) + ", " + - std::to_string(SMLA_NUM_HEADS_Q_UPPER_BOUND) + "]"); - return ACLNN_ERR_PARAM_INVALID; - } - // head_dim: 512 - if (headDim != 512) { - OP_LOGE_FOR_INVALID_VALUE( - SMLA_ACLNN_OP_NAME, "head_dim", std::to_string(headDim), "512"); - return ACLNN_ERR_PARAM_INVALID; - } - if (hasOriKv) { - // ori_topk >= 0 - if (oriTopk < 0) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "ori_topk", - std::to_string(oriTopk), - "When has_ori_kv is true, the value of ori_topk must be " - "greater than or equal to 0"); - return ACLNN_ERR_PARAM_INVALID; - } - if (!((IsA5Smla(socVersion) || IsA6Smla(socVersion))) && oriTopk != 0 && - hasCmpKv) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "ori_topk", - std::to_string(oriTopk), - "ori_topk is reserved and " - "the value of ori_topk must be 0 when has_cmp_kv is true"); - return ACLNN_ERR_PARAM_INVALID; - } - if (IsA5Smla(socVersion) || IsA6Smla(socVersion)) { - // ori_mask_mode: 0, 3, or 4 - if (oriMaskMode != static_cast(SparseModeSmla::DEFAULT_MASK) && - oriMaskMode != - static_cast(SparseModeSmla::RIGHT_DOWN_CAUSAL) && - oriMaskMode != static_cast(SparseModeSmla::BAND)) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "ori_mask_mode", - std::to_string(oriMaskMode), - "When has_ori_kv is true, the value of ori_mask_mode " - "must be in [0, 3, 4]"); - return ACLNN_ERR_PARAM_INVALID; - } - // A5 treats -1 as unlimited window - if (oriWinLeft < -1 || oriWinRight < -1) { - OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "ori_win_left and ori_win_right", - std::to_string(oriWinLeft) + " and " + std::to_string(oriWinRight), - "When has_ori_kv is true, the value of ori_win_left, " - "ori_win_right must be greater than or equal to -1"); - return ACLNN_ERR_PARAM_INVALID; - } - } else { - if (oriTopk != 0) { - if (oriMaskMode != static_cast(SparseModeSmla::DEFAULT_MASK)) { - OP_LOGE_FOR_INVALID_VALUE(SMLA_ACLNN_OP_NAME, - "ori_mask_mode", - std::to_string(oriMaskMode), - "0"); - return ACLNN_ERR_PARAM_INVALID; - } - if (oriWinLeft < 0 || oriWinRight < 0) { - OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "ori_win_left, ori_win_right", - std::to_string(oriWinLeft) + ", " + std::to_string(oriWinRight), - "When has_ori_kv is true and ori_topk is non-zero (DSpark), " - "ori_win_left and ori_win_right must be non-negative"); - return ACLNN_ERR_PARAM_INVALID; - } - } else { - if (oriMaskMode != static_cast(SparseModeSmla::BAND)) { - OP_LOGE_FOR_INVALID_VALUE(SMLA_ACLNN_OP_NAME, - "ori_mask_mode", - std::to_string(oriMaskMode), - "4"); - return ACLNN_ERR_PARAM_INVALID; - } - if (oriWinLeft != 127 || oriWinRight != 0) { - OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "ori_win_left and ori_win_right", - std::to_string(oriWinLeft) + " and " + - std::to_string(oriWinRight), - "When has_ori_kv is true, the value of ori_win_left " - "must be 127 and the value of ori_win_right must be 0"); - return ACLNN_ERR_PARAM_INVALID; - } - } - } - } - if (hasCmpKv) { - // cmp_topk >= 0 - if (cmpTopk < 0) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cmp_topk", - std::to_string(cmpTopk), - "When has_cmp_kv is true, the value of cmp_topk must be " - "greater than or equal to 0"); - return ACLNN_ERR_PARAM_INVALID; - } - if (!((IsA5Smla(socVersion) || IsA6Smla(socVersion))) && cmpTopk > 8192) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cmp_topk", - std::to_string(cmpTopk), - "When has_cmp_kv is true, the value of cmp_topk must be " - "in [1, 8192]"); - return ACLNN_ERR_PARAM_INVALID; - } - if (IsA5Smla(socVersion) || IsA6Smla(socVersion)) { - // cmp_mask_mode: 0 or 3 - if (cmpMaskMode != static_cast(SparseModeSmla::DEFAULT_MASK) && - cmpMaskMode != - static_cast(SparseModeSmla::RIGHT_DOWN_CAUSAL)) { - OP_LOGE_FOR_INVALID_VALUE(SMLA_ACLNN_OP_NAME, - "cmp_mask_mode", - std::to_string(cmpMaskMode), - "0 or 3"); - return ACLNN_ERR_PARAM_INVALID; - } - } else { - if (cmpMaskMode != - static_cast(SparseModeSmla::RIGHT_DOWN_CAUSAL)) { - OP_LOGE_FOR_INVALID_VALUE(SMLA_ACLNN_OP_NAME, - "cmp_mask_mode", - std::to_string(cmpMaskMode), - "3"); - return ACLNN_ERR_PARAM_INVALID; - } - } - if (!IsCmpRatioSupportSmla(socVersion, hasCmpKv, cmpTopk, cmpRatio)) { - if (IsA5Smla(socVersion) || IsA6Smla(socVersion)) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cmp_ratio", - std::to_string(cmpRatio), - "When has_cmp_kv is true, the current value is not " - "within the valid range. The valid range is [" + - std::to_string(SMLA_CMP_RATIO_LOWER_BOUND) + ", " + - std::to_string(SMLA_CMP_RATIO_UPPER_BOUND) + "]"); - } else { - int64_t expectedCmpRatio = (cmpTopk > 0) ? 4 : 128; - if (cmpTopk > 0) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cmp_ratio", - std::to_string(cmpRatio), - "When has_cmp_kv is true and cmp_topk is non-zero" - "(CSA with cmp_sparse_indices), " - "the value of cmp_ratio must be 1, 2 or " + - std::to_string(expectedCmpRatio)); - } else { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cmp_ratio", - std::to_string(cmpRatio), - "When has_cmp_kv is true and cmp_topk is 0" - "(HCA without cmp_sparse_indices), " - "the value of cmp_ratio must be " + - std::to_string(expectedCmpRatio)); - } - } - return ACLNN_ERR_PARAM_INVALID; - } - } - if (layoutQOptional == nullptr) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - SMLA_ACLNN_OP_NAME, "layout_q", "layout_q cannot be empty"); - return ACLNN_ERR_PARAM_INVALID; - } - if (layoutKvOptional == nullptr) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - SMLA_ACLNN_OP_NAME, "layout_kv", "layout_kv cannot be empty"); - return ACLNN_ERR_PARAM_INVALID; - } - // layout_q: BSND or TND - if (strcmp(layoutQOptional, "TND") != 0 && - strcmp(layoutQOptional, "BSND") != 0) { - OP_LOGE_FOR_INVALID_VALUE( - SMLA_ACLNN_OP_NAME, "layout_q", layoutQOptional, "TND or BSND"); - return ACLNN_ERR_PARAM_INVALID; - } - // layout_kv: BSND, TND, or PA_BBND - if (strcmp(layoutKvOptional, "BSND") != 0 && - strcmp(layoutKvOptional, "TND") != 0 && - strcmp(layoutKvOptional, "PA_BBND") != 0) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "layout_kv", - layoutKvOptional, - "The value of layout_kv must be in [TND, BSND, PA_BBND]"); - return ACLNN_ERR_PARAM_INVALID; - } - if (strcmp(layoutKvOptional, "PA_BBND") != 0 && - strcmp(layoutQOptional, layoutKvOptional) != 0) { - OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "layout_q, layout_kv", - std::string(layoutQOptional) + ", " + std::string(layoutKvOptional), - "When layout_kv is not PA_BBND, the values of layout_q, layout_kv must " - "be the same"); - return ACLNN_ERR_PARAM_INVALID; - } - // 校验 layout_q 为 BSND 时,max_seqlen_q 必须大于 0 - if (strcmp(layoutQOptional, "BSND") == 0 && maxSeqlenQ <= 0) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "max_seqlen_q", - std::to_string(maxSeqlenQ), - "When layout_q is BSND, the value of max_seqlen_q " - "must be equal to the size of the second axis of q"); - return ACLNN_ERR_PARAM_INVALID; - } - // 校验 has_ori_kv 且 layout_kv 为 BSND 时,max_seqlen_ori_kv 必须大于 0 - if (hasOriKv && strcmp(layoutKvOptional, "BSND") == 0 && - maxSeqlenOriKv <= 0) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "max_seqlen_ori_kv", - std::to_string(maxSeqlenOriKv), - "When has_ori_kv is true and layout_kv is BSND, " - "the value of max_seqlen_ori_kv " - "must be equal to the size of the second axis of ori_kv"); - return ACLNN_ERR_PARAM_INVALID; - } - // 校验 has_cmp_kv 且 layout_kv 为 BSND 时,max_seqlen_cmp_kv 必须大于 0 - if (hasCmpKv && strcmp(layoutKvOptional, "BSND") == 0 && - maxSeqlenCmpKv <= 0) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "max_seqlen_cmp_kv", - std::to_string(maxSeqlenCmpKv), - "When has_cmp_kv is true and layout_kv is BSND, " - "the value of max_seqlen_cmp_kv " - "must be equal to the size of the second axis of cmp_kv"); - return ACLNN_ERR_PARAM_INVALID; - } - // 核数校验 - if (aicCoreNum == 0) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "aic_core_num", - std::to_string(aicCoreNum), - "The value of aic_core_num must be greater than 0"); - return ACLNN_ERR_PARAM_INVALID; - } - if (aicCoreNum > optiling::AIC_CORE_MAX_NUM) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "aic_core_num", - std::to_string(aicCoreNum), - "The current value is not within the valid range. " - "The valid range is [1, " + - std::to_string(optiling::AIC_CORE_MAX_NUM) + "]"); - return ACLNN_ERR_PARAM_INVALID; - } - if (aivCoreNum == 0) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "aiv_core_num", - std::to_string(aivCoreNum), - "The value of aiv_core_num must be greater than 0"); - return ACLNN_ERR_PARAM_INVALID; - } - if (aivCoreNum > optiling::AIV_CORE_MAX_NUM) { - OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "aiv_core_num", - std::to_string(aivCoreNum), - "The current value is not within the valid range. " - "The valid range is [1, " + - std::to_string(optiling::AIV_CORE_MAX_NUM) + "]"); - return ACLNN_ERR_PARAM_INVALID; - } - // 校验切g模板核数 - if (numHeadsQ == 128) { - if (aicCoreNum == 1 || aivCoreNum == 1) { - OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "num_heads_q and aic_core_num and aiv_core_num", - std::to_string(numHeadsQ) + " and " + std::to_string(aicCoreNum) + - " and " + std::to_string(aivCoreNum), - "When num_heads_q is 128, the value of aic_core_num, " - "aiv_core_num cannot be 1"); - return ACLNN_ERR_PARAM_INVALID; - } - } - return ACLNN_SUCCESS; -} - -aclnnStatus CheckExistenceSmla(const aclTensor* cuSeqlensQOptional, - const aclTensor* cuSeqlensOriKvOptional, - const aclTensor* cuSeqlensCmpKvOptional, - const aclTensor* sequsedOriKvOptional, - const aclTensor* sequsedCmpKvOptional, - const aclTensor* cmpResidualKvOptional, - const aclTensor* oriTopkLengthOptional, - const aclTensor* cmpTopkLengthOptional, - int64_t oriTopk, - int64_t cmpTopk, - int64_t cmpRatio, - int64_t oriMaskMode, - int64_t cmpMaskMode, - bool hasOriKv, - bool hasCmpKv, - const char* layoutQOptional, - const char* layoutKvOptional, - const char* socVersion, - const aclTensor* metadata) { - // cu_seqlens_q 存在性校验 - if (strcmp(layoutQOptional, "TND") == 0) { - if (!IsTensorExistSmla(cuSeqlensQOptional)) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cu_seqlens_q", - "When layout_q is TND, cu_seqlens_q cannot be empty"); - return ACLNN_ERR_PARAM_INVALID; - } - } - if (hasOriKv) { - // cu_seqlens_ori_kv 存在性校验 - if (strcmp(layoutKvOptional, "TND") == 0) { - if (!IsTensorExistSmla(cuSeqlensOriKvOptional)) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cu_seqlens_ori_kv", - "When has_ori_kv is true and layout_kv is TND, " - "cu_seqlens_ori_kv cannot be empty"); - return ACLNN_ERR_PARAM_INVALID; - } - } - // seqused_ori_kv 存在性校验 - if (IsA5Smla(socVersion) || IsA6Smla(socVersion)) { - if ((oriMaskMode != 0 || oriTopk == 0) && - strcmp(layoutKvOptional, "PA_BBND") == 0) { - if (!IsTensorExistSmla(sequsedOriKvOptional)) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "seqused_ori_kv", - "When has_ori_kv is true, ori_mask_mode != 0 or " - "ori_topk == 0, and layout_kv is PA_BBND, " - "seqused_ori_kv cannot be empty"); - return ACLNN_ERR_PARAM_INVALID; - } - } - } else { - if (strcmp(layoutKvOptional, "PA_BBND") == 0) { - if (!IsTensorExistSmla(sequsedOriKvOptional)) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "seqused_ori_kv", - "When has_ori_kv is true and layout_kv is PA_BBND, " - "seqused_ori_kv cannot be empty"); - return ACLNN_ERR_PARAM_INVALID; - } - } - } - // ori_topk_length 存在性校验 - if (oriTopk != 0 && - oriMaskMode == static_cast(SparseModeSmla::DEFAULT_MASK)) { - if (!IsTensorExistSmla(oriTopkLengthOptional)) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "ori_topk_length", - "When has_ori_kv is true, ori_topk is not 0 and " - "ori_mask_mode is 0, ori_topk_length cannot be empty"); - return ACLNN_ERR_PARAM_INVALID; - } - } - } - if (hasCmpKv) { - // cu_seqlens_cmp_kv 存在性校验 - if (strcmp(layoutKvOptional, "TND") == 0) { - if (!IsTensorExistSmla(cuSeqlensCmpKvOptional)) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cu_seqlens_cmp_kv", - "When has_cmp_kv is true and layout_kv is TND, " - "cu_seqlens_cmp_kv cannot be empty"); - return ACLNN_ERR_PARAM_INVALID; - } - } - // seqused_cmp_kv 存在性校验 - if (IsA5Smla(socVersion) || IsA6Smla(socVersion)) { - if ((cmpMaskMode != 0 || cmpTopk == 0) && - strcmp(layoutKvOptional, "PA_BBND") == 0) { - if (!IsTensorExistSmla(sequsedCmpKvOptional)) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "seqused_cmp_kv", - "When has_cmp_kv is true, cmp_mask_mode != 0 or " - "cmp_topk == 0, and layout_kv is PA_BBND, " - "seqused_cmp_kv cannot be empty"); - return ACLNN_ERR_PARAM_INVALID; - } - } - } else { - if (strcmp(layoutKvOptional, "PA_BBND") == 0) { - if (!IsTensorExistSmla(sequsedCmpKvOptional)) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "seqused_cmp_kv", - "When has_cmp_kv is true and layout_kv is PA_BBND, " - "seqused_cmp_kv cannot be empty"); - return ACLNN_ERR_PARAM_INVALID; - } - } - } - // cmp_residual_kv 存在性校验 - if (cmpRatio != 1 && - cmpMaskMode == - static_cast(SparseModeSmla::RIGHT_DOWN_CAUSAL)) { - if (!IsTensorExistSmla(cmpResidualKvOptional)) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cmp_residual_kv", - "When has_cmp_kv is true, cmp_ratio is not 1 and " - "cmp_mask_mode is 3, cmp_residual_kv cannot be empty"); - return ACLNN_ERR_PARAM_INVALID; - } - } - // cmp_topk_length 存在性校验 - if (cmpTopk != 0 && - cmpMaskMode == static_cast(SparseModeSmla::DEFAULT_MASK)) { - if (!IsTensorExistSmla(cmpTopkLengthOptional)) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cmp_topk_length", - "When has_cmp_kv is true, cmp_topk is not 0 and " - "cmp_mask_mode is 0, cmp_topk_length cannot be empty"); - return ACLNN_ERR_PARAM_INVALID; - } - } - } - // metadata 存在性校验 - if (!IsTensorExistSmla(metadata)) { - OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( - SMLA_ACLNN_OP_NAME, "metadata", "metadata cannot be empty"); - return ACLNN_ERR_PARAM_INVALID; - } - return ACLNN_SUCCESS; -} - -int64_t GetQueryBatchSizeSmla(const aclTensor* sequsedQOptional, - const aclTensor* cuSeqlensQOptional, - const char* layoutQOptional, - int64_t batchSize, - std::string* source) { - if (IsTensorExistSmla(sequsedQOptional)) { - *source = "seqused_q"; - return sequsedQOptional->GetViewShape().GetDim(0); - } - if (strcmp(layoutQOptional, "TND") == 0) { - if (IsTensorExistSmla(cuSeqlensQOptional)) { - *source = "cu_seqlens_q"; - return cuSeqlensQOptional->GetViewShape().GetDim(0) - 1; - } - } - *source = "batch_size"; - return batchSize; -} - -int64_t GetOriKvBatchSizeSmla(const aclTensor* sequsedOriKvOptional, - const aclTensor* cuSeqlensOriKvOptional, - const char* layoutKvOptional, - int64_t batchSize, - std::string* source) { - if (IsTensorExistSmla(sequsedOriKvOptional)) { - *source = "seqused_ori_kv"; - return sequsedOriKvOptional->GetViewShape().GetDim(0); - } - if (strcmp(layoutKvOptional, "TND") == 0) { - if (IsTensorExistSmla(cuSeqlensOriKvOptional)) { - *source = "cu_seqlens_ori_kv"; - return cuSeqlensOriKvOptional->GetViewShape().GetDim(0) - 1; - } - } - *source = "batch_size"; - return batchSize; -} - -int64_t GetCmpKvBatchSizeSmla(const aclTensor* sequsedCmpKvOptional, - const aclTensor* cuSeqlensCmpKvOptional, - const char* layoutKvOptional, - int64_t batchSize, - std::string* source) { - if (IsTensorExistSmla(sequsedCmpKvOptional)) { - *source = "seqused_cmp_kv"; - return sequsedCmpKvOptional->GetViewShape().GetDim(0); - } - if (strcmp(layoutKvOptional, "TND") == 0) { - if (IsTensorExistSmla(cuSeqlensCmpKvOptional)) { - *source = "cu_seqlens_cmp_kv"; - return cuSeqlensCmpKvOptional->GetViewShape().GetDim(0) - 1; - } - } - *source = "batch_size"; - return batchSize; -} - -std::string TopkLengthShapeToStringSmla(const aclTensor* topkLengthOptional) { - const auto& shape = topkLengthOptional->GetViewShape(); - std::string result; - for (size_t i = 0; i < shape.GetDimNum(); ++i) { - if (i != 0) { - result += ", "; - } - result += std::to_string(shape.GetDim(i)); - } - return result; -} - -aclnnStatus CheckTopkLengthFirstDimSmla(const aclTensor* topkLengthOptional, - const std::string& topkLengthName, - int64_t queryBatchSize, - const std::string& querySource) { - if (topkLengthOptional->GetViewShape().GetDim(0) == queryBatchSize) { - return ACLNN_SUCCESS; - } - std::string incorrectShape = TopkLengthShapeToStringSmla(topkLengthOptional); - if (IsTensorSourceSmla(querySource)) { - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - topkLengthName, - incorrectShape, - "When layout_q is BSND, the size of the first axis of " + - topkLengthName + " must be equal to " + - GetSourceDescSmla(querySource)); - } else { - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - topkLengthName, - incorrectShape, - "When layout_q is BSND, the size of the first axis of " + - topkLengthName + " must be equal to batch_size"); - } - return ACLNN_ERR_PARAM_INVALID; -} - -struct TopkLengthAxisSmla { - int64_t index; - const char* desc; -}; - -inline constexpr TopkLengthAxisSmla SMLA_TOPK_LENGTH_SECOND_AXIS{1, "second"}; -inline constexpr TopkLengthAxisSmla SMLA_TOPK_LENGTH_THIRD_AXIS{2, "third"}; - -aclnnStatus CheckTopkLengthSingleDimSmla(const aclTensor* topkLengthOptional, - const std::string& topkLengthName, - TopkLengthAxisSmla axis, - int64_t expectedValue, - const std::string& expectedDesc, - const char* layoutQOptional) { - if (topkLengthOptional->GetViewShape().GetDim(axis.index) == expectedValue) { - return ACLNN_SUCCESS; - } - std::string incorrectShape = TopkLengthShapeToStringSmla(topkLengthOptional); - OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - topkLengthName, - incorrectShape, - "When layout_q is " + std::string(layoutQOptional) + - ", the size of the " + axis.desc + " axis of " + topkLengthName + - " must be equal to " + expectedDesc); - return ACLNN_ERR_PARAM_INVALID; -} - -aclnnStatus CheckConsistencySmla(const aclTensor* cuSeqlensQOptional, - const aclTensor* cuSeqlensOriKvOptional, - const aclTensor* cuSeqlensCmpKvOptional, - const aclTensor* sequsedQOptional, - const aclTensor* sequsedOriKvOptional, - const aclTensor* sequsedCmpKvOptional, - const aclTensor* cmpResidualKvOptional, - const aclTensor* oriTopkLengthOptional, - const aclTensor* cmpTopkLengthOptional, - int64_t batchSize, - const char* layoutQOptional, - const char* layoutKvOptional, - bool hasOriKv, - bool hasCmpKv, - int64_t oriTopk, - int64_t cmpTopk, - int64_t oriMaskMode, - int64_t cmpMaskMode, - int64_t maxSeqlenQ, - int64_t numHeadsKv, - const char* socVersion, - const aclTensor* metadata) { - aclDataType dataType = aclDataType::ACL_DT_UNDEFINED; - int64_t dimNum = -1; - if (!((IsA5Smla(socVersion) || IsA6Smla(socVersion)))) { - if (oriTopk == 0 && - CheckReservedOptionalTensorSmla(oriTopkLengthOptional, - "ori_topk_length") != ACLNN_SUCCESS) { - return ACLNN_ERR_PARAM_INVALID; - } - if (CheckReservedOptionalTensorSmla(cmpTopkLengthOptional, - "cmp_topk_length") != ACLNN_SUCCESS) { - return ACLNN_ERR_PARAM_INVALID; - } - } - // 校验 cu_seqlens_q - if (IsTensorExistSmla(cuSeqlensQOptional)) { - // 校验 cu_seqlens_q 维度 - dimNum = GetDimNumSmla(cuSeqlensQOptional); - if (dimNum != 1) { - OP_LOGE_FOR_INVALID_SHAPEDIM( - SMLA_ACLNN_OP_NAME, "cu_seqlens_q", std::to_string(dimNum), "1"); - return ACLNN_ERR_PARAM_INVALID; - } - // 校验 cu_seqlens_q 数据类型 - dataType = GetDataTypeSmla(cuSeqlensQOptional); - if (dataType != aclDataType::ACL_INT32) { - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cu_seqlens_q", - ToString(dataType).GetString(), - "The dtype of cu_seqlens_q must be int32"); - return ACLNN_ERR_PARAM_INVALID; - } - } - // 校验 seqused_q - if (IsTensorExistSmla(sequsedQOptional)) { - // 校验 seqused_q 维度 - dimNum = GetDimNumSmla(sequsedQOptional); - if (dimNum != 1) { - OP_LOGE_FOR_INVALID_SHAPEDIM( - SMLA_ACLNN_OP_NAME, "seqused_q", std::to_string(dimNum), "1"); - return ACLNN_ERR_PARAM_INVALID; - } - // 校验 seqused_q 数据类型 - dataType = GetDataTypeSmla(sequsedQOptional); - if (dataType != aclDataType::ACL_INT32) { - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "seqused_q", - ToString(dataType).GetString(), - "The dtype of seqused_q must be int32"); - return ACLNN_ERR_PARAM_INVALID; - } - } - // ori_kv部分 - if (hasOriKv) { - // 校验 cu_seqlens_ori_kv - if (IsTensorExistSmla(cuSeqlensOriKvOptional)) { - // 校验 cu_seqlens_ori_kv 维度 - dimNum = GetDimNumSmla(cuSeqlensOriKvOptional); - if (dimNum != 1) { - OP_LOGE_FOR_INVALID_SHAPEDIM(SMLA_ACLNN_OP_NAME, - "cu_seqlens_ori_kv", - std::to_string(dimNum), - "1"); - return ACLNN_ERR_PARAM_INVALID; - } - // 校验 cu_seqlens_ori_kv 数据类型 - dataType = GetDataTypeSmla(cuSeqlensOriKvOptional); - if (dataType != aclDataType::ACL_INT32) { - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cu_seqlens_ori_kv", - ToString(dataType).GetString(), - "The dtype of cu_seqlens_ori_kv must be int32"); - return ACLNN_ERR_PARAM_INVALID; - } - } - // 校验 seqused_ori_kv - if (IsTensorExistSmla(sequsedOriKvOptional)) { - // 校验 seqused_ori_kv 维度 - dimNum = GetDimNumSmla(sequsedOriKvOptional); - if (dimNum != 1) { - OP_LOGE_FOR_INVALID_SHAPEDIM( - SMLA_ACLNN_OP_NAME, "seqused_ori_kv", std::to_string(dimNum), "1"); - return ACLNN_ERR_PARAM_INVALID; - } - // 校验 seqused_ori_kv 数据类型 - dataType = GetDataTypeSmla(sequsedOriKvOptional); - if (dataType != aclDataType::ACL_INT32) { - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "seqused_ori_kv", - ToString(dataType).GetString(), - "The dtype of seqused_ori_kv must be int32"); - return ACLNN_ERR_PARAM_INVALID; - } - } - // 校验 ori_topk_length - if (oriTopk != 0 && - oriMaskMode == static_cast(SparseModeSmla::DEFAULT_MASK) && - IsTensorExistSmla(oriTopkLengthOptional)) { - // 校验 ori_topk_length 维度 - dimNum = GetDimNumSmla(oriTopkLengthOptional); - if (strcmp(layoutQOptional, "TND") == 0) { - if (dimNum != 2) { - OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "ori_topk_length", - std::to_string(dimNum), - "The shape dim of ori_topk_length must be 2 " - "when layout_q is TND"); - return ACLNN_ERR_PARAM_INVALID; - } - } else if (strcmp(layoutQOptional, "BSND") == 0) { - if (dimNum != 3) { - OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "ori_topk_length", - std::to_string(dimNum), - "The shape dim of ori_topk_length must be 3 " - "when layout_q is BSND"); - return ACLNN_ERR_PARAM_INVALID; - } - } - // 校验 ori_topk_length 数据类型 - dataType = GetDataTypeSmla(oriTopkLengthOptional); - if (dataType != aclDataType::ACL_INT32) { - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "ori_topk_length", - ToString(dataType).GetString(), - "The dtype of ori_topk_length must be int32"); - return ACLNN_ERR_PARAM_INVALID; - } - } - } - // cmp_kv部分 - if (hasCmpKv) { - // 校验 cu_seqlens_cmp_kv - if (IsTensorExistSmla(cuSeqlensCmpKvOptional)) { - // 校验 cu_seqlens_cmp_kv 维度 - dimNum = GetDimNumSmla(cuSeqlensCmpKvOptional); - if (dimNum != 1) { - OP_LOGE_FOR_INVALID_SHAPEDIM(SMLA_ACLNN_OP_NAME, - "cu_seqlens_cmp_kv", - std::to_string(dimNum), - "1"); - return ACLNN_ERR_PARAM_INVALID; - } - // 校验 cu_seqlens_cmp_kv 数据类型 - dataType = GetDataTypeSmla(cuSeqlensCmpKvOptional); - if (dataType != aclDataType::ACL_INT32) { - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cu_seqlens_cmp_kv", - ToString(dataType).GetString(), - "The dtype of cu_seqlens_cmp_kv must be int32"); - return ACLNN_ERR_PARAM_INVALID; - } - } - // 校验 seqused_cmp_kv - if (IsTensorExistSmla(sequsedCmpKvOptional)) { - // 校验 seqused_cmp_kv 维度 - dimNum = GetDimNumSmla(sequsedCmpKvOptional); - if (dimNum != 1) { - OP_LOGE_FOR_INVALID_SHAPEDIM( - SMLA_ACLNN_OP_NAME, "seqused_cmp_kv", std::to_string(dimNum), "1"); - return ACLNN_ERR_PARAM_INVALID; - } - // 校验 seqused_cmp_kv 数据类型 - dataType = GetDataTypeSmla(sequsedCmpKvOptional); - if (dataType != aclDataType::ACL_INT32) { - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "seqused_cmp_kv", - ToString(dataType).GetString(), - "The dtype of seqused_cmp_kv must be int32"); - return ACLNN_ERR_PARAM_INVALID; - } - } - // 校验 cmp_residual_kv - if (IsTensorExistSmla(cmpResidualKvOptional)) { - // 校验 cmp_residual_kv 维度 - dimNum = GetDimNumSmla(cmpResidualKvOptional); - if (dimNum != 1) { - OP_LOGE_FOR_INVALID_SHAPEDIM( - SMLA_ACLNN_OP_NAME, "cmp_residual_kv", std::to_string(dimNum), "1"); - return ACLNN_ERR_PARAM_INVALID; - } - // 校验 cmp_residual_kv 数据类型 - dataType = GetDataTypeSmla(cmpResidualKvOptional); - if (dataType != aclDataType::ACL_INT32) { - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cmp_residual_kv", - ToString(dataType).GetString(), - "The dtype of cmp_residual_kv must be int32"); - return ACLNN_ERR_PARAM_INVALID; - } - } - // 校验 cmp_topk_length - if (cmpTopk != 0 && - cmpMaskMode == static_cast(SparseModeSmla::DEFAULT_MASK) && - IsTensorExistSmla(cmpTopkLengthOptional)) { - // 校验 cmp_topk_length 维度 - dimNum = GetDimNumSmla(cmpTopkLengthOptional); - if (strcmp(layoutQOptional, "TND") == 0) { - if (dimNum != 2) { - OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cmp_topk_length", - std::to_string(dimNum), - "The shape dim of cmp_topk_length must be 2 " - "when layout_q is TND"); - return ACLNN_ERR_PARAM_INVALID; - } - } else if (strcmp(layoutQOptional, "BSND") == 0) { - if (dimNum != 3) { - OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cmp_topk_length", - std::to_string(dimNum), - "The shape dim of cmp_topk_length must be 3 " - "when layout_q is BSND"); - return ACLNN_ERR_PARAM_INVALID; - } - } - // 校验 cmp_topk_length 数据类型 - dataType = GetDataTypeSmla(cmpTopkLengthOptional); - if (dataType != aclDataType::ACL_INT32) { - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cmp_topk_length", - ToString(dataType).GetString(), - "The dtype of cmp_topk_length must be int32"); - return ACLNN_ERR_PARAM_INVALID; - } - } - } - // 校验 metadata - if (IsTensorExistSmla(metadata)) { - // 校验 metadata 维度 - dimNum = GetDimNumSmla(metadata); - if (dimNum != 1) { - OP_LOGE_FOR_INVALID_SHAPEDIM( - SMLA_ACLNN_OP_NAME, "metadata", std::to_string(dimNum), "1"); - return ACLNN_ERR_PARAM_INVALID; - } - // 校验 metadata 元素数 - if (metadata->GetViewShape().GetDim(0) != - optiling::SMLA_METADATA_TOTAL_SIZE) { - OP_LOGE_FOR_INVALID_SHAPESIZE( - SMLA_ACLNN_OP_NAME, - "metadata", - std::to_string(metadata->GetViewShape().GetDim(0)), - std::to_string(optiling::SMLA_METADATA_TOTAL_SIZE)); - return ACLNN_ERR_PARAM_INVALID; - } - // 校验 metadata 数据类型 - dataType = GetDataTypeSmla(metadata); - if (dataType != aclDataType::ACL_INT32) { - OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "metadata", - ToString(dataType).GetString(), - "The dtype of metadata must be int32"); - return ACLNN_ERR_PARAM_INVALID; - } - } - // 校验 q/kv 维度一致性 - std::string querySource; - int64_t queryBatchSize = GetQueryBatchSizeSmla(sequsedQOptional, - cuSeqlensQOptional, - layoutQOptional, - batchSize, - &querySource); - // 校验TND场景q维度一致性 - if (strcmp(layoutQOptional, "TND") == 0 && - IsTensorExistSmla(sequsedQOptional)) { - int64_t cuSeqlensQBatchSize = - cuSeqlensQOptional->GetViewShape().GetDim(0) - 1; - if (cuSeqlensQBatchSize != queryBatchSize) { - OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cu_seqlens_q and seqused_q", - std::to_string(cuSeqlensQOptional->GetViewShape().GetDim(0)) + - " and " + - std::to_string(sequsedQOptional->GetViewShape().GetDim(0)), - "When layout_q is TND and seqused_q is passed, " - "the shape size of cu_seqlens_q minus 1 must be equal to " - "the shape size of seqused_q"); - return ACLNN_ERR_PARAM_INVALID; - } - } - if (hasOriKv) { - std::string oriKvSource; - int64_t oriKvBatchSize = GetOriKvBatchSizeSmla(sequsedOriKvOptional, - cuSeqlensOriKvOptional, - layoutKvOptional, - batchSize, - &oriKvSource); - // 校验q与ori_kv维度一致性 - if (queryBatchSize != oriKvBatchSize) { - if (IsTensorSourceSmla(querySource) && IsTensorSourceSmla(oriKvSource)) { - OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( - SMLA_ACLNN_OP_NAME, - querySource + " and " + oriKvSource, - std::to_string(GetRawShapeSizeSmla(querySource, queryBatchSize)) + - " and " + - std::to_string( - GetRawShapeSizeSmla(oriKvSource, oriKvBatchSize)), - "When has_ori_kv is true, " + GetSourceDescSmla(querySource) + - " must be equal to " + GetSourceDescSmla(oriKvSource)); - } else if (IsTensorSourceSmla(querySource)) { - OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - querySource, - std::to_string(GetRawShapeSizeSmla(querySource, queryBatchSize)), - "When has_ori_kv is true, " + GetSourceDescSmla(querySource) + - " must be equal to batch_size"); - } else { - OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - oriKvSource, - std::to_string(GetRawShapeSizeSmla(oriKvSource, oriKvBatchSize)), - "When has_ori_kv is true, " + GetSourceDescSmla(oriKvSource) + - " must be equal to batch_size"); - } - return ACLNN_ERR_PARAM_INVALID; - } - // 校验TND场景ori_kv维度一致性 - if (strcmp(layoutKvOptional, "TND") == 0 && - IsTensorExistSmla(sequsedOriKvOptional)) { - int64_t cuSeqlensOriKvBatchSize = - cuSeqlensOriKvOptional->GetViewShape().GetDim(0) - 1; - if (cuSeqlensOriKvBatchSize != oriKvBatchSize) { - OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cu_seqlens_ori_kv and seqused_ori_kv", - std::to_string(cuSeqlensOriKvOptional->GetViewShape().GetDim(0)) + - " and " + - std::to_string(sequsedOriKvOptional->GetViewShape().GetDim(0)), - "When layout_kv is TND and seqused_ori_kv is passed, " - "the shape size of cu_seqlens_ori_kv minus 1 must be " - "equal to the shape size of seqused_ori_kv"); - return ACLNN_ERR_PARAM_INVALID; - } - } - // 校验 ori_topk_length 维度一致性 - if (oriTopk != 0 && - oriMaskMode == static_cast(SparseModeSmla::DEFAULT_MASK) && - IsTensorExistSmla(oriTopkLengthOptional)) { - if (strcmp(layoutQOptional, "BSND") == 0) { - // 校验 ori_topk_length 第一个维度 - aclnnStatus ret = CheckTopkLengthFirstDimSmla(oriTopkLengthOptional, - "ori_topk_length", - queryBatchSize, - querySource); - if (ret != ACLNN_SUCCESS) { - return ret; - } - // 校验 ori_topk_length 第二个维度 - ret = CheckTopkLengthSingleDimSmla(oriTopkLengthOptional, - "ori_topk_length", - SMLA_TOPK_LENGTH_SECOND_AXIS, - maxSeqlenQ, - "max_seqlen_q", - layoutQOptional); - if (ret != ACLNN_SUCCESS) { - return ret; - } - // 校验 ori_topk_length 第三个维度 - ret = CheckTopkLengthSingleDimSmla(oriTopkLengthOptional, - "ori_topk_length", - SMLA_TOPK_LENGTH_THIRD_AXIS, - numHeadsKv, - "num_heads_kv", - layoutQOptional); - if (ret != ACLNN_SUCCESS) { - return ret; - } - } else if (strcmp(layoutQOptional, "TND") == 0) { - // 校验 ori_topk_length 第二个维度 - aclnnStatus ret = - CheckTopkLengthSingleDimSmla(oriTopkLengthOptional, - "ori_topk_length", - SMLA_TOPK_LENGTH_SECOND_AXIS, - numHeadsKv, - "num_heads_kv", - layoutQOptional); - if (ret != ACLNN_SUCCESS) { - return ret; - } - } - } - } - if (hasCmpKv) { - std::string cmpKvSource; - int64_t cmpKvBatchSize = GetCmpKvBatchSizeSmla(sequsedCmpKvOptional, - cuSeqlensCmpKvOptional, - layoutKvOptional, - batchSize, - &cmpKvSource); - // 校验q与cmp_kv维度一致性 - if (queryBatchSize != cmpKvBatchSize) { - if (IsTensorSourceSmla(querySource) && IsTensorSourceSmla(cmpKvSource)) { - OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( - SMLA_ACLNN_OP_NAME, - querySource + " and " + cmpKvSource, - std::to_string(GetRawShapeSizeSmla(querySource, queryBatchSize)) + - " and " + - std::to_string( - GetRawShapeSizeSmla(cmpKvSource, cmpKvBatchSize)), - "When has_cmp_kv is true, " + GetSourceDescSmla(querySource) + - " must be equal to " + GetSourceDescSmla(cmpKvSource)); - } else if (IsTensorSourceSmla(querySource)) { - OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - querySource, - std::to_string(GetRawShapeSizeSmla(querySource, queryBatchSize)), - "When has_cmp_kv is true, " + GetSourceDescSmla(querySource) + - " must be equal to batch_size"); - } else { - OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - cmpKvSource, - std::to_string(GetRawShapeSizeSmla(cmpKvSource, cmpKvBatchSize)), - "When has_cmp_kv is true, " + GetSourceDescSmla(cmpKvSource) + - " must be equal to batch_size"); - } - return ACLNN_ERR_PARAM_INVALID; - } - // 校验TND场景cmp_kv维度一致性 - if (strcmp(layoutKvOptional, "TND") == 0 && - IsTensorExistSmla(sequsedCmpKvOptional)) { - int64_t cuSeqlensCmpKvBatchSize = - cuSeqlensCmpKvOptional->GetViewShape().GetDim(0) - 1; - if (cuSeqlensCmpKvBatchSize != cmpKvBatchSize) { - OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cu_seqlens_cmp_kv and seqused_cmp_kv", - std::to_string(cuSeqlensCmpKvOptional->GetViewShape().GetDim(0)) + - " and " + - std::to_string(sequsedCmpKvOptional->GetViewShape().GetDim(0)), - "When layout_kv is TND and seqused_cmp_kv is passed, " - "the shape size of cu_seqlens_cmp_kv minus 1 must be " - "equal to the shape size of seqused_cmp_kv"); - return ACLNN_ERR_PARAM_INVALID; - } - } - // 校验 cmp_residual_kv 元素数 - if (IsTensorExistSmla(cmpResidualKvOptional)) { - if (cmpResidualKvOptional->GetViewShape().GetDim(0) != queryBatchSize) { - if (IsTensorSourceSmla(querySource)) { - OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cmp_residual_kv and " + querySource, - std::to_string(cmpResidualKvOptional->GetViewShape().GetDim(0)) + - " and " + - std::to_string( - GetRawShapeSizeSmla(querySource, queryBatchSize)), - "The shape size of cmp_residual_kv must be equal to " + - GetSourceDescSmla(querySource)); - } else { - OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( - SMLA_ACLNN_OP_NAME, - "cmp_residual_kv", - std::to_string(cmpResidualKvOptional->GetViewShape().GetDim(0)), - "The shape size of cmp_residual_kv must be equal " - "to batch_size"); - } - return ACLNN_ERR_PARAM_INVALID; - } - } - // 校验 cmp_topk_length 维度一致性 - if (cmpTopk != 0 && - cmpMaskMode == static_cast(SparseModeSmla::DEFAULT_MASK) && - IsTensorExistSmla(cmpTopkLengthOptional)) { - if (strcmp(layoutQOptional, "BSND") == 0) { - // 校验 cmp_topk_length 第一个维度 - aclnnStatus ret = CheckTopkLengthFirstDimSmla(cmpTopkLengthOptional, - "cmp_topk_length", - queryBatchSize, - querySource); - if (ret != ACLNN_SUCCESS) { - return ret; - } - // 校验 cmp_topk_length 第二个维度 - ret = CheckTopkLengthSingleDimSmla(cmpTopkLengthOptional, - "cmp_topk_length", - SMLA_TOPK_LENGTH_SECOND_AXIS, - maxSeqlenQ, - "max_seqlen_q", - layoutQOptional); - if (ret != ACLNN_SUCCESS) { - return ret; - } - // 校验 cmp_topk_length 第三个维度 - ret = CheckTopkLengthSingleDimSmla(cmpTopkLengthOptional, - "cmp_topk_length", - SMLA_TOPK_LENGTH_THIRD_AXIS, - numHeadsKv, - "num_heads_kv", - layoutQOptional); - if (ret != ACLNN_SUCCESS) { - return ret; - } - } else if (strcmp(layoutQOptional, "TND") == 0) { - // 校验 cmp_topk_length 第二个维度 - aclnnStatus ret = - CheckTopkLengthSingleDimSmla(cmpTopkLengthOptional, - "cmp_topk_length", - SMLA_TOPK_LENGTH_SECOND_AXIS, - numHeadsKv, - "num_heads_kv", - layoutQOptional); - if (ret != ACLNN_SUCCESS) { - return ret; - } - } - } - } - return ACLNN_SUCCESS; -} - -static aclnnStatus ParamsCheck(const aclTensor* cuSeqlensQOptional, - const aclTensor* cuSeqlensOriKvOptional, - const aclTensor* cuSeqlensCmpKvOptional, - const aclTensor* sequsedQOptional, - const aclTensor* sequsedOriKvOptional, - const aclTensor* sequsedCmpKvOptional, - const aclTensor* cmpResidualKvOptional, - const aclTensor* oriTopkLengthOptional, - const aclTensor* cmpTopkLengthOptional, - int64_t numHeadsQ, - int64_t numHeadsKv, - int64_t headDim, - int64_t batchSize, - int64_t maxSeqlenQ, - int64_t maxSeqlenOriKv, - int64_t maxSeqlenCmpKv, - int64_t oriTopk, - int64_t cmpTopk, - int64_t cmpRatio, - int64_t oriMaskMode, - int64_t cmpMaskMode, - int64_t oriWinLeft, - int64_t oriWinRight, - const char* layoutQOptional, - const char* layoutKvOptional, - bool hasOriKv, - bool hasCmpKv, - uint32_t aicCoreNum, - uint32_t aivCoreNum, - const char* socVersion, - const aclTensor* metaData) { - if (CheckSingleParamSmla(batchSize, - maxSeqlenQ, - maxSeqlenOriKv, - maxSeqlenCmpKv, - numHeadsQ, - numHeadsKv, - headDim, - oriTopk, - cmpTopk, - cmpRatio, - oriMaskMode, - cmpMaskMode, - oriWinLeft, - oriWinRight, - layoutQOptional, - layoutKvOptional, - hasOriKv, - hasCmpKv, - aicCoreNum, - aivCoreNum, - socVersion) == ACLNN_SUCCESS && - CheckExistenceSmla(cuSeqlensQOptional, - cuSeqlensOriKvOptional, - cuSeqlensCmpKvOptional, - sequsedOriKvOptional, - sequsedCmpKvOptional, - cmpResidualKvOptional, - oriTopkLengthOptional, - cmpTopkLengthOptional, - oriTopk, - cmpTopk, - cmpRatio, - oriMaskMode, - cmpMaskMode, - hasOriKv, - hasCmpKv, - layoutQOptional, - layoutKvOptional, - socVersion, - metaData) == ACLNN_SUCCESS && - CheckConsistencySmla(cuSeqlensQOptional, - cuSeqlensOriKvOptional, - cuSeqlensCmpKvOptional, - sequsedQOptional, - sequsedOriKvOptional, - sequsedCmpKvOptional, - cmpResidualKvOptional, - oriTopkLengthOptional, - cmpTopkLengthOptional, - batchSize, - layoutQOptional, - layoutKvOptional, - hasOriKv, - hasCmpKv, - oriTopk, - cmpTopk, - oriMaskMode, - cmpMaskMode, - maxSeqlenQ, - numHeadsKv, - socVersion, - metaData) == ACLNN_SUCCESS) { - return ACLNN_SUCCESS; - } else { - return ACLNN_ERR_PARAM_INVALID; - } -} -} // namespace - -#ifdef __cplusplus -} -#endif diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/sparse_flash_mla_metadata_infershape.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/sparse_flash_mla_metadata_infershape.cpp deleted file mode 100644 index e8d3bbb5aa..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_host/sparse_flash_mla_metadata_infershape.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file sparse_flash_mla_metadata_infershape.cpp - * \brief - */ -#include "register/op_impl_registry.h" -#include "sparse_flash_mla/op_kernel/sparse_flash_mla_kernel_metadata.h" - -using namespace ge; - -namespace ops { -static ge::graphStatus InferShapeSparseFlashMlaMetadata( - gert::InferShapeContext* context) { - gert::Shape* oShape = context->GetOutputShape(0); - // output shape (SMLA_METADATA_T, ) - oShape->SetDimNum(1); - oShape->SetDim(0, optiling::SMLA_METADATA_TOTAL_SIZE); - return GRAPH_SUCCESS; -} - -static ge::graphStatus InferDtypeSparseFlashMlaMetadata( - gert::InferDataTypeContext* context) { - context->SetOutputDataType(0, DT_INT32); - return GRAPH_SUCCESS; -} - -IMPL_OP_INFERSHAPE(XllmKernelSparseFlashMlaMetadata) - .InferShape(InferShapeSparseFlashMlaMetadata) - .InferDataType(InferDtypeSparseFlashMlaMetadata); -} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.cpp deleted file mode 100644 index 9a7cb84b45..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.cpp +++ /dev/null @@ -1,1954 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file sparse_flash_mla_metadata_aicpu.cpp - * \brief - */ - -#include "sparse_flash_mla_metadata_aicpu.h" - -#include -#include - -#include "log.h" - -using namespace optiling; - -namespace aicpu::xllm_sparse_mla { -uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::Compute( - CpuKernelContext& ctx) { - bool success = Prepare(ctx); - if (!success) { - return KERNEL_STATUS_PARAM_INVALID; - } - SplitResult splitRes{aicCoreNum_, aivCoreNum_}; - success = BalanceSchedule(splitRes) && GenMetadata(splitRes); - return success ? KERNEL_STATUS_OK : KERNEL_STATUS_PARAM_INVALID; -} - -bool XllmKernelSparseFlashMlaMetadataCpuKernel::Prepare(CpuKernelContext& ctx) { - // input - cuSeqlensQ_ = ctx.Input(static_cast(ParamId::cuSeqlensQ)); - cuSeqlensOriKv_ = ctx.Input(static_cast(ParamId::cuSeqlensOriKv)); - cuSeqlensCmpKv_ = ctx.Input(static_cast(ParamId::cuSeqlensCmpKv)); - sequsedQ_ = ctx.Input(static_cast(ParamId::sequsedQ)); - sequsedOriKv_ = ctx.Input(static_cast(ParamId::sequsedOriKv)); - sequsedCmpKv_ = ctx.Input(static_cast(ParamId::sequsedCmpKv)); - cmpResidualKv_ = ctx.Input(static_cast(ParamId::cmpResidualKv)); - oriTopkLength_ = ctx.Input(static_cast(ParamId::oriTopkLength)); - cmpTopkLength_ = ctx.Input(static_cast(ParamId::cmpTopkLength)); - hasOriTopkLength_ = - (oriTopkLength_ != nullptr && oriTopkLength_->GetData() != nullptr && - oriTopkLength_->NumElements() > 0); - // output - metadata_ = ctx.Output(static_cast(ParamId::metaData)); - - bool requiredAttrs = GetAttrValue(ctx, "num_heads_q", numHeadsQ_) && - GetAttrValue(ctx, "num_heads_kv", numHeadsKv_) && - GetAttrValue(ctx, "head_dim", headDim_); - if (!requiredAttrs) { - return false; - } - - // attributes optional - GetAttrValueOpt(ctx, "soc_version", socVersion_); - GetAttrValueOpt(ctx, "aic_core_num", aicCoreNum_); - GetAttrValueOpt(ctx, "aiv_core_num", aivCoreNum_); - GetAttrValueOpt(ctx, "batch_size", batchSize_); - GetAttrValueOpt(ctx, "max_seqlen_q", maxSeqlenQ_); - GetAttrValueOpt(ctx, "max_seqlen_ori_kv", maxSeqlenOriKv_); - GetAttrValueOpt(ctx, "max_seqlen_cmp_kv", maxSeqlenCmpKv_); - GetAttrValueOpt(ctx, "ori_topk", oriTopK_); - GetAttrValueOpt(ctx, "cmp_topk", cmpTopK_); - GetAttrValueOpt(ctx, "cmp_ratio", cmpRatio_); - GetAttrValueOpt(ctx, "ori_mask_mode", oriMaskMode_); - GetAttrValueOpt(ctx, "cmp_mask_mode", cmpMaskMode_); - GetAttrValueOpt(ctx, "ori_win_left", oriWinLeft_); - GetAttrValueOpt(ctx, "ori_win_right", oriWinRight_); - GetAttrValueOpt(ctx, "layout_q", layoutQ_); - GetAttrValueOpt(ctx, "layout_kv", layoutKv_); - GetAttrValueOpt(ctx, "has_ori_kv", hasOriKv_); - GetAttrValueOpt(ctx, "has_cmp_kv", hasCmpKv_); - GetAttrValueOpt(ctx, "is_batch_consistency", isBatchConsistency_); - return (ParamsCheck() && ParamsInit()); -} - -bool XllmKernelSparseFlashMlaMetadataCpuKernel::ParamsCheck() { - // 校验输出 metadata 是否为空 - if (metadata_ == nullptr) { - KERNEL_LOG_ERROR("Output metadata is nullptr"); - return false; - } else if (metadata_->GetData() == nullptr) { - KERNEL_LOG_ERROR("Output metadata data is nullptr"); - return false; - } - int32_t batchSize = GetQueryBatchSize(); - // 校验 cu_seqlens_q 元素 - if (layoutQ_ == "TND") { - if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { - const int32_t* cuSeqlensQPtr = - static_cast(cuSeqlensQ_->GetData()); - // 校验 cu_seqlens_q 首元素为 0 - if (cuSeqlensQPtr[0] != 0) { - KERNEL_LOG_ERROR( - "The first element of cu_seqlens_q should be 0, but got %d", - cuSeqlensQPtr[0]); - return false; - } - for (int i = 0; i < batchSize + 1; i++) { - // 校验 cu_seqlens_q 元素递增 - if (i > 0 && cuSeqlensQPtr[i - 1] > cuSeqlensQPtr[i]) { - KERNEL_LOG_ERROR( - "The elements in cu_seqlens_q must be in ascending order, " - "but got cu_seqlens_q[%d] = %d, cu_seqlens_q[%d] = %d", - i - 1, - cuSeqlensQPtr[i - 1], - i, - cuSeqlensQPtr[i]); - return false; - } - } - } - } - // 校验 seqused_q 元素 - if (sequsedQ_ != nullptr && sequsedQ_->GetData() != nullptr) { - const int32_t* sequsedQPtr = - static_cast(sequsedQ_->GetData()); - const int32_t* cuSeqlensQPtr = - (layoutQ_ == "TND" && cuSeqlensQ_ != nullptr && - cuSeqlensQ_->GetData() != nullptr) - ? static_cast(cuSeqlensQ_->GetData()) - : nullptr; - for (int i = 0; i < batchSize; i++) { - // 校验 seqused_q 元素非负 - if (sequsedQPtr[i] < 0) { - KERNEL_LOG_ERROR( - "The elements in seqused_q should be >= 0, but got seqused_q[%d] = " - "%d", - i, - sequsedQPtr[i]); - return false; - } - // 校验 seqused_q 元素不大于 max_seqlen_q (BSND) 或 cu_seqlens_q 序列长度 - // (TND) - if (layoutQ_ == "BSND" && sequsedQPtr[i] > maxSeqlenQ_) { - KERNEL_LOG_ERROR( - "The elements in seqused_q should not be greater than max_seqlen_q " - "%d, " - "but got seqused_q[%d] = %d", - maxSeqlenQ_, - i, - sequsedQPtr[i]); - return false; - } - if (cuSeqlensQPtr != nullptr) { - int32_t seqLen = cuSeqlensQPtr[i + 1] - cuSeqlensQPtr[i]; - if (sequsedQPtr[i] > seqLen) { - KERNEL_LOG_ERROR( - "The elements in seqused_q should not be greater than the " - "sequence length " - "from cu_seqlens_q %d, but got seqused_q[%d] = %d", - seqLen, - i, - sequsedQPtr[i]); - return false; - } - } - } - } - if (hasOriKv_) { - // 校验 cu_seqlens_ori_kv 元素 - if (layoutKv_ == "TND") { - if (cuSeqlensOriKv_ != nullptr && cuSeqlensOriKv_->GetData() != nullptr) { - const int32_t* cuSeqlensOriKvPtr = - static_cast(cuSeqlensOriKv_->GetData()); - // 校验 cu_seqlens_ori_kv 首元素为 0 - if (cuSeqlensOriKvPtr[0] != 0) { - KERNEL_LOG_ERROR( - "The first element of cu_seqlens_ori_kv should be 0, but got %d", - cuSeqlensOriKvPtr[0]); - return false; - } - for (int i = 0; i < batchSize + 1; i++) { - // 校验 cu_seqlens_ori_kv 元素递增 - if (i > 0 && cuSeqlensOriKvPtr[i - 1] > cuSeqlensOriKvPtr[i]) { - KERNEL_LOG_ERROR( - "The elements in cu_seqlens_ori_kv must be in ascending order, " - "but got cu_seqlens_ori_kv[%d] = %d, cu_seqlens_ori_kv[%d] = " - "%d", - i - 1, - cuSeqlensOriKvPtr[i - 1], - i, - cuSeqlensOriKvPtr[i]); - return false; - } - } - } - } - // 校验 seqused_ori_kv 元素 - if (sequsedOriKv_ != nullptr && sequsedOriKv_->GetData() != nullptr) { - const int32_t* sequsedOriKvPtr = - static_cast(sequsedOriKv_->GetData()); - const int32_t* cuSeqlensOriKvPtr = - (layoutKv_ == "TND" && cuSeqlensOriKv_ != nullptr && - cuSeqlensOriKv_->GetData() != nullptr) - ? static_cast(cuSeqlensOriKv_->GetData()) - : nullptr; - for (int i = 0; i < batchSize; i++) { - // 校验 seqused_ori_kv 元素非负 - if (sequsedOriKvPtr[i] < 0) { - KERNEL_LOG_ERROR( - "The elements in seqused_ori_kv should be >= 0, but got " - "seqused_ori_kv[%d] = %d", - i, - sequsedOriKvPtr[i]); - return false; - } - // 校验 seqused_ori_kv 元素不大于 max_seqlen_ori_kv (BSND) 或 - // cu_seqlens_ori_kv 序列长度 (TND) - if (layoutKv_ == "BSND" && sequsedOriKvPtr[i] > maxSeqlenOriKv_) { - KERNEL_LOG_ERROR( - "The elements in seqused_ori_kv should not be greater than " - "max_seqlen_ori_kv %d, but got seqused_ori_kv[%d] = %d", - maxSeqlenOriKv_, - i, - sequsedOriKvPtr[i]); - return false; - } - if (cuSeqlensOriKvPtr != nullptr) { - int32_t seqLen = cuSeqlensOriKvPtr[i + 1] - cuSeqlensOriKvPtr[i]; - if (sequsedOriKvPtr[i] > seqLen) { - KERNEL_LOG_ERROR( - "The elements in seqused_ori_kv should not be greater than the " - "sequence " - "length from cu_seqlens_ori_kv %d, but got seqused_ori_kv[%d] " - "= %d", - seqLen, - i, - sequsedOriKvPtr[i]); - return false; - } - } - } - } - // 校验 ori_topk_length 元素 - if (oriTopK_ != 0 && - oriMaskMode_ == static_cast(SparseMode::DEFAULT_MASK) && - oriTopkLength_ != nullptr && oriTopkLength_->GetData() != nullptr) { - // 校验 ori_topk_length 元素数量 - int32_t sumOfQuerySeq = GetSumOfQuerySeq(); - const int32_t* oriTopkLengthPtr = - static_cast(oriTopkLength_->GetData()); - auto oriTopkLengthShape = oriTopkLength_->GetTensorShape(); - int32_t oriTopkLengthSize = layoutQ_ == "TND" - ? oriTopkLengthShape->GetDimSize(0) * - oriTopkLengthShape->GetDimSize(1) - : oriTopkLengthShape->GetDimSize(0) * - oriTopkLengthShape->GetDimSize(1) * - oriTopkLengthShape->GetDimSize(2); - if (oriTopkLengthSize < sumOfQuerySeq) { - KERNEL_LOG_ERROR( - "The size of ori_topk_length %d should not be smaller than " - "the sum of query sequence %d!", - oriTopkLengthSize, - sumOfQuerySeq); - return false; - } - // 校验 ori_topk_length 元素非负 - for (int i = 0; i < oriTopkLengthSize; i++) { - if (oriTopkLengthPtr[i] < 0) { - KERNEL_LOG_ERROR( - "The elements in ori_topk_length should be >= 0, but got " - "ori_topk_length[%d] = %d", - i, - oriTopkLengthPtr[i]); - return false; - } - } - } - } - if (hasCmpKv_) { - if (layoutKv_ == "TND") { - // 校验 cu_seqlens_cmp_kv 元素 - if (cuSeqlensCmpKv_ != nullptr && cuSeqlensCmpKv_->GetData() != nullptr) { - const int32_t* cuSeqlensCmpKvPtr = - static_cast(cuSeqlensCmpKv_->GetData()); - // 校验 cu_seqlens_cmp_kv 首元素为 0 - if (cuSeqlensCmpKvPtr[0] != 0) { - KERNEL_LOG_ERROR( - "The first element of cu_seqlens_cmp_kv should be 0, but got %d", - cuSeqlensCmpKvPtr[0]); - return false; - } - for (int i = 0; i < batchSize + 1; i++) { - // 校验 cu_seqlens_cmp_kv 元素递增 - if (i > 0 && cuSeqlensCmpKvPtr[i - 1] > cuSeqlensCmpKvPtr[i]) { - KERNEL_LOG_ERROR( - "The elements in cu_seqlens_cmp_kv must be in ascending order, " - "but got cu_seqlens_cmp_kv[%d] = %d, cu_seqlens_cmp_kv[%d] = " - "%d", - i - 1, - cuSeqlensCmpKvPtr[i - 1], - i, - cuSeqlensCmpKvPtr[i]); - return false; - } - } - } - } - // 校验 seqused_cmp_kv 元素 - if (sequsedCmpKv_ != nullptr && sequsedCmpKv_->GetData() != nullptr) { - const int32_t* sequsedCmpKvPtr = - static_cast(sequsedCmpKv_->GetData()); - const int32_t* cuSeqlensCmpKvPtr = - (layoutKv_ == "TND" && cuSeqlensCmpKv_ != nullptr && - cuSeqlensCmpKv_->GetData() != nullptr) - ? static_cast(cuSeqlensCmpKv_->GetData()) - : nullptr; - for (int i = 0; i < batchSize; i++) { - // 校验 seqused_cmp_kv 元素非负 - if (sequsedCmpKvPtr[i] < 0) { - KERNEL_LOG_ERROR( - "The elements in seqused_cmp_kv should be >= 0, but got " - "seqused_cmp_kv[%d] = %d", - i, - sequsedCmpKvPtr[i]); - return false; - } - // 校验 seqused_cmp_kv 元素不大于 max_seqlen_cmp_kv (BSND) 或 - // cu_seqlens_cmp_kv 序列长度 (TND) - if (layoutKv_ == "BSND" && sequsedCmpKvPtr[i] > maxSeqlenCmpKv_) { - KERNEL_LOG_ERROR( - "The elements in seqused_cmp_kv should not be greater than " - "max_seqlen_cmp_kv %d, but got seqused_cmp_kv[%d] = %d", - maxSeqlenCmpKv_, - i, - sequsedCmpKvPtr[i]); - return false; - } - if (cuSeqlensCmpKvPtr != nullptr) { - int32_t seqLen = cuSeqlensCmpKvPtr[i + 1] - cuSeqlensCmpKvPtr[i]; - if (sequsedCmpKvPtr[i] > seqLen) { - KERNEL_LOG_ERROR( - "The elements in seqused_cmp_kv should not be greater than the " - "sequence " - "length from cu_seqlens_cmp_kv %d, but got seqused_cmp_kv[%d] " - "= %d", - seqLen, - i, - sequsedCmpKvPtr[i]); - return false; - } - } - } - } - // 校验 cmp_residual_kv 元素 - if (cmpResidualKv_ != nullptr && cmpResidualKv_->GetData() != nullptr) { - const int32_t* cmpResidualKvPtr = - static_cast(cmpResidualKv_->GetData()); - for (int i = 0; i < batchSize; i++) { - if (cmpResidualKvPtr[i] < 0 || cmpResidualKvPtr[i] >= cmpRatio_) { - KERNEL_LOG_ERROR( - "The elements in cmp_residual_kv should be in [0, " - "cmpRatio_(%d)), but got " - "cmp_residual_kv[%d] = %d", - cmpRatio_, - i, - cmpResidualKvPtr[i]); - return false; - } - } - } - // 校验 cmp_topk_length 元素 - if (cmpTopK_ != 0 && - cmpMaskMode_ == static_cast(SparseMode::DEFAULT_MASK) && - cmpTopkLength_ != nullptr && cmpTopkLength_->GetData() != nullptr) { - // 校验 cmp_topk_length 元素数量 - int32_t sumOfQuerySeq = GetSumOfQuerySeq(); - const int32_t* cmpTopkLengthPtr = - static_cast(cmpTopkLength_->GetData()); - auto cmpTopkLengthShape = cmpTopkLength_->GetTensorShape(); - int32_t cmpTopkLengthSize = layoutQ_ == "TND" - ? cmpTopkLengthShape->GetDimSize(0) * - cmpTopkLengthShape->GetDimSize(1) - : cmpTopkLengthShape->GetDimSize(0) * - cmpTopkLengthShape->GetDimSize(1) * - cmpTopkLengthShape->GetDimSize(2); - if (cmpTopkLengthSize < sumOfQuerySeq) { - KERNEL_LOG_ERROR( - "The size of cmp_topk_length %d should not be smaller than " - "the sum of query sequence %d!", - cmpTopkLengthSize, - sumOfQuerySeq); - return false; - } - // 校验 cmp_topk_length 元素非负 - for (int i = 0; i < cmpTopkLengthSize; i++) { - if (cmpTopkLengthPtr[i] < 0) { - KERNEL_LOG_ERROR( - "The elements in cmp_topk_length should be >= 0, but got " - "cmp_topk_length[%d] = %d", - i, - cmpTopkLengthPtr[i]); - return false; - } - } - } - } - return true; -} - -int32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetSumOfQuerySeq() { - int32_t batchSize = GetQueryBatchSize(); - // 如果sequsedQ_ 传了,使用sequsedQ_获取 BsSize - if (sequsedQ_ != nullptr && sequsedQ_->GetData() != nullptr) { - if (sequsedQ_->GetTensorShape() != nullptr) { - const int32_t* seqUsedPtr = - static_cast(sequsedQ_->GetData()); - int32_t queryBsSize = 0; - for (int i = 0; i < batchSize; i++) { - queryBsSize += seqUsedPtr[i]; - } - return queryBsSize; - } - } - // sequsedQ_ 没传,判断 Layout - if (layoutQ_ == "TND") { - // 如果是 TND,尝试使用 cuSeqlensQ_获取 BsSize - if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { - if (cuSeqlensQ_->GetTensorShape() != nullptr) { - const int32_t* s1Ptr = - static_cast(cuSeqlensQ_->GetData()); - return s1Ptr[batchSize]; - } - } - } - // 如果不是 TND,或者 cuSeqlensQ_ 为空,使用shape信息计算 BsSize - return batchSize_ * maxSeqlenQ_; -} - -int32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetQueryBatchSize() { - // 1. 如果sequsedQ_ 传了,使用sequsedQ_获取BatchSize - if (sequsedQ_ != nullptr && sequsedQ_->GetData() != nullptr) { - if (sequsedQ_->GetTensorShape() != nullptr) { - return sequsedQ_->GetTensorShape()->GetDimSize(0); - } - } - // 2. sequsedQ_ 没传,判断 Layout - if (layoutQ_ == "TND") { - // 如果是 TND,尝试使用 cuSeqlensQ_获取BatchSize - if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { - if (cuSeqlensQ_->GetTensorShape() != nullptr) { - return cuSeqlensQ_->GetTensorShape()->GetDimSize(0) - 1; - } - } - } - // 3. 如果不是 TND,或者 cuSeqlensQ_ 为空,使用batchSize_ - return batchSize_; -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcOriMaskMode() { - if (oriMaskMode_ == static_cast(SparseMode::DEFAULT_MASK)) { - oriPreToken_ = INT64_MAX; - oriNextToken_ = INT64_MAX; - oriAttentionMode_ = NO_MASK; - } else if (oriMaskMode_ == - static_cast(SparseMode::RIGHT_DOWN_CAUSAL)) { - oriPreToken_ = INT64_MAX; - oriNextToken_ = 0; - oriAttentionMode_ = HAS_MASK; - } else { // SparseMode = 4 - oriPreToken_ = (oriWinLeft_ > -1) ? oriWinLeft_ : INT64_MAX; - oriNextToken_ = (oriWinRight_ > -1) ? oriWinRight_ : INT64_MAX; - oriAttentionMode_ = HAS_MASK; - } -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcCmpMaskMode() { - if (cmpMaskMode_ == static_cast(SparseMode::DEFAULT_MASK)) { - cmpPreToken_ = INT64_MAX; - cmpNextToken_ = INT64_MAX; - cmpAttentionMode_ = NO_MASK; - } else if (cmpMaskMode_ == - static_cast(SparseMode::RIGHT_DOWN_CAUSAL)) { - cmpPreToken_ = INT64_MAX; - cmpNextToken_ = 0; - cmpAttentionMode_ = HAS_MASK; - } else { // SparseMode = 4 - cmpPreToken_ = (oriWinLeft_ > -1) ? oriWinLeft_ : INT64_MAX; - cmpNextToken_ = (oriWinRight_ > -1) ? oriWinRight_ : INT64_MAX; - cmpAttentionMode_ = HAS_MASK; - } -} - -ValidSocVersion XllmKernelSparseFlashMlaMetadataCpuKernel::ProcessSocVersion() { - const std::string ascend960Dt = "Ascend960DT"; - const std::string ascend960Pr = "Ascend960PR"; - const std::string ascend950 = "Ascend950"; - if (socVersion_.find(ascend960Dt) != std::string::npos || - socVersion_.find(ascend960Pr) != std::string::npos) { - return ValidSocVersion::ASCEND960; - } else if (socVersion_.find(ascend950) != std::string::npos) { - return ValidSocVersion::ASCEND950; - } else { - return ValidSocVersion::ASCEND910; - } -} - -bool XllmKernelSparseFlashMlaMetadataCpuKernel::ParamsInit() { - batchSize_ = GetQueryBatchSize(); - CalcOriMaskMode(); - CalcCmpMaskMode(); - isS1G_ = (layoutQ_ == "BSND" || layoutQ_ == "BSH" || layoutQ_ == "TND"); - if (numHeadsKv_ == 0) { - KERNEL_LOG_ERROR("num_heads_kv should not be 0."); - return false; - } - ValidSocVersion validSocVersion = ProcessSocVersion(); - groupSize_ = numHeadsQ_ / numHeadsKv_; - if (hasOriKv_ && oriTopK_ != 0) { - isSparseOriKv_ = true; - } - if (hasCmpKv_ && cmpTopK_ != 0) { - isSparseCmpKv_ = true; - } - if (isBatchConsistency_) { - supportFd_ = true; - } - if (validSocVersion == ValidSocVersion::ASCEND910) { - if (isSparseOriKv_ && !isSparseCmpKv_) { - mBaseSize_ = groupSize_; - } else { - mBaseSize_ = - isSparseCmpKv_ ? groupSize_ : (256U / groupSize_) * groupSize_; - } - s2BaseSize_ = 512U; - } else if (validSocVersion == ValidSocVersion::ASCEND950 || - validSocVersion == ValidSocVersion::ASCEND960) { - if (groupSize_ > 64U) { - isSplitG_ = true; - aicCoreNum_ /= NUM_2; - } - mBaseSize_ = groupSize_; - s2BaseSize_ = 128U; - } else { - mBaseSize_ = groupSize_; - s2BaseSize_ = 128U; - } - return true; -} - -uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetS1Idx(uint32_t s1Size, - uint32_t s1GIdx) { - uint32_t s1GToken = s1GIdx * mBaseSize_; - uint32_t s1Idx = 0; - if (isS1G_) { - s1Idx = s1GToken / static_cast(groupSize_); - } else { - s1Idx = s1GToken % static_cast(s1Size); - } - return s1Idx; -} - -uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetBsStride( - uint32_t bIdx, - uint32_t s1Idx) { - uint32_t bsStride = 0; - if (layoutQ_ == "TND") { - if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { - const int32_t* s1Ptr = - static_cast(cuSeqlensQ_->GetData()); - bsStride = s1Ptr[bIdx] + s1Idx; - return bsStride; - } - } - bsStride = bIdx * static_cast(maxSeqlenQ_) + s1Idx; - return bsStride; -} - -uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetOriTopkLength( - uint32_t bsStride) { - // 尝试使用 oriTopkLength_ - if (oriTopK_ != 0 && - oriMaskMode_ == static_cast(SparseMode::DEFAULT_MASK) && - oriTopkLength_ != nullptr && oriTopkLength_->GetData() != nullptr) { - const int32_t* oriTopkPtr = - static_cast(oriTopkLength_->GetData()); - // 规划 FA/FD - // 任务时,将有效稀疏长度限制到索引宽度,与内核的计算范围保持一致。 - return std::min(static_cast(oriTopkPtr[bsStride]), - static_cast(oriTopK_)); - } - // 如果不是 DEFAULT_MASK,使用 oriTopK_ - return static_cast(oriTopK_); -} - -uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::ReadOriTopkLengthAtRow( - uint32_t bIdx, - uint32_t s1Idx) const { - if (!hasOriTopkLength_) { - return static_cast(oriTopK_); - } - const int32_t* topkLenPtr = - static_cast(oriTopkLength_->GetData()); - if (layoutQ_ == "TND") { - uint32_t tIdx = s1Idx; - if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { - const int32_t* cuPtr = - static_cast(cuSeqlensQ_->GetData()); - tIdx = static_cast(cuPtr[bIdx]) + s1Idx; - } else { - tIdx = bIdx * static_cast(maxSeqlenQ_) + s1Idx; - } - return static_cast( - topkLenPtr[tIdx * static_cast(numHeadsKv_)]); - } - return static_cast( - topkLenPtr[(static_cast(bIdx) * - static_cast(maxSeqlenQ_) + - s1Idx) * - static_cast(numHeadsKv_)]); -} - -uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetOriTopkLength( - uint32_t s1GIdx, - const BatchCache& batchCache) const { - if (!hasOriTopkLength_) { - return static_cast(oriTopK_); - } - int64_t s1GFirstToken = - static_cast(s1GIdx) * static_cast(mBaseSize_); - int64_t s1GLastToken = - std::min(s1GFirstToken + static_cast(mBaseSize_), - static_cast(batchCache.s1Size) * - static_cast(groupSize_)) - - 1; - int64_t s1First = s1GFirstToken / static_cast(groupSize_); - int64_t s1Last = s1GLastToken / static_cast(groupSize_); - uint32_t maxLen = 0U; - for (int64_t s1Idx = s1First; s1Idx <= s1Last; ++s1Idx) { - maxLen = std::max( - maxLen, - ReadOriTopkLengthAtRow(batchCache.bIdx, static_cast(s1Idx))); - } - return std::min(maxLen, static_cast(oriTopK_)); -} - -uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetCmpTopkLength( - uint32_t bsStride) { - // 尝试使用 cmpTopkLength_ - if (cmpTopK_ != 0 && - cmpMaskMode_ == static_cast(SparseMode::DEFAULT_MASK) && - cmpTopkLength_ != nullptr && cmpTopkLength_->GetData() != nullptr) { - const int32_t* cmpTopkPtr = - static_cast(cmpTopkLength_->GetData()); - // 规划 FA/FD - // 任务时,将有效稀疏长度限制到索引宽度,与内核的计算范围保持一致。 - return std::min(static_cast(cmpTopkPtr[bsStride]), - static_cast(cmpTopK_)); - } - // 如果不是 DEFAULT_MASK,使用 cmpTopK_ - return static_cast(cmpTopK_); -} - -uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetS1SeqSize( - uint32_t bIdx) { - // 1. 如果 sequsedQ_ 传了,直接使用 - if (sequsedQ_ != nullptr && sequsedQ_->GetData() != nullptr) { - const int32_t* seqUsedPtr = - static_cast(sequsedQ_->GetData()); - return static_cast(seqUsedPtr[bIdx]); - } - // 2. sequsedQ_ 没传,判断 Layout - if (layoutQ_ == "TND") { - // 如果是 TND,尝试使用 cuSeqlensQ_ - if (cuSeqlensQ_ != nullptr && cuSeqlensQ_->GetData() != nullptr) { - const int32_t* s1Ptr = - static_cast(cuSeqlensQ_->GetData()); - return static_cast(s1Ptr[bIdx + 1U] - s1Ptr[bIdx]); - } - } - // 3. 如果不是 TND,或者 cuSeqlensQ_ 为空,使用 maxSeqlenQ_ - return static_cast(maxSeqlenQ_); -} - -uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetOriS2SeqSize( - uint32_t bIdx) { - // 如果 sequsedOriKv_ 传了,直接使用 - if (sequsedOriKv_ != nullptr && sequsedOriKv_->GetData() != nullptr) { - const int32_t* seqUsedPtr = - static_cast(sequsedOriKv_->GetData()); - return static_cast(seqUsedPtr[bIdx]); - } - // sequsedOriKv_ 没传,判断 Layout - if (layoutKv_ == "TND") { - // 如果是 TND,尝试使用 cuSeqlensOriKv_ - if (cuSeqlensOriKv_ != nullptr && cuSeqlensOriKv_->GetData() != nullptr) { - const int32_t* s2Ptr = - static_cast(cuSeqlensOriKv_->GetData()); - return static_cast(s2Ptr[bIdx + 1U] - s2Ptr[bIdx]); - } - } - // 如果是PA场景,或 max_seqlen_ori_kv 没传入,且 ori_kv 为稀疏的,则尝试从 - // topk 中获取 - if ((layoutKv_ == "PA_BBND" || maxSeqlenOriKv_ == 0) && isSparseOriKv_) { - return UINT32_MAX; - } - // 使用 max_seqlen_ori_kv - return static_cast(maxSeqlenOriKv_); -} - -uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetCmpS2SeqSize( - uint32_t bIdx) { - // 如果 sequsedCmpKv_ 传了,直接使用 - if (sequsedCmpKv_ != nullptr && sequsedCmpKv_->GetData() != nullptr) { - const int32_t* seqUsedPtr = - static_cast(sequsedCmpKv_->GetData()); - return static_cast(seqUsedPtr[bIdx]); - } - // sequsedCmpKv_ 没传,判断 Layout - if (layoutKv_ == "TND") { - // 如果是 TND,尝试使用 cuSeqlensCmpKv_ - if (cuSeqlensCmpKv_ != nullptr && cuSeqlensCmpKv_->GetData() != nullptr) { - const int32_t* s2Ptr = - static_cast(cuSeqlensCmpKv_->GetData()); - return static_cast(s2Ptr[bIdx + 1U] - s2Ptr[bIdx]); - } - } - // 如果是PA场景,或 max_seqlen_cmp_kv 没传入,且 cmp_kv - // 为稀疏的,则尝试从topk中获取 - if ((layoutKv_ == "PA_BBND" || maxSeqlenCmpKv_ == 0) && isSparseCmpKv_) { - return UINT32_MAX; - } - // 使用 max_seqlen_cmp_kv - return static_cast(maxSeqlenCmpKv_); -} - -uint64_t XllmKernelSparseFlashMlaMetadataCpuKernel::GetRevertS2Size( - uint32_t bIdx) { - uint32_t cmpS2Size = GetCmpS2SeqSize(bIdx); - if (cmpResidualKv_ != nullptr && cmpResidualKv_->GetData() != nullptr) { - const int32_t* residualPtr = - static_cast(cmpResidualKv_->GetData()); - return static_cast(cmpS2Size) * static_cast(cmpRatio_) + - residualPtr[bIdx]; - } else { - return static_cast(cmpS2Size) * static_cast(cmpRatio_); - } -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcSplitInfo( - SplitContext& splitContext) { - // 计算每个batch的切分,统计是否为空batch,记录最后有效batch(每个batch的每个N2切分是一样的) - SplitInfo& splitInfo = splitContext.splitInfo; - for (uint32_t bIdx = 0; bIdx < batchSize_; bIdx++) { - uint32_t s1Size = GetS1SeqSize(bIdx); - splitInfo.s1GBaseNum[bIdx] = - (static_cast(s1Size) * groupSize_ + (mBaseSize_ - 1U)) / - mBaseSize_; - splitInfo.s1GTailSize[bIdx] = - (static_cast(s1Size) * groupSize_) % mBaseSize_; - if (hasOriKv_) { - uint32_t curOriS2Size = GetOriS2SeqSize(bIdx); - splitInfo.oriS2BaseNum[bIdx] = - (static_cast(curOriS2Size) + s2BaseSize_ - 1U) / - s2BaseSize_; - } - if (hasCmpKv_) { - uint32_t curCmpS2Size = GetCmpS2SeqSize(bIdx); - splitInfo.cmpS2BaseNum[bIdx] = - (static_cast(curCmpS2Size) + s2BaseSize_ - 1U) / - s2BaseSize_; - } - if (splitInfo.s1GBaseNum[bIdx] != 0U && - (splitInfo.oriS2BaseNum[bIdx] != 0U || - splitInfo.cmpS2BaseNum[bIdx] != 0U)) { - splitInfo.isKvSeqAllZero = false; - } - } -} - -int64_t XllmKernelSparseFlashMlaMetadataCpuKernel::CalcOriPreTokenLeftUp( - uint32_t s1Size, - uint32_t s2Size) { - auto mode = static_cast(oriMaskMode_); - if (mode == SparseMode::BAND) { - return oriPreToken_ == INT64_MAX - ? INT64_MAX - : static_cast(s1Size) - static_cast(s2Size) + - oriPreToken_; - } - return oriPreToken_; -} - -int64_t XllmKernelSparseFlashMlaMetadataCpuKernel::CalcOriNextTokenLeftUp( - uint32_t s1Size, - uint32_t s2Size) { - auto mode = static_cast(oriMaskMode_); - switch (mode) { - case SparseMode::DEFAULT_MASK: - case SparseMode::ALL_MASK: - case SparseMode::LEFT_UP_CAUSAL: - return oriNextToken_; - case SparseMode::RIGHT_DOWN_CAUSAL: - return static_cast(s2Size) - static_cast(s1Size); - case SparseMode::BAND: - return oriNextToken_ == INT64_MAX - ? INT64_MAX - : static_cast(s2Size) - static_cast(s1Size) + - oriNextToken_; - default: - return oriNextToken_; - } -} - -int64_t XllmKernelSparseFlashMlaMetadataCpuKernel::CalcCmpPreTokenLeftUp( - uint32_t s1Size, - uint64_t s2Size) { - auto mode = static_cast(cmpMaskMode_); - if (mode == SparseMode::BAND) { - return cmpPreToken_ == INT64_MAX - ? INT64_MAX - : static_cast(s1Size) - static_cast(s2Size) + - cmpPreToken_; - } - return cmpPreToken_; -} - -int64_t XllmKernelSparseFlashMlaMetadataCpuKernel::CalcCmpNextTokenLeftUp( - uint32_t s1Size, - uint64_t s2Size) { - auto mode = static_cast(cmpMaskMode_); - switch (mode) { - case SparseMode::DEFAULT_MASK: - case SparseMode::ALL_MASK: - case SparseMode::LEFT_UP_CAUSAL: - return cmpNextToken_; - case SparseMode::RIGHT_DOWN_CAUSAL: - return static_cast(s2Size) - static_cast(s1Size); - case SparseMode::BAND: - return cmpNextToken_ == INT64_MAX - ? INT64_MAX - : static_cast(s2Size) - static_cast(s1Size) + - cmpNextToken_; - default: - return cmpNextToken_; - } -} - -int64_t XllmKernelSparseFlashMlaMetadataCpuKernel::OriCalcCost( - uint32_t basicM, - uint32_t basicS2) { - uint32_t oriAlignCoefM = 16U; - uint32_t oriAlignCoefS2 = 64U; - uint32_t oriAlignBasicM = (basicM + oriAlignCoefM - 1U) / oriAlignCoefM; - uint32_t oriAlignBasicS2 = (basicS2 + oriAlignCoefS2 - 1U) / oriAlignCoefS2; - return static_cast(COST_WEIGHT_M * oriAlignBasicM + - COST_WEIGHT_S2 * oriAlignBasicS2); -} - -int64_t XllmKernelSparseFlashMlaMetadataCpuKernel::CmpCalcCost( - uint32_t basicM, - uint32_t basicS2) { - uint32_t cmpAlignCoefM = 16U; - uint32_t cmpAlignCoefS2 = 64U; - uint32_t cmpAlignBasicM = (basicM + cmpAlignCoefM - 1U) / cmpAlignCoefM; - uint32_t cmpAlignBasicS2 = (basicS2 + cmpAlignCoefS2 - 1U) / cmpAlignCoefS2; - return static_cast(COST_WEIGHT_M * cmpAlignBasicM + - COST_WEIGHT_S2 * cmpAlignBasicS2); -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcCostTable( - uint32_t s1GTailSize, - uint32_t reductionBlockSize, - uint32_t oriS2TailSize, - uint32_t cmpS2TailSize) { - uint32_t normalS2Size = isBatchConsistency_ && reductionBlockSize > 0U - ? reductionBlockSize - : s2BaseSize_; - // ori 部分 cost - if (hasOriKv_) { - typeCost_[ORI_NORMAL_BLOCK][ORI_NORMAL_BLOCK] = - OriCalcCost(mBaseSize_, normalS2Size); - typeCost_[ORI_TAIL_BLOCK][ORI_NORMAL_BLOCK] = - (s1GTailSize == 0U) ? 0U : OriCalcCost(s1GTailSize, normalS2Size); - typeCost_[ORI_NORMAL_BLOCK][ORI_TAIL_BLOCK] = - (oriS2TailSize == 0U) ? 0U : OriCalcCost(mBaseSize_, oriS2TailSize); - typeCost_[ORI_TAIL_BLOCK][ORI_TAIL_BLOCK] = - (s1GTailSize == 0U || oriS2TailSize == 0U) - ? 0U - : OriCalcCost(s1GTailSize, oriS2TailSize); - } - // cmp 部分 cost - if (hasCmpKv_) { - typeCost_[CMP_NORMAL_BLOCK][CMP_NORMAL_BLOCK] = - CmpCalcCost(mBaseSize_, normalS2Size); - typeCost_[CMP_TAIL_BLOCK][CMP_NORMAL_BLOCK] = - (s1GTailSize == 0U) ? 0U : CmpCalcCost(s1GTailSize, normalS2Size); - typeCost_[CMP_NORMAL_BLOCK][CMP_TAIL_BLOCK] = - (cmpS2TailSize == 0U) ? 0U : CmpCalcCost(mBaseSize_, cmpS2TailSize); - typeCost_[CMP_TAIL_BLOCK][CMP_TAIL_BLOCK] = - (s1GTailSize == 0U || cmpS2TailSize == 0U) - ? 0U - : CmpCalcCost(s1GTailSize, cmpS2TailSize); - } -} - -Range XllmKernelSparseFlashMlaMetadataCpuKernel::CalcS2TokenRange( - uint32_t s1GIdx, - const BatchCache& batchCache, - bool isCmpKv) { - // actual seq == 0 - if (!isCmpKv) { - if (batchCache.s1Size == 0U || batchCache.oriS2Size == 0U) { - return std::make_pair(0, 0); - } - if (isSparseOriKv_ && !hasCmpKv_) { - uint32_t oriTopkSize = GetOriTopkLength(s1GIdx, batchCache); - if (oriTopkSize == 0U) { - return std::make_pair(0, 0); - } - return std::make_pair(0, static_cast(oriTopkSize) - 1); - } - } else { - if (batchCache.s1Size == 0U || batchCache.cmpRevertS2Size == 0U) { - return std::make_pair(0, 0); - } - } - - // no mask - uint32_t hasMask = 1; - int64_t s2Size = isCmpKv ? static_cast(batchCache.cmpRevertS2Size) - : static_cast(batchCache.oriS2Size); - hasMask = isCmpKv ? cmpAttentionMode_ : oriAttentionMode_; - if (!hasMask) { - return std::make_pair(0, s2Size - 1); - } - - // 1. calc index of s2FirstToken, s2LastToken by index of s1GFirstToken, - // s1GLastToken - int64_t s1GFirstToken = - static_cast(s1GIdx) * static_cast(mBaseSize_); - int64_t s1GLastToken = - std::min(s1GFirstToken + static_cast(mBaseSize_), - static_cast(batchCache.s1Size) * - static_cast(groupSize_)) - - 1; - - int64_t s1FirstToken = 0; - int64_t s1LastToken = 0; - if (isS1G_) { - s1FirstToken = s1GFirstToken / static_cast(groupSize_); - s1LastToken = s1GLastToken / static_cast(groupSize_); - } else { - if (s1GFirstToken / batchCache.s1Size == s1GLastToken / batchCache.s1Size) { - // start and end locate in one G - s1FirstToken = s1GFirstToken % static_cast(batchCache.s1Size); - s1LastToken = s1GLastToken % static_cast(batchCache.s1Size); - } else { - // start and end locate in tow or more G, but working same as crossing a - // complete block - s1FirstToken = 0; - s1LastToken = batchCache.s1Size; - } - } - - int64_t s2FirstToken = 0; - int64_t s2LastToken = 0; - if (!isCmpKv) { - s2FirstToken = s1FirstToken - batchCache.oriPreTokenLeftUp; - s2LastToken = batchCache.oriNextTokenLeftUp == INT64_MAX - ? INT64_MAX - : s1LastToken + batchCache.oriNextTokenLeftUp; - } else { - s2FirstToken = s1FirstToken - batchCache.cmpPreTokenLeftUp; - s2LastToken = batchCache.cmpNextTokenLeftUp == INT64_MAX - ? INT64_MAX - : s1LastToken + batchCache.cmpNextTokenLeftUp; - } - return std::make_pair(s2FirstToken, s2LastToken); -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcBatchCache( - uint32_t bIdx, - const SplitContext& splitContext, - BatchCache& batchCache) { - const SplitInfo& splitInfo = splitContext.splitInfo; - - batchCache.bIdx = bIdx; - batchCache.s1Size = GetS1SeqSize(bIdx); - if (hasOriKv_) { - batchCache.oriS2Size = GetOriS2SeqSize(bIdx); - batchCache.oriPreTokenLeftUp = - CalcOriPreTokenLeftUp(batchCache.s1Size, batchCache.oriS2Size); - batchCache.oriNextTokenLeftUp = - CalcOriNextTokenLeftUp(batchCache.s1Size, batchCache.oriS2Size); - } - if (hasCmpKv_) { - batchCache.cmpRevertS2Size = GetRevertS2Size(bIdx); - batchCache.cmpPreTokenLeftUp = - CalcCmpPreTokenLeftUp(batchCache.s1Size, batchCache.cmpRevertS2Size); - batchCache.cmpNextTokenLeftUp = - CalcCmpNextTokenLeftUp(batchCache.s1Size, batchCache.cmpRevertS2Size); - } -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcOriS1GCache( - S1GCache& s1GCache, - const SplitInfo& splitInfo) { - // 处理 ori 部分 block 信息 - if (s1GCache.oriS2Start >= s1GCache.oriS2End) { - // ori 范围无效, 则整个 s1g 行等效为空行 - s1GCache.oriS1GBlock = 0; - s1GCache.oriS1GCost = 0; - s1GCache.oriS1GLastBlockCost = 0; - s1GCache.oriS1GNormalBlockCost = 0; - } else { - // 计算 ori 方向 Block 数量及 Cost - s1GCache.oriS1GBlock = s1GCache.oriS2End - s1GCache.oriS2Start; - // 判断 ori S2 方向是否包含尾块 - uint32_t curOriTailS2Num = (s1GCache.oriS2TailSize != 0U) ? 1U : 0U; - uint32_t curOriNormalS2Num = s1GCache.oriS1GBlock - curOriTailS2Num; - if (s1GCache.s1GIdx == (splitInfo.s1GBaseNum[s1GCache.bIdx] - 1U) && - splitInfo.s1GTailSize[s1GCache.bIdx] != 0U) { - s1GCache.oriS1GCost = - typeCost_[ORI_TAIL_BLOCK][ORI_NORMAL_BLOCK] * curOriNormalS2Num + - typeCost_[ORI_TAIL_BLOCK][ORI_TAIL_BLOCK] * curOriTailS2Num; - s1GCache.oriS1GLastBlockCost = - curOriTailS2Num > 0U ? typeCost_[ORI_TAIL_BLOCK][ORI_TAIL_BLOCK] - : typeCost_[ORI_TAIL_BLOCK][ORI_NORMAL_BLOCK]; - s1GCache.oriS1GNormalBlockCost = - typeCost_[ORI_TAIL_BLOCK][ORI_NORMAL_BLOCK]; - } else { - s1GCache.oriS1GCost = - typeCost_[ORI_NORMAL_BLOCK][ORI_NORMAL_BLOCK] * curOriNormalS2Num + - typeCost_[ORI_NORMAL_BLOCK][ORI_TAIL_BLOCK] * curOriTailS2Num; - s1GCache.oriS1GLastBlockCost = - curOriTailS2Num > 0U ? typeCost_[ORI_NORMAL_BLOCK][ORI_TAIL_BLOCK] - : typeCost_[ORI_NORMAL_BLOCK][ORI_NORMAL_BLOCK]; - s1GCache.oriS1GNormalBlockCost = - typeCost_[ORI_NORMAL_BLOCK][ORI_NORMAL_BLOCK]; - } - } -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcCmpS1GCache( - S1GCache& s1GCache, - const SplitInfo& splitInfo) { - // 处理cmp部分block信息 - if (s1GCache.cmpS2Start >= s1GCache.cmpS2End) { - // Cmp范围无效, Cost保持为 0 - s1GCache.cmpS1GBlock = 0; - s1GCache.cmpS1GCost = 0; - s1GCache.cmpS1GLastBlockCost = 0; - s1GCache.cmpS1GNormalBlockCost = 0; - } else { - // 计算 cmp 方向 Block 数量及 Cost - s1GCache.cmpS1GBlock = s1GCache.cmpS2End - s1GCache.cmpS2Start; - // 判断 Cmp S2 方向是否包含尾块 - uint32_t curCmpTailS2Num = (s1GCache.cmpS2TailSize != 0U) - ? 1U - : 0U; // Updated check using local var - uint32_t curCmpNormalS2Num = s1GCache.cmpS1GBlock - curCmpTailS2Num; - if (s1GCache.s1GIdx == (splitInfo.s1GBaseNum[s1GCache.bIdx] - 1U) && - splitInfo.s1GTailSize[s1GCache.bIdx] != 0U) { - s1GCache.cmpS1GCost = - typeCost_[CMP_TAIL_BLOCK][CMP_NORMAL_BLOCK] * curCmpNormalS2Num + - typeCost_[CMP_TAIL_BLOCK][CMP_TAIL_BLOCK] * curCmpTailS2Num; - s1GCache.cmpS1GLastBlockCost = - curCmpTailS2Num > 0U ? typeCost_[CMP_TAIL_BLOCK][CMP_TAIL_BLOCK] - : typeCost_[CMP_TAIL_BLOCK][CMP_NORMAL_BLOCK]; - s1GCache.cmpS1GNormalBlockCost = - typeCost_[CMP_TAIL_BLOCK][CMP_NORMAL_BLOCK]; - } else { - s1GCache.cmpS1GCost = - typeCost_[CMP_NORMAL_BLOCK][CMP_NORMAL_BLOCK] * curCmpNormalS2Num + - typeCost_[CMP_NORMAL_BLOCK][CMP_TAIL_BLOCK] * curCmpTailS2Num; - s1GCache.cmpS1GLastBlockCost = - curCmpTailS2Num > 0U ? typeCost_[CMP_NORMAL_BLOCK][CMP_TAIL_BLOCK] - : typeCost_[CMP_NORMAL_BLOCK][CMP_NORMAL_BLOCK]; - s1GCache.cmpS1GNormalBlockCost = - typeCost_[CMP_NORMAL_BLOCK][CMP_NORMAL_BLOCK]; - } - } -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcOriBlockRange( - const Range& oriS2TokenRange, - const BatchCache& batchCache, - S1GCache& s1GCache) { - int64_t oriS2FirstToken = oriS2TokenRange.first; - int64_t oriS2LastToken = oriS2TokenRange.second; - s1GCache.oriS2Start = 0; - // ori 部分 s2 起止和 tailSize - if (oriS2FirstToken >= static_cast(batchCache.oriS2Size) || - oriS2LastToken < 0 || oriS2LastToken < oriS2FirstToken) { - s1GCache.oriS2End = 0; - s1GCache.oriS2TailSize = 0; - } else { - oriS2FirstToken = Clip(oriS2FirstToken, - static_cast(0), - static_cast(batchCache.oriS2Size - 1U)); - oriS2LastToken = Clip(oriS2LastToken, - static_cast(0), - static_cast(batchCache.oriS2Size - 1U)); - // oriS2LastToken 与 topk 取最小 - uint32_t s1Idx = GetS1Idx(batchCache.s1Size, s1GCache.s1GIdx); - uint32_t bsStride = GetBsStride(s1GCache.bIdx, s1Idx); - uint32_t oriTopkSize = - isSparseOriKv_ - ? GetOriTopkLength(s1GCache.s1GIdx, batchCache) - : GetOriTopkLength(GetBsStride( - s1GCache.bIdx, GetS1Idx(batchCache.s1Size, s1GCache.s1GIdx))); - s1GCache.actOriS2Size = - isSparseOriKv_ - ? std::min( - static_cast(oriS2LastToken - oriS2FirstToken + 1), - oriTopkSize) - : static_cast(oriS2LastToken - oriS2FirstToken + 1); - s1GCache.oriS2End = s1GCache.actOriS2Size == 0 - ? 0 - : (s1GCache.actOriS2Size - 1U) / s2BaseSize_ + 1U; - s1GCache.oriS2TailSize = s1GCache.actOriS2Size % s2BaseSize_; - } -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcCmpBlockRange( - const Range& cmpRevertS2TokenRange, - const BatchCache& batchCache, - S1GCache& s1GCache) { - int64_t cmpRevertS2FirstToken = cmpRevertS2TokenRange.first; - int64_t cmpRevertS2LastToken = cmpRevertS2TokenRange.second; - s1GCache.cmpS2Start = s1GCache.oriS2End; - // cmp 部分 s2 起止和 tailSize - if (cmpRevertS2FirstToken >= - static_cast(batchCache.cmpRevertS2Size) || - cmpRevertS2LastToken < 0 || - cmpRevertS2LastToken < cmpRevertS2FirstToken) { - s1GCache.cmpS2End = s1GCache.cmpS2Start; - s1GCache.cmpS2TailSize = 0; - } else { - cmpRevertS2FirstToken = - Clip(cmpRevertS2FirstToken, - static_cast(0), - static_cast(batchCache.cmpRevertS2Size - 1U)); - cmpRevertS2LastToken = - Clip(cmpRevertS2LastToken, - static_cast(0), - static_cast(batchCache.cmpRevertS2Size - 1U)); - // 如果压缩后长度为0,则直接返回 - if ((cmpRevertS2LastToken + 1) / cmpRatio_ == 0) { - s1GCache.cmpS2End = s1GCache.cmpS2Start; - s1GCache.cmpS2TailSize = 0; - return; - } - // 获取压缩后的 token 索引 - uint64_t cmpS2FirstToken = - (cmpRevertS2FirstToken + 1) / cmpRatio_ == 0 - ? 0 - : (cmpRevertS2FirstToken + 1) / cmpRatio_ - 1U; - uint64_t cmpS2LastToken = (cmpRevertS2LastToken + 1) / cmpRatio_ - 1U; - // cmpS2LastToken 与 topk 取最小 - uint32_t s1Idx = GetS1Idx(batchCache.s1Size, s1GCache.s1GIdx); - uint32_t bsStride = GetBsStride(s1GCache.bIdx, s1Idx); - uint32_t cmpTopkSize = GetCmpTopkLength(bsStride); - s1GCache.actCmpS2Size = - isSparseCmpKv_ - ? std::min( - static_cast(cmpS2LastToken - cmpS2FirstToken + 1), - cmpTopkSize) - : static_cast(cmpS2LastToken - cmpS2FirstToken + 1); - s1GCache.cmpS2End = s1GCache.actCmpS2Size == 0 - ? s1GCache.cmpS2Start - : s1GCache.cmpS2Start + - (s1GCache.actCmpS2Size - 1U) / s2BaseSize_ + - 1U; - s1GCache.cmpS2TailSize = s1GCache.actCmpS2Size % s2BaseSize_; - } -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::GatherOriAndCmpCache( - S1GCache& s1GCache) { - s1GCache.s2Start = 0; - if (s1GCache.cmpS1GBlock > 0) { - s1GCache.s1GLastBlockCost = s1GCache.cmpS1GLastBlockCost; - s1GCache.s2End = s1GCache.cmpS2End; - } else { - s1GCache.s1GLastBlockCost = s1GCache.oriS1GLastBlockCost; - s1GCache.s2End = s1GCache.oriS2End; - } - s1GCache.s1GBlock = s1GCache.oriS1GBlock + s1GCache.cmpS1GBlock; - s1GCache.s1GCost = s1GCache.oriS1GCost + s1GCache.cmpS1GCost; -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcS1GCache( - uint32_t s1GIdx, - const SplitContext& splitContext, - const BatchCache& batchCache, - S1GCache& s1GCache) { - const SplitInfo& splitInfo = splitContext.splitInfo; - // 如果s1G是空行,则直接返回 - if (splitInfo.s1GBaseNum[batchCache.bIdx] == 0) { - s1GCache.s1GCost = 0; - s1GCache.s1GLastBlockCost = 0; - s1GCache.oriS1GNormalBlockCost = 0; - s1GCache.oriS1GLastBlockCost = 0; - s1GCache.cmpS1GNormalBlockCost = 0; - s1GCache.cmpS1GLastBlockCost = 0; - s1GCache.s1GBlock = 0; - s1GCache.s2Loop = 0; - s1GCache.s2Start = 0; - s1GCache.cmpS2Start = 0; - s1GCache.s2End = 0; - return; - } - s1GCache.bIdx = batchCache.bIdx; - s1GCache.s1GIdx = s1GIdx; - s1GCache.actOriS2Size = 0U; - s1GCache.actCmpS2Size = 0U; - s1GCache.reductionBlockSize = 0U; - // 计算 ori_kv 有效负载起止 - if (hasOriKv_) { - // 计算 ori_kv 的 s2Token 起止 - auto oriS2TokenRange = CalcS2TokenRange(s1GIdx, batchCache, ORI_KV); - // 计算 ori_kv 的 s2Block 起止 - CalcOriBlockRange(oriS2TokenRange, batchCache, s1GCache); - } else { - // ori_kv s2Token 起止初始化为0 - s1GCache.oriS2Start = 0; - s1GCache.oriS2End = s1GCache.oriS2Start; - s1GCache.oriS2TailSize = 0; - } - // 计算 cmp_kv 有效负载起止 - if (hasCmpKv_) { - // 计算 cmp_kv 的 s2Token 起止 - auto cmpRevertS2TokenRange = CalcS2TokenRange(s1GIdx, batchCache, CMP_KV); - // 计算 cmp_kv 的 s2Block 起止 - CalcCmpBlockRange(cmpRevertS2TokenRange, batchCache, s1GCache); - } else { - // cmp_kv s2Token 起止初始化为0 - s1GCache.cmpS2Start = s1GCache.oriS2End; - s1GCache.cmpS2End = s1GCache.cmpS2Start; - s1GCache.cmpS2TailSize = 0; - } - if (isBatchConsistency_) { - // 规约块大小只依赖当前行,ORI、CMP 分别划分规约块。 - uint64_t actTotalS2Size = - static_cast(s1GCache.actOriS2Size) + s1GCache.actCmpS2Size; - if (actTotalS2Size > 0U) { - uint64_t rawReductionBlockSize = - (actTotalS2Size + BATCH_CONSISTENCY_MAX_REDUCTION_PARTS - 1U) / - BATCH_CONSISTENCY_MAX_REDUCTION_PARTS; - s1GCache.reductionBlockSize = - static_cast((rawReductionBlockSize + s2BaseSize_ - 1U) / - s2BaseSize_ * s2BaseSize_); - s1GCache.reductionBlockSize = - std::max(s1GCache.reductionBlockSize, s2BaseSize_); - s1GCache.oriS2End = - s1GCache.actOriS2Size == 0U - ? 0U - : (s1GCache.actOriS2Size - 1U) / s1GCache.reductionBlockSize + 1U; - s1GCache.oriS2TailSize = - s1GCache.actOriS2Size % s1GCache.reductionBlockSize; - s1GCache.cmpS2Start = s1GCache.oriS2End; - s1GCache.cmpS2End = - s1GCache.actCmpS2Size == 0U - ? s1GCache.cmpS2Start - : s1GCache.cmpS2Start + - (s1GCache.actCmpS2Size - 1U) / s1GCache.reductionBlockSize + - 1U; - s1GCache.cmpS2TailSize = - s1GCache.actCmpS2Size % s1GCache.reductionBlockSize; - } - } - // 计算基本块负载 - CalcCostTable(splitInfo.s1GTailSize[s1GCache.bIdx], - s1GCache.reductionBlockSize, - s1GCache.oriS2TailSize, - s1GCache.cmpS2TailSize); - // 计算 ori 和 cmp 部分的 cost 和 block 信息 - CalcOriS1GCache(s1GCache, splitInfo); - CalcCmpS1GCache(s1GCache, splitInfo); - // 汇总 ori 和 cmp 部分的 cost 和 block 信息 - GatherOriAndCmpCache(s1GCache); - s1GCache.s2Loop = static_cast( - (static_cast(s1GCache.actOriS2Size) + s2BaseSize_ - 1U) / - s2BaseSize_ + - (static_cast(s1GCache.actCmpS2Size) + s2BaseSize_ - 1U) / - s2BaseSize_); -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcBatchCost( - uint32_t bIdx, - const SplitContext& splitContext, - CostInfo& costInfo) { - const SplitInfo& splitInfo = splitContext.splitInfo; - - costInfo.bN2CostOfEachBatch[bIdx] = 0; - costInfo.bN2BlockOfEachBatch[bIdx] = 0U; - costInfo.bN2S2LoopOfEachBatch[bIdx] = 0U; - costInfo.bN2LastBlockCostOfEachBatch[bIdx] = 0U; - - if (GetS1SeqSize(bIdx) == 0U) { - return; - } - if (!hasOriKv_ && !hasCmpKv_) { - return; - } else if (!hasOriKv_) { - if (GetCmpS2SeqSize(bIdx) == 0U) { - return; - } - } else if (!hasCmpKv_) { - if (GetOriS2SeqSize(bIdx) == 0U) { - return; - } - } else { - if ((GetOriS2SeqSize(bIdx) == 0U) && GetCmpS2SeqSize(bIdx) == 0U) { - return; - } - } - - BatchCache bCache; - S1GCache s1GCache; - CalcBatchCache(bIdx, splitContext, bCache); - for (uint32_t s1GIdx = 0; s1GIdx < splitInfo.s1GBaseNum[bIdx]; s1GIdx++) { - CalcS1GCache(s1GIdx, splitContext, bCache, s1GCache); - costInfo.bN2CostOfEachBatch[bIdx] += s1GCache.s1GCost; - costInfo.bN2BlockOfEachBatch[bIdx] += s1GCache.s1GBlock; - costInfo.bN2S2LoopOfEachBatch[bIdx] += s1GCache.s2Loop; - // 更新最大S1G行开销 - if (s1GCache.s1GCost > costInfo.maxS1GCost) { - costInfo.maxS1GCost = s1GCache.s1GCost; - } - if (s1GCache.s1GBlock > 0) { - costInfo.bN2LastBlockCostOfEachBatch[bIdx] = s1GCache.s1GLastBlockCost; - } - } -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcCostInfo( - SplitContext& splitContext) { - const SplitInfo& splitInfo = splitContext.splitInfo; - CostInfo& costInfo = splitContext.costInfo; - - if (splitInfo.isKvSeqAllZero) { - costInfo.totalCost = 0; - costInfo.totalBlockNum = 0U; - return; - } - - // 计算 batch - // 的负载并记录,用于按batch分配,需要按行计算起止点,统计块数、负载 - for (uint32_t bIdx = 0; bIdx < batchSize_; bIdx++) { - CalcBatchCost(bIdx, splitContext, costInfo); - costInfo.totalCost += costInfo.bN2CostOfEachBatch[bIdx] * numHeadsKv_; - costInfo.totalBlockNum += costInfo.bN2BlockOfEachBatch[bIdx] * numHeadsKv_; - } -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::UpdateCursor( - const SplitContext& splitContext, - AssignContext& assignContext) { - const SplitInfo& splitInfo = splitContext.splitInfo; - const CostInfo& costInfo = splitContext.costInfo; - - bool UpdateS1G = false; - bool UpdateBatch = false; - - // Update S2 - if (assignContext.curS2Idx >= - assignContext.s1GCache.s2End) { // 边界assignInfo.s2End是取不到的开区间 - assignContext.curS2Idx = 0U; - assignContext.curS1GIdx++; - UpdateS1G = true; - } - - // Update S1G - if (assignContext.curS1GIdx >= splitInfo.s1GBaseNum[assignContext.curBIdx]) { - assignContext.curS1GIdx = 0U; - assignContext.curBN2Idx++; - } - - // Update Batch - if (assignContext.curBN2Idx == - batchSize_ * - numHeadsKv_) { // 所有负载全部分配完,设置最后一个核的右开区间,返回 - assignContext.curS1GIdx = 0U; - assignContext.curS2Idx = 0U; - assignContext.isFinished = true; - return; - } - - if (assignContext.curBN2Idx / numHeadsKv_ != assignContext.curBIdx) { - assignContext.curBIdx = assignContext.curBN2Idx / numHeadsKv_; - assignContext.curS1GIdx = 0U; - UpdateBatch = true; - UpdateS1G = true; - } - - // Update Cache - if (UpdateBatch) { - CalcBatchCache( - assignContext.curBIdx, splitContext, assignContext.batchCache); - assignContext.bN2Cost = costInfo.bN2CostOfEachBatch[assignContext.curBIdx]; - assignContext.bN2Block = - costInfo.bN2BlockOfEachBatch[assignContext.curBIdx]; - assignContext.bN2S2Loop = - costInfo.bN2S2LoopOfEachBatch[assignContext.curBIdx]; - } - if (UpdateS1G) { - CalcS1GCache(assignContext.curS1GIdx, - splitContext, - assignContext.batchCache, - assignContext.s1GCache); - assignContext.curS2Idx = - supportFd_ ? assignContext.s1GCache.oriS2Start : 0U; - } -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::AssignByBatch( - const SplitContext& splitContext, - AssignContext& assignContext) { - if (assignContext.isFinished) { - return; - } - const CostInfo& costInfo = splitContext.costInfo; - const SplitInfo& splitInfo = splitContext.splitInfo; - while (assignContext.bN2Cost == 0 || - IsWithinTolerance( - assignContext.coreCache.costLimit, - costInfo.bN2LastBlockCostOfEachBatch[assignContext.curBIdx] / - FA_TOLERANCE_RATIO, - assignContext.coreCache.cost + assignContext.bN2Cost)) { - assignContext.coreCache.cost += assignContext.bN2Cost; - assignContext.coreCache.block += assignContext.bN2Block; - assignContext.coreCache.s2Loop += assignContext.bN2S2Loop; - assignContext.curBN2Idx++; - // to the end - if (assignContext.curBN2Idx == batchSize_ * numHeadsKv_) { - assignContext.curS1GIdx = 0U; - assignContext.curS2Idx = 0U; - assignContext.isFinished = true; - return; - } - - // next batch - if (assignContext.curBN2Idx / numHeadsKv_ != assignContext.curBIdx) { - assignContext.curBIdx = assignContext.curBN2Idx / numHeadsKv_; - CalcBatchCache( - assignContext.curBIdx, splitContext, assignContext.batchCache); - } - - assignContext.bN2Cost = costInfo.bN2CostOfEachBatch[assignContext.curBIdx]; - assignContext.bN2Block = - costInfo.bN2BlockOfEachBatch[assignContext.curBIdx]; - assignContext.bN2S2Loop = - costInfo.bN2S2LoopOfEachBatch[assignContext.curBIdx]; - assignContext.curS1GIdx = 0U; - CalcS1GCache(assignContext.curS1GIdx, - splitContext, - assignContext.batchCache, - assignContext.s1GCache); - assignContext.curS2Idx = assignContext.s1GCache.s2Start; - } -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::AssignByRow( - const SplitContext& splitContext, - AssignContext& assignContext) { - if (assignContext.isFinished) { - return; - } - - while (IsWithinTolerance( - assignContext.coreCache.costLimit, - assignContext.s1GCache.s1GLastBlockCost / FA_TOLERANCE_RATIO, - assignContext.coreCache.cost + assignContext.s1GCache.s1GCost)) { - assignContext.coreCache.cost += assignContext.s1GCache.s1GCost; - assignContext.coreCache.block += assignContext.s1GCache.s1GBlock; - assignContext.coreCache.s2Loop += assignContext.s1GCache.s2Loop; - // 当前batch被分配一行出去,更新剩余负载 - assignContext.bN2Cost = - assignContext.bN2Cost > assignContext.s1GCache.s1GCost - ? assignContext.bN2Cost - assignContext.s1GCache.s1GCost - : 0; - assignContext.bN2Block = - assignContext.bN2Block > assignContext.s1GCache.s1GBlock - ? assignContext.bN2Block - assignContext.s1GCache.s1GBlock - : 0U; - assignContext.bN2S2Loop = - assignContext.bN2S2Loop > assignContext.s1GCache.s2Loop - ? assignContext.bN2S2Loop - assignContext.s1GCache.s2Loop - : 0U; - // 计算新一行的信息 - do { - assignContext.curS1GIdx++; - CalcS1GCache(assignContext.curS1GIdx, - splitContext, - assignContext.batchCache, - assignContext.s1GCache); - } while (assignContext.s1GCache.s1GBlock == 0); - assignContext.curS2Idx = assignContext.s1GCache.s2Start; - } -} - -int64_t XllmKernelSparseFlashMlaMetadataCpuKernel::CalcCurBlockCost( - const AssignContext& assignContext) { - int64_t curCost = 0; - if (assignContext.curS2Idx < assignContext.s1GCache.cmpS2Start) { - curCost = assignContext.s1GCache.oriS1GNormalBlockCost; - if (assignContext.curS2Idx == (assignContext.s1GCache.cmpS2Start - 1U)) { - curCost = assignContext.s1GCache.oriS1GLastBlockCost; - } - } else { - curCost = assignContext.s1GCache.cmpS1GNormalBlockCost; - if (assignContext.curS2Idx == (assignContext.s1GCache.s2End - 1U)) { - curCost = assignContext.s1GCache.cmpS1GLastBlockCost; - } - } - return curCost; -} - -uint32_t XllmKernelSparseFlashMlaMetadataCpuKernel::CalcCurBlockS2Loop( - const AssignContext& assignContext) { - if (!isBatchConsistency_) { - return 1U; - } - const S1GCache& s1GCache = assignContext.s1GCache; - uint32_t blockSize = s1GCache.reductionBlockSize; - if (assignContext.curS2Idx < s1GCache.cmpS2Start) { - if (assignContext.curS2Idx + 1U == s1GCache.cmpS2Start && - s1GCache.oriS2TailSize != 0) { - blockSize = static_cast(s1GCache.oriS2TailSize); - } - } else if (assignContext.curS2Idx + 1U == s1GCache.s2End && - s1GCache.cmpS2TailSize != 0) { - blockSize = static_cast(s1GCache.cmpS2TailSize); - } - return (blockSize + s2BaseSize_ - 1U) / s2BaseSize_; -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::AssignByBlock( - const SplitContext& splitContext, - AssignContext& assignContext) { - if (assignContext.isFinished || !supportFd_) { - return; - } - - int64_t curCost = CalcCurBlockCost(assignContext); - uint32_t curS2Loop = CalcCurBlockS2Loop(assignContext); - - // (costLimit - curCostOnCore) * FA_TOLERANCE_RATIO > curCost;至少分配1块 - while (IsWithinTolerance(assignContext.coreCache.costLimit, - curCost / FA_TOLERANCE_RATIO, - assignContext.coreCache.cost + curCost)) { - assignContext.coreCache.cost += curCost; - assignContext.coreCache.block++; - assignContext.coreCache.s2Loop += curS2Loop; - assignContext.curS2Idx++; - // 当前batch被分配一块出去,更新剩余负载 - assignContext.bN2Cost = assignContext.bN2Cost - curCost; - // 当前行被分配一块出去,更新剩余负载 - assignContext.s1GCache.s1GCost = assignContext.s1GCache.s1GCost - curCost; - assignContext.bN2Block--; - assignContext.s1GCache.s1GBlock--; - assignContext.bN2S2Loop = assignContext.bN2S2Loop > curS2Loop - ? assignContext.bN2S2Loop - curS2Loop - : 0U; - assignContext.s1GCache.s2Loop = - assignContext.s1GCache.s2Loop > curS2Loop - ? assignContext.s1GCache.s2Loop - curS2Loop - : 0U; - curCost = CalcCurBlockCost(assignContext); - curS2Loop = CalcCurBlockS2Loop(assignContext); - } -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::ForceAssign( - const SplitContext& splitContext, - AssignContext& assignContext) { - if (assignContext.isFinished) { - return; - } - - int64_t curCost = CalcCurBlockCost(assignContext); - uint32_t curS2Loop = CalcCurBlockS2Loop(assignContext); - - assignContext.coreCache.cost += curCost; - assignContext.coreCache.block++; - assignContext.coreCache.s2Loop += curS2Loop; - assignContext.curS2Idx++; - // 当前batch被分配一块出去,更新剩余负载 - assignContext.bN2Cost = assignContext.bN2Cost - curCost; - assignContext.bN2Block--; - assignContext.bN2S2Loop = assignContext.bN2S2Loop > curS2Loop - ? assignContext.bN2S2Loop - curS2Loop - : 0U; - // 当前行被分配一块出去,更新剩余负载 - assignContext.s1GCache.s1GCost = assignContext.s1GCache.s1GCost - curCost; - assignContext.s1GCache.s1GBlock--; - assignContext.s1GCache.s2Loop = - assignContext.s1GCache.s2Loop > curS2Loop - ? assignContext.s1GCache.s2Loop - curS2Loop - : 0U; - UpdateCursor(splitContext, assignContext); -} - -bool XllmKernelSparseFlashMlaMetadataCpuKernel::IsNeedRecordFDInfo( - const AssignContext& assignContext, - const SplitResult& splitRes) { - // 切分点大概率不会刚好在行尾,因此滞后处理归约信息的统计,到下一个切分点再判断是否需要归约 - // 核0无需处理 - if (assignContext.curCoreIdx == 0U) { - return false; - } - // 无跨核行,无需处理 - if (assignContext.curKvSplitPart <= 1U) { - return false; - } - // 需要归约的行还未处理完 - if (assignContext.curBN2Idx == - splitRes.bN2End[assignContext.curCoreIdx - 1U] && - assignContext.curS1GIdx == - splitRes.gS1End[assignContext.curCoreIdx - 1U]) { - return false; - } - return true; -} - -bool XllmKernelSparseFlashMlaMetadataCpuKernel::IsFirstReductionBlock( - const AssignContext& assignContext, - const SplitResult& splitRes) { - if (assignContext.curCoreIdx == 0U || - splitRes.s2End[assignContext.curCoreIdx - 1U] == 0U) { - return true; - } - return assignContext.curBN2Idx != - splitRes.bN2End[assignContext.curCoreIdx - 1U] || - assignContext.curS1GIdx != - splitRes.gS1End[assignContext.curCoreIdx - 1U]; -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::RecordFDInfo( - const SplitContext& splitContext, - const AssignContext& assignContext, - SplitResult& result) { - const SplitInfo& splitInfo = splitContext.splitInfo; - // 需要规约的行是上一个核的切分点所在位置 - uint32_t splitBIdx = - result.bN2End[assignContext.curCoreIdx - 1U] / numHeadsKv_; - uint32_t splitS1GIdx = result.gS1End[assignContext.curCoreIdx - 1U]; - uint32_t s1Size = GetS1SeqSize(splitBIdx); - - // 计算归约数据的FD均衡划分信息 - uint32_t curFdS1gSize = - (splitS1GIdx == splitInfo.s1GBaseNum[splitBIdx] - 1U) - ? (static_cast(s1Size) * groupSize_ - - static_cast(splitS1GIdx) * mBaseSize_) - : mBaseSize_; - // 记录 - result.maxS2SplitNum = - std::max(result.maxS2SplitNum, assignContext.curKvSplitPart); - // 若存在头归约,则切分点一定为上一个核结束的位置 - result.fdRes.fdBN2Idx[result.numOfFdHead] = - result.bN2End[assignContext.curCoreIdx - 1U]; - result.fdRes.fdMIdx[result.numOfFdHead] = - result.gS1End[assignContext.curCoreIdx - 1U]; - result.fdRes.fdWorkspaceIdx[result.numOfFdHead] = assignContext.preFdDataNum; - result.fdRes.fdS2SplitNum[result.numOfFdHead] = assignContext.curKvSplitPart; - result.fdRes.fdMSize[result.numOfFdHead] = curFdS1gSize; - result.numOfFdHead++; -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::AssignBlocksToCore( - const SplitContext& splitContext, - AssignContext& assignContext, - SplitResult& result) { - const CostInfo& costInfo = splitContext.costInfo; - result.firstFdDataWorkspaceIdx[assignContext.curCoreIdx] = - assignContext.preFdDataNum + assignContext.curKvSplitPart - 1U; - int64_t avgCost = - assignContext.unassignedCost / (aicCoreNum_ - assignContext.curCoreIdx); - assignContext.coreCache = {}; - if (!supportFd_) { - assignContext.coreCache.costLimit = std::max(avgCost, costInfo.maxS1GCost); - } else { - assignContext.coreCache.costLimit = avgCost; - } - // 1、按整batch分配 - AssignByBatch(splitContext, assignContext); - // 2、按行分配 - AssignByRow(splitContext, assignContext); - // 3、按块分配 - AssignByBlock(splitContext, assignContext); - // 4、强制分配 - if (assignContext.coreCache.block == 0 && supportFd_) { - ForceAssign(splitContext, assignContext); - } - result.bN2End[assignContext.curCoreIdx] = assignContext.curBN2Idx; - result.gS1End[assignContext.curCoreIdx] = assignContext.curS1GIdx; - result.s2End[assignContext.curCoreIdx] = assignContext.curS2Idx; - result.maxCost = std::max(result.maxCost, assignContext.coreCache.cost); - assignContext.unassignedCost -= assignContext.coreCache.cost; - result.maxS2LoopNum = - std::max(assignContext.coreCache.s2Loop, result.maxS2LoopNum); - // 对之前的归约信息进行记录并清理 - if (IsNeedRecordFDInfo(assignContext, result)) { - if (isBatchConsistency_ && remainedBlockNum_ > 0U) { - // curKvSplitPart already reserves one slot for the core that finishes - // this row. - assignContext.curKvSplitPart += remainedBlockNum_ - 1U; - } - RecordFDInfo(splitContext, assignContext, result); - assignContext.preFdDataNum += assignContext.curKvSplitPart; - assignContext.curKvSplitPart = 1U; - remainedBlockNum_ = 0U; - } - // 更新S2切分信息 - if (assignContext.curS2Idx > assignContext.s1GCache.s2Start && - assignContext.curS2Idx <= assignContext.s1GCache.s2End) { - if (isBatchConsistency_) { - if (IsFirstReductionBlock(assignContext, result)) { - assignContext.curKvSplitPart++; - } else { - assignContext.curKvSplitPart += - result.s2End[assignContext.curCoreIdx] - - result.s2End[assignContext.curCoreIdx - 1U]; - } - remainedBlockNum_ = assignContext.s1GCache.s1GBlock; - } else { - assignContext.curKvSplitPart++; - } - } -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::CalcSplitPlan( - int64_t costLimit, - const SplitContext& splitContext, - SplitResult& result) { - const CostInfo& costInfo = splitContext.costInfo; - const SplitInfo& splitInfo = splitContext.splitInfo; - if (aicCoreNum_ == 0U) { - return; - } - result.maxCost = 0U; - result.usedCoreNum = 0U; - - AssignContext assignContext{}; - assignContext.curBIdx = 0U; - assignContext.curS1GIdx = 0U; - assignContext.unassignedCost = costInfo.totalCost; - assignContext.bN2Cost = costInfo.bN2CostOfEachBatch[assignContext.curBIdx]; - assignContext.bN2Block = costInfo.bN2BlockOfEachBatch[assignContext.curBIdx]; - assignContext.bN2S2Loop = - costInfo.bN2S2LoopOfEachBatch[assignContext.curBIdx]; - CalcBatchCache(assignContext.curBIdx, splitContext, assignContext.batchCache); - CalcS1GCache(assignContext.curS1GIdx, - splitContext, - assignContext.batchCache, - assignContext.s1GCache); - assignContext.curS2Idx = assignContext.s1GCache.s2Start; - // 负载分配 - for (uint32_t i = 0; i < aicCoreNum_; ++i) { - if (result.maxCost > costLimit) { - return; - } - if (assignContext.isFinished || assignContext.unassignedCost <= 0) { - break; - } - assignContext.curCoreIdx = i; - AssignBlocksToCore(splitContext, assignContext, result); - } - result.usedCoreNum = assignContext.curCoreIdx + 1; -} - -void XllmKernelSparseFlashMlaMetadataCpuKernel::SplitFD(SplitResult& splitRes) { - // 计算FD的总数据量 - uint64_t totalFDLoad = 0; - for (uint32_t i = 0; i < splitRes.numOfFdHead; i++) { - totalFDLoad += splitRes.fdRes.fdS2SplitNum[i] * splitRes.fdRes.fdMSize[i]; - } - // 计算当前最大冗余vec核数 - uint32_t emptyVectorNum = aivCoreNum_ - splitRes.numOfFdHead; - // 计算每个核处理的load - uint64_t averageLoad = (totalFDLoad + aivCoreNum_ - 1U) / - aivCoreNum_; // 向上取整,避免核负载为0 - uint32_t curCoreIndex = 0; - for (uint32_t i = 0; i < splitRes.numOfFdHead; i++) { - // 冗余vec核数为0,此时规约任务无法进行更小的切分,只能1个vec核计算1个规约任务 - if (emptyVectorNum == 0U) { - splitRes.fdRes.fdIdx[curCoreIndex] = i; - splitRes.fdRes.fdMStart[curCoreIndex] = 0U; - splitRes.fdRes.fdMNum[curCoreIndex] = splitRes.fdRes.fdMSize[i]; - curCoreIndex++; - continue; - } - // 计算当前归约任务所用核数,向下取整,避免使用核数超出总核数 - uint32_t curFDVectorNum = splitRes.fdRes.fdS2SplitNum[i] * - splitRes.fdRes.fdMSize[i] / averageLoad; - curFDVectorNum = std::max(1U, curFDVectorNum); - // 计算当前归约任务每个核的行数,向上取整,避免行数为0 - uint32_t curAveMSize = - (splitRes.fdRes.fdMSize[i] + curFDVectorNum - 1U) / curFDVectorNum; - curFDVectorNum = - (splitRes.fdRes.fdMSize[i] + curAveMSize - 1U) / curAveMSize; - // 需要使用的vec核数与当前剩余可用vec核数取最小 - curFDVectorNum = - std::min(curFDVectorNum, emptyVectorNum + 1U); // 1: Fd任务自身带一个核 - // FD负载分配 - for (uint32_t vid = 0; vid < curFDVectorNum; vid++) { - splitRes.fdRes.fdIdx[curCoreIndex] = i; - splitRes.fdRes.fdMStart[curCoreIndex] = vid * curAveMSize; - splitRes.fdRes.fdMNum[curCoreIndex] = - (vid < curFDVectorNum - 1) - ? curAveMSize - : (splitRes.fdRes.fdMSize[i] - vid * curAveMSize); - curCoreIndex++; - } - // 更新冗余vec核数 - emptyVectorNum -= (curFDVectorNum - 1U); // 1: 空余核不包含FD自身的核,要-1 - } - splitRes.fdRes.fdUsedVecNum = curCoreIndex; -} - -bool XllmKernelSparseFlashMlaMetadataCpuKernel::BalanceSchedule( - SplitResult& splitRes) { - SplitContext splitContext(batchSize_); - - // 1、划分基本块,统计信息 - CalcSplitInfo(splitContext); - // 全空case - if (splitContext.splitInfo.isKvSeqAllZero) { - splitRes.usedCoreNum = 1U; - splitRes.bN2End[0] = batchSize_ * numHeadsKv_; - splitRes.gS1End[0] = 0U; - splitRes.s2End[0] = 0U; - return true; - } - CalcCostInfo(splitContext); - - // 2、获取每个核的分配方案 - splitRes.maxCost = INT64_MAX; - splitRes.usedCoreNum = 1U; - - CalcSplitPlan(splitRes.maxCost, splitContext, splitRes); - // 3、存在FD任务,对FD进行负载均衡分配 - if (splitRes.numOfFdHead > 0U) { - SplitFD(splitRes); - } - splitRes.usedCoreNum = std::max(splitRes.usedCoreNum, 1U); // 至少使用1个core - return true; -} - -bool XllmKernelSparseFlashMlaMetadataCpuKernel::GenMetadata( - SplitResult& splitRes) { - optiling::detail::SmlaMetadata* metadataPtr = - static_cast(metadata_->GetData()); - *metadataPtr = {}; - // FA Metadata Generate - if (isSplitG_) { - for (size_t i = 0; i < aicCoreNum_; i++) { - // 单核s2计算轮次最大数量 - metadataPtr->faMetadata[2 * i][FA_S2_MAX_NUM] = splitRes.maxS2LoopNum; - metadataPtr->faMetadata[2 * i + 1][FA_S2_MAX_NUM] = splitRes.maxS2LoopNum; - - if (i >= splitRes.usedCoreNum) { - metadataPtr->faMetadata[2 * i][FA_CORE_ENABLE_INDEX] = - 0; // AIC disenable - metadataPtr->faMetadata[2 * i + 1][FA_CORE_ENABLE_INDEX] = - 0; // AIC disenable - continue; - } - metadataPtr->faMetadata[2 * i][FA_CORE_ENABLE_INDEX] = 1; // AIC enable - metadataPtr->faMetadata[2 * i + 1][FA_CORE_ENABLE_INDEX] = - 1; // AIC enable - // FA START - metadataPtr->faMetadata[2 * i][FA_BN2_START_INDEX] = - i == 0 ? 0 : splitRes.bN2End[i - 1]; - metadataPtr->faMetadata[2 * i][FA_M_START_INDEX] = - i == 0 ? 0 : splitRes.gS1End[i - 1]; - metadataPtr->faMetadata[2 * i][FA_S2_START_INDEX] = - i == 0 ? 0 : splitRes.s2End[i - 1]; - - metadataPtr->faMetadata[2 * i + 1][FA_BN2_START_INDEX] = - i == 0 ? 0 : splitRes.bN2End[i - 1]; - metadataPtr->faMetadata[2 * i + 1][FA_M_START_INDEX] = - i == 0 ? 0 : splitRes.gS1End[i - 1]; - metadataPtr->faMetadata[2 * i + 1][FA_S2_START_INDEX] = - i == 0 ? 0 : splitRes.s2End[i - 1]; - // FA END - metadataPtr->faMetadata[2 * i][FA_BN2_END_INDEX] = splitRes.bN2End[i]; - metadataPtr->faMetadata[2 * i][FA_M_END_INDEX] = splitRes.gS1End[i]; - metadataPtr->faMetadata[2 * i][FA_S2_END_INDEX] = splitRes.s2End[i]; - - metadataPtr->faMetadata[2 * i + 1][FA_BN2_END_INDEX] = splitRes.bN2End[i]; - metadataPtr->faMetadata[2 * i + 1][FA_M_END_INDEX] = splitRes.gS1End[i]; - metadataPtr->faMetadata[2 * i + 1][FA_S2_END_INDEX] = splitRes.s2End[i]; - // firstFdDataWorkspace - metadataPtr->faMetadata[2 * i][FA_FIRST_FD_DATA_WORKSPACE_IDX_INDEX] = - splitRes.firstFdDataWorkspaceIdx[i]; - metadataPtr->faMetadata[2 * i + 1][FA_FIRST_FD_DATA_WORKSPACE_IDX_INDEX] = - splitRes.firstFdDataWorkspaceIdx[i]; - } - } else { - for (size_t i = 0; i < aicCoreNum_; ++i) { - if (i >= splitRes.usedCoreNum) { - metadataPtr->faMetadata[i][FA_CORE_ENABLE_INDEX] = 0; // AIC disenable - continue; - } - metadataPtr->faMetadata[i][FA_CORE_ENABLE_INDEX] = 1; // AIC enable - // FA START - metadataPtr->faMetadata[i][FA_BN2_START_INDEX] = - i == 0 ? 0 : splitRes.bN2End[i - 1]; - metadataPtr->faMetadata[i][FA_M_START_INDEX] = - i == 0 ? 0 : splitRes.gS1End[i - 1]; - metadataPtr->faMetadata[i][FA_S2_START_INDEX] = - i == 0 ? 0 : splitRes.s2End[i - 1]; - // FA END - metadataPtr->faMetadata[i][FA_BN2_END_INDEX] = splitRes.bN2End[i]; - metadataPtr->faMetadata[i][FA_M_END_INDEX] = splitRes.gS1End[i]; - metadataPtr->faMetadata[i][FA_S2_END_INDEX] = splitRes.s2End[i]; - // firstFdDataWorkspace - metadataPtr->faMetadata[i][FA_FIRST_FD_DATA_WORKSPACE_IDX_INDEX] = - splitRes.firstFdDataWorkspaceIdx[i]; - } - } - - // FD Metadata Generate - for (size_t i = 0; i < aivCoreNum_; ++i) { - if (i >= splitRes.fdRes.fdUsedVecNum) { - metadataPtr->fdMetadata[i][FD_CORE_ENABLE_INDEX] = 0; // AIV disenable - continue; - } - metadataPtr->fdMetadata[i][FD_CORE_ENABLE_INDEX] = 1; // AIV enable - uint32_t curFdIdx = splitRes.fdRes.fdIdx[i]; - metadataPtr->fdMetadata[i][FD_BN2_IDX_INDEX] = - splitRes.fdRes.fdBN2Idx[curFdIdx]; - metadataPtr->fdMetadata[i][FD_M_IDX_INDEX] = - splitRes.fdRes.fdMIdx[curFdIdx]; - metadataPtr->fdMetadata[i][FD_WORKSPACE_IDX_INDEX] = - splitRes.fdRes.fdWorkspaceIdx[curFdIdx]; - metadataPtr->fdMetadata[i][FD_WORKSPACE_NUM_INDEX] = - splitRes.fdRes.fdS2SplitNum[curFdIdx]; - metadataPtr->fdMetadata[i][FD_M_START_INDEX] = splitRes.fdRes.fdMStart[i]; - metadataPtr->fdMetadata[i][FD_M_NUM_INDEX] = splitRes.fdRes.fdMNum[i]; - } - return true; -} - -namespace { -static const char* kernelType = "XllmKernelSparseFlashMlaMetadata"; -REGISTER_CPU_KERNEL(kernelType, XllmKernelSparseFlashMlaMetadataCpuKernel); -} // namespace - -}; // namespace aicpu::xllm_sparse_mla diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.h b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.h deleted file mode 100644 index d23c68d778..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.h +++ /dev/null @@ -1,430 +0,0 @@ -/** - * Copyright (c) 2026 Huawei Technologies Co., Ltd. - * This program is free software, you can redistribute it and/or modify it under - * the terms and conditions of CANN Open Software License Agreement Version 2.0 - * (the "License"). Please refer to the License for details. You may not use - * this file except in compliance with the License. THIS SOFTWARE IS PROVIDED ON - * AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS - * FOR A PARTICULAR PURPOSE. See LICENSE in the root of the software repository - * for the full text of the License. - */ - -/*! - * \file sparse_flash_mla_metadata_aicpu.h - * \brief - */ - -#ifndef SPARSE_FLASH_MLA_METADATA_AICPU_H -#define SPARSE_FLASH_MLA_METADATA_AICPU_H - -#include -#include -#include - -#include "cpu_context.h" -#include "cpu_kernel.h" -#include "cpu_tensor.h" -#include "quant_lightning_indexer_metadata/op_kernel_aicpu/cpu_context_util.h" -#include "sparse_flash_mla/op_kernel/sparse_flash_mla_kernel_metadata.h" - -namespace aicpu::xllm_sparse_mla { -constexpr int64_t FA_TOLERANCE_RATIO = 2; -constexpr uint32_t COST_WEIGHT_M = 6U; -constexpr uint32_t COST_WEIGHT_S2 = 10U; -constexpr uint32_t BATCH_CONSISTENCY_MAX_REDUCTION_PARTS = 32U; - -constexpr bool ORI_KV = false; -constexpr bool CMP_KV = true; -constexpr uint32_t NO_MASK = 0; -constexpr uint32_t HAS_MASK = 1; -constexpr uint32_t NUM_2 = 2; - -enum BlockType : uint32_t { - ORI_NORMAL_BLOCK = 0, - ORI_TAIL_BLOCK, - CMP_NORMAL_BLOCK, - CMP_TAIL_BLOCK, - BLOCK_MAX_TYPE -}; - -enum class SparseMode : uint8_t { - DEFAULT_MASK = 0, - ALL_MASK, - LEFT_UP_CAUSAL, - RIGHT_DOWN_CAUSAL, - BAND, - SPARSE_BUTT, -}; - -enum class ValidSocVersion { ASCEND910 = 0, ASCEND950, ASCEND960 }; - -template -using Range = std::pair; - -template -using BlockCost = std::array(BLOCK_MAX_TYPE)>, - static_cast(BLOCK_MAX_TYPE)>; - -template -T Clip(T value, T minValue, T maxValue) { - if (value < minValue) { - return minValue; - } - if (value > maxValue) { - return maxValue; - } - return value; -} - -template -inline bool IsWithinTolerance(T limit, T tolerance, T value) { - return limit + tolerance >= value; -} - -// 分核功能模块输出:FD信息,包含需要归约的数据索引及其分核信息 -struct FlashDecodeResult { - uint32_t fdUsedVecNum{0U}; // 归约过程使用的vector数量 - // 1、归约任务的索引信息 - std::vector - fdBN2Idx{}; // 每个归约任务的BN2索引,脚标为归约任务的序号,最大为核数-1 - std::vector - fdMIdx{}; // 每个归约任务的GS1索引,脚标为归约任务的序号 - std::vector - fdWorkspaceIdx{}; // 每个归约任务在workspace中的存放位置 - std::vector - fdS2SplitNum{}; // 每个归约任务的S2核间切分份数,脚标为归约任务的序号 - std::vector fdMSize{}; // 每个归约任务m轴大小,脚标为归约任务的序号 - // 2、FD负载均衡阶段,归约任务的分核(vec)信息 - std::vector - fdIdx{}; // FD负载均衡阶段,每个vector处理的归约任务对应ID - std::vector - fdMStart{}; // FD负载均衡阶段,每个vector处理的归约任务的m轴起点 - std::vector - fdMNum{}; // FD负载均衡阶段,每个vector处理的归约任务的m轴行数 - - FlashDecodeResult(uint32_t aicNum, uint32_t aivNum) - : fdBN2Idx(aicNum), - fdMIdx(aicNum), - fdWorkspaceIdx(aicNum), - fdS2SplitNum(aicNum), - fdMSize(aicNum), - fdIdx(aivNum), - fdMStart(aivNum), - fdMNum(aivNum) {} -}; - -// 分核功能模块输出:FA阶段的核间分核信息 -struct SplitResult { - uint32_t usedCoreNum{0U}; // 使用的核数量 - std::vector bN2End{}; // 每个核处理数据的BN2结束点 - std::vector gS1End{}; // 每个核处理数据的GS1结束点 - std::vector s2End{}; // 每个核处理数据的S2结束点 - std::vector - firstFdDataWorkspaceIdx{}; // 每个核第一份归约任务的存放位置 - int64_t maxCost{0}; // 慢核开销 - uint32_t numOfFdHead{0U}; // 归约任务数量 - uint32_t maxS2SplitNum{0U}; // 单个归约任务最大分核数量 - uint32_t maxS2LoopNum{0U}; // 单个核最大s2计算轮次数量 - FlashDecodeResult fdRes{0U, 0U}; // FD信息 - - SplitResult(uint32_t aicNum, uint32_t aivNum) - : bN2End(aicNum), - gS1End(aicNum), - s2End(aicNum), - firstFdDataWorkspaceIdx(aicNum), - fdRes(aicNum, aivNum) {}; -}; - -// 分核功能模块内部使用:记录切分信息 -struct SplitInfo { - std::vector s1GBaseNum{}; // S1G方向,切了多少个基本块 - std::vector oriS2BaseNum{}; // oriS2方向,切了多少个基本块 - std::vector cmpS2BaseNum{}; // cmpS2方向,切了多少个基本块 - std::vector s1GTailSize{}; // S1G方向,尾块size - std::vector oriS2TailSize{}; // oriS2方向,尾块size - std::vector cmpS2TailSize{}; // cmpS2方向,尾块size - bool isKvSeqAllZero{true}; - - explicit SplitInfo(uint32_t batchSize) - : s1GBaseNum(batchSize), - oriS2BaseNum(batchSize), - cmpS2BaseNum(batchSize), - s1GTailSize(batchSize), - oriS2TailSize(batchSize), - cmpS2TailSize(batchSize) {} -}; - -// 分核功能模块内部使用:记录batch的开销信息 -struct CostInfo { - std::vector bN2CostOfEachBatch{}; // 整个batch的开销 - std::vector bN2BlockOfEachBatch{}; // 整个batch的开销 - std::vector bN2S2LoopOfEachBatch{}; // 整个batch的s2计算轮次数量 - std::vector bN2LastBlockCostOfEachBatch{}; // batch最后一块的开销 - uint32_t totalBlockNum{0U}; - int64_t totalCost{0}; - int64_t maxS1GCost{0}; // 记录所有S1G行中的最大开销 - - explicit CostInfo(uint32_t batchSize) - : bN2CostOfEachBatch(batchSize), - bN2BlockOfEachBatch(batchSize), - bN2S2LoopOfEachBatch(batchSize), - bN2LastBlockCostOfEachBatch(batchSize) {} -}; - -// 分核功能模块内部使用:分核过程中,case基本信息的上下文信息,组合以减少接口传参数量 -struct SplitContext { - SplitInfo splitInfo{0U}; - CostInfo costInfo{0U}; - - explicit SplitContext(uint32_t batchSize) - : splitInfo(batchSize), costInfo(batchSize) {} -}; - -// 分核功能模块内部使用:记录batch相关的临时信息 -struct BatchCache { - uint32_t bIdx{0U}; - uint32_t s1Size{0U}; - uint32_t oriS2Size{0U}; - uint64_t cmpRevertS2Size{0U}; - int64_t oriPreTokenLeftUp{0}; - int64_t oriNextTokenLeftUp{0}; - int64_t cmpPreTokenLeftUp{0}; - int64_t cmpNextTokenLeftUp{0}; - BlockCost typeCost{}; -}; - -// 分核功能模块内部使用:记录当前行(S1G)的临时信息 -struct S1GCache { - uint32_t bIdx{0U}; - uint32_t s1GIdx{0U}; - uint32_t s2Start{0U}; - uint32_t s2End{0U}; - uint32_t oriS2Start{0U}; - uint32_t oriS2End{0U}; - uint32_t cmpS2Start{0U}; // win部分与cmp部分的切分点 - uint32_t cmpS2End{0U}; - int64_t s1GCost{0}; - int64_t s1GLastBlockCost{0}; - uint32_t s1GBlock{0U}; - uint32_t s2Loop{0U}; - uint32_t oriS1GBlock{0U}; - int64_t oriS1GCost{0}; - int64_t oriS1GLastBlockCost{0}; - int64_t oriS1GNormalBlockCost{0}; - uint32_t cmpS1GBlock{0U}; - int64_t cmpS1GCost{0}; - int64_t cmpS1GLastBlockCost{0}; - int64_t cmpS1GNormalBlockCost{0}; - int64_t oriS2TailSize{0}; - int64_t cmpS2TailSize{0}; - uint32_t actOriS2Size{0U}; - uint32_t actCmpS2Size{0U}; - uint32_t reductionBlockSize{0U}; -}; - -// 分核功能模块内部使用:记录分配过程中,当前核的负载信息 -struct CoreCache { - int64_t costLimit{0}; // 负载上限 - int64_t cost{0}; // 已分配负载 - uint32_t block{0U}; // 已分配块数 - uint32_t s2Loop{0U}; // 已分配s2计算轮次数量 -}; - -// 分核功能模块内部使用:记录分配过程中的上下文信息 -struct AssignContext { - uint32_t curBIdx{0U}; - uint32_t curBN2Idx{0U}; - uint32_t curS1GIdx{0U}; - uint32_t curS2Idx{0U}; - uint32_t curCoreIdx{0U}; - int64_t unassignedCost{0}; - uint32_t curKvSplitPart{1U}; - uint32_t preFdDataNum{0U}; - - int64_t bN2Cost{0}; - uint32_t bN2Block{0U}; - uint32_t bN2S2Loop{0U}; - bool isFinished{false}; - BatchCache batchCache{}; - S1GCache s1GCache{}; - CoreCache coreCache{}; -}; - -class XllmKernelSparseFlashMlaMetadataCpuKernel : public CpuKernel { - public: - XllmKernelSparseFlashMlaMetadataCpuKernel() = default; - ~XllmKernelSparseFlashMlaMetadataCpuKernel() = default; - uint32_t Compute(CpuKernelContext& ctx) override; - - private: - bool Prepare(CpuKernelContext& ctx); - int32_t GetQueryBatchSize(); - void CalcOriMaskMode(); - void CalcCmpMaskMode(); - ValidSocVersion ProcessSocVersion(); - bool ParamsCheck(); - int32_t GetSumOfQuerySeq(); - bool ParamsInit(); - bool BalanceSchedule(SplitResult& splitRes); - bool GenMetadata(SplitResult& splitRes); - // util - uint32_t GetS1SeqSize(uint32_t bIdx); - uint32_t GetOriS2SeqSize(uint32_t bIdx); - uint32_t GetCmpS2SeqSize(uint32_t bIdx); - uint64_t GetRevertS2Size(uint32_t bIdx); - uint32_t GetS1Idx(uint32_t s1Size, uint32_t s1GIdx); - uint32_t GetBsStride(uint32_t bIdx, uint32_t s1Idx); - uint32_t GetOriTopkLength(uint32_t bsStride); - uint32_t GetOriTopkLength(uint32_t s1GIdx, - const BatchCache& batchCache) const; - uint32_t ReadOriTopkLengthAtRow(uint32_t bIdx, uint32_t s1Idx) const; - uint32_t GetCmpTopkLength(uint32_t bsStride); - int64_t CalcOriPreTokenLeftUp(uint32_t s1Size, uint32_t s2Size); - int64_t CalcOriNextTokenLeftUp(uint32_t s1Size, uint32_t s2Size); - int64_t CalcCmpPreTokenLeftUp(uint32_t s1Size, uint64_t s2Size); - int64_t CalcCmpNextTokenLeftUp(uint32_t s1Size, uint64_t s2Size); - Range CalcS2TokenRange(uint32_t s1GIdx, - const BatchCache& batchCache, - bool isCmpKv); - int64_t OriCalcCost(uint32_t basicM, uint32_t basicS2); - int64_t CmpCalcCost(uint32_t basicM, uint32_t basicS2); - void CalcCostTable(uint32_t s1GTailSize, - uint32_t reductionBlockSize, - uint32_t oriS2TailSize, - uint32_t cmpS2TailSize); - - // cache calculation - void CalcBatchCache(uint32_t bIdx, - const SplitContext& splitContext, - BatchCache& batchCache); - void CalcOriBlockRange(const Range& oriS2TokenRange, - const BatchCache& batchCache, - S1GCache& s1GCache); - void CalcCmpBlockRange(const Range& cmpS2TokenRange, - const BatchCache& batchCache, - S1GCache& s1GCache); - void CalcOriS1GCache(S1GCache& s1GCache, const SplitInfo& splitInfo); - void CalcCmpS1GCache(S1GCache& s1GCache, const SplitInfo& splitInfo); - void GatherOriAndCmpCache(S1GCache& s1GCache); - void CalcS1GCache(uint32_t s1GIdx, - const SplitContext& splitContext, - const BatchCache& batchCache, - S1GCache& s1GCache); - - // preprocess - void CalcSplitInfo(SplitContext& splitContext); - void CalcBatchCost(uint32_t bIdx, - const SplitContext& splitContext, - CostInfo& costInfo); - void CalcCostInfo(SplitContext& splitContext); - - // assign - void UpdateCursor(const SplitContext& splitContext, - AssignContext& assignContext); - void AssignByBatch(const SplitContext& splitContext, - AssignContext& assignContext); - void AssignByRow(const SplitContext& splitContext, - AssignContext& assignContext); - int64_t CalcCurBlockCost(const AssignContext& assignContext); - uint32_t CalcCurBlockS2Loop(const AssignContext& assignContext); - void AssignByBlock(const SplitContext& splitContext, - AssignContext& assignContext); - void ForceAssign(const SplitContext& splitContext, - AssignContext& assignContext); - void AssignBlocksToCore(const SplitContext& splitContext, - AssignContext& assignContext, - SplitResult& result); - - // FD - bool IsNeedRecordFDInfo(const AssignContext& assignContext, - const SplitResult& splitRes); - bool IsFirstReductionBlock(const AssignContext& assignContext, - const SplitResult& splitRes); - void RecordFDInfo(const SplitContext& splitContext, - const AssignContext& assignContext, - SplitResult& result); - - // main - void SplitFD(SplitResult& splitRes); - void CalcSplitPlan(int64_t costLimit, - const SplitContext& splitContext, - SplitResult& result); - - private: - // input - Tensor* cuSeqlensQ_ = nullptr; - Tensor* cuSeqlensOriKv_ = nullptr; - Tensor* cuSeqlensCmpKv_ = nullptr; - Tensor* sequsedQ_ = nullptr; - Tensor* sequsedOriKv_ = nullptr; - Tensor* sequsedCmpKv_ = nullptr; - Tensor* cmpResidualKv_ = nullptr; - Tensor* oriTopkLength_ = nullptr; - Tensor* cmpTopkLength_ = nullptr; - - // output - Tensor* metadata_ = nullptr; - - // attributes - int32_t batchSize_ = 0; - int32_t maxSeqlenQ_ = 0; - int32_t numHeadsQ_ = 0; - int32_t maxSeqlenOriKv_ = 0; - int32_t maxSeqlenCmpKv_ = 0; - int32_t numHeadsKv_ = 1; - int32_t headDim_ = 0; - int32_t oriTopK_ = 0; - int32_t cmpTopK_ = 0; - int32_t cmpRatio_ = 1; - int32_t oriMaskMode_ = static_cast(SparseMode::BAND); - int32_t cmpMaskMode_ = static_cast(SparseMode::RIGHT_DOWN_CAUSAL); - int64_t oriWinLeft_ = 127; - int64_t oriWinRight_ = 0; - std::string layoutQ_ = "BSND"; - std::string layoutKv_ = "PA_BBND"; - bool hasOriKv_ = true; - bool hasCmpKv_ = true; - uint32_t aicCoreNum_ = optiling::AIC_CORE_MAX_NUM; - uint32_t aivCoreNum_ = optiling::AIV_CORE_MAX_NUM; - bool isBatchConsistency_ = false; - - // attr - std::string socVersion_ = "Ascend950"; - int64_t oriPreToken_ = 0; - int64_t oriNextToken_ = 0; - int64_t cmpPreToken_ = 0; - int64_t cmpNextToken_ = 0; - uint32_t groupSize_ = 0; - uint32_t mBaseSize_ = 0; - uint32_t s2BaseSize_ = 128U; - bool isS1G_ = true; - bool supportFd_ = false; - uint32_t oriAttentionMode_ = HAS_MASK; - uint32_t cmpAttentionMode_ = HAS_MASK; - BlockCost typeCost_ = {}; - bool isSplitG_ = false; - bool isSparseOriKv_ = false; - bool isSparseCmpKv_ = false; - bool hasOriTopkLength_ = false; - uint32_t remainedBlockNum_ = 0U; - - private: - enum class ParamId : uint32_t { - // input - cuSeqlensQ = 0, - cuSeqlensOriKv = 1, - cuSeqlensCmpKv = 2, - sequsedQ = 3, - sequsedOriKv = 4, - sequsedCmpKv = 5, - cmpResidualKv = 6, - oriTopkLength = 7, - cmpTopkLength = 8, - // output - metaData = 0, - }; -}; -} // namespace aicpu::xllm_sparse_mla - -#endif diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.json b/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.json deleted file mode 100644 index e7736eaf11..0000000000 --- a/xllm-kernel/csrc/ascendc/sparse_flash_mla_metadata/op_kernel_aicpu/sparse_flash_mla_metadata_aicpu.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "XllmKernelSparseFlashMlaMetadata":{ - "opInfo":{ - "computeCost":"100", - "engine":"DNN_VM_AICPU", - "flagAsync":"False", - "flagPartial":"False", - "functionName":"RunCpuKernel", - "kernelSo":"libmath_aicpu_kernels.so", - "opKernelLib":"CUSTAICPUKernel", - "userDefined":"True", - "workspaceSize":"100" - } - } -} diff --git a/xllm-kernel/csrc/ascendc/v41_sparse_mla.cmake b/xllm-kernel/csrc/ascendc/v41_sparse_mla.cmake deleted file mode 100644 index 14fa904d11..0000000000 --- a/xllm-kernel/csrc/ascendc/v41_sparse_mla.cmake +++ /dev/null @@ -1,48 +0,0 @@ -# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. - -if(NOT "ascend910_93" IN_LIST ASCEND_COMPUTE_UNIT) - return() -endif() - -set(smla "${CMAKE_CURRENT_SOURCE_DIR}/sparse_flash_mla") -set(smla_host "${smla}/op_host") -set(smla_metadata "${CMAKE_CURRENT_SOURCE_DIR}/sparse_flash_mla_metadata") -list(APPEND op_definitions "${smla_host}/sparse_flash_mla_def.cpp") -file(GLOB smla_checkers CONFIGURE_DEPENDS "${smla_host}/checkers/*.cpp") -list(APPEND sparse_attention_tiling - "${smla_host}/sparse_flash_mla_infershape.cpp" - "${smla_host}/sparse_flash_mla_tiling.cpp" - ${smla_checkers} - "${smla_metadata}/op_host/sparse_flash_mla_metadata_infershape.cpp" -) -set(smla_metadata_api - "${smla_metadata}/op_host/op_api/aclnn_sparse_flash_mla_metadata.cpp" - "${smla_metadata}/op_host/op_api/sparse_flash_mla_metadata.cpp" -) -set_property(SOURCE ${smla_metadata_api} APPEND PROPERTY - COMPILE_DEFINITIONS OP_LOG_LIBOPAPI_ONLY) -set_property(SOURCE ${smla_metadata_api} APPEND PROPERTY - INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}" "${ASCEND_CANN_PACKAGE_PATH}/pkg_inc/op_common") -set_property(SOURCE ${smla_checkers} "${smla_host}/sparse_flash_mla_tiling.cpp" - "${smla_host}/sparse_flash_mla_infershape.cpp" APPEND PROPERTY - INCLUDE_DIRECTORIES "${smla_host}" "${ASCEND_CANN_PACKAGE_PATH}/pkg_inc/op_common") -list(APPEND sparse_attention_api - "${ASCEND_AUTOGEN_PATH}/aclnn_xllm_kernel_sparse_flash_mla.cpp" - ${smla_metadata_api} -) -list(APPEND v41_metadata_graph_sources "${smla_metadata}/op_graph/sparse_flash_mla_metadata_proto.cpp") -list(APPEND v41_aicpu_components sparse_flash_mla_metadata) -list(APPEND v41_aicpu_headers - "${smla}/op_kernel/sparse_flash_mla_kernel_metadata.h" - "${smla}/op_kernel/arch35/common/smla_metadata_common.h" -) -macro(v41_sparse_mla_kernel) - npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelSparseFlashMla - KERNEL_DIR sparse_flash_mla/op_kernel KERNEL_FILE xllm_kernel_sparse_flash_mla.cpp) - npu_op_kernel_options(ascendc_kernels XllmKernelSparseFlashMla - OPTIONS --cce-auto-sync=off -Wno-deprecated-declarations -Werror - -mllvm -cce-vf-remove-membar=false -mllvm -cce-aicore-hoist-movemask=false) -endmacro() -install(FILES "${smla_metadata}/op_host/op_api/aclnn_sparse_flash_mla_metadata.h" - DESTINATION "packages/vendors/${vendor}/op_api/include" - RENAME aclnn_xllm_kernel_sparse_flash_mla_metadata.h) diff --git a/xllm-kernel/csrc/npu/v41_quant_indexer.cpp b/xllm-kernel/csrc/npu/v41_quant_indexer.cpp index e5eebd7b97..3c821993a7 100644 --- a/xllm-kernel/csrc/npu/v41_quant_indexer.cpp +++ b/xllm-kernel/csrc/npu/v41_quant_indexer.cpp @@ -64,7 +64,7 @@ constexpr int64_t kNoReturnValue = 0; constexpr int64_t kRightDownCausal = 3; constexpr int64_t kCandidateSource = 1; -torch::Tensor quant_lightning_indexer_v2_metadata( +torch::Tensor quant_lightning_indexer_v2_metadata_va( const torch::Tensor& query_offsets, const torch::Tensor& committed_lengths, const std::optional& residual_lengths, @@ -152,7 +152,7 @@ torch::Tensor quant_sparse_lightning_indexer_metadata( return metadata; } -std::tuple quant_lightning_indexer_v2( +std::tuple quant_lightning_indexer_v2_va( const torch::Tensor& query, const torch::Tensor& key, const torch::Tensor& weights, @@ -310,13 +310,13 @@ quant_lightning_indexer_v3( TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { m.def("prepare_ascendc_v41_indexer() -> ()", &prepare_ascendc_v41_indexer); m.def( - "quant_lightning_indexer_v2_metadata(Tensor query_offsets, Tensor " + "quant_lightning_indexer_v2_metadata_va(Tensor query_offsets, Tensor " "committed_lengths, " "Tensor? residual_lengths, int query_heads, int head_dim, int topk, " "int max_query_len, int max_committed_len, int compression_ratio) -> " "Tensor"); m.def( - "quant_lightning_indexer_v2(Tensor query, Tensor key, Tensor weights, " + "quant_lightning_indexer_v2_va(Tensor query, Tensor key, Tensor weights, " "Tensor query_scale, Tensor key_scale, Tensor query_offsets, " "Tensor committed_lengths, Tensor? residual_lengths, Tensor block_table, " "Tensor metadata, Tensor? candidate_blocks, int topk, int max_query_len, " @@ -340,9 +340,10 @@ TORCH_LIBRARY_IMPL(xllm_kernel, PrivateUse1, m) { m.impl("quant_sparse_lightning_indexer_metadata", TORCH_FN(quant_sparse_lightning_indexer_metadata)); m.impl("quant_lightning_indexer_v3", TORCH_FN(quant_lightning_indexer_v3)); - m.impl("quant_lightning_indexer_v2_metadata", - TORCH_FN(quant_lightning_indexer_v2_metadata)); - m.impl("quant_lightning_indexer_v2", TORCH_FN(quant_lightning_indexer_v2)); + m.impl("quant_lightning_indexer_v2_metadata_va", + TORCH_FN(quant_lightning_indexer_v2_metadata_va)); + m.impl("quant_lightning_indexer_v2_va", + TORCH_FN(quant_lightning_indexer_v2_va)); } } // namespace } // namespace xllm_kernel diff --git a/xllm-kernel/csrc/npu/v41_sparse_mla.cpp b/xllm-kernel/csrc/npu/v41_sparse_mla.cpp deleted file mode 100644 index bcfa1ba878..0000000000 --- a/xllm-kernel/csrc/npu/v41_sparse_mla.cpp +++ /dev/null @@ -1,206 +0,0 @@ -// Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. - -#include -#include - -#include -#include -#include - -#include "csrc/ascendc/sparse_flash_mla/op_kernel/sparse_flash_mla_kernel_metadata.h" -#include "csrc/npu/ascendc_api.h" -#include "op_plugin/utils/op_api_common_base.h" - -namespace xllm_kernel { -namespace { - -const AscendcApi& mla_api() { - static const auto api = - load_ascendc_api("aclnnXllmKernelSparseFlashMla", - "aclnnXllmKernelSparseFlashMlaGetWorkspaceSize"); - return api; -} - -const AscendcApi& metadata_api() { - static const auto api = - load_ascendc_api("aclnnXllmKernelSparseFlashMlaMetadata", - "aclnnXllmKernelSparseFlashMlaMetadataGetWorkspaceSize"); - return api; -} - -void GetApiFunc(const char* name, - const char* /*workspace_name*/, - void*& launch, - void*& workspace) { - const auto& api = std::string_view(name) == "aclnnXllmKernelSparseFlashMla" - ? mla_api() - : metadata_api(); - launch = api.launch; - workspace = api.workspace; -} - -constexpr int64_t kSwaMaskMode = 4; -constexpr int64_t kNonCausalMaskMode = 0; -constexpr int64_t kNumKvHeads = 1; -constexpr int64_t kCmpCausalMaskMode = 3; -constexpr int64_t kWinRight = 0; -constexpr int64_t kTopkValueMode = 1; -constexpr bool kHasOriKv = true; -constexpr bool kReturnSoftmaxLse = false; - -torch::Tensor sparse_flash_mla_metadata( - const torch::Tensor& cu_seqlens_q, - const torch::Tensor& seqused_kv, - const std::optional& seqused_cmp_kv, - const std::optional& cmp_residual_kv, - int64_t num_heads_q, - int64_t head_dim, - int64_t max_seqlen_q, - int64_t max_seqlen_kv, - int64_t max_seqlen_cmp_kv, - int64_t cmp_topk, - int64_t cmp_ratio, - int64_t window_size, - const std::optional& ori_topk_length, - int64_t ori_topk) { - auto output = cu_seqlens_q.new_empty({optiling::SMLA_METADATA_TOTAL_SIZE}); - auto empty = cu_seqlens_q.new_empty({0}); - const int64_t batch_size = seqused_kv.numel(); - const int64_t win_left = window_size - 1; - const bool has_cmp_kv = cmp_ratio > 0; - const int64_t cmp_mask_mode = has_cmp_kv ? kCmpCausalMaskMode : 0; - char layout_q[] = "TND"; - char layout_kv[] = "PA_BBND"; - const auto cmp_lengths = seqused_cmp_kv.value_or(empty); - const auto residual = cmp_residual_kv.value_or(empty); - const auto ori_lengths = ori_topk_length.value_or(empty); - const int64_t ori_mask_mode = - ori_topk > 0 ? kNonCausalMaskMode : kSwaMaskMode; - EXEC_NPU_CMD_EXT(aclnnXllmKernelSparseFlashMlaMetadata, - cu_seqlens_q, - /*cu_seqlens_ori_kv=*/empty, - /*cu_seqlens_cmp_kv=*/empty, - /*seqused_q=*/empty, - seqused_kv, - cmp_lengths, - residual, - ori_lengths, - /*cmp_topk_length=*/empty, - num_heads_q, - kNumKvHeads, - head_dim, - batch_size, - max_seqlen_q, - max_seqlen_kv, - max_seqlen_cmp_kv, - ori_topk, - cmp_topk, - cmp_ratio, - ori_mask_mode, - cmp_mask_mode, - win_left, - kWinRight, - layout_q, - layout_kv, - kHasOriKv, - has_cmp_kv, - output); - return output; -} - -torch::Tensor sparse_flash_mla( - const torch::Tensor& q, - const torch::Tensor& kv, - const torch::Tensor& block_table, - const torch::Tensor& cu_seqlens_q, - const torch::Tensor& seqused_kv, - const std::optional& cmp_kv, - const std::optional& cmp_block_table, - const std::optional& cmp_indices, - const std::optional& seqused_cmp_kv, - const std::optional& cmp_residual_kv, - const std::optional& sinks, - const torch::Tensor& metadata, - double softmax_scale, - int64_t cmp_ratio, - int64_t window_size, - const std::optional& ori_sparse_indices, - const std::optional& ori_topk_length) { - auto output = torch::empty_like(q); - auto softmax_lse = torch::empty({0}, q.options().dtype(torch::kFloat32)); - const int64_t win_left = window_size - 1; - const bool has_cmp_kv = cmp_ratio > 0; - const int64_t cmp_mask_mode = has_cmp_kv ? kCmpCausalMaskMode : 0; - const std::optional absent; - const int64_t ori_mask_mode = - ori_sparse_indices.has_value() ? kNonCausalMaskMode : kSwaMaskMode; - char layout_q[] = "TND"; - char layout_kv[] = "PA_BBND"; - // A3 requires a per-head sink. A logit of -inf adds zero softmax mass. - auto sink_logits = sinks - ? *sinks - : torch::full({q.size(1)}, - -std::numeric_limits::infinity(), - q.options().dtype(torch::kFloat32)); - EXEC_NPU_CMD_EXT(aclnnXllmKernelSparseFlashMla, - q, - kv, - cmp_kv, - ori_sparse_indices, - cmp_indices, - block_table, - cmp_block_table, - cu_seqlens_q, - /*cu_seqlens_ori_kv=*/absent, - /*cu_seqlens_cmp_kv=*/absent, - /*seqused_q=*/absent, - seqused_kv, - seqused_cmp_kv, - cmp_residual_kv, - ori_topk_length, - /*cmp_topk_length=*/absent, - sink_logits, - metadata, - softmax_scale, - cmp_ratio, - ori_mask_mode, - cmp_mask_mode, - win_left, - kWinRight, - layout_q, - layout_kv, - kTopkValueMode, - kReturnSoftmaxLse, - output, - softmax_lse); - return output; -} - -TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { - m.def("prepare_ascendc_v41_mla() -> ()", []() { - mla_api(); - metadata_api(); - }); - m.def( - "sparse_flash_mla_metadata(Tensor cu_seqlens_q, Tensor seqused_kv, " - "Tensor? seqused_cmp_kv, Tensor? cmp_residual_kv, int num_heads_q, " - "int head_dim, int max_seqlen_q, int max_seqlen_kv, " - "int max_seqlen_cmp_kv, int cmp_topk, int cmp_ratio, int window_size, " - "Tensor? ori_topk_length=None, int ori_topk=0) -> Tensor"); - m.def( - "sparse_flash_mla(Tensor q, Tensor kv, Tensor block_table, " - "Tensor cu_seqlens_q, Tensor seqused_kv, Tensor? cmp_kv, " - "Tensor? cmp_block_table, Tensor? cmp_indices, Tensor? seqused_cmp_kv, " - "Tensor? cmp_residual_kv, Tensor? sinks, Tensor metadata, " - "float softmax_scale, int cmp_ratio, int window_size, " - "Tensor? ori_sparse_indices=None, Tensor? ori_topk_length=None) -> " - "Tensor"); -} - -TORCH_LIBRARY_IMPL(xllm_kernel, PrivateUse1, m) { - m.impl("sparse_flash_mla_metadata", TORCH_FN(sparse_flash_mla_metadata)); - m.impl("sparse_flash_mla", TORCH_FN(sparse_flash_mla)); -} - -} // namespace -} // namespace xllm_kernel diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/__init__.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/__init__.py index ebf4248346..6cbc134ea1 100644 --- a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/__init__.py +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/__init__.py @@ -119,17 +119,13 @@ def v41_c2_decode_pool_norm( ), ) for name in ( - "quant_lightning_indexer_v2_metadata", - "quant_lightning_indexer_v2", + "quant_lightning_indexer_v2_metadata_va", + "quant_lightning_indexer_v2_va", "quant_sparse_lightning_indexer_metadata", "quant_lightning_indexer_v3", - "sparse_flash_mla_metadata", - "sparse_flash_mla", ) ) -(_INDEXER_METADATA, _INDEXER, _SPARSE_INDEXER_METADATA, _INDEXER_V3, _SPARSE_FLASH_MLA_METADATA, _SPARSE_FLASH_MLA) = ( - ASCENDC_OPERATIONS -) +_INDEXER_METADATA, _INDEXER, _SPARSE_INDEXER_METADATA, _INDEXER_V3 = ASCENDC_OPERATIONS OPERATIONS = TILELANG_OPERATIONS + TRITON_OPERATIONS + ASCENDC_OPERATIONS diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/ascendc.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/ascendc.py index f6d1166041..fdb2915751 100644 --- a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/ascendc.py +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/ascendc.py @@ -1,5 +1,5 @@ # Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. -"""Prepare the package-owned Ascend A3 candidate indexer and sparse MLA.""" +"""Prepare the package-owned Ascend A3 candidate indexer.""" import torch @@ -9,7 +9,6 @@ from xllm_kernel.registry import register_kernel torch.ops.xllm_kernel.prepare_ascendc_v41_indexer() -torch.ops.xllm_kernel.prepare_ascendc_v41_mla() for operation, domain in zip( ASCENDC_OPERATIONS, @@ -18,8 +17,6 @@ "Paged INT8 index keys with FP16 scales and optional sparse candidate blocks on Ascend A3.", "Device-side candidate counts and committed lengths for sparse QLI on Ascend A3.", "Paged INT8 index keys with candidate block IDs and per-row valid block counts on Ascend A3.", - "Device lengths for the sliding window and optional compressed KV cache on Ascend A3.", - "BF16 sliding-window attention with optional compressed sparse KV on Ascend A3.", ), strict=True, ): diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/indexer.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/indexer.py index 890b838fbd..44993aa6b8 100644 --- a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/indexer.py +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/indexer.py @@ -11,7 +11,7 @@ import torch -def quant_lightning_indexer_v2_metadata( +def quant_lightning_indexer_v2_metadata_va( query_offsets: torch.Tensor, committed_lengths: torch.Tensor, residual_lengths: torch.Tensor | None, @@ -35,7 +35,7 @@ def quant_lightning_indexer_v2_metadata( ) -def quant_lightning_indexer_v2( +def quant_lightning_indexer_v2_va( query: torch.Tensor, key: torch.Tensor, weights: torch.Tensor, diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/mla.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/mla.py deleted file mode 100644 index 3da7ce0cf9..0000000000 --- a/xllm-kernel/python/xllm_kernel/ops/attention/dsv41/mla.py +++ /dev/null @@ -1,87 +0,0 @@ -# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. -"""Paged original and compressed KV attention for DeepSeek V4.1 on Ascend A3.""" - -from __future__ import annotations - -from typing import TYPE_CHECKING - -from xllm_kernel.ops.attention.dsv41 import _SPARSE_FLASH_MLA, _SPARSE_FLASH_MLA_METADATA - -if TYPE_CHECKING: - import torch - - -def sparse_flash_mla_metadata( - cu_seqlens_q: torch.Tensor, - seqused_kv: torch.Tensor, - seqused_cmp_kv: torch.Tensor | None, - cmp_residual_kv: torch.Tensor | None, - num_heads_q: int, - head_dim: int, - max_seqlen_q: int, - max_seqlen_kv: int, - max_seqlen_cmp_kv: int, - cmp_topk: int, - cmp_ratio: int, - window_size: int, - ori_topk_length: torch.Tensor | None = None, - ori_topk: int = 0, -) -> torch.Tensor: - """Generate device tiling from the lengths and optional sparse SWA selection.""" - return _SPARSE_FLASH_MLA_METADATA.get_prepared().function( - cu_seqlens_q, - seqused_kv, - seqused_cmp_kv, - cmp_residual_kv, - num_heads_q, - head_dim, - max_seqlen_q, - max_seqlen_kv, - max_seqlen_cmp_kv, - cmp_topk, - cmp_ratio, - window_size, - ori_topk_length, - ori_topk, - ) - - -def sparse_flash_mla( - q: torch.Tensor, - kv: torch.Tensor, - block_table: torch.Tensor, - cu_seqlens_q: torch.Tensor, - seqused_kv: torch.Tensor, - cmp_kv: torch.Tensor | None, - cmp_block_table: torch.Tensor | None, - cmp_indices: torch.Tensor | None, - seqused_cmp_kv: torch.Tensor | None, - cmp_residual_kv: torch.Tensor | None, - sinks: torch.Tensor | None, - metadata: torch.Tensor, - softmax_scale: float, - cmp_ratio: int, - window_size: int, - ori_sparse_indices: torch.Tensor | None = None, - ori_topk_length: torch.Tensor | None = None, -) -> torch.Tensor: - """Attend over the sliding window and selected compressed KV tokens.""" - return _SPARSE_FLASH_MLA.get_prepared().function( - q, - kv, - block_table, - cu_seqlens_q, - seqused_kv, - cmp_kv, - cmp_block_table, - cmp_indices, - seqused_cmp_kv, - cmp_residual_kv, - sinks, - metadata, - softmax_scale, - cmp_ratio, - window_size, - ori_sparse_indices, - ori_topk_length, - ) diff --git a/xllm-kernel/setup.py b/xllm-kernel/setup.py index 771e387723..b4379f747d 100644 --- a/xllm-kernel/setup.py +++ b/xllm-kernel/setup.py @@ -157,7 +157,6 @@ def get_outputs(self) -> list[str]: "csrc/npu/sparse_attention.cpp", "csrc/npu/sparse_indexing.cpp", "csrc/npu/v41_quant_indexer.cpp", - "csrc/npu/v41_sparse_mla.cpp", "csrc/npu/top_k_top_p.cpp", "csrc/npu/sampling_bindings.cpp", ], diff --git a/xllm-kernel/test/npu/test_dsv41_sparse_attention_npu.py b/xllm-kernel/test/npu/test_dsv41_candidate_indexer_npu.py similarity index 71% rename from xllm-kernel/test/npu/test_dsv41_sparse_attention_npu.py rename to xllm-kernel/test/npu/test_dsv41_candidate_indexer_npu.py index d48b9defef..b37815ccc9 100644 --- a/xllm-kernel/test/npu/test_dsv41_sparse_attention_npu.py +++ b/xllm-kernel/test/npu/test_dsv41_candidate_indexer_npu.py @@ -1,17 +1,14 @@ # Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. -"""Exercise the A3 sparse kernels together with their device-generated metadata.""" - -import math +"""Exercise the A3 candidate indexer with device-generated metadata.""" import pytest import torch from xllm_kernel.ops.attention.dsv41.indexer import ( - quant_lightning_indexer_v2, - quant_lightning_indexer_v2_metadata, + quant_lightning_indexer_v2_metadata_va, + quant_lightning_indexer_v2_va, quant_lightning_indexer_v3, quant_sparse_lightning_indexer_metadata, ) -from xllm_kernel.ops.attention.dsv41.mla import sparse_flash_mla, sparse_flash_mla_metadata pytestmark = pytest.mark.skipif(not torch.npu.get_device_name().startswith("Ascend910_93"), reason="requires Ascend A3") @@ -28,8 +25,8 @@ def test_indexer_uses_supplied_candidate_blocks() -> None: lengths = torch.tensor([1024], dtype=torch.int32, device="npu") table = torch.arange(8, dtype=torch.int32, device="npu").reshape(1, 8) candidates = torch.arange(64, 128, dtype=torch.int32, device="npu").reshape(1, 1, 64) - metadata = quant_lightning_indexer_v2_metadata(offsets, lengths, None, heads, 128, topk, 1, 1024, 1) - indices, _ = quant_lightning_indexer_v2( + metadata = quant_lightning_indexer_v2_metadata_va(offsets, lengths, None, heads, 128, topk, 1, 1024, 1) + indices, _ = quant_lightning_indexer_v2_va( query, keys.npu(), weights, @@ -66,7 +63,7 @@ def test_indexer_source_and_consumer_share_device_counts() -> None: table = torch.tensor([list(reversed(range(8)))] * 2, dtype=torch.int32, device="npu") common = (query, keys, weights, torch.ones_like(weights), scales, offsets, lengths, None, table) args = (topk, 1, 1) - metadata = quant_lightning_indexer_v2_metadata(offsets, lengths, None, heads, 128, topk, 1, 1024, 1) + metadata = quant_lightning_indexer_v2_metadata_va(offsets, lengths, None, heads, 128, topk, 1, 1024, 1) _, candidates, counts = quant_lightning_indexer_v3(*common, metadata, None, None, *args, 1, 64, 8) sparse_meta = quant_sparse_lightning_indexer_metadata(offsets, lengths, None, counts, heads, 128, topk, 1, 1024, 1) indices, _, _ = quant_lightning_indexer_v3(*common, sparse_meta, candidates, counts, *args, 2, 64, 8) @@ -125,38 +122,3 @@ def consume() -> torch.Tensor: counts.fill_(count) graph.replay() torch.testing.assert_close(indices.cpu().flatten().sort().values, expected) - - -@pytest.mark.parametrize(("sink_logit", "expected"), [(None, 2.0), (math.log(128), 1.0)]) -def test_sparse_mla_applies_window_after_page_lookup(sink_logit: float | None, expected: float) -> None: - heads, head_dim, window = 16, 512, 128 - query = torch.zeros((1, heads, head_dim), dtype=torch.bfloat16, device="npu") - kv = torch.full((2, window, 1, head_dim), -300, dtype=torch.bfloat16) - # Logical tokens 0..127 live on page 1. Token 0 must fall out of the window. - kv[1].fill_(1) - kv[1, 0].fill_(1024) - kv[0, 0].fill_(129) - table = torch.tensor([[1, 0]], dtype=torch.int32, device="npu") - offsets = torch.tensor([0, 1], dtype=torch.int32, device="npu") - lengths = torch.tensor([129], dtype=torch.int32, device="npu") - metadata = sparse_flash_mla_metadata(offsets, lengths, None, None, heads, head_dim, 1, 256, 0, 0, 0, window) - sinks = None if sink_logit is None else torch.full((heads,), sink_logit, dtype=torch.float32, device="npu") - result = sparse_flash_mla( - query, - kv.npu(), - table, - offsets, - lengths, - None, - None, - None, - None, - None, - sinks, - metadata, - softmax_scale=head_dim**-0.5, - cmp_ratio=0, - window_size=window, - ) - # Visible values sum to 256. The optional sink doubles the softmax denominator from 128 to 256. - torch.testing.assert_close(result.cpu(), torch.full(query.shape, expected, dtype=query.dtype), rtol=0, atol=0.016)