From 87b3df3f83381d88bfaa743a9a46234882f48e57 Mon Sep 17 00:00:00 2001 From: Xu Zhang Date: Fri, 20 Nov 2026 13:13:33 +0800 Subject: [PATCH 1/3] refactor: migrate compressed and sparse attention kernels. --- .../python/test_sparse_attention_dispatch.py | 11 +- xllm-kernel/csrc/ascendc/CMakeLists.txt | 40 +- .../aicpu.cmake | 38 +- .../csrc/ascendc/compressor/SOURCE.txt | 7 + .../compressor/op_host/compressor_def.cpp | 142 + .../compressor/op_host/compressor_proto.cpp | 282 ++ .../compressor/op_host/compressor_tiling.cpp | 1403 ++++++++++ .../compressor/op_host/compressor_tiling.h | 290 ++ .../compressor/op_kernel/arch32/arch32.h | 25 + .../op_kernel/arch32/compressor_block_cube.h | 749 +++++ .../arch32/compressor_block_cube_perf.h | 598 ++++ .../op_kernel/arch32/compressor_block_vec.h | 1819 +++++++++++++ .../arch32/compressor_block_vec_perf.h | 1976 ++++++++++++++ .../op_kernel/arch32/compressor_vector_comm.h | 432 +++ .../compressor/op_kernel/arch32/rms_norm.h | 89 + .../compressor/op_kernel/arch32/rope.h | 186 ++ .../compressor/op_kernel/arch32/soft_max.h | 61 + .../op_kernel/arch35/compressor_block_cube.h | 765 ++++++ .../op_kernel/arch35/compressor_block_vec.h | 1793 ++++++++++++ .../compressor/op_kernel/arch35/vf/vf_add.h | 75 + .../compressor/op_kernel/arch35/vf/vf_mul.h | 154 ++ .../op_kernel/arch35/vf/vf_rms_norm.h | 122 + .../compressor/op_kernel/arch35/vf/vf_rope.h | 365 +++ .../op_kernel/arch35/vf/vf_softmax.h | 1393 ++++++++++ .../compressor/op_kernel/compressor_comm.h | 304 +++ .../compressor/op_kernel/compressor_kernel.h | 747 +++++ .../op_kernel/compressor_kernel_perf.h | 762 ++++++ .../compressor_template_tiling_key.h | 64 + .../op_kernel/compressor_tiling_data.h | 69 + .../compressor/op_kernel/compressor_tools.h | 835 ++++++ .../op_kernel/xllm_kernel_compressor.cpp | 100 + .../ascendc/sparse_attn_sharedkv/SOURCE.txt | 7 + .../op_host/sparse_attn_sharedkv_def.cpp | 137 + .../op_host/sparse_attn_sharedkv_proto.cpp | 72 + .../op_host/sparse_attn_sharedkv_tiling.cpp | 1860 +++++++++++++ .../op_host/sparse_attn_sharedkv_tiling.h | 590 ++++ .../sparse_attn_sharedkv_scfa_block_cube.h | 1000 +++++++ .../sparse_attn_sharedkv_scfa_block_vector.h | 1441 ++++++++++ .../arch32/sparse_attn_sharedkv_scfa_kernel.h | 990 +++++++ .../sparse_attn_sharedkv_swa_block_cube.h | 1125 ++++++++ .../sparse_attn_sharedkv_swa_block_vector.h | 1115 ++++++++ .../arch32/sparse_attn_sharedkv_swa_kernel.h | 918 +++++++ .../sparse_attn_sharedkv_scfa_block_cube.h | 1047 +++++++ .../sparse_attn_sharedkv_scfa_block_vector.h | 1458 ++++++++++ .../arch35/sparse_attn_sharedkv_scfa_kernel.h | 1006 +++++++ .../sparse_attn_sharedkv_swa_block_cube.h | 1092 ++++++++ .../sparse_attn_sharedkv_swa_block_vector.h | 1134 ++++++++ .../arch35/sparse_attn_sharedkv_swa_kernel.h | 933 +++++++ .../op_kernel/sparse_attn_sharedkv_common.h | 341 +++ .../op_kernel/sparse_attn_sharedkv_metadata.h | 83 + ...sparse_attn_sharedkv_template_tiling_key.h | 96 + .../xllm_kernel_sparse_attn_sharedkv.cpp | 132 + .../sparse_attn_sharedkv_metadata/SOURCE.txt | 7 + .../aclnn_sparse_attn_sharedkv_metadata.cpp | 211 ++ .../aclnn_sparse_attn_sharedkv_metadata.h | 60 + .../l0_sparse_attn_sharedkv_metadata.cpp | 132 + .../op_api/l0_sparse_attn_sharedkv_metadata.h | 49 + .../sparse_attn_sharedkv_metadata_proto.cpp | 51 + ...arse_attn_sharedkv_metadata_infershape.cpp | 41 + .../sparse_attn_sharedkv_metadata_aicpu.cpp | 1179 ++++++++ .../sparse_attn_sharedkv_metadata_aicpu.h | 384 +++ .../sparse_attn_sharedkv_metadata_aicpu.json | 15 + .../sparse_flash_attention_lse/SOURCE.txt | 7 + .../sparse_flash_attention_lse_def.cpp | 104 + .../sparse_flash_attention_lse_infershape.cpp | 148 + .../sparse_flash_attention_lse_tiling.cpp | 2406 +++++++++++++++++ .../sparse_flash_attention_lse_tiling.h | 682 +++++ .../sparse_flash_attention_lse_kernel_mla.h | 1238 +++++++++ ...rse_flash_attention_lse_service_cube_mla.h | 1424 ++++++++++ ...e_flash_attention_lse_service_vector_mla.h | 1991 ++++++++++++++ .../sparse_flash_attention_lse_common.h | 216 ++ ..._flash_attention_lse_template_tiling_key.h | 253 ++ ...xllm_kernel_sparse_flash_attention_lse.cpp | 99 + xllm-kernel/csrc/npu/sparse_attention.cpp | 742 +++++ xllm-kernel/python/xllm_kernel/catalog.py | 1 + .../python/xllm_kernel/ops/__init__.py | 12 + .../attention/sparse_attention/__init__.py | 290 ++ .../ops/attention/sparse_attention/ascendc.py | 33 + xllm-kernel/setup.py | 6 +- xllm-kernel/test/npu/conftest.py | 5 + .../test/npu/test_sparse_attention_npu.py | 225 ++ xllm-kernel/test/test_operator_preparation.py | 5 + xllm/python/__init__.py | 5 + xllm/python/kernels_npu/dsa.py | 187 +- xllm/python/kernels_npu/sparse_attention.py | 15 +- 85 files changed, 44289 insertions(+), 207 deletions(-) rename xllm-kernel/csrc/ascendc/{quant_lightning_indexer_metadata => }/aicpu.cmake (50%) create mode 100644 xllm-kernel/csrc/ascendc/compressor/SOURCE.txt create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_host/compressor_def.cpp create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_host/compressor_proto.cpp create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_host/compressor_tiling.cpp create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_host/compressor_tiling.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/arch32.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_block_cube.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_block_cube_perf.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_block_vec.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_block_vec_perf.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_vector_comm.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/rms_norm.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/rope.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/soft_max.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/compressor_block_cube.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/compressor_block_vec.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_add.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_mul.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_rms_norm.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_rope.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_softmax.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_comm.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_kernel.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_kernel_perf.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_template_tiling_key.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_tiling_data.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_tools.h create mode 100644 xllm-kernel/csrc/ascendc/compressor/op_kernel/xllm_kernel_compressor.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/SOURCE.txt create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_host/sparse_attn_sharedkv_def.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_host/sparse_attn_sharedkv_proto.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_host/sparse_attn_sharedkv_tiling.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_host/sparse_attn_sharedkv_tiling.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_scfa_block_cube.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_scfa_block_vector.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_scfa_kernel.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_swa_block_cube.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_swa_block_vector.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_swa_kernel.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_scfa_block_cube.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_scfa_block_vector.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_scfa_kernel.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_swa_block_cube.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_swa_block_vector.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_swa_kernel.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_common.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_metadata.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_template_tiling_key.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/xllm_kernel_sparse_attn_sharedkv.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/SOURCE.txt create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_api/aclnn_sparse_attn_sharedkv_metadata.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_api/aclnn_sparse_attn_sharedkv_metadata.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_api/l0_sparse_attn_sharedkv_metadata.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_api/l0_sparse_attn_sharedkv_metadata.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_graph/sparse_attn_sharedkv_metadata_proto.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_host/sparse_attn_sharedkv_metadata_infershape.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_kernel_aicpu/sparse_attn_sharedkv_metadata_aicpu.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_kernel_aicpu/sparse_attn_sharedkv_metadata_aicpu.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_kernel_aicpu/sparse_attn_sharedkv_metadata_aicpu.json create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/SOURCE.txt create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_host/sparse_flash_attention_lse_def.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_host/sparse_flash_attention_lse_infershape.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_host/sparse_flash_attention_lse_tiling.cpp create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_host/sparse_flash_attention_lse_tiling.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/arch22/sparse_flash_attention_lse_kernel_mla.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/arch22/sparse_flash_attention_lse_service_cube_mla.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/arch22/sparse_flash_attention_lse_service_vector_mla.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/sparse_flash_attention_lse_common.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/sparse_flash_attention_lse_template_tiling_key.h create mode 100644 xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/xllm_kernel_sparse_flash_attention_lse.cpp create mode 100644 xllm-kernel/csrc/npu/sparse_attention.cpp create mode 100644 xllm-kernel/python/xllm_kernel/ops/attention/sparse_attention/__init__.py create mode 100644 xllm-kernel/python/xllm_kernel/ops/attention/sparse_attention/ascendc.py create mode 100644 xllm-kernel/test/npu/test_sparse_attention_npu.py diff --git a/tests/python/test_sparse_attention_dispatch.py b/tests/python/test_sparse_attention_dispatch.py index 4380fdf55c..16b3c5f5d9 100644 --- a/tests/python/test_sparse_attention_dispatch.py +++ b/tests/python/test_sparse_attention_dispatch.py @@ -18,6 +18,7 @@ import pytest import torch +from xllm_kernel.ops.attention import sparse_attention as package_attention from xllm.python.kernels_npu import sparse_attention @@ -44,9 +45,9 @@ def write_out(*args: object) -> torch.Tensor: return output custom_out = MagicMock(side_effect=write_out) - monkeypatch.setattr(torch.ops.xllm_ops, "sparse_flash_attention_lse", custom, raising=False) + monkeypatch.setattr(package_attention, "sparse_flash_attention_lse", custom, raising=False) monkeypatch.setattr(torch.ops.npu, "npu_sparse_flash_attention", native, raising=False) - monkeypatch.setattr(torch.ops.xllm_ops, "sparse_flash_attention_lse_out", custom_out, raising=False) + monkeypatch.setattr(package_attention, "sparse_flash_attention_lse_out", custom_out, raising=False) args = ( query, key, @@ -81,7 +82,7 @@ def write_out(*args: object) -> torch.Tensor: tail = (9223372036854775807, 9223372036854775807, 2, False) if entry == "out" and rope: - custom_out.assert_called_once_with(*args, *tail, buffer) + custom_out.assert_called_once_with(*args, buffer) custom.assert_not_called() native.assert_not_called() elif rope: @@ -121,9 +122,9 @@ def test_partial_rope_pair_is_rejected_before_operator_execution( custom = MagicMock() native = MagicMock() custom_out = MagicMock() - monkeypatch.setattr(torch.ops.xllm_ops, "sparse_flash_attention_lse", custom, raising=False) + monkeypatch.setattr(package_attention, "sparse_flash_attention_lse", custom, raising=False) monkeypatch.setattr(torch.ops.npu, "npu_sparse_flash_attention", native, raising=False) - monkeypatch.setattr(torch.ops.xllm_ops, "sparse_flash_attention_lse_out", custom_out, raising=False) + monkeypatch.setattr(package_attention, "sparse_flash_attention_lse_out", custom_out, raising=False) tensor = torch.zeros(1) key_rope = tensor if query_rope is None else None args = ( diff --git a/xllm-kernel/csrc/ascendc/CMakeLists.txt b/xllm-kernel/csrc/ascendc/CMakeLists.txt index 4e039a4a13..85bb795531 100644 --- a/xllm-kernel/csrc/ascendc/CMakeLists.txt +++ b/xllm-kernel/csrc/ascendc/CMakeLists.txt @@ -51,6 +51,13 @@ set(mega_varlen_host "${CMAKE_CURRENT_SOURCE_DIR}/mega_gdn_mtp_decode_varlen/op_ set(qli "${CMAKE_CURRENT_SOURCE_DIR}/quant_lightning_indexer") set(qli_metadata "${CMAKE_CURRENT_SOURCE_DIR}/quant_lightning_indexer_metadata") 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) +foreach(component IN LISTS sparse_attention_components) + set(host "${CMAKE_CURRENT_SOURCE_DIR}/${component}/op_host") + list(APPEND sparse_attention_definitions "${host}/${component}_def.cpp") + list(APPEND sparse_attention_tiling "${host}/${component}_tiling.cpp") +endforeach() set(pto_include "${CMAKE_CURRENT_SOURCE_DIR}/../../third_party/pto-isa/include") if(NOT EXISTS "${pto_include}/pto/pto-inst.hpp") message(FATAL_ERROR "MegaChunkGdn needs PTO headers. " @@ -68,6 +75,7 @@ list(APPEND op_definitions "${mega_mtp_host}/mega_gdn_mtp_decode_def.cpp" "${qli}/op_host/quant_lightning_indexer_def.cpp" "${scatter}/op_host/scatter_nd_update_v2_def.cpp" + ${sparse_attention_definitions} ) if("ascend910b" IN_LIST ASCEND_COMPUTE_UNIT OR "ascend910_93" IN_LIST ASCEND_COMPUTE_UNIT) list(APPEND op_definitions @@ -128,6 +136,9 @@ npu_op_code_gen( PACKAGE ${vendor} OUT_DIR "${ASCEND_AUTOGEN_PATH}" ) +foreach(component IN LISTS sparse_attention_components) + list(APPEND sparse_attention_api "${ASCEND_AUTOGEN_PATH}/aclnn_xllm_kernel_${component}.cpp") +endforeach() npu_op_library(cust_opapi ACLNN "${gamma_host}/op_api/aclnn_gamma_add_rms_norm.cpp" "${gamma_host}/op_api/gamma_add_rms_norm.cpp" @@ -156,6 +167,9 @@ npu_op_library(cust_opapi ACLNN "${qli_metadata}/op_api/l0_quant_lightning_indexer_metadata.cpp" "${scatter}/op_host/op_api/aclnn_scatter_nd_update_v2.cpp" "${scatter}/op_host/op_api/scatter_nd_update_v2.cpp" + ${sparse_attention_api} + "${sas_metadata}/op_api/aclnn_sparse_attn_sharedkv_metadata.cpp" + "${sas_metadata}/op_api/l0_sparse_attn_sharedkv_metadata.cpp" ${a2_aclnn_sources} ) target_include_directories(cust_opapi PRIVATE @@ -173,6 +187,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" + "${sas_metadata}/op_graph/sparse_attn_sharedkv_metadata_proto.cpp" ) npu_op_library(cust_optiling TILING ${op_definitions} @@ -218,6 +233,11 @@ npu_op_library(cust_optiling TILING "${qli_metadata}/op_host/quant_lightning_indexer_metadata_infershape.cpp" "${scatter}/op_host/scatter_nd_update_infershape.cpp" "${scatter}/op_host/scatter_nd_update_v2_tiling.cpp" + ${sparse_attention_tiling} + "${CMAKE_CURRENT_SOURCE_DIR}/compressor/op_host/compressor_proto.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/sparse_attn_sharedkv/op_host/sparse_attn_sharedkv_proto.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/sparse_flash_attention_lse/op_host/sparse_flash_attention_lse_infershape.cpp" + "${sas_metadata}/op_host/sparse_attn_sharedkv_metadata_infershape.cpp" ${a2_tiling_sources} ${generated_fallback} ) @@ -228,6 +248,7 @@ endforeach() target_include_directories(cust_optiling PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}" "${qli}/op_host" + "${ASCEND_CANN_PACKAGE_PATH}/pkg_inc" "${ASCEND_CANN_PACKAGE_PATH}/include/op_common/op_host" ) target_link_libraries(cust_optiling PRIVATE "${ASCEND_CANN_PACKAGE_PATH}/lib64/libascendalog.so") @@ -364,8 +385,25 @@ npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelScatterNdUpdateV2 npu_op_kernel_options(ascendc_kernels XllmKernelScatterNdUpdateV2 OPTIONS --cce-auto-sync=on -Wno-deprecated-declarations -Wno-error) +npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelCompressor + KERNEL_DIR compressor/op_kernel KERNEL_FILE xllm_kernel_compressor.cpp) +npu_op_kernel_options(ascendc_kernels XllmKernelCompressor + OPTIONS --cce-auto-sync=off -Wno-deprecated-declarations -Wno-error + -mllvm -cce-aicore-hoist-movemask=false --op_relocatable_kernel_binary=true + "-I${CMAKE_CURRENT_SOURCE_DIR}" "-I${CMAKE_CURRENT_SOURCE_DIR}/compressor/op_kernel") +npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelSparseAttnSharedkv + KERNEL_DIR sparse_attn_sharedkv/op_kernel KERNEL_FILE xllm_kernel_sparse_attn_sharedkv.cpp) +npu_op_kernel_sources(ascendc_kernels OP_TYPE XllmKernelSparseFlashAttentionLse + KERNEL_DIR sparse_flash_attention_lse/op_kernel KERNEL_FILE xllm_kernel_sparse_flash_attention_lse.cpp) +foreach(op_type XllmKernelSparseAttnSharedkv XllmKernelSparseFlashAttentionLse) + npu_op_kernel_options(ascendc_kernels ${op_type} + 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}") +endforeach() + npu_op_kernel_library(ascendc_kernels SRC_BASE "${CMAKE_CURRENT_SOURCE_DIR}" TILING_LIBRARY cust_optiling) -include("${qli_metadata}/aicpu.cmake") +include("${CMAKE_CURRENT_SOURCE_DIR}/aicpu.cmake") npu_op_package_add(${vendor} LIBRARY cust_opapi cust_op_proto cust_optiling ascendc_kernels) diff --git a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_metadata/aicpu.cmake b/xllm-kernel/csrc/ascendc/aicpu.cmake similarity index 50% rename from xllm-kernel/csrc/ascendc/quant_lightning_indexer_metadata/aicpu.cmake rename to xllm-kernel/csrc/ascendc/aicpu.cmake index 90d44e0ac8..fb29f22fdd 100644 --- a/xllm-kernel/csrc/ascendc/quant_lightning_indexer_metadata/aicpu.cmake +++ b/xllm-kernel/csrc/ascendc/aicpu.cmake @@ -1,6 +1,5 @@ # Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. -set(aicpu "${CMAKE_CURRENT_LIST_DIR}/op_kernel_aicpu") set(cann "${ASCEND_CANN_PACKAGE_PATH}") find_program(aicpu_cxx NAMES aarch64-target-linux-gnu-g++ HINTS "${cann}/toolkit/toolchain/hcc/bin" "${cann}/toolchain/hcc/bin" @@ -9,9 +8,24 @@ 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(qli_aicpu_library "${CMAKE_CURRENT_BINARY_DIR}/libxllm_kernel_aicpu.so") +set(aicpu_library "${CMAKE_CURRENT_BINARY_DIR}/libxllm_kernel_aicpu.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(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") + set(config "${directory}/${component}_aicpu.json") + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${config}") + file(READ "${config}" component_json) + string(JSON operator MEMBER "${component_json}" 0) + string(JSON definition GET "${component_json}" "${operator}") + string(JSON aicpu_json SET "${aicpu_json}" "${operator}" "${definition}") +endforeach() +file(GENERATE OUTPUT "${aicpu_config}" CONTENT "${aicpu_json}\n") + add_custom_command( - OUTPUT "${qli_aicpu_library}" + OUTPUT "${aicpu_library}" COMMAND "${aicpu_cxx}" -std=c++17 -O2 -shared -fPIC -fvisibility=hidden -fvisibility-inlines-hidden -fstack-protector-all -Dgoogle=ascend_private -DDISABLE_COMPILE_V1 -D_FORTIFY_SOURCE=2 -D_GLIBCXX_USE_CXX11_ABI=1 @@ -19,20 +33,20 @@ add_custom_command( "-I${cann}/include" "-I${cann}/include/aicpu" "-I${cann}/pkg_inc" "-I${cann}/pkg_inc/base" "-I${cann}/pkg_inc/aicpu_common/context/common" "-I${cann}/pkg_inc/aicpu_common/context/cpu_proto" "-I${cann}/pkg_inc/aicpu_common/context/utils" - "${aicpu}/quant_lightning_indexer_metadata_aicpu.cpp" + ${aicpu_sources} -Wl,--whole-archive "${aicpu_context}" "${aicpu_protobuf}" -Wl,--no-whole-archive -Wl,-Bsymbolic -Wl,--exclude-libs=libbase_ascend_protobuf.a - -o "${qli_aicpu_library}" + -o "${aicpu_library}" DEPENDS - "${aicpu}/quant_lightning_indexer_metadata_aicpu.cpp" - "${aicpu}/quant_lightning_indexer_metadata_aicpu.h" - "${aicpu}/cpu_context_util.h" + ${aicpu_sources} + ${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" "${aicpu_context}" "${aicpu_protobuf}" VERBATIM ) -add_custom_target(xllm_kernel_aicpu ALL DEPENDS "${qli_aicpu_library}") +add_custom_target(xllm_kernel_aicpu ALL DEPENDS "${aicpu_library}") set(cpu_destination "packages/vendors/${vendor}/op_impl/cpu") -install(FILES "${qli_aicpu_library}" DESTINATION "${cpu_destination}/aicpu_kernel/impl") -install(FILES "${aicpu}/quant_lightning_indexer_metadata_aicpu.json" - DESTINATION "${cpu_destination}/config" RENAME cust_aicpu_kernel.json) +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/compressor/SOURCE.txt b/xllm-kernel/csrc/ascendc/compressor/SOURCE.txt new file mode 100644 index 0000000000..42f5e3a693 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/SOURCE.txt @@ -0,0 +1,7 @@ +Compressor CANN implementation + +Source: https://gitcode.com/xLLM-AI/xllm_ops +Revision: 8bd2b014c38fec33ecf14dd33e05e8ad792ec5c8 +Directory: xllm_ops/attention/compressor + +Packaged under a private CANN operator type and ACLNN entry points. diff --git a/xllm-kernel/csrc/ascendc/compressor/op_host/compressor_def.cpp b/xllm-kernel/csrc/ascendc/compressor/op_host/compressor_def.cpp new file mode 100644 index 0000000000..3b239adfde --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_host/compressor_def.cpp @@ -0,0 +1,142 @@ +/** + * 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.  */ + +#include "register/op_def_registry.h" + +namespace ops { +class XllmKernelCompressor : public OpDef { + public: + static constexpr uint32_t ROPE_HEAD_DIM_VALUE = 64; + static constexpr uint32_t CMP_RATIO_VALUE = 4; + static constexpr uint32_t COFF_VALUE = 1; + static constexpr uint32_t ROTARY_MODE_VALUE = 1; + + explicit XllmKernelCompressor(const char* name) : OpDef(name) { + this->Input("x") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("wkv") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("wgate") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("kv_state") + .ParamType(REQUIRED) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("score_state") + .ParamType(REQUIRED) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("ape") + .ParamType(REQUIRED) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("norm_weight") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("rope_sin") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("rope_cos") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("kv_block_table") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("score_block_table") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cu_seqlens") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("seqused") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("start_pos") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Output("cmp_kv") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}); + this->Output("kv_state") + .ParamType(REQUIRED) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}); + this->Output("score_state") + .ParamType(REQUIRED) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}); + this->Output("wkv_proj") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}); + this->Output("softmax_res") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}); + this->Output("norm_x") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}); + this->Output("norm_rstd") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}); + this->Attr("rope_head_dim").AttrType(REQUIRED).Int(ROPE_HEAD_DIM_VALUE); + this->Attr("cmp_ratio").AttrType(REQUIRED).Int(CMP_RATIO_VALUE); + this->Attr("coff").AttrType(OPTIONAL).Int(COFF_VALUE); + this->Attr("norm_eps").AttrType(OPTIONAL).Float(1e-6f); + this->Attr("rotary_mode").AttrType(OPTIONAL).Int(ROTARY_MODE_VALUE); + this->Attr("enable_grad").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"); // set value of aclnn support + this->AICore().AddConfig("ascend910b", aicore_config); + this->AICore().AddConfig("ascend910_93", aicore_config); + this->AICore().AddConfig("ascend950", aicore_config); + } +}; +OP_ADD(XllmKernelCompressor, optiling::CompressorCompileInfo); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/compressor/op_host/compressor_proto.cpp b/xllm-kernel/csrc/ascendc/compressor/op_host/compressor_proto.cpp new file mode 100644 index 0000000000..169d34d04f --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_host/compressor_proto.cpp @@ -0,0 +1,282 @@ +/** + * 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.  */ + +#include +#include + +#include "common/error/ops_error.h" + +using namespace ge; + +namespace ops { +// INPUT +constexpr uint32_t TOKEN_X_INPUT_INDEX = 0; +constexpr uint32_t WEIGHT_KV_INPUT_INDEX = 1; +constexpr uint32_t WEIGHT_WGATE_INPUT_INDEX = 2; +constexpr uint32_t KV_STATE_INPUT_INDEX = 3; +constexpr uint32_t SCORE_STATE_INPUT_INDEX = 4; +constexpr uint32_t APE_INPUT_INDEX = 5; +constexpr uint32_t NORM_WEIGHT_INPUT_INDEX = 6; +constexpr uint32_t ROPE_SIN_INPUT_INDEX = 7; +constexpr uint32_t ROPE_COS_INPUT_INDEX = 8; + +// INPUT(OPTION) +constexpr uint32_t KV_BLOCK_TABLE_INPUT_INDEX = 9; +constexpr uint32_t SCORE_BLOCK_TABLE_INPUT_INDEX = 10; +constexpr uint32_t CU_SEQ_LEN_INPUT_INDEX = 11; +constexpr uint32_t SEQ_USED_INPUT_INDEX = 12; +constexpr uint32_t START_POS_INPUT_INDEX = 13; + +// ATTR +constexpr uint32_t ROPE_HEAD_DIM_ATTR_INDEX = 0; +constexpr uint32_t CMP_RATIO_ATTR_INDEX = 1; +constexpr uint32_t COFF_ATTR_INDEX = 2; +constexpr uint32_t NORM_EPS_ATTR_INDEX = 3; +constexpr uint32_t ROTARY_MODE_ATTR_INDEX = 4; +constexpr uint32_t ENABLE_GRAD_ATTR_INDEX = 5; + +// OUTPUT +constexpr uint32_t CMP_KV_OUTPUT_INDEX = 0; +constexpr uint32_t WKV_PROJ_OUTPUT_INDEX = 1; +constexpr uint32_t SOFTMAX_RES_OUTPUT_INDEX = 2; +constexpr uint32_t NORM_X_OUTPUT_INDEX = 3; +constexpr uint32_t NORM_RSTD_OUTPUT_INDEX = 4; + +// ATTR DEFAULT VALUE +constexpr uint32_t CMP_RATIO_VALUE = 4; +constexpr uint32_t COFF_VALUE = 1; + +struct CompressorProtoShapeParam { + bool isBsMerge{false}; + int64_t B{0}; + int64_t T{0}; + int64_t S{0}; + int64_t Sr{0}; + int64_t H{0}; + int64_t D{0}; +}; + +// tmp +constexpr uint32_t DIM_NUM_1 = 1; +constexpr uint32_t DIM_NUM_2 = 2; +constexpr uint32_t DIM_NUM_3 = 3; +constexpr uint32_t DIM_NUM_4 = 4; +constexpr uint32_t DIM_INDEX_0 = 0; +constexpr uint32_t DIM_INDEX_1 = 1; +constexpr uint32_t DIM_INDEX_2 = 2; +constexpr uint32_t DIM_INDEX_3 = 3; + +ge::graphStatus GetCompressorShapeDim(const gert::InferShapeContext* context, + CompressorProtoShapeParam& shapeParam) { + auto xShape = context->GetRequiredInputShape( + TOKEN_X_INPUT_INDEX); // (B, S, H) | (T, H) + OPS_LOG_E_IF_NULL(context, xShape, return ge::GRAPH_FAILED) + auto wkvShape = + context->GetRequiredInputShape(WEIGHT_KV_INPUT_INDEX); // (coff * D, H) + OPS_LOG_E_IF_NULL(context, wkvShape, return ge::GRAPH_FAILED) + auto wgateShape = context->GetRequiredInputShape( + WEIGHT_WGATE_INPUT_INDEX); // (coff * D, H) + OPS_LOG_E_IF_NULL(context, wgateShape, return ge::GRAPH_FAILED) + auto kvStateShape = context->GetRequiredInputShape( + KV_STATE_INPUT_INDEX); // (block_num, block_size, coff * D) + OPS_LOG_E_IF_NULL(context, kvStateShape, return ge::GRAPH_FAILED) + auto scoreStateShape = context->GetRequiredInputShape( + SCORE_STATE_INPUT_INDEX); // (block_num, block_size, coff * D) + OPS_LOG_E_IF_NULL(context, scoreStateShape, return ge::GRAPH_FAILED) + auto apeShape = + context->GetRequiredInputShape(APE_INPUT_INDEX); // (r, coff * D) + OPS_LOG_E_IF_NULL(context, apeShape, return ge::GRAPH_FAILED) + auto normWeightShape = + context->GetRequiredInputShape(NORM_WEIGHT_INPUT_INDEX); // (D) + OPS_LOG_E_IF_NULL(context, normWeightShape, return ge::GRAPH_FAILED) + auto ropeSinShape = context->GetRequiredInputShape( + ROPE_SIN_INPUT_INDEX); // (B, ceil(S / r), rD) | (min(T, T/r + B), rD) + OPS_LOG_E_IF_NULL(context, ropeSinShape, return ge::GRAPH_FAILED) + auto ropeCosShape = context->GetRequiredInputShape( + ROPE_COS_INPUT_INDEX); // (B, ceil(S / r), rD) | (min(T, T/r + B), rD) + OPS_LOG_E_IF_NULL(context, ropeCosShape, return ge::GRAPH_FAILED) + auto kvBlockTableShape = context->GetRequiredInputShape( + KV_BLOCK_TABLE_INPUT_INDEX); // (B, sMax/block_size) + OPS_LOG_E_IF_NULL(context, kvBlockTableShape, return ge::GRAPH_FAILED) + auto scoreBlockTableShape = context->GetRequiredInputShape( + SCORE_BLOCK_TABLE_INPUT_INDEX); // (B, sMax/block_size) + OPS_LOG_E_IF_NULL(context, scoreBlockTableShape, return ge::GRAPH_FAILED) + auto cuSeqlensShape = + context->GetRequiredInputShape(CU_SEQ_LEN_INPUT_INDEX); // (B+1,) + OPS_LOG_E_IF_NULL(context, cuSeqlensShape, return ge::GRAPH_FAILED) + auto seqUsedShape = + context->GetRequiredInputShape(SEQ_USED_INPUT_INDEX); // (B,) + OPS_LOG_E_IF_NULL(context, seqUsedShape, return ge::GRAPH_FAILED) + auto startPosShape = + context->GetRequiredInputShape(START_POS_INPUT_INDEX); // (B,) + OPS_LOG_E_IF_NULL(context, startPosShape, return ge::GRAPH_FAILED) + + if (xShape->GetDimNum() == DIM_NUM_3) { // BS + shapeParam.isBsMerge = false; + shapeParam.B = xShape->GetDim(DIM_INDEX_0); + shapeParam.S = xShape->GetDim(DIM_INDEX_1); + shapeParam.H = xShape->GetDim(DIM_INDEX_2); + shapeParam.T = shapeParam.B * shapeParam.S; + } else { // T + shapeParam.isBsMerge = true; + shapeParam.T = xShape->GetDim(DIM_INDEX_0); + shapeParam.H = xShape->GetDim(DIM_INDEX_1); + } + + shapeParam.D = normWeightShape->GetDim(DIM_INDEX_0); + shapeParam.Sr = ropeSinShape->GetDim(DIM_INDEX_1); + + return GRAPH_SUCCESS; +} + +ge::graphStatus SetCompressorShapeDim( + const CompressorProtoShapeParam& shapeParam, + gert::InferShapeContext* context) { + auto cmpKvShape = context->GetOutputShape( + CMP_KV_OUTPUT_INDEX); // query: (B, S, N, Hckv) | (T, N, Hckv) + OPS_LOG_E_IF_NULL(context, cmpKvShape, return ge::GRAPH_FAILED) + auto wkvProjShape = context->GetOutputShape(WKV_PROJ_OUTPUT_INDEX); + OPS_LOG_E_IF_NULL(context, wkvProjShape, return ge::GRAPH_FAILED) + auto softmaxResShape = context->GetOutputShape(SOFTMAX_RES_OUTPUT_INDEX); + OPS_LOG_E_IF_NULL(context, softmaxResShape, return ge::GRAPH_FAILED) + auto normXShape = context->GetOutputShape(NORM_X_OUTPUT_INDEX); + OPS_LOG_E_IF_NULL(context, normXShape, return ge::GRAPH_FAILED) + auto normRstdShape = context->GetOutputShape(NORM_RSTD_OUTPUT_INDEX); + OPS_LOG_E_IF_NULL(context, normRstdShape, return ge::GRAPH_FAILED) + auto attr = context->GetAttrs(); + const uint32_t* cmpRatioPtr = + attr->GetAttrPointer(CMP_RATIO_ATTR_INDEX); + uint32_t cmpRatio = (cmpRatioPtr != nullptr) ? *cmpRatioPtr : CMP_RATIO_VALUE; + const uint32_t* coffPtr = attr->GetAttrPointer(COFF_ATTR_INDEX); + uint32_t coff = (coffPtr != nullptr) ? *coffPtr : COFF_VALUE; + const bool* enableGradPtr = + attr->GetAttrPointer(ENABLE_GRAD_ATTR_INDEX); + bool enableGrad = (enableGradPtr != nullptr) ? *enableGradPtr : false; + // Set output shape + if (!shapeParam.isBsMerge) { + cmpKvShape->SetDimNum(DIM_NUM_3); // (B, Sr, H) + cmpKvShape->SetDim(DIM_INDEX_0, shapeParam.B); + cmpKvShape->SetDim(DIM_INDEX_1, shapeParam.Sr); + cmpKvShape->SetDim(DIM_INDEX_2, shapeParam.H); + if (enableGrad) { + wkvProjShape->SetDimNum(DIM_NUM_3); + wkvProjShape->SetDim(DIM_INDEX_0, shapeParam.B); + wkvProjShape->SetDim(DIM_INDEX_1, shapeParam.S); + wkvProjShape->SetDim(DIM_INDEX_2, coff * shapeParam.D); + softmaxResShape->SetDimNum(DIM_NUM_4); + softmaxResShape->SetDim(DIM_INDEX_0, shapeParam.B); + softmaxResShape->SetDim(DIM_INDEX_1, shapeParam.Sr); + softmaxResShape->SetDim(DIM_INDEX_2, coff * cmpRatio); + softmaxResShape->SetDim(DIM_INDEX_3, shapeParam.D); + normXShape->SetDimNum(DIM_NUM_3); + normXShape->SetDim(DIM_INDEX_0, shapeParam.B); + normXShape->SetDim(DIM_INDEX_1, shapeParam.Sr); + normXShape->SetDim(DIM_INDEX_2, coff * shapeParam.D); + normRstdShape->SetDimNum(DIM_NUM_2); + normRstdShape->SetDim(DIM_INDEX_0, shapeParam.B); + normRstdShape->SetDim(DIM_INDEX_1, shapeParam.Sr); + } else { + wkvProjShape->SetDimNum(DIM_NUM_3); + wkvProjShape->SetDim(DIM_INDEX_0, 0); + wkvProjShape->SetDim(DIM_INDEX_1, 0); + wkvProjShape->SetDim(DIM_INDEX_2, 0); + softmaxResShape->SetDimNum(DIM_NUM_4); + softmaxResShape->SetDim(DIM_INDEX_0, 0); + softmaxResShape->SetDim(DIM_INDEX_1, 0); + softmaxResShape->SetDim(DIM_INDEX_2, 0); + softmaxResShape->SetDim(DIM_INDEX_3, 0); + normXShape->SetDimNum(DIM_NUM_3); + normXShape->SetDim(DIM_INDEX_0, 0); + normXShape->SetDim(DIM_INDEX_1, 0); + normXShape->SetDim(DIM_INDEX_2, 0); + normRstdShape->SetDimNum(DIM_NUM_2); + normRstdShape->SetDim(DIM_INDEX_0, 0); + normRstdShape->SetDim(DIM_INDEX_1, 0); + } + } else { + cmpKvShape->SetDimNum(DIM_NUM_2); // (T, N, Hckv) + cmpKvShape->SetDim(DIM_INDEX_0, shapeParam.Sr); + cmpKvShape->SetDim(DIM_INDEX_1, shapeParam.H); + if (enableGrad) { + wkvProjShape->SetDimNum(DIM_NUM_2); + wkvProjShape->SetDim(DIM_INDEX_0, shapeParam.T); + wkvProjShape->SetDim(DIM_INDEX_1, coff * shapeParam.D); + softmaxResShape->SetDimNum(DIM_NUM_3); + softmaxResShape->SetDim(DIM_INDEX_0, shapeParam.Sr); + softmaxResShape->SetDim(DIM_INDEX_1, coff * cmpRatio); + softmaxResShape->SetDim(DIM_INDEX_2, shapeParam.D); + normXShape->SetDimNum(DIM_NUM_2); + normXShape->SetDim(DIM_INDEX_0, shapeParam.Sr); + normXShape->SetDim(DIM_INDEX_1, coff * shapeParam.D); + normRstdShape->SetDimNum(DIM_NUM_1); + normRstdShape->SetDim(DIM_INDEX_0, shapeParam.Sr); + } else { + wkvProjShape->SetDimNum(DIM_NUM_2); + wkvProjShape->SetDim(DIM_INDEX_0, 0); + wkvProjShape->SetDim(DIM_INDEX_1, 0); + softmaxResShape->SetDimNum(DIM_NUM_3); + softmaxResShape->SetDim(DIM_INDEX_0, 0); + softmaxResShape->SetDim(DIM_INDEX_1, 0); + softmaxResShape->SetDim(DIM_INDEX_2, 0); + normXShape->SetDimNum(DIM_NUM_2); + normXShape->SetDim(DIM_INDEX_0, 0); + normXShape->SetDim(DIM_INDEX_1, 0); + normRstdShape->SetDimNum(DIM_NUM_1); + normRstdShape->SetDim(DIM_INDEX_0, 0); + } + } + + return GRAPH_SUCCESS; +} + +ge::graphStatus InferDataTypeCompressor(gert::InferDataTypeContext* context) { + OPS_ERR_IF(context == nullptr, + OPS_REPORT_VECTOR_INNER_ERR("XllmKernelCompressor", + "Context is nullptr."), + return ge::GRAPH_FAILED); + OPS_LOG_I(context->GetNodeName(), + "Enter XllmKernelCompressor inferDataType impl."); + + context->SetOutputDataType( + CMP_KV_OUTPUT_INDEX, + context->GetRequiredInputDataType(TOKEN_X_INPUT_INDEX)); + + return GRAPH_SUCCESS; +} + +ge::graphStatus InferShapeCompressor(gert::InferShapeContext* context) { + OPS_ERR_IF(context == nullptr, + OPS_REPORT_VECTOR_INNER_ERR("XllmKernelCompressor", + "Context is nullptr."), + return ge::GRAPH_FAILED); + OPS_LOG_I(context->GetNodeName(), + "Enter XllmKernelCompressor infershape impl."); + + CompressorProtoShapeParam shapeParam{}; + auto apiRet = GetCompressorShapeDim(context, shapeParam); + OPS_LOG_E_IF((apiRet != GRAPH_SUCCESS), + context, + return ge::GRAPH_FAILED, + "Context get input shape failed"); + + apiRet = SetCompressorShapeDim(shapeParam, context); + OPS_LOG_E_IF((apiRet != GRAPH_SUCCESS), + context, + return ge::GRAPH_FAILED, + "Context set output shape failed"); + + return GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(XllmKernelCompressor) + .InferShape(InferShapeCompressor) + .InferDataType(InferDataTypeCompressor); +} // namespace ops \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_host/compressor_tiling.cpp b/xllm-kernel/csrc/ascendc/compressor/op_host/compressor_tiling.cpp new file mode 100644 index 0000000000..de91826720 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_host/compressor_tiling.cpp @@ -0,0 +1,1403 @@ +/** + * 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 compressor_tiling.cpp + * \file compressor_tiling.cpp + * \brief + */ + +#include "compressor_tiling.h" + +#include + +#include +#include +#include +#include + +#include "err/ops_err.h" +#include "register/op_def_registry.h" + +using namespace ge; +using namespace AscendC; +namespace optiling { + +static const std::string X_NAME = "query"; +static const std::string WKV_NAME = "wkv"; +static const std::string WGATE_NAME = "wgate"; +static const std::string KV_STATE_NAME = "kv_state"; +static const std::string SCORE_STATE_NAME = "score_state"; +static const std::string APE_NAME = "ape"; +static const std::string NORM_WEIGHT_NAME = "norm_weight"; +static const std::string ROPE_SIN_NAME = "rope_sin"; +static const std::string ROPE_COS_NAME = "rope_cos"; +static const std::string KV_BLOCK_TABLE_NAME = "kv_block_table"; +static const std::string SCORE_BLOCK_TABLE_NAME = "score_block_table"; +static const std::string CU_SEQLENS_NAME = "cu_seqlens"; +static const std::string SEQUSED_NAME = "seq_used"; +static const std::string START_POS_NAME = "start_pos"; +static const std::string ROPE_HEAD_DIM_NAME = "rope_head_dim"; +static const std::string CMP_RATIO_NAME = "cmp_ratio"; +static const std::string COFF_NAME = "coff"; +static const std::string NORM_EPS_NAME = "nrom_eps"; +static const std::string ROTARY_MODE_NAME = "rotary_mode"; +static const std::string CMP_KV_NAME = "cmp_kv"; +static std::string DataTypeToSerialString(ge::DataType type); +const std::map> DTYPE_SUPPORT_MAP = { + {X_NAME, {ge::DT_BF16, ge::DT_FLOAT16}}, + {WKV_NAME, {ge::DT_BF16, ge::DT_FLOAT16}}, + {WGATE_NAME, {ge::DT_BF16, ge::DT_FLOAT16}}, + {KV_STATE_NAME, {ge::DT_FLOAT}}, + {SCORE_STATE_NAME, {ge::DT_FLOAT}}, + {APE_NAME, {ge::DT_FLOAT}}, + {NORM_WEIGHT_NAME, {ge::DT_BF16, ge::DT_FLOAT16}}, + {ROPE_SIN_NAME, {ge::DT_BF16, ge::DT_FLOAT16}}, + {ROPE_COS_NAME, {ge::DT_BF16, ge::DT_FLOAT16}}, + {KV_BLOCK_TABLE_NAME, {ge::DT_INT32}}, + {SCORE_BLOCK_TABLE_NAME, {ge::DT_INT32}}, + {CU_SEQLENS_NAME, {ge::DT_INT32}}, + {SEQUSED_NAME, {ge::DT_INT32}}, + {START_POS_NAME, {ge::DT_INT32}}, + {CMP_KV_NAME, {ge::DT_BF16, ge::DT_FLOAT16}}}; +const std::map> DIM_NUM_MAP = { + {X_NAME, {COMPRESSOR_DIM_NUM_2, COMPRESSOR_DIM_NUM_3}}, + {WKV_NAME, {COMPRESSOR_DIM_NUM_2}}, + {WGATE_NAME, {COMPRESSOR_DIM_NUM_2}}, + {KV_STATE_NAME, {COMPRESSOR_DIM_NUM_3}}, + {SCORE_STATE_NAME, {COMPRESSOR_DIM_NUM_3}}, + {APE_NAME, {COMPRESSOR_DIM_NUM_2}}, + {NORM_WEIGHT_NAME, {COMPRESSOR_DIM_NUM_1}}, + {ROPE_SIN_NAME, {COMPRESSOR_DIM_NUM_2, COMPRESSOR_DIM_NUM_3}}, + {ROPE_COS_NAME, {COMPRESSOR_DIM_NUM_2, COMPRESSOR_DIM_NUM_3}}, + {KV_BLOCK_TABLE_NAME, {COMPRESSOR_DIM_NUM_2}}, + {SCORE_BLOCK_TABLE_NAME, {COMPRESSOR_DIM_NUM_2}}, + {CU_SEQLENS_NAME, {COMPRESSOR_DIM_NUM_1}}, + {SEQUSED_NAME, {COMPRESSOR_DIM_NUM_1}}, + {START_POS_NAME, {COMPRESSOR_DIM_NUM_1}}, + {CMP_KV_NAME, {COMPRESSOR_DIM_NUM_2, COMPRESSOR_DIM_NUM_3}}}; +static const std::map LAYOUT_DIM_MAP = { + {"BSH", COMPRESSOR_DIM_NUM_3}, + {"TH", COMPRESSOR_DIM_NUM_2}, +}; +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 +}; + +void CompressorTiling::ConvertRequiredParams( + gert::TilingContext& context, + CompressorContext& compressorContext) { + compressorContext.x.desc = context.GetRequiredInputDesc(TOKEN_X_INPUT_INDEX); + compressorContext.x.shape = + context.GetRequiredInputShape(TOKEN_X_INPUT_INDEX); + compressorContext.wkv.desc = + context.GetRequiredInputDesc(WEIGHT_KV_INPUT_INDEX); + compressorContext.wkv.shape = + context.GetRequiredInputShape(WEIGHT_KV_INPUT_INDEX); + compressorContext.wgate.desc = + context.GetRequiredInputDesc(WEIGHT_WGATE_INPUT_INDEX); + compressorContext.wgate.shape = + context.GetRequiredInputShape(WEIGHT_WGATE_INPUT_INDEX); + compressorContext.kvState.desc = + context.GetRequiredInputDesc(KV_STATE_INPUT_INDEX); + compressorContext.kvState.shape = + context.GetRequiredInputShape(KV_STATE_INPUT_INDEX); + compressorContext.scoreState.desc = + context.GetRequiredInputDesc(SCORE_STATE_INPUT_INDEX); + compressorContext.scoreState.shape = + context.GetRequiredInputShape(SCORE_STATE_INPUT_INDEX); + compressorContext.ape.desc = context.GetRequiredInputDesc(APE_INPUT_INDEX); + compressorContext.ape.shape = context.GetRequiredInputShape(APE_INPUT_INDEX); + compressorContext.normWeight.desc = + context.GetRequiredInputDesc(NORM_WEIGHT_INPUT_INDEX); + compressorContext.normWeight.shape = + context.GetRequiredInputShape(NORM_WEIGHT_INPUT_INDEX); + compressorContext.ropeSin.desc = + context.GetRequiredInputDesc(ROPE_SIN_INPUT_INDEX); + compressorContext.ropeSin.shape = + context.GetRequiredInputShape(ROPE_SIN_INPUT_INDEX); + compressorContext.ropeCos.desc = + context.GetRequiredInputDesc(ROPE_COS_INPUT_INDEX); + compressorContext.ropeCos.shape = + context.GetRequiredInputShape(ROPE_COS_INPUT_INDEX); + + compressorContext.cmpKv.desc = context.GetOutputDesc(CMP_KV_OUTPUT_INDEX); + compressorContext.cmpKv.shape = context.GetOutputShape(CMP_KV_OUTPUT_INDEX); + + compressorContext.dtype = compressorContext.x.desc->GetDataType(); + auto xDimNum = compressorContext.x.shape->GetStorageShape().GetDimNum(); + if (xDimNum == COMPRESSOR_DIM_NUM_3) { + compressorContext.layout = LayoutType::LAYOUT_BSH; + } else if (xDimNum == COMPRESSOR_DIM_NUM_2) { + compressorContext.layout = LayoutType::LAYOUT_TH; + } +} + +void CompressorTiling::ConvertOptionalParams( + gert::TilingContext& context, + CompressorContext& compressorContext) { + compressorContext.kvBlockTable.desc = + context.GetOptionalInputDesc(KV_BLOCK_TABLE_INPUT_INDEX); + compressorContext.kvBlockTable.shape = + context.GetOptionalInputShape(KV_BLOCK_TABLE_INPUT_INDEX); + compressorContext.scoreBlockTable.desc = + context.GetOptionalInputDesc(SCORE_BLOCK_TABLE_INPUT_INDEX); + compressorContext.scoreBlockTable.shape = + context.GetOptionalInputShape(SCORE_BLOCK_TABLE_INPUT_INDEX); + compressorContext.cuSeqlens.desc = + context.GetOptionalInputDesc(CU_SEQ_LEN_INPUT_INDEX); + compressorContext.cuSeqlens.shape = + context.GetOptionalInputShape(CU_SEQ_LEN_INPUT_INDEX); + compressorContext.seqUsed.desc = + context.GetOptionalInputDesc(SEQ_USED_INPUT_INDEX); + compressorContext.seqUsed.shape = + context.GetOptionalInputShape(SEQ_USED_INPUT_INDEX); + compressorContext.startPos.desc = + context.GetOptionalInputDesc(START_POS_INPUT_INDEX); + compressorContext.startPos.shape = + context.GetOptionalInputShape(START_POS_INPUT_INDEX); +} + +ge::graphStatus CompressorTiling::ConvertContext( + gert::TilingContext& context, + CompressorContext& compressorContext) { + if (context.GetNodeName() == nullptr) { + OP_LOGE("XllmKernelCompressor", "opName got from TilingContext is nullptr"); + return ge::GRAPH_FAILED; + } + + OP_LOGI("Getting Context"); + + compressorContext.opName = context.GetNodeName(); + compressorContext.opType = context.GetNodeType(); + compressorContext.platformInfo = context.GetPlatformInfo(); + ConvertRequiredParams(context, compressorContext); + ConvertOptionalParams(context, compressorContext); + + auto attrs = context.GetAttrs(); + OP_CHECK_IF(attrs == nullptr, + OP_LOGE(context.GetNodeName(), "attrs got from ge is nullptr"), + return ge::GRAPH_FAILED); + compressorContext.ropeHeadDim = + attrs->GetAttrPointer(ROPE_HEAD_DIM_ATTR_INDEX); + compressorContext.coff = attrs->GetAttrPointer(COFF_ATTR_INDEX); + compressorContext.cmpRatio = attrs->GetAttrPointer(CMP_RATIO_ATTR_INDEX); + compressorContext.normEps = attrs->GetAttrPointer(NORM_EPS_ATTR_INDEX); + compressorContext.rotaryMode = + attrs->GetAttrPointer(ROTARY_MODE_ATTR_INDEX); + + OP_CHECK_IF( + context.GetWorkspaceSizes(1) == nullptr, + OPS_REPORT_VECTOR_INNER_ERR(context.GetNodeName(), + "workSpaceSize got from ge is nullptr"), + return ge::GRAPH_FAILED); + compressorContext.workSpaces = context.GetWorkspaceSizes(1); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::GetNpuInfo() { + OP_CHECK_IF(context_->platformInfo == nullptr, + OPS_REPORT_VECTOR_INNER_ERR(context_->opName, + "GetPlatformInfo is nullptr."), + return ge::GRAPH_FAILED); + + auto ascendcPlatform = + platform_ascendc::PlatformAscendC(context_->platformInfo); + socVersion_ = ascendcPlatform.GetSocVersion(); + + libapiSize_ = ascendcPlatform.GetLibApiWorkSpaceSize(); + socVersion_ = ascendcPlatform.GetSocVersion(); + + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSize_); + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L1, l1Size_); + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_C, l0cSize_); + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_B, l0bSize_); + + aivNum_ = ascendcPlatform.GetCoreNumAiv(); + aicNum_ = ascendcPlatform.GetCoreNumAic(); + + OP_CHECK_IF(aicNum_ == 0 || aivNum_ == 0, + OPS_REPORT_VECTOR_INNER_ERR(context_->opName, + "num of core obtained is 0."), + return GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::SetBaseInfo() { + if (context_->x.shape->GetStorageShape().GetDimNum() == + COMPRESSOR_DIM_NUM_3) { + baseParams_->batchSize = + context_->x.shape->GetStorageShape().GetDim(COMPRESSOR_DIM_INDEX_0); + baseParams_->seqSize = + context_->x.shape->GetStorageShape().GetDim(COMPRESSOR_DIM_INDEX_1); + baseParams_->hiddenSize = + context_->x.shape->GetStorageShape().GetDim(COMPRESSOR_DIM_INDEX_2); + baseParams_->tokenSize = baseParams_->batchSize * baseParams_->seqSize; + baseParams_->cgSize = context_->ropeSin.shape->GetStorageShape().GetDim( + COMPRESSOR_DIM_INDEX_1); + } else { + baseParams_->batchSize = + context_->cuSeqlens.shape->GetStorageShape().GetDim( + COMPRESSOR_DIM_INDEX_0) - + 1; + baseParams_->tokenSize = + context_->x.shape->GetStorageShape().GetDim(COMPRESSOR_DIM_INDEX_0); + baseParams_->hiddenSize = + context_->x.shape->GetStorageShape().GetDim(COMPRESSOR_DIM_INDEX_1); + baseParams_->cgSize = context_->ropeSin.shape->GetStorageShape().GetDim( + COMPRESSOR_DIM_INDEX_0); + } + + baseParams_->headDim = context_->normWeight.shape->GetStorageShape().GetDim( + COMPRESSOR_DIM_INDEX_0); + baseParams_->cmpRatio = static_cast(*context_->cmpRatio); + baseParams_->csSize = + baseParams_->seqSize - (baseParams_->seqSize % baseParams_->cmpRatio); + baseParams_->ropeHeadDim = static_cast(*context_->ropeHeadDim); + baseParams_->normEps = static_cast(*context_->normEps); + baseParams_->reciprocalD = 1.0 / baseParams_->headDim; + baseParams_->cgSize = + (baseParams_->seqSize + baseParams_->cmpRatio - 1) / + baseParams_->cmpRatio; // number of token after compress + coff = static_cast(*context_->coff); + baseParams_->nSize = 2; // 2:每个核处理两个基本块后做全核同步 + + OP_LOGI(context_->opName, + "[TILING] bSize:%u tSize:%u cmpRatio:%u coff:%u", + baseParams_->batchSize, + baseParams_->tokenSize, + baseParams_->cmpRatio, + coff); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::SetPageAttentionInfo() { + pageAttentionParams_->blockNum = + context_->kvState.shape->GetStorageShape().GetDim(COMPRESSOR_DIM_INDEX_0); + pageAttentionParams_->blockSize = + context_->kvState.shape->GetStorageShape().GetDim(COMPRESSOR_DIM_INDEX_1); + pageAttentionParams_->maxBlockNumPerBatch = + context_->kvBlockTable.shape->GetStorageShape().GetDim( + COMPRESSOR_DIM_INDEX_1); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::SetWorkSpaceInfo() { + workspaceParams_->preMm1ResSize = 0; + if (coff == 2) { // 2:需要做overlap + workspaceParams_->preMm1ResSize = innerSplitParams_->mBaseSize * + innerSplitParams_->dBaseSize * + 2; // 2 wkv和score合一起 + } + workspaceParams_->curMm1ResSize = innerSplitParams_->mBaseSize * + innerSplitParams_->dBaseSize * + 2; // 2 wkv和score合一起 + if (context_->templateId == TemplateId::PERF) { + workspaceParams_->vec1ResSize = innerSplitParams_->mBaseSize * + innerSplitParams_->dBaseSize * + baseParams_->nSize; + } else { + workspaceParams_->vec1ResSize = + innerSplitParams_->mBaseSize / baseParams_->cmpRatio * + innerSplitParams_->dBaseSize * baseParams_->nSize; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::SetScenarioInfo() { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::SetTemplateId() { + if (socVersion_ == platform_ascendc::SocVersion::ASCEND910_95) { + return ge::GRAPH_SUCCESS; + } + if (context_->seqUsed.desc != nullptr || context_->seqUsed.shape != nullptr) { + return ge::GRAPH_SUCCESS; + } + if (context_->layout == LayoutType::LAYOUT_BSH) { + return ge::GRAPH_SUCCESS; + } + // 设置高性能模板 + context_->templateId = TemplateId::PERF; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::SetInnerSplitInfo() { + innerSplitParams_->mBaseSize = 256; // 256:核间切分,M轴基本块大小 + innerSplitParams_->dBaseSize = 128 / coff; // 128:核间切分,D轴基本块大小 + if (context_->templateId == TemplateId::PERF) { + if (coff == 2) { + innerSplitParams_->mBaseSize = 128; + } else { + innerSplitParams_->mBaseSize = 256; + } + innerSplitParams_->dBaseSize = 64; + } else { + innerSplitParams_->mBaseSize = 256; // 256:核间切分,M轴基本块大小 + innerSplitParams_->dBaseSize = 128 / coff; // 128:核间切分,D轴基本块大小 + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CalcWorkSpace() { + constexpr uint32_t MM1_RES_ELEM_SIZE = 4; // 4: fp32 + constexpr uint32_t V1_RES_ELEM_SIZE = 2; // 2: fp16/bf16 + workspaceSize_ = libapiSize_; + workspaceSize_ += + aicNum_ * workspaceParams_->preMm1ResSize * MM1_RES_ELEM_SIZE; + workspaceSize_ += + aicNum_ * workspaceParams_->curMm1ResSize * MM1_RES_ELEM_SIZE; + workspaceSize_ += aicNum_ * workspaceParams_->vec1ResSize * V1_RES_ELEM_SIZE; + + workspaceSize_ += 1024 * 1024 * 1024; // 1024:申请workspace大小 + if (context_->workSpaces) { + context_->workSpaces[0] = workspaceSize_; + } + + OP_LOGI( + context_->opName, "Tiling info: workspaceSize_ = %zu", workspaceSize_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckEmptyTensor() const { + if (context_->layout == LayoutType::LAYOUT_BSH && + context_->x.shape->GetStorageShape().GetDim(COMPRESSOR_DIM_INDEX_1) == + 0 || + context_->layout == LayoutType::LAYOUT_TH && + context_->x.shape->GetStorageShape().GetDim(COMPRESSOR_DIM_INDEX_0) == + 0) { + context_->templateId = TemplateId::EMPTY_X; + } else { + if (context_->x.shape->GetStorageShape().GetShapeSize() == 0 || + context_->wkv.shape->GetStorageShape().GetShapeSize() == 0 || + context_->wgate.shape->GetStorageShape().GetShapeSize() == 0 || + context_->kvState.shape->GetStorageShape().GetShapeSize() == 0 || + context_->scoreState.shape->GetStorageShape().GetShapeSize() == 0 || + context_->ape.shape->GetStorageShape().GetShapeSize() == 0 || + context_->normWeight.shape->GetStorageShape().GetShapeSize() == 0 || + context_->ropeSin.shape->GetStorageShape().GetShapeSize() == 0 || + context_->ropeCos.shape->GetStorageShape().GetShapeSize() == 0 || + context_->kvBlockTable.shape->GetStorageShape().GetShapeSize() == 0 || + context_->scoreBlockTable.shape->GetStorageShape().GetShapeSize() == + 0) { + return ge::GRAPH_FAILED; + } + context_->templateId = TemplateId::NORMAL; + OP_LOGI(context_->opName, "Only input tensor x supports empty state"); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::RunBigKernelTiling( + CompressorTilingData* tilingData) { + this->baseParams_ = &tilingData->baseParams; + this->pageAttentionParams_ = &tilingData->pageAttentionParams; + this->innerSplitParams_ = &tilingData->innerSplitParams; + this->workspaceParams_ = &tilingData->workspaceParams; + using StatusFunction = std::function; + std::vector requiredTilingFuncs{ + std::bind(&CompressorTiling::CheckRequiredParaExistence, this), + std::bind(&CompressorTiling::CheckEmptyTensor, this), + std::bind(&CompressorTiling::CheckSinglePara, this), + std::bind(&CompressorTiling::GetNpuInfo, this), + std::bind(&CompressorTiling::SetBaseInfo, this), + std::bind(&CompressorTiling::SetPageAttentionInfo, this), + std::bind(&CompressorTiling::CheckFeature, this), + std::bind(&CompressorTiling::CheckMultiParaConsistency, this), + std::bind(&CompressorTiling::SetTemplateId, this), + std::bind(&CompressorTiling::SetInnerSplitInfo, this), + std::bind(&CompressorTiling::SetWorkSpaceInfo, this), + std::bind(&CompressorTiling::SetScenarioInfo, this)}; + for (const auto& func : requiredTilingFuncs) { + if (func() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + if (context_->templateId == TemplateId::EMPTY_X) { + GenTilingKey(); + context_->blockDim = 1U; + return ge::GRAPH_SUCCESS; + } + } + + std::vector optionalTilingFuncs{ + std::bind(&CompressorTiling::CalcWorkSpace, this), + std::bind(&CompressorTiling::GenTilingKey, this)}; + for (const auto& func : optionalTilingFuncs) { + if (func() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + } + + baseParams_->usedCoreNum = aicNum_; + + context_->blockDim = aicNum_; + + OP_LOGI("Run big kernel"); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::GenTilingKey() const { + // 0:BF16, 1:FP16 + uint8_t dtype = 0; + // 0: BSH 1:TH + uint8_t layout = 0; + uint8_t rotaryMode = static_cast(*context_->rotaryMode); + uint8_t templateId = static_cast(context_->templateId); + + auto xDtype = context_->x.desc->GetDataType(); + if (xDtype == ge::DT_BF16) { + dtype = 0; + } else if (xDtype == ge::DT_FLOAT16) { + dtype = 1; + } + auto xDimNum = context_->x.shape->GetStorageShape().GetDimNum(); + if (xDimNum == COMPRESSOR_DIM_NUM_3) { + layout = 0; + } else { + layout = 1; + } + + context_->tilingKey = + GET_TPL_TILING_KEY(layout, dtype, coff, rotaryMode, templateId); + + OP_LOGI(context_->opName, + "XllmKernelCompressor dtype:%hhu layout:%hhu coff:%hhu " + "rotary_mode:%hhu, template_id:%hhu", + dtype, + layout, + coff, + rotaryMode, + templateId); + OP_LOGI(context_->opName, + "XllmKernelCompressor tilingKey:%lu", + context_->tilingKey); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSinglePara() const { + if (ge::GRAPH_SUCCESS != CheckSingleParaX() || + ge::GRAPH_SUCCESS != CheckSingleParaWkv() || + ge::GRAPH_SUCCESS != CheckSingleParaWgate() || + ge::GRAPH_SUCCESS != CheckSingleParaKvState() || + ge::GRAPH_SUCCESS != CheckSingleParaScoreState() || + ge::GRAPH_SUCCESS != CheckSingleParaApe() || + ge::GRAPH_SUCCESS != CheckSingleParaNormWeight() || + ge::GRAPH_SUCCESS != CheckSingleParaRopeSin() || + ge::GRAPH_SUCCESS != CheckSingleParaRopeCos() || + ge::GRAPH_SUCCESS != CheckSingleParaKvBlockTable() || + ge::GRAPH_SUCCESS != CheckSingleParaScoreBlockTable() || + ge::GRAPH_SUCCESS != CheckSingleParaCuSeqlens() || + ge::GRAPH_SUCCESS != CheckSingleParaSeqused() || + ge::GRAPH_SUCCESS != CheckSingleParaStartPos() || + ge::GRAPH_SUCCESS != CheckSingleParaCmpKv() || + ge::GRAPH_SUCCESS != CheckSingleParaRopeHeadDim() || + ge::GRAPH_SUCCESS != CheckSingleParaCmpRatio() || + ge::GRAPH_SUCCESS != CheckSingleParaCoff() || + ge::GRAPH_SUCCESS != CheckSingleParaNormEps() || + ge::GRAPH_SUCCESS != CheckSingleParaRotaryMode()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +template +ge::graphStatus CompressorTiling::CheckFeatureValueSupport( + const T* featureValue, + const std::vector& expectFeatureValList, + const std::string& name) const { + if (std::find(expectFeatureValList.begin(), + expectFeatureValList.end(), + *featureValue) == expectFeatureValList.end()) { + LogErrorNumberSupport( + expectFeatureValList, *featureValue, name, "feature value"); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +template +ge::graphStatus CompressorTiling::CheckAttrValueSupport( + const T* attrValue, + const std::vector& expectAttrValList, + const std::string& name) const { + if (attrValue == nullptr) { + return ge::GRAPH_SUCCESS; + } + + if (std::find(expectAttrValList.begin(), + expectAttrValList.end(), + *attrValue) == expectAttrValList.end()) { + LogErrorNumberSupport(expectAttrValList, *attrValue, name, "attr value"); + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +template +void CompressorTiling::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("XllmKernelCompressor", + "%s %s only supports %s, but got %s", + name.c_str(), + subName.c_str(), + oss.str().c_str(), + std::to_string(actualValue).c_str()); +} + +std::string LayoutTypeToStr(LayoutType layout) { + switch (layout) { + case LayoutType::LAYOUT_BSH: + return "BSH"; + case LayoutType::LAYOUT_TH: + return "TH"; + default: + return "UNKNOWN_LAYOUT"; + } +} + +ge::graphStatus CompressorTiling::CheckDimNumInLayoutSupport( + const std::string& layout, + const gert::StorageShape* shape, + const std::string& name) const { + const auto& dimIt = LAYOUT_DIM_MAP.find(layout); + OP_CHECK_IF( + shape->GetStorageShape().GetDimNum() != dimIt->second, + OP_LOGE("XllmKernelCompressor", + "When layout is %s, %s dimension should be %zu, but it's %zu", + layout.c_str(), + name.c_str(), + dimIt->second, + shape->GetStorageShape().GetDimNum()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckDtypeSupport( + const gert::CompileTimeTensorDesc* desc, + const std::string& name) const { + if (desc != nullptr) { + const auto& it = DTYPE_SUPPORT_MAP.find(name); + OP_CHECK_IF( + it == DTYPE_SUPPORT_MAP.end(), + OP_LOGE( + "XllmKernelCompressor", + "%s datatype support list should be specify in DTYPE_SUPPORT_MAP", + name.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 CompressorTiling::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 << DataTypeToSerialString(expectDtypeList[i]); + if (i < expectDtypeList.size() - 1) { + oss << ", "; + } + } + OP_LOGE("XllmKernelCompressor", + "Tensor %s only supports dtype %s, but got %s", + name.c_str(), + oss.str().c_str(), + DataTypeToSerialString(actualDtype).c_str()); +} + +static std::string DataTypeToSerialString(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("XllmKernelCompressor", "datatype %d not support", type); + return "UNDEFINED"; + } +} + +ge::graphStatus CompressorTiling::CheckDimNumSupport( + const gert::StorageShape* shape, + const std::string& name) const { + if (shape == nullptr) { + return ge::GRAPH_SUCCESS; + } + const auto& it = DIM_NUM_MAP.find(name); + OP_CHECK_IF( + it == DIM_NUM_MAP.end(), + OP_LOGE("XllmKernelCompressor", + "%s dim number support list should be specify in DIM_NUM_MAP", + name.c_str()), + return ge::GRAPH_FAILED); + auto& expectDimNumList = it->second; + OP_CHECK_IF( + std::find(expectDimNumList.begin(), + expectDimNumList.end(), + shape->GetStorageShape().GetDimNum()) == expectDimNumList.end(), + LogErrorNumberSupport( + expectDimNumList, + static_cast(shape->GetStorageShape().GetDimNum()), + name, + "dimension"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaX() const { + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(context_->x.desc, X_NAME) || + ge::GRAPH_SUCCESS != CheckDimNumSupport(context_->x.shape, X_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumInLayoutSupport( + LayoutTypeToStr(context_->layout), context_->x.shape, X_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaWkv() const { + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(context_->wkv.desc, WKV_NAME) || + ge::GRAPH_SUCCESS != CheckDimNumSupport(context_->wkv.shape, WKV_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaWgate() const { + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(context_->wgate.desc, WGATE_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(context_->wgate.shape, WGATE_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaKvState() const { + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(context_->kvState.desc, KV_STATE_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(context_->kvState.shape, KV_STATE_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaScoreState() const { + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(context_->scoreState.desc, SCORE_STATE_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(context_->scoreState.shape, SCORE_STATE_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaApe() const { + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(context_->ape.desc, APE_NAME) || + ge::GRAPH_SUCCESS != CheckDimNumSupport(context_->ape.shape, APE_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaNormWeight() const { + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(context_->normWeight.desc, NORM_WEIGHT_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(context_->normWeight.shape, NORM_WEIGHT_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaRopeSin() const { + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(context_->ropeSin.desc, ROPE_SIN_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(context_->ropeSin.shape, ROPE_SIN_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumInLayoutSupport(LayoutTypeToStr(context_->layout), + context_->ropeSin.shape, + ROPE_SIN_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaRopeCos() const { + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(context_->ropeCos.desc, ROPE_COS_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(context_->ropeCos.shape, ROPE_COS_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumInLayoutSupport(LayoutTypeToStr(context_->layout), + context_->ropeCos.shape, + ROPE_COS_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaKvBlockTable() const { + if (context_->kvBlockTable.desc == nullptr) { + return ge::GRAPH_SUCCESS; + } + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(context_->kvBlockTable.desc, KV_BLOCK_TABLE_NAME) || + ge::GRAPH_SUCCESS != CheckDimNumSupport(context_->kvBlockTable.shape, + KV_BLOCK_TABLE_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaScoreBlockTable() const { + if (context_->scoreBlockTable.desc == nullptr) { + return ge::GRAPH_SUCCESS; + } + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(context_->scoreBlockTable.desc, + SCORE_BLOCK_TABLE_NAME) || + ge::GRAPH_SUCCESS != CheckDimNumSupport(context_->scoreBlockTable.shape, + SCORE_BLOCK_TABLE_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaCuSeqlens() const { + if (context_->cuSeqlens.desc == nullptr) { + return ge::GRAPH_SUCCESS; + } + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(context_->cuSeqlens.desc, CU_SEQLENS_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(context_->cuSeqlens.shape, CU_SEQLENS_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaSeqused() const { + if (context_->seqUsed.desc == nullptr) { + return ge::GRAPH_SUCCESS; + } + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(context_->seqUsed.desc, SEQUSED_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(context_->seqUsed.shape, SEQUSED_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaStartPos() const { + if (context_->startPos.desc == nullptr) { + return ge::GRAPH_SUCCESS; + } + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(context_->startPos.desc, START_POS_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(context_->startPos.shape, START_POS_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaCmpKv() const { + if (context_->cmpKv.desc == nullptr) { + return ge::GRAPH_SUCCESS; + } + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(context_->cmpKv.desc, CMP_KV_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(context_->cmpKv.shape, CMP_KV_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaRopeHeadDim() const { + if (CheckAttrValueSupport( + context_->ropeHeadDim, ROPE_HEAD_DIM, ROPE_HEAD_DIM_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaCmpRatio() const { + if (CheckAttrValueSupport(context_->cmpRatio, CMP_RATIO, CMP_RATIO_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaCoff() const { + if (CheckAttrValueSupport(context_->coff, COFF, COFF_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaNormEps() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckSingleParaRotaryMode() const { + if (ge::GRAPH_SUCCESS != CheckAttrValueSupport(context_->rotaryMode, + ROTARY_MODE, + ROTARY_MODE_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckRequiredParaExistence() const { + if (CheckRequiredInOutExistence() != ge::GRAPH_SUCCESS || + CheckRequiredAttrExistence() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckRequiredInOutExistence() const { + OP_CHECK_IF(context_->x.shape == nullptr, + OP_LOGE("XllmKernelCompressor", "Shape of tensor x is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->x.desc == nullptr, + OP_LOGE("XllmKernelCompressor", "Desc of tensor x is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->wkv.shape == nullptr, + OP_LOGE("XllmKernelCompressor", "Shape of tensor wkv is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->wkv.desc == nullptr, + OP_LOGE("XllmKernelCompressor", "Desc of tensor wkv is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context_->wgate.shape == nullptr, + OP_LOGE("XllmKernelCompressor", "Shape of tensor wgate is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context_->wgate.desc == nullptr, + OP_LOGE("XllmKernelCompressor", "Desc of tensor wgate is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context_->kvState.shape == nullptr, + OP_LOGE("XllmKernelCompressor", "Shape of tensor kvState is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context_->kvState.desc == nullptr, + OP_LOGE("XllmKernelCompressor", "Desc of tensor kvState is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context_->scoreState.shape == nullptr, + OP_LOGE("XllmKernelCompressor", "Shape of tensor scoreState is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context_->scoreState.desc == nullptr, + OP_LOGE("XllmKernelCompressor", "Desc of tensor scoreState is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->ape.shape == nullptr, + OP_LOGE("XllmKernelCompressor", "Shape of tensor ape is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->ape.desc == nullptr, + OP_LOGE("XllmKernelCompressor", "Desc of tensor ape is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context_->normWeight.shape == nullptr, + OP_LOGE("XllmKernelCompressor", "Shape of tensor normWeight is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context_->normWeight.desc == nullptr, + OP_LOGE("XllmKernelCompressor", "Desc of tensor normWeight is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context_->ropeSin.shape == nullptr, + OP_LOGE("XllmKernelCompressor", "Shape of tensor ropeSin is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context_->ropeSin.desc == nullptr, + OP_LOGE("XllmKernelCompressor", "Desc of tensor ropeSin is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context_->ropeCos.shape == nullptr, + OP_LOGE("XllmKernelCompressor", "Shape of tensor ropeCos is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context_->ropeCos.desc == nullptr, + OP_LOGE("XllmKernelCompressor", "Desc of tensor ropeCos is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->kvBlockTable.shape == nullptr, + OP_LOGE("XllmKernelCompressor", + "Shape of tensor kvBlockTable is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context_->kvBlockTable.desc == nullptr, + OP_LOGE("XllmKernelCompressor", "Desc of tensor kvBlockTable is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->scoreBlockTable.shape == nullptr, + OP_LOGE("XllmKernelCompressor", + "Shape of tensor scoreBlockTable is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->scoreBlockTable.desc == nullptr, + OP_LOGE("XllmKernelCompressor", + "Desc of tensor scoreBlockTable is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context_->cmpKv.shape == nullptr, + OP_LOGE("XllmKernelCompressor", "Shape of tensor cmpKv is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context_->cmpKv.desc == nullptr, + OP_LOGE("XllmKernelCompressor", "Desc of tensor cmpKv is nullptr"), + return ge::GRAPH_FAILED); + if (context_->layout == LayoutType::LAYOUT_TH) { + OP_CHECK_IF( + context_->cuSeqlens.desc == nullptr, + OP_LOGE( + "XllmKernelCompressor", + "In TH situation, desc of tensor cuSeqlens should not be nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + context_->cuSeqlens.shape == nullptr, + OP_LOGE( + "XllmKernelCompressor", + "In TH situation, shape of tensor cuSeqlens should not be nullptr"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckRequiredAttrExistence() const { + OP_CHECK_IF(context_->ropeHeadDim == nullptr, + OP_LOGE("XllmKernelCompressor", "attr ropeHeadDim is nullptr"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(context_->cmpRatio == nullptr, + OP_LOGE("XllmKernelCompressor", "attr cmpRatio is nullptr"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckFeature() const { + if (ge::GRAPH_SUCCESS != + CheckFeatureValueSupport(&baseParams_->headDim, HEAD_DIM, "headDim")) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF(baseParams_->hiddenSize > MAX_HIDDEN_SIZE || + baseParams_->hiddenSize < MIN_HIDDEN_SIZE || + baseParams_->hiddenSize % ALIGN_FACTOR_HIDDEN_SIZE != 0, + OP_LOGE("XllmKernelCompressor", + "hiddenSize should be whthin [1k, 10k] and be " + "512-aligned, but got %u", + baseParams_->hiddenSize), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + pageAttentionParams_->blockSize > MAX_BLOCK_SIZE || + pageAttentionParams_->blockSize < MIN_BLOCK_SIZE || + pageAttentionParams_->blockSize % ALIGN_FACTOR_BLOCK_SIZE != 0, + OP_LOGE( + "XllmKernelCompressor", + "blockSize should be whthin [16, 1024] and be 16-aligned, but got %u", + pageAttentionParams_->blockSize), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::LogErrorShapeConsistency( + const std::string& name, + const gert::StorageShape* shape, + const uint32_t& dimNum, + const std::string& subName, + const uint32_t& expectNum) const { + if (shape == nullptr) { + return ge::GRAPH_SUCCESS; + } + + const uint32_t actualNum = shape->GetStorageShape().GetDim(dimNum); + OP_CHECK_IF(actualNum != expectNum, + OP_LOGE("XllmKernelCompressor", + "%s shape dim [%s] should be equal to %u, but got %u", + name.c_str(), + subName.c_str(), + expectNum, + actualNum), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckShapeConsistency() const { + if (CheckShapeConsistencyRope() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + auto coffD = coff * baseParams_->headDim; + if (ge::GRAPH_SUCCESS != + LogErrorShapeConsistency("kvBlockTable", + context_->kvBlockTable.shape, + COMPRESSOR_DIM_INDEX_0, + "batchSize", + baseParams_->batchSize) || + ge::GRAPH_SUCCESS != + LogErrorShapeConsistency("scoreBlockTable", + context_->scoreBlockTable.shape, + COMPRESSOR_DIM_INDEX_0, + "batchSize", + baseParams_->batchSize) || + ge::GRAPH_SUCCESS != + LogErrorShapeConsistency("cuSeqlens", + context_->cuSeqlens.shape, + COMPRESSOR_DIM_INDEX_0, + "batchSize+1", + baseParams_->batchSize + 1) || + ge::GRAPH_SUCCESS != LogErrorShapeConsistency("seqUsed", + context_->seqUsed.shape, + COMPRESSOR_DIM_INDEX_0, + "batchSize", + baseParams_->batchSize) || + ge::GRAPH_SUCCESS != LogErrorShapeConsistency("startPos", + context_->startPos.shape, + COMPRESSOR_DIM_INDEX_0, + "batchSize", + baseParams_->batchSize) || + ge::GRAPH_SUCCESS != LogErrorShapeConsistency("wkv", + context_->wkv.shape, + COMPRESSOR_DIM_INDEX_1, + "hiddenSize", + baseParams_->hiddenSize) || + ge::GRAPH_SUCCESS != LogErrorShapeConsistency("wgate", + context_->wgate.shape, + COMPRESSOR_DIM_INDEX_1, + "hiddenSize", + baseParams_->hiddenSize) || + ge::GRAPH_SUCCESS != + LogErrorShapeConsistency("wkv", + context_->wkv.shape, + COMPRESSOR_DIM_INDEX_0, + "coff*headDim", + static_cast(coffD)) || + ge::GRAPH_SUCCESS != + LogErrorShapeConsistency("wgate", + context_->wgate.shape, + COMPRESSOR_DIM_INDEX_0, + "coff*headDim", + static_cast(coffD)) || + ge::GRAPH_SUCCESS != + LogErrorShapeConsistency("kvState", + context_->kvState.shape, + COMPRESSOR_DIM_INDEX_2, + "coff*headDim", + static_cast(coffD)) || + ge::GRAPH_SUCCESS != + LogErrorShapeConsistency("scoreState", + context_->scoreState.shape, + COMPRESSOR_DIM_INDEX_2, + "coff*headDim", + static_cast(coffD)) || + ge::GRAPH_SUCCESS != + LogErrorShapeConsistency("ape", + context_->ape.shape, + COMPRESSOR_DIM_INDEX_1, + "coff*headDim", + static_cast(coffD)) || + ge::GRAPH_SUCCESS != LogErrorShapeConsistency("ape", + context_->ape.shape, + COMPRESSOR_DIM_INDEX_0, + "cmpRatio", + baseParams_->cmpRatio)) { + return ge::GRAPH_FAILED; + } + const auto& scoreStateShape = context_->scoreState.shape->GetStorageShape(); + uint32_t actualDim0 = scoreStateShape.GetDim(COMPRESSOR_DIM_INDEX_0); + uint32_t actualDim1 = scoreStateShape.GetDim(COMPRESSOR_DIM_INDEX_1); + const uint32_t expectDim0 = pageAttentionParams_->blockNum; + const uint32_t expectDim1 = pageAttentionParams_->blockSize; + OP_CHECK_IF(actualDim0 != expectDim0 || actualDim1 != expectDim1, + OP_LOGE("XllmKernelCompressor", + "scoreState shape dim0 should be blockNum(%u), dim1 " + "should be blockSize(%u), but got dim0=%u, dim1=%u", + expectDim0, + expectDim1, + actualDim0, + actualDim1), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckShapeConsistencyRope() const { + auto cmpT = std::min( + baseParams_->tokenSize, + baseParams_->tokenSize / baseParams_->cmpRatio + baseParams_->batchSize); + if (context_->layout == LayoutType::LAYOUT_BSH) { + if (ge::GRAPH_SUCCESS != LogErrorShapeConsistency("ropeSin", + context_->ropeSin.shape, + COMPRESSOR_DIM_INDEX_0, + "0:batchSize", + baseParams_->batchSize) || + ge::GRAPH_SUCCESS != LogErrorShapeConsistency("ropeCos", + context_->ropeCos.shape, + COMPRESSOR_DIM_INDEX_0, + "0:batchSize", + baseParams_->batchSize) || + ge::GRAPH_SUCCESS != + LogErrorShapeConsistency("ropeSin", + context_->ropeSin.shape, + COMPRESSOR_DIM_INDEX_1, + "1:ceil(seqSize/cmpRatio)", + baseParams_->cgSize) || + ge::GRAPH_SUCCESS != + LogErrorShapeConsistency("ropeCos", + context_->ropeCos.shape, + COMPRESSOR_DIM_INDEX_1, + "1:ceil(seqSize/cmpRatio)", + baseParams_->cgSize) || + ge::GRAPH_SUCCESS != + LogErrorShapeConsistency("ropeSin", + context_->ropeSin.shape, + COMPRESSOR_DIM_INDEX_2, + "2:ropeHeadDim", + baseParams_->ropeHeadDim) || + ge::GRAPH_SUCCESS != + LogErrorShapeConsistency("ropeCos", + context_->ropeCos.shape, + COMPRESSOR_DIM_INDEX_2, + "2:ropeHeadDim", + baseParams_->ropeHeadDim)) { + return ge::GRAPH_FAILED; + } + } else { + if (ge::GRAPH_SUCCESS != + LogErrorShapeConsistency( + "ropeSin", + context_->ropeSin.shape, + COMPRESSOR_DIM_INDEX_0, + "0:min(tokenSize, tokenSize/cmpRatio+batchSize)", + static_cast(cmpT)) || + ge::GRAPH_SUCCESS != + LogErrorShapeConsistency( + "ropeCos", + context_->ropeCos.shape, + COMPRESSOR_DIM_INDEX_0, + "0:min(tokenSize, tokenSize/cmpRatio+batchSize)", + static_cast(cmpT)) || + ge::GRAPH_SUCCESS != + LogErrorShapeConsistency("ropeSin", + context_->ropeSin.shape, + COMPRESSOR_DIM_INDEX_1, + "1:ropeHeadDim", + baseParams_->ropeHeadDim) || + ge::GRAPH_SUCCESS != + LogErrorShapeConsistency("ropeCos", + context_->ropeCos.shape, + COMPRESSOR_DIM_INDEX_1, + "1:ropeHeadDim", + baseParams_->ropeHeadDim)) { + return ge::GRAPH_FAILED; + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckDtypeConsistencyX( + const gert::CompileTimeTensorDesc* desc, + const std::string& name) const { + const auto actualDtype = desc->GetDataType(); + OP_CHECK_IF(actualDtype != context_->dtype, + OP_LOGE("XllmKernelCompressor", + "%s datatype should be same with x: %s, but got %s", + name.c_str(), + DataTypeToSerialString(actualDtype).c_str(), + DataTypeToSerialString(context_->dtype).c_str()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckDtypeConsistency() const { + if (CheckDtypeConsistencyX(context_->wkv.desc, WKV_NAME) != + ge::GRAPH_SUCCESS || + CheckDtypeConsistencyX(context_->wgate.desc, WGATE_NAME) != + ge::GRAPH_SUCCESS || + CheckDtypeConsistencyX(context_->normWeight.desc, NORM_WEIGHT_NAME) != + ge::GRAPH_SUCCESS || + CheckDtypeConsistencyX(context_->ropeSin.desc, ROPE_SIN_NAME) != + ge::GRAPH_SUCCESS || + CheckDtypeConsistencyX(context_->ropeCos.desc, ROPE_COS_NAME) != + ge::GRAPH_SUCCESS || + CheckDtypeConsistencyX(context_->cmpKv.desc, CMP_KV_NAME) != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckDimNumConsistency() const { + auto xDimNum = context_->x.shape->GetStorageShape().GetDimNum(); + OP_CHECK_IF(xDimNum != context_->ropeSin.shape->GetStorageShape().GetDimNum(), + OP_LOGE("XllmKernelCompressor", + "ropeSin dim num should be equal to x: %u, but got %u", + xDimNum, + context_->ropeSin.shape->GetStorageShape().GetDimNum()), + return ge::GRAPH_FAILED); + OP_CHECK_IF(xDimNum != context_->ropeCos.shape->GetStorageShape().GetDimNum(), + OP_LOGE("XllmKernelCompressor", + "ropeCos dim num should be equal to x: %u, but got %u", + xDimNum, + context_->ropeCos.shape->GetStorageShape().GetDimNum()), + return ge::GRAPH_FAILED); + OP_CHECK_IF(xDimNum != context_->cmpKv.shape->GetStorageShape().GetDimNum(), + OP_LOGE("XllmKernelCompressor", + "cmpKv dim num should be equal to x: %u, but got %u", + xDimNum, + context_->cmpKv.shape->GetStorageShape().GetDimNum()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckScenarioConsistency() const { + auto curCmpratio = baseParams_->cmpRatio; + auto curHeaddim = baseParams_->headDim; + auto curCoff = static_cast(*context_->coff); + std::vector curScenario{curCmpratio, curCoff, curHeaddim}; + const std::vector> allowdScenarios = { + {4, 2, 512}, {4, 2, 128}, {128, 1, 512}}; + + OP_CHECK_IF( + std::find(allowdScenarios.begin(), allowdScenarios.end(), curScenario) == + allowdScenarios.end(), + OP_LOGE( + "XllmKernelCompressor", + "Cmpratio Coff Headdim should be equal to {4, 2, 512}, {4, 2, 128}, {128, 1, 512},\ + but now cmpratio=%u, coff=%u, headdim=%u", + curCmpratio, + curCoff, + curHeaddim), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus CompressorTiling::CheckMultiParaConsistency() const { + if (CheckShapeConsistency() != ge::GRAPH_SUCCESS || + CheckDtypeConsistency() != ge::GRAPH_SUCCESS || + CheckDimNumConsistency() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } +#ifdef DAY0_SCOPE + if (CheckScenarioConsistency() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } +#endif + return ge::GRAPH_SUCCESS; +} + +CMP_EXTERN_C ge::graphStatus TilingCompressor(gert::TilingContext* context) { + OP_CHECK_IF(context == nullptr, + OPS_REPORT_VECTOR_INNER_ERR("XllmKernelCompressor", + "Context is nullptr."), + return ge::GRAPH_FAILED); + + OP_LOGI("Getting Tiling"); + + CompressorContext compressorContext{}; + if (CompressorTiling::ConvertContext(*context, compressorContext) != + ge::GRAPH_SUCCESS) { + OP_LOGE(context->GetNodeName(), + "Error occurred while converting tilingContext to " + "XllmKernelCompressor context"); + return ge::GRAPH_FAILED; + } + CompressorTiling compressorTiling(&compressorContext); + CompressorTilingData* tilingData = + context->GetTilingData(); + OP_CHECK_IF(tilingData == nullptr, + OPS_REPORT_VECTOR_INNER_ERR(context->GetNodeName(), + "TilingData is nullptr."), + return ge::GRAPH_FAILED); + // 使用SyncAll,需要设置为batchmode模式,所有核同时启动,否则多流方式下执行可能会卡死 + context->SetScheduleMode(BATCH_MODE_SCHEDULE); + if (compressorTiling.RunBigKernelTiling(tilingData) == ge::SUCCESS) { + context->SetTilingKey(compressorContext.tilingKey); + context->SetBlockDim(compressorContext.blockDim); + OP_LOGI(context->GetNodeName(), + "XllmKernelCompressor block dim: %u.", + compressorContext.blockDim); + return ge::GRAPH_SUCCESS; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus TilingPrepareForCompressor(gert::TilingParseContext* context) { + (void)context; + return ge::GRAPH_SUCCESS; +} + +IMPL_OP_OPTILING(XllmKernelCompressor) + .Tiling(TilingCompressor) + .TilingParse(TilingPrepareForCompressor); +} // namespace optiling \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_host/compressor_tiling.h b/xllm-kernel/csrc/ascendc/compressor/op_host/compressor_tiling.h new file mode 100644 index 0000000000..4b1fae226e --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_host/compressor_tiling.h @@ -0,0 +1,290 @@ +/** + * 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 compressor_tiling.h + * \brief + */ + +#ifndef COMPRESSOR_TILING_H +#define COMPRESSOR_TILING_H + +#include +#include +#include +#include +#include +#include +#include + +#include "compressor/op_kernel/compressor_template_tiling_key.h" +#include "compressor/op_kernel/compressor_tiling_data.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/tiling_api.h" + +#ifdef ASCENDC_OP_TEST +#define CMP_EXTERN_C extern "C" +#else +#define CMP_EXTERN_C +#endif +// #define DAY0_SCOPE + +namespace optiling { + +// INPUT +constexpr uint32_t TOKEN_X_INPUT_INDEX = 0; +constexpr uint32_t WEIGHT_KV_INPUT_INDEX = 1; +constexpr uint32_t WEIGHT_WGATE_INPUT_INDEX = 2; +constexpr uint32_t KV_STATE_INPUT_INDEX = 3; +constexpr uint32_t SCORE_STATE_INPUT_INDEX = 4; +constexpr uint32_t APE_INPUT_INDEX = 5; +constexpr uint32_t NORM_WEIGHT_INPUT_INDEX = 6; +constexpr uint32_t ROPE_SIN_INPUT_INDEX = 7; +constexpr uint32_t ROPE_COS_INPUT_INDEX = 8; + +// INPUT(OPTION) +constexpr uint32_t KV_BLOCK_TABLE_INPUT_INDEX = 9; +constexpr uint32_t SCORE_BLOCK_TABLE_INPUT_INDEX = 10; +constexpr uint32_t CU_SEQ_LEN_INPUT_INDEX = 11; +constexpr uint32_t SEQ_USED_INPUT_INDEX = 12; +constexpr uint32_t START_POS_INPUT_INDEX = 13; + +// ATTR +constexpr uint32_t ROPE_HEAD_DIM_ATTR_INDEX = 0; +constexpr uint32_t CMP_RATIO_ATTR_INDEX = 1; +constexpr uint32_t COFF_ATTR_INDEX = 2; +constexpr uint32_t NORM_EPS_ATTR_INDEX = 3; +constexpr uint32_t ROTARY_MODE_ATTR_INDEX = 4; + +// OUTPUT +constexpr uint32_t CMP_KV_OUTPUT_INDEX = 0; + +constexpr uint32_t COMPRESSOR_DIM_NUM_1 = 1; +constexpr uint32_t COMPRESSOR_DIM_NUM_2 = 2; +constexpr uint32_t COMPRESSOR_DIM_NUM_3 = 3; +constexpr uint32_t COMPRESSOR_DIM_NUM_4 = 4; +constexpr uint32_t COMPRESSOR_DIM_INDEX_0 = 0; +constexpr uint32_t COMPRESSOR_DIM_INDEX_1 = 1; +constexpr uint32_t COMPRESSOR_DIM_INDEX_2 = 2; +constexpr uint32_t COMPRESSOR_DIM_INDEX_3 = 3; + +// CONSTRAINTS +constexpr uint32_t MAX_HIDDEN_SIZE = 10240; +constexpr uint32_t MIN_HIDDEN_SIZE = 1024; +constexpr uint32_t ALIGN_FACTOR_HIDDEN_SIZE = 512; +constexpr uint32_t MAX_BLOCK_SIZE = 1024; +constexpr uint32_t MIN_BLOCK_SIZE = 16; +constexpr uint32_t ALIGN_FACTOR_BLOCK_SIZE = 16; + +constexpr uint32_t BATCH_MODE_SCHEDULE = 1; + +struct CompressorCompileInfo { + int64_t core_num; +}; + +struct RequiredParaInfo { + const gert::CompileTimeTensorDesc* desc; + const gert::StorageShape* shape; +}; + +struct OptionalParaInfo { + const gert::CompileTimeTensorDesc* desc; + const gert::StorageShape* shape; + const gert::Tensor* tensor; +}; + +enum class LayoutType { LAYOUT_BSH, LAYOUT_TH }; + +enum class TemplateId : uint8_t { NORMAL = 0, EMPTY_X = 1, PERF = 2 }; + +CMP_EXTERN_C ge::graphStatus TilingCompressor(gert::TilingContext* context); +struct CompressorBaseShapeInfo { + uint32_t bSize = 0; // B + uint32_t sSize = 0; // S + uint32_t hSize = 0; // Hidden size + uint32_t tSize = 0; // T + uint32_t nSize = 0; // N + uint32_t dSize = 0; // D + uint32_t coffSize = 0; // Coff: 1 or 2 + uint32_t csSize = 0; // Compress sequence len + uint32_t rSize = 0; // Compress ratio + uint32_t cgSize = 0; // Compress group size + uint32_t drSize = 0; // Dr +}; + +const std::vector ROPE_HEAD_DIM{64}; +const std::vector COFF{1, 2}; +#ifdef DAY0_SCOPE +const std::vector CMP_RATIO{4, 128}; +const std::vector ROTARY_MODE{2}; +#else +const std::vector CMP_RATIO{2, 4, 8, 16, 32, 64, 128}; +const std::vector ROTARY_MODE{1, 2}; +#endif +const std::vector HEAD_DIM{128, 512}; + +enum class ROTARY_MODE : uint8_t { HALF = 1, INTERLEAVE = 2 }; + +struct CompressorContext { + const char* opName; + const char* opType; + fe::PlatFormInfos* platformInfo; + + RequiredParaInfo x; + RequiredParaInfo wkv; + RequiredParaInfo wgate; + RequiredParaInfo kvState; + RequiredParaInfo scoreState; + RequiredParaInfo ape; + RequiredParaInfo normWeight; + RequiredParaInfo ropeSin; + RequiredParaInfo ropeCos; + OptionalParaInfo kvBlockTable; + OptionalParaInfo scoreBlockTable; + OptionalParaInfo cuSeqlens; + OptionalParaInfo seqUsed; + OptionalParaInfo startPos; + RequiredParaInfo cmpKv; + + const int* ropeHeadDim; + const int* coff; + const int* cmpRatio; + const float* normEps; + const int* rotaryMode; + TemplateId templateId; + + ge::DataType dtype = ge::DT_BF16; + LayoutType layout = LayoutType::LAYOUT_BSH; + + size_t* workSpaces; + uint64_t tilingKey; + uint32_t blockDim; +}; + +class CompressorTiling { + public: + explicit CompressorTiling(CompressorContext* context) : context_(context) {} + ~CompressorTiling() = default; + + static ge::graphStatus ConvertContext(gert::TilingContext& context, + CompressorContext& compressorContext); + ge::graphStatus RunBigKernelTiling(CompressorTilingData* tilingData); + + private: + static void ConvertRequiredParams(gert::TilingContext& context, + CompressorContext& compressorContext); + + static void ConvertOptionalParams(gert::TilingContext& context, + CompressorContext& compressorContext); + ge::graphStatus GetNpuInfo(); + ge::graphStatus SetBaseInfo(); + ge::graphStatus SetPageAttentionInfo(); + ge::graphStatus SetWorkSpaceInfo(); + ge::graphStatus SetScenarioInfo(); + ge::graphStatus SetTemplateId(); + ge::graphStatus SetInnerSplitInfo(); + ge::graphStatus CalcWorkSpace(); + ge::graphStatus CheckSinglePara() const; + ge::graphStatus GenTilingKey() const; + template + ge::graphStatus CheckFeatureValueSupport( + const T* featureValue, + const std::vector& expectFeatureValList, + const std::string& name) const; + template + ge::graphStatus CheckAttrValueSupport(const T* attrValue, + const std::vector& expectAttrValList, + 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 CheckDimNumInLayoutSupport(const std::string& layout, + const gert::StorageShape* shape, + const std::string& name) const; + ge::graphStatus CheckDtypeSupport(const gert::CompileTimeTensorDesc* desc, + const std::string& name) const; + void LogErrorDtypeSupport(const std::vector& expectDtypeList, + const ge::DataType& actualDtype, + const std::string& name) const; + ge::graphStatus CheckDimNumSupport(const gert::StorageShape* shape, + const std::string& name) const; + ge::graphStatus LogErrorShapeConsistency(const std::string& name, + const gert::StorageShape* shape, + const uint32_t& dimNum, + const std::string& subName, + const uint32_t& expectNum) const; + ge::graphStatus CheckSingleParaX() const; + ge::graphStatus CheckSingleParaWkv() const; + ge::graphStatus CheckSingleParaWgate() const; + ge::graphStatus CheckSingleParaKvState() const; + ge::graphStatus CheckSingleParaScoreState() const; + ge::graphStatus CheckSingleParaApe() const; + ge::graphStatus CheckSingleParaNormWeight() const; + ge::graphStatus CheckSingleParaRopeSin() const; + ge::graphStatus CheckSingleParaRopeCos() const; + ge::graphStatus CheckSingleParaKvBlockTable() const; + ge::graphStatus CheckSingleParaScoreBlockTable() const; + ge::graphStatus CheckSingleParaCuSeqlens() const; + ge::graphStatus CheckSingleParaSeqused() const; + ge::graphStatus CheckSingleParaStartPos() const; + ge::graphStatus CheckSingleParaCmpKv() const; + ge::graphStatus CheckSingleParaRopeHeadDim() const; + ge::graphStatus CheckSingleParaCmpRatio() const; + ge::graphStatus CheckSingleParaCoff() const; + ge::graphStatus CheckSingleParaNormEps() const; + ge::graphStatus CheckSingleParaRotaryMode() const; + ge::graphStatus CheckRequiredParaExistence() const; + ge::graphStatus CheckRequiredInOutExistence() const; + ge::graphStatus CheckRequiredAttrExistence() const; + ge::graphStatus CheckFeature() const; + ge::graphStatus CheckShapeConsistency() const; + ge::graphStatus CheckShapeConsistencyRope() const; + ge::graphStatus CheckDtypeConsistencyX( + const gert::CompileTimeTensorDesc* desc, + const std::string& name) const; + ge::graphStatus CheckDtypeConsistency() const; + ge::graphStatus CheckMultiParaConsistency() const; + ge::graphStatus CheckDimNumConsistency() const; + ge::graphStatus CheckEmptyTensor() const; + ge::graphStatus CheckScenarioConsistency() const; + + size_t ubSize_ = 0; + size_t l1Size_ = 0; + size_t l0cSize_ = 0; + size_t l0bSize_ = 0; + uint32_t coreNum_ = 0; + uint32_t aicNum_ = 0; + uint32_t aivNum_ = 0; + platform_ascendc::SocVersion socVersion_ = + platform_ascendc::SocVersion::ASCEND910B; + size_t libapiSize_ = 0; + // platform_ascendc::SocVersion socVersion_; + size_t workspaceSize_ = 0; + uint8_t coff = 1; + + uint32_t mBaseSize = 0; + uint32_t dbaseSize = 0; + + CompressorBaseShapeInfo baseShapeInfo_; + CompressorContext* context_ = nullptr; + CompressorBaseParams* baseParams_ = nullptr; + CompressorPageAttentionParams* pageAttentionParams_ = nullptr; + CompressorInnerSplitParams* innerSplitParams_ = nullptr; + CompressorWorkspaceParams* workspaceParams_ = nullptr; +}; +} // namespace optiling + +#endif diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/arch32.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/arch32.h new file mode 100644 index 0000000000..a1186391cf --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/arch32.h @@ -0,0 +1,25 @@ +/** + * 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 rms_norm.h + * \brief + */ + +#ifndef ARCH_32_H +#define ARCH_32_H + +#include "compressor_vector_comm.h" +#include "rms_norm.h" +#include "rope.h" +#include "soft_max.h" + +#endif \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_block_cube.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_block_cube.h new file mode 100644 index 0000000000..e0bae47ea9 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_block_cube.h @@ -0,0 +1,749 @@ +/** + * 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 compressor_block_cube.h + * \brief + */ + +#ifndef COMPRESSOR_BLOCK_CUBE_H +#define COMPRESSOR_BLOCK_CUBE_H + +#include "compressor/op_kernel/compressor_comm.h" + +using namespace AscendC; + +namespace XllmKernelCompressor { + +template +class CompressorBlockCube { + using MM1_OUT_T = float; + + public: + __aicore__ inline CompressorBlockCube(){}; + __aicore__ inline void InitParams(const ConstInfo& constInfo); + __aicore__ inline void Init(__gm__ uint8_t* x, + __gm__ uint8_t* wKv, + __gm__ uint8_t* wGate, + __gm__ uint8_t* kvState, + __gm__ uint8_t* scoreState, + __gm__ uint8_t* ape, + __gm__ uint8_t* normWeight, + __gm__ uint8_t* ropeSin, + __gm__ uint8_t* ropeCos, + __gm__ uint8_t* kvBlockTable, + __gm__ uint8_t* scoreBlockTable, + __gm__ uint8_t* cuSeqlens, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* startPos, + __gm__ uint8_t* cmpKvOut); + __aicore__ inline void InitBuffers(TPipe* pipe); + __aicore__ inline void InitGlobalBuffers( + const GlobalTensor& preMm1ResGm, + const GlobalTensor& curMm1ResGm); + __aicore__ inline void AllocEventID(TPipe* pipe); + __aicore__ inline void FreeEventID(TPipe* pipe); + __aicore__ inline void ComputeMm1(const RunInfo& info); + + private: + using T = float; + using X_T = typename AscendC:: + Conditional::type; + + __aicore__ inline uint32_t GetSeqUsed(uint32_t bIdx); + __aicore__ inline uint32_t GetStartPos(uint32_t bIdx); + __aicore__ inline uint32_t GetTIdxByBatch(uint32_t bIdx); + __aicore__ inline void CopyWeightGmToL1(const RunInfo& info, + LocalTensor wL1Tensor, + uint32_t hIdx, + uint32_t kBase, + uint32_t nLoopIdx); + __aicore__ inline void CopyXGmToL1(const RunInfo& info, + LocalTensor xL1Tensor, + uint32_t hIdx, + uint32_t kBase, + uint32_t mStart, + uint32_t mDealSize, + bool isLastM); + __aicore__ inline void LoadAToL0(LocalTensor aL0Tensor, + LocalTensor xL1Tensor, + uint32_t mStart, + uint32_t mDealSize, + uint32_t kBase, + uint32_t mSize, + bool isRightLeft); + __aicore__ inline void LoadBToL0(LocalTensor bL0Tensor, + LocalTensor wL1Tensor, + uint32_t nStart, + uint32_t nDealSize, + uint32_t nBase, + uint32_t kBase); + __aicore__ inline void MatrixMmad(LocalTensor cL0Tensor, + LocalTensor aL0Tensor, + LocalTensor bL0Tensor, + uint32_t mActSize, + uint32_t nDealSize, + uint32_t kActSize, + bool isInitL0C); + __aicore__ inline void CopyL0CDataToUb(LocalTensor ubTensor, + LocalTensor cL0Tensor, + uint32_t vecCoreIdx, + uint32_t mSizeAlign, + uint32_t nSizeAlign, + uint32_t nIdx); + + ConstInfo constInfo_ = {}; + + // GM + GlobalTensor xGm_; + GlobalTensor wkvGm_; + GlobalTensor wgateGm_; + GlobalTensor preMm1ResGm; + GlobalTensor curMm1ResGm; + GlobalTensor cuSeqlensGm_; + GlobalTensor sequsedGm_; + GlobalTensor startPosGm_; + bool isExistSeqUsed = false; + bool isExistStartPos = false; + + // =================================L1 Buffer================================= + static constexpr uint32_t L1_X_SIZE = 128 * 1024; + static constexpr uint32_t L1_W_SIZE = 64 * 1024; + // L1 Buffer + TBuf xBufL1; + TBuf wBufL1; + // =================================L0 Buffer================================= + // L0 buffer size + 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; + // L0_A + TBuf tmpBufL0A; + // L0_B + TBuf tmpBufL0B; + // L0_C + TBuf tmpBufL0C; + // =================================Event&Buffer ID=========================== + // mte2 <> mte1 EventID + static constexpr uint32_t X_EVENT0 = EVENT_ID0; + static constexpr uint32_t X_EVENT1 = EVENT_ID1; + uint32_t xBufId = 0; + static constexpr uint32_t W_EVENT0 = EVENT_ID2; + static constexpr uint32_t W_EVENT1 = EVENT_ID3; + uint32_t wBufId = 0; + static constexpr uint32_t M_LOCK_EVENT0 = EVENT_ID4; + static constexpr uint32_t M_LOCK_EVENT1 = EVENT_ID5; + uint32_t mLockId = 0; + static constexpr uint32_t N_LOCK_EVENT0 = EVENT_ID6; + static constexpr uint32_t N_LOCK_EVENT1 = EVENT_ID7; + uint32_t nLockId = 0; + // mte1 <> mmad EventID + static constexpr uint32_t L0AB_EVENT0 = EVENT_ID3; + static constexpr uint32_t L0AB_EVENT1 = EVENT_ID4; + uint32_t l0abBufId = 0; + // mmad <> fixpipe EventID + static constexpr uint32_t L0C_EVENT0 = EVENT_ID0; + static constexpr uint32_t L0C_EVENT1 = EVENT_ID1; + uint32_t l0cBufId = 0; + + // =================================Loop====================================== + uint32_t curBIdx_ = 0; + uint32_t curSIdx_ = 0; +}; + +template +__aicore__ inline void CompressorBlockCube::InitParams( + const ConstInfo& constInfo) { + this->constInfo_ = constInfo; +} + +template +__aicore__ inline void CompressorBlockCube::Init( + __gm__ uint8_t* x, + __gm__ uint8_t* wKv, + __gm__ uint8_t* wGate, + __gm__ uint8_t* kvState, + __gm__ uint8_t* scoreState, + __gm__ uint8_t* ape, + __gm__ uint8_t* normWeight, + __gm__ uint8_t* ropeSin, + __gm__ uint8_t* ropeCos, + __gm__ uint8_t* kvBlockTable, + __gm__ uint8_t* scoreBlockTable, + __gm__ uint8_t* cuSeqlens, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* startPos, + __gm__ uint8_t* cmpKvOut) { + xGm_.SetGlobalBuffer((__gm__ X_T*)x); + wkvGm_.SetGlobalBuffer((__gm__ X_T*)wKv); + wgateGm_.SetGlobalBuffer((__gm__ X_T*)wGate); + isExistSeqUsed = (seqUsed != nullptr); + isExistStartPos = (startPos != nullptr); + if (isExistStartPos) { + startPosGm_.SetGlobalBuffer((__gm__ int32_t*)startPos); + } + if (isExistSeqUsed) { + sequsedGm_.SetGlobalBuffer((__gm__ int32_t*)seqUsed); + } + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + cuSeqlensGm_.SetGlobalBuffer((__gm__ int32_t*)cuSeqlens); + } +} + +template +__aicore__ inline void CompressorBlockCube::InitBuffers(TPipe* pipe) { + // L1 + pipe->InitBuffer(xBufL1, L1_X_SIZE * 2); + pipe->InitBuffer(wBufL1, L1_W_SIZE * 2); + + // L0 + pipe->InitBuffer(tmpBufL0A, L0A_PP_SIZE * 2); + pipe->InitBuffer(tmpBufL0B, L0B_PP_SIZE * 2); + pipe->InitBuffer(tmpBufL0C, L0C_PP_SIZE * 2); +} + +template +__aicore__ inline void CompressorBlockCube::InitGlobalBuffers( + const GlobalTensor& preMm1ResGm, + const GlobalTensor& curMm1ResGm) { + this->preMm1ResGm = preMm1ResGm; + this->curMm1ResGm = curMm1ResGm; +} + +template +__aicore__ inline void CompressorBlockCube::AllocEventID(TPipe* pipe) { + SetFlag(X_EVENT0); + SetFlag(X_EVENT1); + SetFlag(W_EVENT0); + SetFlag(W_EVENT1); + SetFlag(M_LOCK_EVENT0); + SetFlag(M_LOCK_EVENT1); + SetFlag(N_LOCK_EVENT0); + SetFlag(N_LOCK_EVENT1); + + SetFlag(L0AB_EVENT0); + SetFlag(L0AB_EVENT1); + + SetFlag(L0C_EVENT0); + SetFlag(L0C_EVENT1); +} + +template +__aicore__ inline void CompressorBlockCube::FreeEventID(TPipe* pipe) { + WaitFlag(X_EVENT0); + WaitFlag(X_EVENT1); + WaitFlag(W_EVENT0); + WaitFlag(W_EVENT1); + WaitFlag(M_LOCK_EVENT0); + WaitFlag(M_LOCK_EVENT1); + WaitFlag(N_LOCK_EVENT0); + WaitFlag(N_LOCK_EVENT1); + + WaitFlag(L0AB_EVENT0); + WaitFlag(L0AB_EVENT1); + + WaitFlag(L0C_EVENT0); + WaitFlag(L0C_EVENT1); +} + +template +__aicore__ inline void CompressorBlockCube::CopyWeightGmToL1( + const RunInfo& info, + LocalTensor wL1Tensor, + uint32_t hIdx, + uint32_t kBase, + uint32_t nLoopIdx) { + // hIdx: hidden_size轴的索引ID + // kBase: hidden_size轴单次往L1搬运的长度, 128 + // nLoopIdx: D方向L1搬运的循环ID, 0/1 + // coff=1时, nLoopIdx=0, 搬运wkv nBase, nLoopIdx=1, 搬运wgate nBase + if constexpr (COMP::coff == COFF::OVERLAP) { + // coff=2时, constInfo_.dBaseSize = 64, wkv和wgate在D轴各占一半 + // nLoopIdx=0, 搬运coffIdx=0的数据; nLoopIdx=1, 搬运coffIdx=1的数据 + uint64_t coffIdx = nLoopIdx; + uint64_t dIdx = + constInfo_.aiCoreIdx % constInfo_.dBasicBlockNum * constInfo_.dBaseSize; + uint64_t gmOffset = coffIdx * constInfo_.headDim * constInfo_.hSize + + dIdx * constInfo_.hSize + hIdx; + uint32_t wkvUbOffset = nLoopIdx * (kBase * 2 * constInfo_.dBaseSize); + uint32_t wgateUbOffset = + wkvUbOffset + constInfo_.dBaseSize * (32 / sizeof(X_T)); + CopySingleMatrixNDToNZ(wL1Tensor[wkvUbOffset], + wkvGm_[gmOffset], + constInfo_.dBaseSize, + kBase, + constInfo_.hSize, + 2 * constInfo_.dBaseSize); + CopySingleMatrixNDToNZ(wL1Tensor[wgateUbOffset], + wgateGm_[gmOffset], + constInfo_.dBaseSize, + kBase, + constInfo_.hSize, + 2 * constInfo_.dBaseSize); + } else { + // coff=1时, constInfo_.dBaseSize = 128, nLoopIdx=0, 搬运wkv nBase, + // nLoopIdx=1, 搬运wgate nBase + uint64_t dIdx = + constInfo_.aiCoreIdx % constInfo_.dBasicBlockNum * constInfo_.dBaseSize; + uint64_t gmOffset = dIdx * constInfo_.hSize + hIdx; + uint32_t ubOffset = nLoopIdx * kBase * constInfo_.dBaseSize; + if (nLoopIdx == 0) { + CopySingleMatrixNDToNZ(wL1Tensor[ubOffset], + wkvGm_[gmOffset], + constInfo_.dBaseSize, + kBase, + constInfo_.hSize, + constInfo_.dBaseSize); + } else { + CopySingleMatrixNDToNZ(wL1Tensor[ubOffset], + wgateGm_[gmOffset], + constInfo_.dBaseSize, + kBase, + constInfo_.hSize, + constInfo_.dBaseSize); + } + } +} + +template +__aicore__ inline uint32_t CompressorBlockCube::GetSeqUsed( + uint32_t bIdx) { + if (isExistSeqUsed) { + return (uint32_t)sequsedGm_.GetValue(bIdx); + } else { + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + return (uint32_t)(cuSeqlensGm_.GetValue(bIdx + 1) - + cuSeqlensGm_.GetValue(bIdx)); + } else { + return constInfo_.sSize; + } + } +} + +template +__aicore__ inline uint32_t CompressorBlockCube::GetStartPos( + uint32_t bIdx) { + if (isExistStartPos) { + return (uint32_t)startPosGm_.GetValue(bIdx); + } + return 0; +} + +template +__aicore__ inline uint32_t CompressorBlockCube::GetTIdxByBatch( + uint32_t bIdx) { + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + return (uint32_t)(cuSeqlensGm_.GetValue(bIdx)); + } else { + return constInfo_.sSize * bIdx; + } +} + +template +__aicore__ inline void CompressorBlockCube::CopyXGmToL1( + const RunInfo& info, + LocalTensor xL1Tensor, + uint32_t hIdx, + uint32_t kBase, + uint32_t mStart, + uint32_t mDealSize, + bool isLastM) { + uint32_t bStartPos; + uint32_t bSeqUsed; + bool copyLastCmpBlock = false; + if constexpr (COMP::coff == COFF::OVERLAP) { + if (mStart == 0) { + curBIdx_ = info.bStart; + curSIdx_ = info.sStart; + // update cur idx + if (curSIdx_ == 0) { + if (curBIdx_ == 0) { + copyLastCmpBlock = true; + } else { + // 取上一个batch的尾 + // S=0时向前取B + do { + curBIdx_ = + (curBIdx_ - 1 + constInfo_.batchSize) % constInfo_.batchSize; + bStartPos = GetStartPos(curBIdx_); + bSeqUsed = GetSeqUsed(curBIdx_); + } while (bSeqUsed == 0); + + curSIdx_ = + bStartPos + bSeqUsed == 0 + ? 0 + : max(Trunc(bStartPos + bSeqUsed - 1, constInfo_.cmpRatio), + bStartPos) - + bStartPos; + } + } else { + curSIdx_ = + curSIdx_ < constInfo_.cmpRatio ? 0 : curSIdx_ - constInfo_.cmpRatio; + } + } + if (isLastM) { + mDealSize = mDealSize + constInfo_.cmpRatio; + } + } else { + if (mStart == 0) { + curBIdx_ = info.bStart; + curSIdx_ = info.sStart; + } + } + + uint32_t ubOffset = mStart * (32 / sizeof(X_T)); + uint32_t mSizeFinish = 0; + if (copyLastCmpBlock) { + uint32_t lastBIdx = constInfo_.batchSize; + // S=0时向前取B + do { + lastBIdx = (lastBIdx - 1 + constInfo_.batchSize) % constInfo_.batchSize; + bStartPos = GetStartPos(lastBIdx); + bSeqUsed = GetSeqUsed(lastBIdx); + } while (bSeqUsed == 0); + + uint32_t copySeqCnt = (bStartPos + bSeqUsed) % constInfo_.cmpRatio; + if (copySeqCnt == 0) { + copySeqCnt = constInfo_.cmpRatio; + } + if (bSeqUsed < copySeqCnt) { + copySeqCnt = bSeqUsed; + } + uint64_t tmpSeqId = bSeqUsed - copySeqCnt; + uint32_t rOffset = (bStartPos + bSeqUsed - copySeqCnt) % + constInfo_.cmpRatio * (32 / sizeof(X_T)); + uint64_t sIdx = GetTIdxByBatch(lastBIdx) + tmpSeqId; + uint64_t gmOffset = sIdx * constInfo_.hSize + hIdx; + uint32_t nValue = copySeqCnt; + uint32_t dValue = kBase; + uint32_t srcDValue = constInfo_.hSize; + uint32_t dstNzC0Stride = + (info.dealTcNum * constInfo_.cmpRatio + 15) / 16 * 16; + if constexpr (COMP::coff == COFF::OVERLAP) { + dstNzC0Stride = + (info.dealTcNum * constInfo_.cmpRatio + constInfo_.cmpRatio + 15) / + 16 * 16; + } + CopySingleMatrixNDToNZ(xL1Tensor[ubOffset + rOffset], + xGm_[gmOffset], + nValue, + dValue, + srcDValue, + dstNzC0Stride); + + ubOffset += constInfo_.cmpRatio * (32 / sizeof(X_T)); + mSizeFinish += constInfo_.cmpRatio; + } + + while (mSizeFinish < mDealSize) { + if (curBIdx_ > info.bEnd) { + break; + } + uint32_t bSeqUsed = GetSeqUsed(curBIdx_); + uint32_t bStartPos = GetStartPos(curBIdx_); + + // 如果S=0,直接到下一个B + if (bSeqUsed == 0) { + curBIdx_++; + curSIdx_ = 0; + continue; + } + + uint32_t headHolderCnt = (bStartPos + curSIdx_) % constInfo_.cmpRatio; + uint32_t canCopyCnt = bSeqUsed - curSIdx_; + if (mSizeFinish + headHolderCnt + canCopyCnt > mDealSize) { + canCopyCnt = mDealSize - (mSizeFinish + headHolderCnt); + } + uint32_t tailHolderCnt = + constInfo_.cmpRatio - + (bStartPos + curSIdx_ + canCopyCnt) % constInfo_.cmpRatio; + if (tailHolderCnt == constInfo_.cmpRatio) { + tailHolderCnt = 0; + } + if (canCopyCnt == 0) { + continue; + } + + // 跳过batch头部的预留行 + ubOffset += headHolderCnt * (32 / sizeof(X_T)); + + uint64_t sIdx = GetTIdxByBatch(curBIdx_) + curSIdx_; + uint64_t gmOffset = sIdx * constInfo_.hSize + hIdx; + uint32_t nValue = canCopyCnt; + uint32_t dValue = kBase; + uint32_t srcDValue = constInfo_.hSize; + uint32_t dstNzC0Stride = + (info.dealTcNum * constInfo_.cmpRatio + 15) / 16 * 16; + if constexpr (COMP::coff == COFF::OVERLAP) { + dstNzC0Stride = + (info.dealTcNum * constInfo_.cmpRatio + constInfo_.cmpRatio + 15) / + 16 * 16; + } + CopySingleMatrixNDToNZ(xL1Tensor[ubOffset], + xGm_[gmOffset], + nValue, + dValue, + srcDValue, + dstNzC0Stride); + ubOffset += (canCopyCnt + tailHolderCnt) * (32 / sizeof(X_T)); + + curSIdx_ += canCopyCnt; + if (curSIdx_ == bSeqUsed) { + curBIdx_++; + curSIdx_ = 0; + } + + mSizeFinish += headHolderCnt + canCopyCnt + tailHolderCnt; + } +} + +template +__aicore__ inline void CompressorBlockCube::LoadAToL0( + LocalTensor aL0Tensor, + LocalTensor xL1Tensor, + uint32_t mStart, + uint32_t mDealSize, + uint32_t kBase, + uint32_t mSize, + bool isRightLeft) { + if constexpr (COMP::coff == COFF::OVERLAP) { + if (isRightLeft) { + mStart += constInfo_.cmpRatio; + } + mSize += constInfo_.cmpRatio; + } + uint32_t xTensorOffset = mStart * (32 / sizeof(X_T)); + uint32_t mLoop = (mDealSize + 15) / 16; + for (uint32_t i = 0; i < mLoop; i++) { + LoadData2DParams loadData2DParams; + loadData2DParams.startIndex = i; + loadData2DParams.repeatTimes = kBase / 16; + loadData2DParams.srcStride = (mSize + 15) / 16; + loadData2DParams.dstGap = 0; + loadData2DParams.ifTranspose = false; + LoadData( + aL0Tensor[16 * i * kBase], xL1Tensor[xTensorOffset], loadData2DParams); + } +} + +template +__aicore__ inline void CompressorBlockCube::LoadBToL0( + LocalTensor bL0Tensor, + LocalTensor wL1Tensor, + uint32_t nStart, + uint32_t nDealSize, + uint32_t nBase, + uint32_t kBase) { + uint64_t wTensorOffset = (nStart / nBase) * (nBase * kBase); + LoadData2DParams loadData2DParams; + loadData2DParams.startIndex = 0; + loadData2DParams.repeatTimes = (nBase / 16) * (kBase / 16); + loadData2DParams.srcStride = 1; + loadData2DParams.dstGap = 0; + loadData2DParams.ifTranspose = false; + LoadData(bL0Tensor, wL1Tensor[wTensorOffset], loadData2DParams); +} + +template +__aicore__ inline void CompressorBlockCube::MatrixMmad( + LocalTensor cL0Tensor, + LocalTensor aL0Tensor, + LocalTensor bL0Tensor, + uint32_t mActSize, + uint32_t nDealSize, + uint32_t kActSize, + bool isInitL0C) { + MmadParams mmadParams; + mmadParams.m = (mActSize + 15) / 16 * 16; + if (mmadParams.m == 1) { + mmadParams.m = 16; + } + mmadParams.n = nDealSize; + mmadParams.k = kActSize; + mmadParams.cmatrixInitVal = true; + mmadParams.cmatrixSource = false; + Mmad(cL0Tensor, aL0Tensor, bL0Tensor, mmadParams); + AscendC::PipeBarrier(); +} + +template +__aicore__ inline void CompressorBlockCube::CopyL0CDataToUb( + LocalTensor ubTensor, + LocalTensor cL0Tensor, + uint32_t vecCoreIdx, + uint32_t mSizeAlign, + uint32_t nSizeAlign, + uint32_t nIdx) {} + +template +__aicore__ inline void CompressorBlockCube::ComputeMm1( + const RunInfo& info) { + static constexpr uint32_t K_SIZE = 256; + static constexpr uint32_t K_L1_BASE = 128; + static constexpr uint32_t N_L1_BASE = 128; + static constexpr uint32_t M_L1_BASE = 128; + static constexpr uint32_t K_L1_LOOP = K_SIZE / K_L1_BASE; + + uint32_t nSize = constInfo_.dBaseSize * 2 * ((uint32_t)COMP::coff); + uint32_t mSize = info.dealTcNum * constInfo_.cmpRatio; + bool needMLock = (mSize > M_L1_BASE); + + uint32_t hSize = constInfo_.hSize; + for (uint32_t h = 0; h < hSize; h += K_SIZE) { + for (uint32_t kL1Idx = 0; kL1Idx < K_L1_LOOP; kL1Idx++) { + WaitFlag(X_EVENT0 + xBufId); + WaitFlag(W_EVENT0 + wBufId); + + LocalTensor xL1Tensor = xBufL1.GetWithOffset( + L1_X_SIZE / sizeof(X_T), xBufId * L1_X_SIZE); + LocalTensor wL1Tensor = wBufL1.GetWithOffset( + L1_W_SIZE / sizeof(X_T), wBufId * L1_W_SIZE); + for (uint32_t nL1 = 0; nL1 < nSize; nL1 += N_L1_BASE) { + // nLockId = nL1 / N_L1_BASE + WaitFlag(N_LOCK_EVENT0 + nLockId); + CopyWeightGmToL1(info, + wL1Tensor, + h + kL1Idx * K_L1_BASE, + K_L1_BASE, + nL1 / N_L1_BASE); + SetFlag(N_LOCK_EVENT0 + nLockId); + WaitFlag(N_LOCK_EVENT0 + nLockId); + for (uint32_t mL1 = 0; mL1 < mSize; mL1 += M_L1_BASE) { + uint32_t mDealSize = M_L1_BASE; + bool isLastM = (mL1 + M_L1_BASE >= mSize); + if (isLastM) { + mDealSize = mSize - mL1; + } + + if (nL1 == 0) { + mLockId = mL1 / M_L1_BASE; + if (needMLock) { + WaitFlag(M_LOCK_EVENT0 + mLockId); + } + // 当Coff=2时,mL1为最后一块时,需要多拷贝一个cmpRatio + CopyXGmToL1(info, + xL1Tensor, + h + kL1Idx * K_L1_BASE, + K_L1_BASE, + mL1, + mDealSize, + isLastM); + + // m轴可以一次拷贝时, 不需要m轴的拷贝锁;同步替换成大锁 + if (needMLock) { + SetFlag(M_LOCK_EVENT0 + mLockId); + WaitFlag(M_LOCK_EVENT0 + mLockId); + } else { + SetFlag(X_EVENT0 + xBufId); + WaitFlag(X_EVENT0 + xBufId); + } + } + + { + // 获取L0C + WaitFlag(L0C_EVENT0 + l0cBufId); + LocalTensor cL0Tensor = tmpBufL0C.GetWithOffset( + (L0C_PP_SIZE / sizeof(T)), l0cBufId * L0C_PP_SIZE); + { + WaitFlag(L0AB_EVENT0 + l0abBufId); + LocalTensor aL0Tensor = tmpBufL0A.GetWithOffset( + L0A_PP_SIZE / sizeof(X_T), l0abBufId * L0A_PP_SIZE); + LocalTensor bL0Tensor = tmpBufL0B.GetWithOffset( + L0B_PP_SIZE / sizeof(X_T), l0abBufId * L0B_PP_SIZE); + // 当Coff=2时,nL1=0时计算的是pre数据,nL1=N_L1_BASE时计算的是cur数据 + uint32_t K_L0_BASE = K_L1_BASE; + LoadAToL0(aL0Tensor, + xL1Tensor, + mL1, + mDealSize, + K_L0_BASE, + mSize, + (nL1 > 0)); + uint32_t N_L0_BASE = N_L1_BASE; + + LoadBToL0( + bL0Tensor, wL1Tensor, nL1, N_L0_BASE, N_L0_BASE, K_L0_BASE); + SetFlag(L0AB_EVENT0 + l0abBufId); + WaitFlag(L0AB_EVENT0 + l0abBufId); + MatrixMmad(cL0Tensor, + aL0Tensor, + bL0Tensor, + mDealSize, + N_L0_BASE, + K_L0_BASE, + (h == 0) && (kL1Idx == 0)); + + SetFlag(L0AB_EVENT0 + l0abBufId); + l0abBufId = (l0abBufId + 1) % 2; + } + { + SetFlag(L0C_EVENT0 + l0cBufId); + WaitFlag(L0C_EVENT0 + l0cBufId); + + if (kL1Idx != 0 || h != 0) { + SetAtomicAdd(); + } + if constexpr (COMP::coff == COFF::OVERLAP) { + FixpipeParamsV220 fixParams; + fixParams.mSize = (mDealSize + 15) / 16 * 16; + fixParams.nSize = N_L1_BASE; + fixParams.srcStride = (mDealSize + 15) / 16 * 16; // 需要16对齐 + fixParams.dstStride = constInfo_.dBaseSize * 2; + fixParams.ndNum = 1; + if (nL1 < nSize / 2) { + Fixpipe(preMm1ResGm[mL1 * constInfo_.dBaseSize * 2], + cL0Tensor, + fixParams); + } else { + Fixpipe(curMm1ResGm[mL1 * constInfo_.dBaseSize * 2], + cL0Tensor, + fixParams); + } + } else { + FixpipeParamsV220 fixParams; + fixParams.mSize = (mDealSize + 15) / 16 * 16; + fixParams.nSize = N_L1_BASE; + fixParams.srcStride = (mDealSize + 15) / 16 * 16; // 需要16对齐 + fixParams.dstStride = constInfo_.dBaseSize * 2; + fixParams.ndNum = 1; + Fixpipe(curMm1ResGm[mL1 * nSize + nL1], cL0Tensor, fixParams); + } + + if (kL1Idx != 0 || h != 0) { + SetAtomicNone(); + } + } + SetFlag(L0C_EVENT0 + l0cBufId); + l0cBufId = (l0cBufId + 1) % 2; + } + + if (nL1 + N_L1_BASE >= nSize) { + if (needMLock) { + mLockId = mL1 / M_L1_BASE; + SetFlag(M_LOCK_EVENT0 + mLockId); + } + } + } + SetFlag(N_LOCK_EVENT0 + nLockId); + nLockId = (nLockId + 1) % 2; + } + + SetFlag(X_EVENT0 + xBufId); + xBufId = (xBufId + 1) % 2; + SetFlag(W_EVENT0 + wBufId); + wBufId = (wBufId + 1) % 2; + } + } +} + +} // namespace XllmKernelCompressor + +#endif // COMPRESSOR_BLOCK_CUBE_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_block_cube_perf.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_block_cube_perf.h new file mode 100644 index 0000000000..506ebfccde --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_block_cube_perf.h @@ -0,0 +1,598 @@ +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved. + * This file is a part of the CANN Open Software. + * Licensed under CANN Open Software License Agreement Version 1.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 compressor_block_cube_perf.h + * \brief + */ + +#ifndef COMPRESSOR_BLOCK_CUBE_PERF_H +#define COMPRESSOR_BLOCK_CUBE_PERF_H + +#include "compressor/op_kernel/compressor_comm.h" +#include "compressor/op_kernel/compressor_tools.h" + +using namespace AscendC; + +namespace XllmKernelCompressor { + +template +class CompressorBlockCubePerf { + using MM1_OUT_T = float; + + public: + __aicore__ inline CompressorBlockCubePerf(){}; + __aicore__ inline void InitParams(const ConstInfo& constInfo, + const CompressorTools& tools); + __aicore__ inline void Init(__gm__ uint8_t* x, + __gm__ uint8_t* wKv, + __gm__ uint8_t* wGate, + __gm__ uint8_t* kvState, + __gm__ uint8_t* scoreState, + __gm__ uint8_t* ape, + __gm__ uint8_t* normWeight, + __gm__ uint8_t* ropeSin, + __gm__ uint8_t* ropeCos, + __gm__ uint8_t* kvBlockTable, + __gm__ uint8_t* scoreBlockTable, + __gm__ uint8_t* cuSeqlens, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* startPos, + __gm__ uint8_t* cmpKvOut); + __aicore__ inline void InitBuffers(TPipe* pipe); + __aicore__ inline void InitGlobalBuffers( + const GlobalTensor& preMm1ResGm, + const GlobalTensor& curMm1ResGm); + __aicore__ inline void AllocEventID(TPipe* pipe); + __aicore__ inline void FreeEventID(TPipe* pipe); + __aicore__ inline void ComputeMm1(const RunInfo& info); + + private: + using T = float; + using X_T = typename AscendC:: + Conditional::type; + + __aicore__ inline uint32_t GetMSize(const RunInfo& info, uint32_t coffId); + __aicore__ inline void CopyXGmToL1(const RunInfo& info, + LocalTensor xL1Tensor, + uint32_t hIdx, + uint32_t kBase); + __aicore__ inline void CopyWeightGmToL1(LocalTensor wL1Tensor, + uint32_t hIdx, + uint32_t kBase, + uint32_t coffId); + __aicore__ inline void LoadAToL0(const RunInfo& info, + LocalTensor aL0Tensor, + LocalTensor xL1Tensor, + uint32_t coffId, + uint32_t kStart, + uint32_t kBase, + uint32_t mStart, + uint32_t mDealSize); + __aicore__ inline void LoadBToL0(LocalTensor bL0Tensor, + LocalTensor wL1Tensor, + uint32_t kStart, + uint32_t kBase); + __aicore__ inline void MatrixMmad(LocalTensor cL0Tensor, + LocalTensor aL0Tensor, + LocalTensor bL0Tensor, + uint32_t mActSize, + uint32_t nDealSize, + uint32_t kActSize, + bool isInitL0C); + __aicore__ inline void CopyOutMm1Res(const RunInfo& info, + LocalTensor cL0Tensor, + uint32_t coffId, + uint32_t mStart, + uint32_t mDealSize); + + ConstInfo constInfo_ = {}; + CompressorTools tools_; + + // GM + GlobalTensor xGm_; + GlobalTensor wkvGm_; + GlobalTensor wgateGm_; + GlobalTensor preMm1ResGm; + GlobalTensor curMm1ResGm; + GlobalTensor cuSeqlensGm_; + GlobalTensor sequsedGm_; + GlobalTensor startPosGm_; + bool isExistSeqUsed = false; + + // =================================L1 Buffer================================= + static constexpr uint32_t L1_X_SIZE = 128 * 1024; + static constexpr uint32_t L1_W_SIZE = 64 * 1024; + // L1 Buffer + TBuf xBufL1; + TBuf wBufL1; + // =================================L0 Buffer================================= + // L0 buffer size + static constexpr uint32_t L0A_PP_SIZE = 32 * 1024; // 128 * 128 * 2 = 32k + static constexpr uint32_t L0B_PP_SIZE = 32 * 1024; // 128 * 128 * 2 = 32k + static constexpr uint32_t L0C_PP_SIZE = + 64 * 1024; // (128 * 2) * 64 * 4 = 64k + // L0_A + TBuf tmpBufL0A; + // L0_B + TBuf tmpBufL0B; + // L0_C + TBuf tmpBufL0C; + // =================================Event&Buffer ID=========================== + // mte2 <> mte1 EventID + static constexpr uint32_t X_EVENT0 = EVENT_ID0; + static constexpr uint32_t X_EVENT1 = EVENT_ID1; + uint32_t xBufId = 0; // 用于DB计数 + static constexpr uint32_t W_EVENT0 = EVENT_ID4; + static constexpr uint32_t W_EVENT1 = EVENT_ID5; + static constexpr uint32_t W_EVENT2 = EVENT_ID6; + static constexpr uint32_t W_EVENT3 = EVENT_ID7; + uint32_t wBufId = 0; // 用于DB计数 + // mte1 <> mmad EventID + static constexpr uint32_t L0AB_EVENT0 = EVENT_ID3; + static constexpr uint32_t L0AB_EVENT1 = EVENT_ID4; + uint32_t l0abBufId = 0; + // mmad <> fixpipe EventID + static constexpr uint32_t L0C_EVENT0 = EVENT_ID0; // 每块L0C单独分配EVENT_ID + static constexpr uint32_t L0C_EVENT1 = EVENT_ID1; + uint32_t l0cBufId = 0; + + // =================================Loop====================================== + uint32_t curBIdx_ = 0; + uint32_t curSIdx_ = 0; +}; + +template +__aicore__ inline void CompressorBlockCubePerf::InitParams( + const ConstInfo& constInfo, + const CompressorTools& tools) { + this->constInfo_ = constInfo; + this->tools_ = tools; +} + +template +__aicore__ inline void CompressorBlockCubePerf::Init( + __gm__ uint8_t* x, + __gm__ uint8_t* wKv, + __gm__ uint8_t* wGate, + __gm__ uint8_t* kvState, + __gm__ uint8_t* scoreState, + __gm__ uint8_t* ape, + __gm__ uint8_t* normWeight, + __gm__ uint8_t* ropeSin, + __gm__ uint8_t* ropeCos, + __gm__ uint8_t* kvBlockTable, + __gm__ uint8_t* scoreBlockTable, + __gm__ uint8_t* cuSeqlens, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* startPos, + __gm__ uint8_t* cmpKvOut) { + xGm_.SetGlobalBuffer((__gm__ X_T*)x); + wkvGm_.SetGlobalBuffer((__gm__ X_T*)wKv); + wgateGm_.SetGlobalBuffer((__gm__ X_T*)wGate); + startPosGm_.SetGlobalBuffer((__gm__ int32_t*)startPos); + isExistSeqUsed = (seqUsed != nullptr); + if (isExistSeqUsed) { + sequsedGm_.SetGlobalBuffer((__gm__ int32_t*)seqUsed); + } + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + cuSeqlensGm_.SetGlobalBuffer((__gm__ int32_t*)cuSeqlens); + } +} + +template +__aicore__ inline void CompressorBlockCubePerf::InitBuffers(TPipe* pipe) { + // L1 + // 1. coff=1时, mBase=256, kL1=256, + // X单次拷贝到L1的数据量最大为mBase*kL1*sizeof(BF16/FP16)=256*256*2=128K + // 2. coff=2时, mBase=128, kL1=256, r最大为128, + // X单次拷贝到L1的最大数据量为(128+r)*kL1*sizeof(BF16/FP16)<=128K + pipe->InitBuffer(xBufL1, L1_X_SIZE * 2); + // dBaseSize<=64, wkv和wgate各一份, kL1=256, + // 右矩阵为dBaseSize*2*sizeof(BF16/FP16)<=64K cur和pre循环使用, + // 2份buffer就足够 + pipe->InitBuffer(wBufL1, L1_W_SIZE * 4); + + // L0 + pipe->InitBuffer(tmpBufL0A, L0A_PP_SIZE * 2); + pipe->InitBuffer(tmpBufL0B, L0B_PP_SIZE * 2); + pipe->InitBuffer(tmpBufL0C, L0C_PP_SIZE * 2); +} + +template +__aicore__ inline void CompressorBlockCubePerf::InitGlobalBuffers( + const GlobalTensor& preMm1ResGm, + const GlobalTensor& curMm1ResGm) { + this->preMm1ResGm = preMm1ResGm; + this->curMm1ResGm = curMm1ResGm; +} + +template +__aicore__ inline void CompressorBlockCubePerf::AllocEventID( + TPipe* pipe) { + SetFlag(X_EVENT0); + SetFlag(X_EVENT1); + + SetFlag(W_EVENT0); + SetFlag(W_EVENT1); + SetFlag(W_EVENT2); + SetFlag(W_EVENT3); + + SetFlag(L0AB_EVENT0); + SetFlag(L0AB_EVENT1); + + SetFlag(L0C_EVENT0); + SetFlag(L0C_EVENT1); +} + +template +__aicore__ inline void CompressorBlockCubePerf::FreeEventID(TPipe* pipe) { + WaitFlag(X_EVENT0); + WaitFlag(X_EVENT1); + + WaitFlag(W_EVENT0); + WaitFlag(W_EVENT1); + WaitFlag(W_EVENT2); + WaitFlag(W_EVENT3); + + WaitFlag(L0AB_EVENT0); + WaitFlag(L0AB_EVENT1); + + WaitFlag(L0C_EVENT0); + WaitFlag(L0C_EVENT1); +} + +template +__aicore__ inline void CompressorBlockCubePerf::CopyXGmToL1( + const RunInfo& info, + LocalTensor xL1Tensor, + uint32_t hIdx, + uint32_t kBase) { + uint32_t preTSeqCnt = tools_.GetTIdxByBatch(info.preBStart) + + info.preSStart; // 前序在整个序列中的位置 + uint32_t preSeqCnt = info.preFirstSeqCnt; // 前序需要拷贝的长度 + uint32_t tStart = tools_.GetTIdxByBatch(info.bStart) + + info.sStart; // 此基本块在整个序列中的位置 + uint32_t copySeqCnt = info.dealSeqCnt; // 此基本块处理的长度 + + if constexpr (COMP::coff == COFF::OVERLAP) { + uint32_t dValue = kBase; // 拷贝的列数kBase + uint32_t srcDValue = constInfo_.hSize; + uint32_t dstNzC0Stride = (copySeqCnt + preSeqCnt + 15) / 16 * + 16; // 1行变2行的行方向的偏移,需要16对齐 + if (info.bStart == 0 && info.sStart == 0) { + // 按照分核所给信息 + uint32_t xL1Offset = 0 * (32 / sizeof(X_T)); + uint64_t sIdx = preTSeqCnt; + uint64_t gmOffset = sIdx * constInfo_.hSize + hIdx; + uint32_t nValue = preSeqCnt; + CopySingleMatrixNDToNZ(xL1Tensor[xL1Offset], + xGm_[gmOffset], + nValue, + dValue, + srcDValue, + dstNzC0Stride); + // 再从0开始拷贝全部, + xL1Offset = preSeqCnt * (32 / sizeof(X_T)); + sIdx = 0; + gmOffset = sIdx * constInfo_.hSize + hIdx; + nValue = copySeqCnt; + CopySingleMatrixNDToNZ(xL1Tensor[xL1Offset], + xGm_[gmOffset], + nValue, + dValue, + srcDValue, + dstNzC0Stride); + } else { + // 需拷贝前一个压缩块的尾块 + uint32_t xL1Offset = 0 * (32 / sizeof(X_T)); + uint64_t sIdx = preTSeqCnt; + uint64_t gmOffset = sIdx * constInfo_.hSize + hIdx; + uint32_t nValue = copySeqCnt + preSeqCnt; + CopySingleMatrixNDToNZ(xL1Tensor[xL1Offset], + xGm_[gmOffset], + nValue, + dValue, + srcDValue, + dstNzC0Stride); + } + } else { + uint32_t xL1Offset = 0 * (32 / sizeof(X_T)); + uint64_t sIdx = tStart; // 起始s在整个T的起始点 + uint64_t gmOffset = sIdx * constInfo_.hSize + hIdx; + uint32_t nValue = copySeqCnt; + uint32_t dValue = kBase; // 拷贝的列数kBase + uint32_t srcDValue = constInfo_.hSize; + uint32_t dstNzC0Stride = + (copySeqCnt + 15) / 16 * 16; // 1行变2行的行方向的偏移,需要16对齐 + CopySingleMatrixNDToNZ(xL1Tensor[xL1Offset], + xGm_[gmOffset], + nValue, + dValue, + srcDValue, + dstNzC0Stride); + } +} + +template +__aicore__ inline void CompressorBlockCubePerf::CopyWeightGmToL1( + LocalTensor wL1Tensor, + uint32_t hIdx, + uint32_t kBase, + uint32_t coffId) { + // coffId=0, 搬运左矩阵的数据; coffId=1, 搬运右矩阵的数据 + uint64_t gmOffset = coffId * constInfo_.headDim * constInfo_.hSize + + constInfo_.dIdx * constInfo_.hSize + hIdx; + uint32_t wkvL1Offset = 0; + uint32_t wgateL1Offset = + constInfo_.dBaseSize * + (32 / sizeof(X_T)); // wgate与wkv的起始点相隔dBaseSize个32B + uint32_t nValue = constInfo_.dBaseSize; + uint32_t dValue = kBase; + uint32_t srcDValue = constInfo_.hSize; + uint32_t dstNzC0Stride = + 2 * + constInfo_ + .dBaseSize; // 2: wkv和wgate各搬运dBaseSize行, dBaseSize需保证8的倍数 + CopySingleMatrixNDToNZ(wL1Tensor[wkvL1Offset], + wkvGm_[gmOffset], + nValue, + dValue, + srcDValue, + dstNzC0Stride); + CopySingleMatrixNDToNZ(wL1Tensor[wgateL1Offset], + wgateGm_[gmOffset], + nValue, + dValue, + srcDValue, + dstNzC0Stride); +} + +template +__aicore__ inline void CompressorBlockCubePerf::LoadAToL0( + const RunInfo& info, + LocalTensor aL0Tensor, + LocalTensor xL1Tensor, + uint32_t coffId, + uint32_t kStart, + uint32_t kBase, + uint32_t mStart, + uint32_t mDealSize) { + uint32_t mSize = info.dealSeqCnt; + // 当Coff=2时,coffId=0时计算的是pre数据,coffId=1时计算的是cur数据 + if constexpr (COMP::coff == COFF::OVERLAP) { + if (coffId > 0) { // 右矩阵需要跳过多搬的长度 + mStart += info.preFirstSeqCnt; // 右矩阵需要的偏移量 + } + mSize = info.preFirstSeqCnt + info.dealSeqCnt; + } + + uint32_t mSizeAlign = Align(mSize, 16U); + uint32_t xTensorOffset = kStart * mSizeAlign + mStart * (32 / sizeof(X_T)); + uint32_t mLoop = Align(mDealSize, 16U) / 16; + + for (uint32_t i = 0; i < mLoop; i++) { + LoadData2DParams loadData2DParams; + loadData2DParams.startIndex = i; + loadData2DParams.repeatTimes = kBase / (32 / sizeof(X_T)); + loadData2DParams.srcStride = mSizeAlign / 16; + loadData2DParams.dstGap = 0; + loadData2DParams.ifTranspose = false; + LoadData(aL0Tensor[i * 16 * kBase], + xL1Tensor[xTensorOffset], + loadData2DParams); // 16: 一个分型的行数 + } +} + +template +__aicore__ inline void CompressorBlockCubePerf::LoadBToL0( + LocalTensor bL0Tensor, + LocalTensor wL1Tensor, + uint32_t kStart, + uint32_t kBase) { + uint32_t rowCnt = + 2 * + constInfo_ + .dBaseSize; // 2: wkv和wgate各搬运dBaseSize行, dBaseSize需保证8的倍数 + uint64_t wTensorOffset = rowCnt * kStart; + LoadData2DParams loadData2DParams; + loadData2DParams.startIndex = 0; + loadData2DParams.repeatTimes = (rowCnt / 16) * (kBase / (32 / sizeof(X_T))); + loadData2DParams.srcStride = 1; + loadData2DParams.dstGap = 0; + loadData2DParams.ifTranspose = false; + LoadData(bL0Tensor, wL1Tensor[wTensorOffset], loadData2DParams); +} + +template +__aicore__ inline void CompressorBlockCubePerf::MatrixMmad( + LocalTensor cL0Tensor, + LocalTensor aL0Tensor, + LocalTensor bL0Tensor, + uint32_t mActSize, + uint32_t nDealSize, + uint32_t kActSize, + bool isInitL0C) { + MmadParams mmadParams; + mmadParams.m = (mActSize + 15) / 16 * 16; + mmadParams.n = nDealSize; + mmadParams.k = kActSize; + mmadParams.cmatrixInitVal = isInitL0C; + mmadParams.cmatrixSource = false; + Mmad(cL0Tensor, aL0Tensor, bL0Tensor, mmadParams); + AscendC::PipeBarrier(); +} + +template +__aicore__ inline void CompressorBlockCubePerf::CopyOutMm1Res( + const RunInfo& info, + LocalTensor cL0Tensor, + uint32_t coffId, + uint32_t mStart, + uint32_t mDealSize) { + uint32_t nDealSize = + 2 * + constInfo_ + .dBaseSize; // 2: wkv和wgate各搬运dBaseSize行, dBaseSize需保证8的倍数 + FixpipeParamsV220 fixParams; + fixParams.mSize = mDealSize; + fixParams.nSize = nDealSize; + fixParams.srcStride = (mDealSize + 15) / 16 * 16; // 需要16对齐 + fixParams.dstStride = nDealSize; + fixParams.ndNum = 1; + + uint64_t gmOffset = mStart * fixParams.dstStride; + + if constexpr (COMP::coff == COFF::OVERLAP) { + Fixpipe((coffId == 0) ? preMm1ResGm[gmOffset] : curMm1ResGm[gmOffset], + cL0Tensor, + fixParams); + } else { + Fixpipe(curMm1ResGm[gmOffset], cL0Tensor, fixParams); + } + + // kv和score不拼起来,搬运俩个矩阵,待打开 + // uint32_t nDealSize = constInfo_.dBaseSize; // 2: + // wkv和wgate各搬运dBaseSize行, dBaseSize需保证8的倍数 FixpipeParamsV220 + // fixParams; fixParams.mSize = mDealSize; fixParams.nSize = nDealSize; + // fixParams.srcStride = (mDealSize + 15) / 16 * 16; // 需要16对齐 + // fixParams.dstStride = nDealSize; + // fixParams.ndNum = 2; + // fixParams.srcNdStride = constInfo_.dBaseSize; + // fixParams.dstNdStride = nDealSize * mDealSize; + + // uint64_t gmOffset = mStart * constInfo_.dBaseSize * 2; + + // if constexpr (COMP::coff == COFF::OVERLAP) { + // Fixpipe((coffId == 0) ? preMm1ResGm[gmOffset] : curMm1ResGm[gmOffset], + // cL0Tensor, fixParams); + // } else { + // Fixpipe(curMm1ResGm[gmOffset], cL0Tensor, fixParams); + // } +} + +template +__aicore__ inline uint32_t CompressorBlockCubePerf::GetMSize( + const RunInfo& info, + uint32_t coffId) { + if constexpr (COMP::coff == COFF::OVERLAP) { + if (coffId == 0) { + return info.preDealSeqCnt; + } else { + return info.dealSeqCnt; + } + } else { + return info.dealSeqCnt; + } +} + +template +__aicore__ inline void CompressorBlockCubePerf::ComputeMm1( + const RunInfo& info) { + static constexpr uint32_t K_SIZE = 512; + static constexpr uint32_t K_L1_BASE = 256; + static constexpr uint32_t M_L0_BASE = 128; + static constexpr uint32_t K_L0_BASE = 128; + uint32_t nCoff = (uint32_t)COMP::coff; + + // hSize为K_SIZE=512的倍数 + uint32_t hSize = constInfo_.hSize; + uint32_t hIdxStart = (constInfo_.aiCoreIdx % constInfo_.dBasicBlockNum) * + K_L1_BASE; // 每组核内的h循环起始不同 + for (uint32_t h = 0; h < hSize; h += K_SIZE) { + for (uint32_t k = 0; k < K_SIZE; k += K_L1_BASE) { + bool isFirst = (h == 0 && k == 0); + bool isLast = ((h + K_SIZE >= hSize) && (k + K_L1_BASE >= K_SIZE)); + uint32_t hIdx = (h + k + hIdxStart) % hSize; // h方向错位搬运 + WaitFlag(X_EVENT0 + xBufId); + LocalTensor xL1Tensor = xBufL1.GetWithOffset( + L1_X_SIZE / sizeof(X_T), xBufId * L1_X_SIZE); + CopyXGmToL1(info, xL1Tensor, hIdx, K_L1_BASE); + SetFlag(X_EVENT0 + xBufId); + WaitFlag(X_EVENT0 + xBufId); + for (uint32_t i = nCoff; i > 0; i--) { + // coffId=0, 计算pre数据; coffId=1, 计算cur数据 + uint32_t coffId = i - 1; + WaitFlag(W_EVENT0 + wBufId); + LocalTensor wL1Tensor = wBufL1.GetWithOffset( + L1_W_SIZE / sizeof(X_T), wBufId * L1_W_SIZE); + CopyWeightGmToL1(wL1Tensor, hIdx, K_L1_BASE, coffId); + SetFlag(W_EVENT0 + wBufId); + WaitFlag(W_EVENT0 + wBufId); + + uint32_t mSize = GetMSize(info, coffId); + uint32_t actMDealSize = M_L0_BASE; + for (uint32_t mL0 = 0; mL0 < mSize; mL0 += M_L0_BASE) { + if (mL0 + M_L0_BASE > mSize) { + actMDealSize = mSize - mL0; + } + + l0cBufId = coffId + (mL0 / M_L0_BASE); + LocalTensor cL0Tensor = tmpBufL0C.GetWithOffset( + (L0C_PP_SIZE / sizeof(T)), l0cBufId * L0C_PP_SIZE); + if (isFirst) { + WaitFlag(L0C_EVENT0 + l0cBufId); + } + uint32_t nDealSize = + 2 * constInfo_.dBaseSize; // 2: wkv和wgate各搬运dBaseSize行, + // dBaseSize需保证8的倍数 + for (uint32_t kL0 = 0; kL0 < K_L1_BASE; kL0 += K_L0_BASE) { + WaitFlag(L0AB_EVENT0 + l0abBufId); + LocalTensor aL0Tensor = tmpBufL0A.GetWithOffset( + L0A_PP_SIZE / sizeof(X_T), l0abBufId * L0A_PP_SIZE); + LocalTensor bL0Tensor = tmpBufL0B.GetWithOffset( + L0B_PP_SIZE / sizeof(X_T), l0abBufId * L0B_PP_SIZE); + LoadAToL0(info, + aL0Tensor, + xL1Tensor, + coffId, + kL0, + K_L0_BASE, + mL0, + actMDealSize); + LoadBToL0(bL0Tensor, wL1Tensor, kL0, K_L0_BASE); + SetFlag(L0AB_EVENT0 + l0abBufId); + WaitFlag(L0AB_EVENT0 + l0abBufId); + bool isInitL0C = isFirst && (kL0 == 0); + MatrixMmad(cL0Tensor, + aL0Tensor, + bL0Tensor, + actMDealSize, + nDealSize, + K_L0_BASE, + isInitL0C); + SetFlag(L0AB_EVENT0 + l0abBufId); + l0abBufId = (l0abBufId + 1) % 2; + } + if (isLast) { + SetFlag(L0C_EVENT0 + l0cBufId); + WaitFlag(L0C_EVENT0 + l0cBufId); + CopyOutMm1Res(info, cL0Tensor, coffId, mL0, actMDealSize); + SetFlag(L0C_EVENT0 + l0cBufId); + } + } + + SetFlag(W_EVENT0 + wBufId); + wBufId = (wBufId + 1) % 4; + } + SetFlag(X_EVENT0 + xBufId); + xBufId = (xBufId + 1) % 2; + } + } + + // DumpTensorForDim2(preMm1ResGm, 1, 128 * 2 * constInfo_.dBaseSize); + // DumpTensorForDim2(curMm1ResGm, 2, 128 * 2 * constInfo_.dBaseSize); +} + +} // namespace XllmKernelCompressor + +#endif // COMPRESSOR_BLOCK_CUBE_PERF_H diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_block_vec.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_block_vec.h new file mode 100644 index 0000000000..f127cab0fd --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_block_vec.h @@ -0,0 +1,1819 @@ +/** + * 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 compressor_block_vec.h + * \brief + */ + +#ifndef COMPRESSOR_BLOCK_VEC_H +#define COMPRESSOR_BLOCK_VEC_H + +#include "arch32.h" +#include "compressor/op_kernel/compressor_comm.h" + +using namespace AscendC; + +namespace XllmKernelCompressor { +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; +template +class CompressorBlockVector { + public: + static constexpr bool X_DTYPE = COMP::xDtype == X_DTYPE::BF16; + static constexpr uint64_t BLOCK_VEC_BASE_BUFFER_SIZE = 32 * 1024; // 32k + static constexpr uint32_t DATABLOCK_BYTES = 32; + static constexpr float FLOAT_ZERO = 0; + // =================================类型定义区================================= + // 中间计算数据类型为float,高精度模式 + using T = float; + using X_T = typename AscendC::Conditional::type; + + __aicore__ inline CompressorBlockVector(){}; + // =================================设置参数================================= + __aicore__ inline void InitParams(const ConstInfo& constInfo); + __aicore__ inline void Init(__gm__ uint8_t* x, + __gm__ uint8_t* wKv, + __gm__ uint8_t* wGate, + __gm__ uint8_t* kvState, + __gm__ uint8_t* scoreState, + __gm__ uint8_t* ape, + __gm__ uint8_t* normWeight, + __gm__ uint8_t* ropeSin, + __gm__ uint8_t* ropeCos, + __gm__ uint8_t* kvBlockTable, + __gm__ uint8_t* scoreBlockTable, + __gm__ uint8_t* cuSeqlens, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* startPos, + __gm__ uint8_t* cmpKvOut); + // =================================资源管理================================= + __aicore__ inline void InitBuffers(TPipe* pipe); + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + // =================================执行计算================================= + __aicore__ inline void ComputeVec1(const XllmKernelCompressor::RunInfo& info); + __aicore__ inline uint32_t GetBasicNum(); + __aicore__ inline uint32_t GetScSize(); + __aicore__ inline void GetScIdxInfo(uint32_t bStart, + uint32_t scStart, + uint32_t dealScSize, + uint32_t v2TcStart, + uint32_t v2TcEnd, + uint32_t& outputBStart, + uint32_t& outputSStart, + uint32_t& outputScSize); + __aicore__ inline void CalcScEndIdx(uint32_t bStart, + uint32_t scStart, + uint32_t dealScSize, + uint32_t& bEnd, + uint32_t& scEnd); + __aicore__ inline void InitVec1GlobalTensor(GlobalTensor preMm1ResGm, + GlobalTensor curMm1ResGm, + GlobalTensor vec1ResGm, + GlobalTensor vec2InputGm); + __aicore__ inline void ComputeVec2(const XllmKernelCompressor::RunInfo& info); + __aicore__ inline void WriteToCacheState( + const GlobalTensor& state, + const GlobalTensor& blockTableGm, + const LocalTensor& input, + uint32_t batchIdx, + uint32_t startSeqIdx, + uint32_t endSeqIdx, + uint32_t dStart, + uint32_t dDealSize); + __aicore__ inline void ReadFromCacheState( + const LocalTensor& output, + const GlobalTensor& state, + const GlobalTensor& blockTableGm, + uint32_t batchIdx, + uint32_t startSeqIdx, + uint32_t endSeqIdx, + uint32_t dStart, + uint32_t dDealSize); + + protected: + GlobalTensor vec1ResGm_; + GlobalTensor vec2InputGm_; + GlobalTensor preMm1ResGm_; + GlobalTensor curMm1ResGm_; + + private: + __aicore__ inline uint32_t GetSeqUsed(uint32_t bIdx); + __aicore__ inline uint32_t GetStartPos(uint32_t bIdx); + __aicore__ inline uint32_t GetSeqLength(uint32_t bIdx); + __aicore__ inline uint32_t GetBsLength(uint32_t index); + __aicore__ inline void CalcGlobalScStart(uint32_t bStart, + uint32_t scStart, + uint32_t bEnd, + uint32_t scEnd, + uint64_t& globalScStart); + __aicore__ inline void UpdateOutputIdx(uint32_t& outputBStart, + uint32_t& outputSStart, + uint32_t& dealScSize, + uint32_t& curDealScSize); + __aicore__ inline void DealVec1BaseBlock(const RunInfo& info, + BlockInfo& blockInfo, + uint32_t startTcIdx, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void UpdateBlockInfo(BlockInfo& blockInfo); + __aicore__ inline void CopyInApe(LocalTensor apeUb, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void AddApeToScore(LocalTensor& scoreLocal, + LocalTensor& apeUb, + uint32_t tcDealSize, + uint32_t dDealSize); + __aicore__ inline void DataCopyAlignUbToUb(LocalTensor dstLocal, + LocalTensor srcLocal, + uint32_t copyRowCount, + uint32_t copyColCount, + uint32_t srcSingleRowCount, + uint32_t dstSingleRowCount); + __aicore__ inline void DataCopyAlignGmToUb(LocalTensor dstLocal, + GlobalTensor srcGm, + uint32_t copyRowCount, + uint32_t copyColCount, + uint32_t srcSingleRowCount, + uint32_t dstSingleRowCount); + __aicore__ inline void OverLapScore(LocalTensor scoreLocal, + const RunInfo& info, + uint32_t tcStartIdx, + uint32_t tcDealSize, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void OverLapKv(LocalTensor kvLocal, + const RunInfo& info, + uint32_t tcStartIdx, + uint32_t tcDealSize, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void UpdateState(LocalTensor kvLocal, + LocalTensor scoreLocal, + uint32_t startTcIdx, + const BlockInfo& blockInfo, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void SoftmaxDN(LocalTensor& scoreLocal, + LocalTensor& tmpUb, + uint32_t tcDealSize, + uint32_t dDealSize); + __aicore__ inline void KvMulReduceScore(LocalTensor& kvLocal, + LocalTensor& scoreLocal, + LocalTensor& dstLocal, + LocalTensor& tmpUb, + uint32_t tcDealSize, + uint32_t dDealSize); + __aicore__ inline void CopyOutVec1Res(const RunInfo& info, + LocalTensor comporessedUb, + uint32_t compressTcSize, + uint32_t dStartIdx, + uint32_t dDealSize); + + __aicore__ inline void SplitCoreV2(const XllmKernelCompressor::RunInfo& info); + __aicore__ inline void CopyFinalResultOut( + const XllmKernelCompressor::RunInfo& info, + const LocalTensor& cmpKvOutUb, + uint32_t startRow, + uint32_t dealRowCount); + __aicore__ inline void DealVec2BaseBlock( + const XllmKernelCompressor::RunInfo& info, + uint32_t startRow, + uint32_t dealRowCount); + __aicore__ inline void MultRowRmsNorm( + LocalTensor& normResUb, + LocalTensor& vec1ResUb, + LocalTensor& normWeightUb, + LocalTensor& tempLocal, + const XllmKernelCompressor::RunInfo& info, + uint32_t dealRowCount); + __aicore__ inline void CalRope(const XllmKernelCompressor::RunInfo& info, + LocalTensor& outputUb, + LocalTensor& normResUb, + uint32_t startRow, + uint32_t dealRowCount); + __aicore__ inline void SaveLeftFirst(const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const BlockInfo& blockInfo, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void SaveState(const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const BlockInfo& blockInfo, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void ReadState(const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const BlockInfo& blockInfo, + uint32_t dStartIdx, + uint32_t dDealSize); + // static constexpr uint64_t SYNC_INPUT_BUF1_FLAG = 2; + // static constexpr uint64_t SYNC_INPUT_BUF1_PONG_FLAG = 3; + uint32_t cmpRatio_ = 0U; + uint32_t coff_ = 0U; + uint32_t curStartPos_ = 0; + uint32_t curActSeqLength_ = 0; + uint32_t compressedCnt_ = 0; + uint32_t v1SplitSize_ = 0; + uint32_t v1ScLoopTimes_ = 0; + uint32_t v1DLoopTimes_ = 0; + uint32_t dealTcNum_ = 0; + bool apeIsLoad_ = false; + bool isExistSeqUsed = false; + bool isExistStartPos = false; + // vec2 + uint32_t v2MBaseSize = 16; // Tc块数量:32 * 1024 / (512 * 4) + uint32_t v2TcStartIdx = 0U; + uint32_t v2TcEndIdx = 0U; + uint32_t mmResColSize_ = 128; + int64_t vec1ResGmStart = 0U; + uint32_t usedCoreNum = 16; + uint32_t OutputBStartIdx, OutputSStartIdx, OutputSize; + uint32_t mmResBaseOffset_ = 0; + ConstInfo constInfo_ = {}; + MSplitInfo mSplitInfo = {}; + GlobalTensor startPosGm_; + GlobalTensor cuSeqlensGm_; + GlobalTensor sequsedGm_; + GlobalTensor kvBlockTableGm_; + GlobalTensor scoreBlockTableGm_; + GlobalTensor kvStateGm_; + GlobalTensor scoreStateGm_; + GlobalTensor apeGm_; + GlobalTensor normWeightGm_; + GlobalTensor ropeSinGm_; + GlobalTensor ropeCosGm_; + GlobalTensor cmpKvOutGm_; + + // ================================Local + // Buffer区==================================== + LocalTensor mm1ResTensor; + LocalTensor leftStateTensor; + LocalTensor rightStateTensor; + LocalTensor normWeightUb; + LocalTensor gatherOffsetCastUb; + // 临时tbuf + TBuf tmpBuff1; + TBuf tmpBuff2; + TBuf gatherOffsetBuf; + // in queue + TQue inputQue1; + TQue inputQue2; + TBuf normWeightBuf; + // out queue + TQue outputQue1; +}; + +template +__aicore__ inline void CompressorBlockVector::InitParams( + const ConstInfo& constInfo) { + this->constInfo_ = constInfo; + v2MBaseSize = + BLOCK_VEC_BASE_BUFFER_SIZE / (constInfo_.headDim * sizeof(float)); +} + +template +__aicore__ inline void CompressorBlockVector::Init( + __gm__ uint8_t* x, + __gm__ uint8_t* wKv, + __gm__ uint8_t* wGate, + __gm__ uint8_t* kvState, + __gm__ uint8_t* scoreState, + __gm__ uint8_t* ape, + __gm__ uint8_t* normWeight, + __gm__ uint8_t* ropeSin, + __gm__ uint8_t* ropeCos, + __gm__ uint8_t* kvBlockTable, + __gm__ uint8_t* scoreBlockTable, + __gm__ uint8_t* cuSeqlens, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* startPos, + __gm__ uint8_t* cmpKvOut) { + kvBlockTableGm_.SetGlobalBuffer((__gm__ int32_t*)kvBlockTable); + scoreBlockTableGm_.SetGlobalBuffer((__gm__ int32_t*)scoreBlockTable); + kvStateGm_.SetGlobalBuffer((__gm__ T*)kvState); + scoreStateGm_.SetGlobalBuffer((__gm__ T*)scoreState); + apeGm_.SetGlobalBuffer((__gm__ T*)ape); + normWeightGm_.SetGlobalBuffer((__gm__ X_T*)normWeight); + ropeSinGm_.SetGlobalBuffer((__gm__ X_T*)ropeSin); + ropeCosGm_.SetGlobalBuffer((__gm__ X_T*)ropeCos); + cmpKvOutGm_.SetGlobalBuffer((__gm__ X_T*)cmpKvOut); + isExistSeqUsed = (seqUsed != nullptr); + isExistStartPos = (startPos != nullptr); + if (isExistSeqUsed) { + sequsedGm_.SetGlobalBuffer((__gm__ int32_t*)seqUsed); + } + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + cuSeqlensGm_.SetGlobalBuffer((__gm__ int32_t*)cuSeqlens); + } + if (isExistStartPos) { + startPosGm_.SetGlobalBuffer((__gm__ int32_t*)startPos); + } +} + +template +__aicore__ inline void CompressorBlockVector::InitBuffers(TPipe* pipe) { + pipe->InitBuffer(inputQue1, 1, BUFFER_SIZE_BYTE_32K); + pipe->InitBuffer(tmpBuff1, BUFFER_SIZE_BYTE_32K); + pipe->InitBuffer(tmpBuff2, BUFFER_SIZE_BYTE_64K); + pipe->InitBuffer(outputQue1, 1, BUFFER_SIZE_BYTE_16K); + pipe->InitBuffer(inputQue2, 1, BUFFER_SIZE_BYTE_2K); + pipe->InitBuffer(normWeightBuf, BUFFER_SIZE_BYTE_4K); + pipe->InitBuffer(gatherOffsetBuf, BUFFER_SIZE_BYTE_2K); + normWeightUb = normWeightBuf.Get(); + LocalTensor normweightInUb = inputQue2.AllocTensor(); + LocalTensor gatherOffsetUb = gatherOffsetBuf.Get(); + DataCopy(normweightInUb, + normWeightGm_, + constInfo_.headDim); // 获取normWeight,常驻 + inputQue2.EnQue(normweightInUb); + inputQue2.DeQue(); + Cast(normWeightUb, normweightInUb, RoundMode::CAST_NONE, constInfo_.headDim); + inputQue2.FreeTensor(normweightInUb); + if constexpr (COMP::rotaryMode == + XllmKernelCompressor::ROTARY_MODE::INTERLEAVE) { + SetGatherSrcOffset(gatherOffsetUb, constInfo_.headDim); + } + gatherOffsetCastUb = gatherOffsetUb.ReinterpretCast(); + PipeBarrier(); +} + +template +__aicore__ inline void CompressorBlockVector::AllocEventID() { + // SetFlag(SYNC_INPUT_BUF1_FLAG); + // SetFlag(SYNC_INPUT_BUF1_PONG_FLAG); +} + +template +__aicore__ inline void CompressorBlockVector::FreeEventID() { + // WaitFlag(SYNC_INPUT_BUF1_FLAG); + // WaitFlag(SYNC_INPUT_BUF1_PONG_FLAG); +} + +template +__aicore__ inline void CompressorBlockVector::InitVec1GlobalTensor( + GlobalTensor preMm1ResGm, + GlobalTensor curMm1ResGm, + GlobalTensor vec1ResGm, + GlobalTensor vec2InputGm) { + this->preMm1ResGm_ = preMm1ResGm; + this->curMm1ResGm_ = curMm1ResGm; + this->vec1ResGm_ = vec1ResGm; + this->vec2InputGm_ = vec2InputGm; +} + +template +__aicore__ inline uint32_t CompressorBlockVector::GetSeqUsed( + uint32_t bIdx) { + if (isExistSeqUsed) { + return (uint32_t)sequsedGm_.GetValue(bIdx); + } else { + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + return (uint32_t)(cuSeqlensGm_.GetValue(bIdx + 1) - + cuSeqlensGm_.GetValue(bIdx)); + } else { + return constInfo_.sSize; + } + } +} + +template +__aicore__ inline uint32_t CompressorBlockVector::GetStartPos( + uint32_t bIdx) { + if (isExistStartPos) { + return startPosGm_.GetValue(bIdx); + } + return 0; +} + +template +__aicore__ inline uint32_t CompressorBlockVector::GetSeqLength( + uint32_t bIdx) { + if (isExistSeqUsed) { + return sequsedGm_.GetValue(bIdx); + } else if (COMP::xLayout == X_LAYOUT::TH) { + return cuSeqlensGm_.GetValue(bIdx + 1) - cuSeqlensGm_.GetValue(bIdx); + } else { + return constInfo_.sSize; + } +} + +template +__aicore__ inline uint32_t CompressorBlockVector::GetBsLength( + uint32_t index) { + if (COMP::xLayout == X_LAYOUT::TH) { + return cuSeqlensGm_.GetValue(index); + } else { + return index * constInfo_.sSize; + } +} + +template +__aicore__ inline uint32_t CompressorBlockVector::GetBasicNum() { + // 获取 m方向上对应基本单元Tc的个数 + uint32_t curBasicNum = 0; + uint32_t headSize = 0; + if (curStartPos_ % constInfo_.cmpRatio != 0) { + headSize = constInfo_.cmpRatio - curStartPos_ % constInfo_.cmpRatio; + headSize = headSize > curActSeqLength_ ? curActSeqLength_ : headSize; + curBasicNum++; + } + // 加上中间整块及尾块 + curBasicNum += (curActSeqLength_ - headSize + constInfo_.cmpRatio - 1) / + constInfo_.cmpRatio; + return curBasicNum; +} + +template +__aicore__ inline uint32_t CompressorBlockVector::GetScSize() { + uint32_t curBasicNum = + (curStartPos_ + curActSeqLength_) / constInfo_.cmpRatio - + curStartPos_ / constInfo_.cmpRatio; + return curBasicNum; +} + +// 根据计算Tc开始结束索引 +template +__aicore__ inline void CompressorBlockVector::CalcScEndIdx( + uint32_t bStart, + uint32_t scStart, + uint32_t dealScSize, + uint32_t& bEnd, + uint32_t& scEnd) { + uint32_t accScSize = 0; + for (int bIdx = bStart; bIdx < constInfo_.batchSize; ++bIdx) { + bEnd = bIdx; + + curActSeqLength_ = GetSeqLength(bIdx); + curStartPos_ = GetStartPos(bIdx); + // 计算起始batch的剩余块 + if (bIdx == bStart) { + accScSize += GetScSize() - scStart; // 需要减去本batch已经处理完的sc + if (accScSize >= dealScSize) { + scEnd = scStart + dealScSize; + return; + } + } else { + uint32_t curBasicNum = GetScSize(); + uint32_t curBasicNumEnd = dealScSize - accScSize; + + if (accScSize + curBasicNum >= dealScSize) { + scEnd = curBasicNumEnd; + return; + } + accScSize += curBasicNum; + } + } +} + +// 根据sc的开始索引计算vec输出时的b、sc的索引 +template +__aicore__ inline void CompressorBlockVector::GetScIdxInfo( + uint32_t bStart, + uint32_t scStart, + uint32_t dealScSize, + uint32_t v2TcStart, + uint32_t v2TcEnd, + uint32_t& outputBStart, + uint32_t& outputSStart, + uint32_t& outputScSize) { + outputScSize = v2TcEnd - v2TcStart; + uint32_t scEnd = 0; + uint32_t bEnd = 0; + CalcScEndIdx(bStart, scStart, v2TcStart, bEnd, scEnd); + outputSStart = scEnd; + outputBStart = bEnd; + // 处理跳batch + curActSeqLength_ = GetSeqLength(bEnd); + curStartPos_ = GetStartPos(bEnd); + uint32_t curScSize = GetScSize(); + if (curScSize == scEnd) { + outputSStart = 0; + outputBStart++; + } +} + +template +__aicore__ inline void CompressorBlockVector::CopyInApe( + LocalTensor apeUb, + uint32_t dStartIdx, + uint32_t dDealSize) { + uint32_t copyRowCount = constInfo_.cmpRatio; + uint32_t copyColCount = dDealSize; + uint32_t dstSingleRowCount = ((uint32_t)COMP::coff) * dDealSize; + uint32_t srcSingleRowCount = ((uint32_t)COMP::coff) * constInfo_.headDim; + + uint32_t gmOffset = (constInfo_.aiCoreIdx % constInfo_.dBasicBlockNum) * + constInfo_.dBaseSize + + dStartIdx; + uint32_t dstUbOffset = 0; + if constexpr (COMP::coff == COFF::OVERLAP) { + DataCopyAlignGmToUb(apeUb[dstUbOffset], + apeGm_[gmOffset], + copyRowCount, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); + + gmOffset += constInfo_.headDim; + dstUbOffset += dDealSize; + } + DataCopyAlignGmToUb(apeUb[dstUbOffset], + apeGm_[gmOffset], + copyRowCount, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); +} + +template +__aicore__ inline void CompressorBlockVector::AddApeToScore( + LocalTensor& scoreLocal, + LocalTensor& apeUb, + uint32_t tcDealSize, + uint32_t dDealSize) { + uint32_t ReduceSize = COMP::coff == COFF::OVERLAP ? 2 * constInfo_.cmpRatio + : constInfo_.cmpRatio; + uint32_t rCnt = ReduceSize * dDealSize; + for (uint32_t r = 0; r < tcDealSize; r++) { + Add(scoreLocal[r * rCnt], scoreLocal[r * rCnt], apeUb, rCnt); + } +} + +template +__aicore__ inline void CompressorBlockVector::DataCopyAlignUbToUb( + LocalTensor dstLocal, + LocalTensor srcLocal, + uint32_t copyRowCount, + uint32_t copyColCount, + uint32_t srcSingleRowCount, + uint32_t dstSingleRowCount) { + DataCopyParams intriParams; + intriParams.blockCount = copyRowCount; + intriParams.blockLen = copyColCount / (32 / sizeof(T)); + intriParams.dstStride = (dstSingleRowCount - copyColCount) / (32 / sizeof(T)); + intriParams.srcStride = (srcSingleRowCount - copyColCount) / (32 / sizeof(T)); + DataCopy(dstLocal, srcLocal, intriParams); +} + +template +__aicore__ inline void CompressorBlockVector::DataCopyAlignGmToUb( + LocalTensor dstLocal, + GlobalTensor srcGm, + uint32_t copyRowCount, + uint32_t copyColCount, + uint32_t srcSingleRowCount, + uint32_t dstSingleRowCount) { + DataCopyParams intriParams; + intriParams.blockCount = copyRowCount; + intriParams.blockLen = copyColCount / (32 / sizeof(T)); + intriParams.dstStride = (dstSingleRowCount - copyColCount) / (32 / sizeof(T)); + intriParams.srcStride = (srcSingleRowCount - copyColCount) / (32 / sizeof(T)); + DataCopy(dstLocal, srcGm, intriParams); +} + +template +__aicore__ inline void CompressorBlockVector::OverLapScore( + LocalTensor scoreLocal, + const RunInfo& info, + uint32_t tcStartIdx, + uint32_t tcDealSize, + uint32_t dStartIdx, + uint32_t dDealSize) { + // scoreUb data layout after overlap when r = 4 and coff = 2: + // Tc0_seq01: |--- --D_L--- -|------D_R-----| + // Tc0_seq02: |--- --D_L--- -|------D_R-----| + // Tc0_seq03: |--- --D_L--- -|------D_R-----| + // Tc0_seq04: |--- --D_L--- -|------D_R-----| + // Tc1_seq01: |--- --D_L--- -|------D_R-----| + // Tc1_seq02: |--- --D_L--- -|------D_R-----| + // Tc1_seq03: |--- --D_L--- -|------D_R-----| + // Tc1_seq04: |--- --D_L--- -|------D_R-----| + uint32_t srcSingleRowElemNum = + constInfo_.dBaseSize * 2; // 2: kv和score各一份 + uint32_t copyRowCount = tcDealSize * constInfo_.cmpRatio; + uint32_t copyColCount = dDealSize; + uint32_t srcSingleRowCount = srcSingleRowElemNum; + uint32_t dstSingleRowCount = + ((uint32_t)COMP::coff) * dDealSize; // left和right在seq方向是交错存储的 + uint32_t srcScoreUbOffset = + (tcStartIdx * constInfo_.cmpRatio) * srcSingleRowElemNum + + constInfo_.dBaseSize + dStartIdx; + if (GetBlockIdx() % 2 == 1) { + srcScoreUbOffset += 128 * srcSingleRowElemNum; + } + + uint32_t dstUbOffset = 0; + if constexpr (COMP::coff == COFF::OVERLAP) { + DataCopyAlignGmToUb(scoreLocal[dstUbOffset], + preMm1ResGm_[srcScoreUbOffset], + copyRowCount, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); + dstUbOffset += dDealSize; + } + DataCopyAlignGmToUb(scoreLocal[dstUbOffset], + curMm1ResGm_[srcScoreUbOffset], + copyRowCount, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); +} + +template +__aicore__ inline void CompressorBlockVector::OverLapKv( + LocalTensor kvLocal, + const RunInfo& info, + uint32_t tcStartIdx, + uint32_t tcDealSize, + uint32_t dStartIdx, + uint32_t dDealSize) { + // kvUb data layout after overlap when r = 4 and coff = 2: + // Tc0_seq01: |--- --D_L--- -|------D_R-----| + // Tc0_seq02: |--- --D_L--- -|------D_R-----| + // Tc0_seq03: |--- --D_L--- -|------D_R-----| + // Tc0_seq04: |--- --D_L--- -|------D_R-----| + // Tc1_seq01: |--- --D_L--- -|------D_R-----| + // Tc1_seq02: |--- --D_L--- -|------D_R-----| + // Tc1_seq03: |--- --D_L--- -|------D_R-----| + // Tc1_seq04: |--- --D_L--- -|------D_R-----| + uint32_t srcSingleRowElemNum = + constInfo_.dBaseSize * 2; // 2: kv和score各一份 + uint32_t copyRowCount = tcDealSize * constInfo_.cmpRatio; + uint32_t copyColCount = dDealSize; + uint32_t srcSingleRowCount = srcSingleRowElemNum; + uint32_t dstSingleRowCount = + ((uint32_t)COMP::coff) * dDealSize; // left和right在seq方向是交错存储的 + uint32_t srcKvUbOffset = + (tcStartIdx * constInfo_.cmpRatio) * srcSingleRowElemNum + dStartIdx; + if (GetBlockIdx() % 2 == 1) { + srcKvUbOffset += 128 * srcSingleRowElemNum; + } + + uint32_t dstUbOffset = 0; + if constexpr (COMP::coff == COFF::OVERLAP) { + DataCopyAlignGmToUb(kvLocal[dstUbOffset], + preMm1ResGm_[srcKvUbOffset], + copyRowCount, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); + dstUbOffset += dDealSize; + } + DataCopyAlignGmToUb(kvLocal[dstUbOffset], + curMm1ResGm_[srcKvUbOffset], + copyRowCount, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); +} + +template +__aicore__ inline void CompressorBlockVector::ReadFromCacheState( + const LocalTensor& output, + const GlobalTensor& state, + const GlobalTensor& blockTableGm, + uint32_t batchIdx, + uint32_t startSeqIdx, + uint32_t endSeqIdx, + uint32_t dStart, + uint32_t dDealSize) { + uint32_t coff = static_cast(COMP::coff); + uint64_t blockTablebaseOffset = batchIdx * constInfo_.maxBlockNumPerBatch; + uint32_t curSeqIdx = startSeqIdx; + uint32_t copyFinishRowCnt = 0; + uint32_t seqCnt = endSeqIdx - startSeqIdx; + while (copyFinishRowCnt < seqCnt) { + uint64_t blockIdOffset = curSeqIdx / constInfo_.blockSize; + uint64_t remainRowCnt = curSeqIdx % constInfo_.blockSize; + uint64_t idInBlockTable = + blockTableGm.GetValue(blockTablebaseOffset + blockIdOffset); + uint32_t copyRowCnt = constInfo_.blockSize - remainRowCnt; + if (copyFinishRowCnt + copyRowCnt > seqCnt) { + copyRowCnt = seqCnt - copyFinishRowCnt; + } + + uint64_t stateOffset = + idInBlockTable * constInfo_.blockSize * coff * constInfo_.headDim + + remainRowCnt * coff * constInfo_.headDim + + (constInfo_.aiCoreIdx % constInfo_.dBasicBlockNum) * + constInfo_.dBaseSize + + dStart; + + DataCopyParams copyParams; + copyParams.blockCount = copyRowCnt; + copyParams.blockLen = dDealSize / (32 / sizeof(T)); + copyParams.dstStride = (coff * dDealSize - dDealSize) / (32 / sizeof(T)); + copyParams.srcStride = + (coff * constInfo_.headDim - dDealSize) / (32 / sizeof(T)); + DataCopy(output[copyFinishRowCnt * coff * dDealSize], + state[stateOffset], + copyParams); + + copyFinishRowCnt += copyRowCnt; + curSeqIdx += copyRowCnt; + } +} + +template +__aicore__ inline void CompressorBlockVector::WriteToCacheState( + const GlobalTensor& state, + const GlobalTensor& blockTableGm, + const LocalTensor& input, + uint32_t batchIdx, + uint32_t startSeqIdx, + uint32_t endSeqIdx, + uint32_t dStart, + uint32_t dDealSize) { + uint32_t coff = static_cast(COMP::coff); + uint64_t blockTablebaseOffset = batchIdx * constInfo_.maxBlockNumPerBatch; + uint32_t curSeqIdx = startSeqIdx; + uint32_t copyFinishRowCnt = 0; + uint32_t seqCnt = endSeqIdx - startSeqIdx; + while (copyFinishRowCnt < seqCnt) { + uint64_t blockIdOffset = curSeqIdx / constInfo_.blockSize; + uint64_t remainRowCnt = curSeqIdx % constInfo_.blockSize; + uint64_t idInBlockTable = + blockTableGm.GetValue(blockTablebaseOffset + blockIdOffset); + uint32_t copyRowCnt = constInfo_.blockSize - remainRowCnt; + if (copyFinishRowCnt + copyRowCnt > seqCnt) { + copyRowCnt = seqCnt - copyFinishRowCnt; + } + + if (idInBlockTable != 0) { // 32 + uint64_t stateOffset = + idInBlockTable * constInfo_.blockSize * coff * constInfo_.headDim + + remainRowCnt * coff * constInfo_.headDim + + (constInfo_.aiCoreIdx % constInfo_.dBasicBlockNum) * + constInfo_.dBaseSize + + dStart; + + DataCopyParams copyParams; + copyParams.blockCount = copyRowCnt; + copyParams.blockLen = dDealSize / (32 / sizeof(T)); + copyParams.dstStride = + (coff * constInfo_.headDim - dDealSize) / (32 / sizeof(T)); + copyParams.srcStride = (coff * dDealSize - dDealSize) / (32 / sizeof(T)); + DataCopy(state[stateOffset], + input[copyFinishRowCnt * coff * dDealSize], + copyParams); + } + + copyFinishRowCnt += copyRowCnt; + curSeqIdx += copyRowCnt; + } +} + +template +__aicore__ inline void CompressorBlockVector::SaveLeftFirst( + const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const BlockInfo& blockInfo, + uint32_t dStartIdx, + uint32_t dDealSize) { + uint32_t coff = static_cast(COMP::coff); + uint32_t preBIdx = 0; + // 左边为上一个batch或者最后一个batch的数据 + preBIdx = (blockInfo.bIdx - 1 + constInfo_.batchSize) % constInfo_.batchSize; + + uint32_t bSeqUsed = GetSeqUsed(preBIdx); + uint32_t bStartPos = GetStartPos(preBIdx); + // S=0时,跳B + while (bSeqUsed == 0) { + preBIdx = (preBIdx - 1 + constInfo_.batchSize) % constInfo_.batchSize; + bSeqUsed = GetSeqUsed(preBIdx); + bStartPos = GetStartPos(preBIdx); + } + + uint32_t endIdxInBlock = (bStartPos + bSeqUsed) % constInfo_.cmpRatio; + if (endIdxInBlock == 0) { + endIdxInBlock = constInfo_.cmpRatio; + } + + uint32_t copySeqCnt = (endIdxInBlock > bSeqUsed) ? bSeqUsed : endIdxInBlock; + uint64_t endSeqIdx = bStartPos + bSeqUsed; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = (endIdxInBlock - copySeqCnt) * coff * dDealSize; + WriteToCacheState(kvStateGm_, + kvBlockTableGm_, + kvLocal[srcBaseOffset], + preBIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + WriteToCacheState(scoreStateGm_, + scoreBlockTableGm_, + scoreLocal[srcBaseOffset], + preBIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); +} + +template +__aicore__ inline void CompressorBlockVector::SaveState( + const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const BlockInfo& blockInfo, + uint32_t dStartIdx, + uint32_t dDealSize) { + if (COMP::coff == COFF::OVERLAP) { + uint32_t coff = static_cast(COMP::coff); + // 存右边 + if (blockInfo.sIdx + blockInfo.validSeqCnt == blockInfo.bSeqUsed) { + uint32_t copySeqCnt = constInfo_.cmpRatio - blockInfo.tailHolderSeqCnt; + if (blockInfo.validSeqCnt < copySeqCnt) { + copySeqCnt = blockInfo.validSeqCnt; + } else { + if (blockInfo.tailHolderSeqCnt > 0) { + if (blockInfo.validSeqCnt - copySeqCnt > constInfo_.cmpRatio) { + copySeqCnt += constInfo_.cmpRatio; + } else { + copySeqCnt += blockInfo.validSeqCnt - copySeqCnt; + } + } + } + uint64_t endSeqIdx = + blockInfo.bStartPos + blockInfo.sIdx + blockInfo.validSeqCnt; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = + (blockInfo.headHolderSeqCnt + blockInfo.validSeqCnt - copySeqCnt) * + coff * dDealSize; + WriteToCacheState(kvStateGm_, + kvBlockTableGm_, + kvLocal[srcBaseOffset + dDealSize], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx + constInfo_.headDim, + dDealSize); + WriteToCacheState(scoreStateGm_, + scoreBlockTableGm_, + scoreLocal[srcBaseOffset + dDealSize], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx + constInfo_.headDim, + dDealSize); + } else if (blockInfo.sIdx + blockInfo.validSeqCnt + constInfo_.cmpRatio > + blockInfo.bSeqUsed) { + uint32_t copySeqCnt = constInfo_.cmpRatio; + if (copySeqCnt > blockInfo.validSeqCnt) { + copySeqCnt = blockInfo.validSeqCnt; + } + uint64_t endSeqIdx = + blockInfo.bStartPos + blockInfo.sIdx + blockInfo.validSeqCnt; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = + (blockInfo.headHolderSeqCnt + blockInfo.validSeqCnt - copySeqCnt) * + coff * dDealSize; + WriteToCacheState(kvStateGm_, + kvBlockTableGm_, + kvLocal[srcBaseOffset + dDealSize], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx + constInfo_.headDim, + dDealSize); + WriteToCacheState(scoreStateGm_, + scoreBlockTableGm_, + scoreLocal[srcBaseOffset + dDealSize], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx + constInfo_.headDim, + dDealSize); + } + + // 存左边 + if (blockInfo.dealTcSize == 1) { + // 左边尾块和首块是同一块 + if (blockInfo.sIdx == 0) { + SaveLeftFirst(kvLocal, scoreLocal, blockInfo, dStartIdx, dDealSize); + } else { + if (blockInfo.tailHolderSeqCnt > 0) { + // 左边为本batch数据 + uint32_t copySeqCnt = constInfo_.cmpRatio; + if (blockInfo.sIdx < copySeqCnt) { + copySeqCnt = blockInfo.sIdx; + } + uint64_t endSeqIdx = + blockInfo.bStartPos + blockInfo.sIdx + blockInfo.validSeqCnt - + (constInfo_.cmpRatio - blockInfo.tailHolderSeqCnt); + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = + (blockInfo.headHolderSeqCnt + blockInfo.validSeqCnt + + blockInfo.tailHolderSeqCnt - copySeqCnt) * + coff * dDealSize; + WriteToCacheState(kvStateGm_, + kvBlockTableGm_, + kvLocal[srcBaseOffset], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + WriteToCacheState(scoreStateGm_, + scoreBlockTableGm_, + scoreLocal[srcBaseOffset], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } + } else { + // 存左边第一块 + if (blockInfo.sIdx == 0) { + SaveLeftFirst(kvLocal, scoreLocal, blockInfo, dStartIdx, dDealSize); + } + + // 存左边最后一块 + if (blockInfo.tailHolderSeqCnt > 0) { + // 左边为本batch数据 + uint32_t copySeqCnt = constInfo_.cmpRatio; + if (blockInfo.validSeqCnt - + (constInfo_.cmpRatio - blockInfo.tailHolderSeqCnt) < + copySeqCnt) { + copySeqCnt = blockInfo.validSeqCnt - + (constInfo_.cmpRatio - blockInfo.tailHolderSeqCnt); + } + uint64_t endSeqIdx = blockInfo.bStartPos + blockInfo.sIdx + + blockInfo.validSeqCnt - + (constInfo_.cmpRatio - blockInfo.tailHolderSeqCnt); + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = + (blockInfo.headHolderSeqCnt + blockInfo.validSeqCnt + + blockInfo.tailHolderSeqCnt - copySeqCnt) * + coff * dDealSize; + WriteToCacheState(kvStateGm_, + kvBlockTableGm_, + kvLocal[srcBaseOffset], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + WriteToCacheState(scoreStateGm_, + scoreBlockTableGm_, + scoreLocal[srcBaseOffset], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } + } else { + if (blockInfo.tailHolderSeqCnt > 0) { // 仅尾块不满时需要存到state上 + uint32_t copySeqCnt = constInfo_.cmpRatio - blockInfo.tailHolderSeqCnt; + if (copySeqCnt > blockInfo.validSeqCnt) { + copySeqCnt = blockInfo.validSeqCnt; + } + uint64_t srcBaseOffset = + (blockInfo.headHolderSeqCnt + blockInfo.validSeqCnt - copySeqCnt) * + dDealSize; + uint64_t endSeqIdx = + blockInfo.bStartPos + blockInfo.sIdx + blockInfo.validSeqCnt; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + WriteToCacheState(kvStateGm_, + kvBlockTableGm_, + kvLocal[srcBaseOffset], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + WriteToCacheState(scoreStateGm_, + scoreBlockTableGm_, + scoreLocal[srcBaseOffset], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } +} + +template +__aicore__ inline void CompressorBlockVector::ReadState( + const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const BlockInfo& blockInfo, + uint32_t dStartIdx, + uint32_t dDealSize) { + // 没有需要压缩的块时, 不需要读state的信息 + if (blockInfo.compressTcSize == 0) { + return; + } + + if (COMP::coff == XllmKernelCompressor::COFF::OVERLAP) { + float SOFTMAX_MIN_NUM = static_cast(-1.0 / 0.0); + // 填充右边 + if (blockInfo.headHolderSeqCnt > 0) { + // 整个batch的第一块 + uint32_t copySeqCnt = blockInfo.bStartPos % constInfo_.cmpRatio; + uint64_t endSeqIdx = blockInfo.bStartPos; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = 0; + ReadFromCacheState(kvLocal[dDealSize], + kvStateGm_, + kvBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx + constInfo_.headDim, + dDealSize); + ReadFromCacheState(scoreLocal[dDealSize], + scoreStateGm_, + scoreBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx + constInfo_.headDim, + dDealSize); + } + + // 填充左边 + if (blockInfo.compressTcSize == 1) { + if (blockInfo.sIdx == 0) { + // 右边为整个batch的第一块 + if (blockInfo.bStartPos < constInfo_.cmpRatio) { + // 无历史数据 + // dDealSize必须为64 + Duplicate(kvLocal, + FLOAT_ZERO, + dDealSize, + constInfo_.cmpRatio, + 1, + 2 * dDealSize / 8); + Duplicate(scoreLocal, + SOFTMAX_MIN_NUM, + dDealSize, + constInfo_.cmpRatio, + 1, + 2 * dDealSize / 8); + } else { + // 存在前一个压缩组, 左侧数据全部在state中 + uint32_t copySeqCnt = constInfo_.cmpRatio; + uint64_t endSeqIdx = + blockInfo.bStartPos / constInfo_.cmpRatio * constInfo_.cmpRatio; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = 0; + ReadFromCacheState(kvLocal, + kvStateGm_, + kvBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + ReadFromCacheState(scoreLocal, + scoreStateGm_, + scoreBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } else if (blockInfo.sIdx == + (constInfo_.cmpRatio - + (blockInfo.bStartPos % constInfo_.cmpRatio))) { + // 右边为本次需要压缩的第二个压缩组 + if ((blockInfo.bStartPos % constInfo_.cmpRatio) > 0) { + uint32_t copySeqCnt = blockInfo.bStartPos % constInfo_.cmpRatio; + uint64_t endSeqIdx = blockInfo.bStartPos; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = 0; + ReadFromCacheState(kvLocal, + kvStateGm_, + kvBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + ReadFromCacheState(scoreLocal, + scoreStateGm_, + scoreBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } + } else { + if (blockInfo.sIdx == 0) { + if (blockInfo.bStartPos < constInfo_.cmpRatio) { + // 无历史数据 + // dDealSize必须为64 + Duplicate(kvLocal, + FLOAT_ZERO, + dDealSize, + constInfo_.cmpRatio, + 1, + 2 * dDealSize / 8); + Duplicate(scoreLocal, + SOFTMAX_MIN_NUM, + dDealSize, + constInfo_.cmpRatio, + 1, + 2 * dDealSize / 8); + } else { + uint32_t copySeqCnt = + constInfo_.cmpRatio + blockInfo.bStartPos % constInfo_.cmpRatio; + uint64_t endSeqIdx = blockInfo.bStartPos; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = 0; + ReadFromCacheState(kvLocal, + kvStateGm_, + kvBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + ReadFromCacheState(scoreLocal, + scoreStateGm_, + scoreBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } + } + } else { + // 需要压缩时, 首块如果头部有占位行, 必然需要从state拷贝数据 + if (blockInfo.headHolderSeqCnt > 0) { + // 整个batch的第一块 + uint32_t copySeqCnt = blockInfo.bStartPos % constInfo_.cmpRatio; + uint64_t endSeqIdx = blockInfo.bStartPos; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = 0; + ReadFromCacheState(kvLocal, + kvStateGm_, + kvBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + ReadFromCacheState(scoreLocal, + scoreStateGm_, + scoreBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } +} + +template +__aicore__ inline void CompressorBlockVector::UpdateState( + LocalTensor kvLocal, + LocalTensor scoreLocal, + uint32_t startTcIdx, + const BlockInfo& blockInfo, + uint32_t dStartIdx, + uint32_t dDealSize) { + event_t eventId_V_MTE3 = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_MTE3)); + event_t eventId_MTE3_MTE2 = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE3_MTE2)); + event_t eventId_MTE3_V = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE3_V)); + event_t eventId_MTE2_V = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + + SetFlag(eventId_V_MTE3); + WaitFlag(eventId_V_MTE3); + SaveState(kvLocal, scoreLocal, blockInfo, dStartIdx, dDealSize); + SetFlag(eventId_MTE3_MTE2); + SetFlag(eventId_MTE3_V); + WaitFlag(eventId_MTE3_MTE2); + WaitFlag(eventId_MTE3_V); + ReadState(kvLocal, scoreLocal, blockInfo, dStartIdx, dDealSize); + SetFlag(eventId_MTE2_V); + WaitFlag(eventId_MTE2_V); +} + +template +__aicore__ inline void CompressorBlockVector::SoftmaxDN( + LocalTensor& scoreLocal, + LocalTensor& tmpUb, + uint32_t tcDealSize, + uint32_t dDealSize) { + float minValue = -2e38; + uint32_t ReduceSize = COMP::coff == COFF::OVERLAP ? 2 * constInfo_.cmpRatio + : constInfo_.cmpRatio; + uint32_t rCnt = ReduceSize * dDealSize; + for (uint32_t r = 0; r < tcDealSize; r++) { + ColumnSoftMax(scoreLocal[r * rCnt], + scoreLocal[r * rCnt], + tmpUb[r * rCnt], + ReduceSize, + dDealSize); + } +} + +template +__aicore__ inline void CompressorBlockVector::KvMulReduceScore( + LocalTensor& kvLocal, + LocalTensor& scoreLocal, + LocalTensor& dstLocal, + LocalTensor& tmpUb, + uint32_t tcDealSize, + uint32_t dDealSize) { + uint32_t ReduceSize = COMP::coff == COFF::OVERLAP ? 2 * constInfo_.cmpRatio + : constInfo_.cmpRatio; + uint32_t rCnt = ReduceSize * dDealSize; + Mul(kvLocal, kvLocal, scoreLocal, tcDealSize * rCnt); + PipeBarrier(); + for (uint32_t r = 0; r < tcDealSize; r++) { + ColumnSum(dstLocal[r * dDealSize], + kvLocal[r * rCnt], + tmpUb[r * rCnt], + ReduceSize, + dDealSize); + } +} + +template +__aicore__ inline void CompressorBlockVector::CopyOutVec1Res( + const RunInfo& info, + LocalTensor comporessedUb, + uint32_t compressTcSize, + uint32_t dStartIdx, + uint32_t dDealSize) { + uint64_t outGmOffset = + info.vec1ResOffset + compressedCnt_ * constInfo_.headDim + dStartIdx; + DataCopyParams copyParams; + copyParams.blockCount = compressTcSize; + copyParams.blockLen = dDealSize / (32 / sizeof(T)); + copyParams.dstStride = (constInfo_.headDim - dDealSize) / (32 / sizeof(T)); + copyParams.srcStride = 0; + DataCopy(vec1ResGm_[outGmOffset], comporessedUb, copyParams); +} + +template +__aicore__ inline void CompressorBlockVector::UpdateBlockInfo( + BlockInfo& blockInfo) { + if (!blockInfo.isFirst) { + blockInfo.sIdx += blockInfo.validSeqCnt; + if (blockInfo.sIdx == blockInfo.bSeqUsed) { + blockInfo.sIdx = 0; + do { + if (blockInfo.bIdx > constInfo_.batchSize) { + break; + } + blockInfo.bIdx++; + blockInfo.bSeqUsed = GetSeqUsed(blockInfo.bIdx); + blockInfo.bStartPos = GetStartPos(blockInfo.bIdx); + } while (blockInfo.bSeqUsed == 0); + } + if (blockInfo.dealSeqSize == 0) { + return; + } + } else { + if (blockInfo.dealSeqSize == 0) { + return; + } + blockInfo.bSeqUsed = GetSeqUsed(blockInfo.bIdx); + // 如果S=0,跳B + while (blockInfo.bSeqUsed == 0) { + if (blockInfo.bIdx > constInfo_.batchSize) { + break; + } + blockInfo.bIdx++; + blockInfo.bSeqUsed = GetSeqUsed(blockInfo.bIdx); + } + blockInfo.bStartPos = GetStartPos(blockInfo.bIdx); + blockInfo.isFirst = false; + } + + // 计算头部占位行数、有效数据行数、尾部占位行数 + blockInfo.headHolderSeqCnt = + (blockInfo.bStartPos + blockInfo.sIdx) % constInfo_.cmpRatio; + blockInfo.validSeqCnt = blockInfo.bSeqUsed - blockInfo.sIdx; + if (blockInfo.headHolderSeqCnt + blockInfo.validSeqCnt > + blockInfo.dealSeqSize) { + blockInfo.validSeqCnt = blockInfo.dealSeqSize - blockInfo.headHolderSeqCnt; + } + blockInfo.tailHolderSeqCnt = + constInfo_.cmpRatio - + (blockInfo.bStartPos + blockInfo.sIdx + blockInfo.validSeqCnt) % + constInfo_.cmpRatio; + if (blockInfo.tailHolderSeqCnt == constInfo_.cmpRatio) { + blockInfo.tailHolderSeqCnt = 0; + } + + // 计算本次可以处理的Tc个数 + blockInfo.dealTcSize = (blockInfo.headHolderSeqCnt + blockInfo.validSeqCnt + + blockInfo.tailHolderSeqCnt) / + constInfo_.cmpRatio; + + // 因为是一个batch的数据, 只有最后一个压缩块才可能不需要压缩, + // 此时blockInfo.tailHolderSeqCnt > 0 + blockInfo.compressTcSize = blockInfo.dealTcSize; + if (blockInfo.tailHolderSeqCnt > 0) { + blockInfo.compressTcSize = + blockInfo.dealTcSize - 1; // 最后一个压缩块不满时,其不需要压缩 + } + + // 更新剩余未处理的行数 + blockInfo.dealSeqSize -= blockInfo.headHolderSeqCnt + blockInfo.validSeqCnt + + blockInfo.tailHolderSeqCnt; +} + +template +__aicore__ inline void CompressorBlockVector::DealVec1BaseBlock( + const RunInfo& info, + BlockInfo& blockInfo, + uint32_t startTcIdx, + uint32_t dStartIdx, + uint32_t dDealSize) { + while (blockInfo.dealSeqSize > 0) { + UpdateBlockInfo(blockInfo); + LocalTensor scoreUb = inputQue1.AllocTensor(); + OverLapScore( + scoreUb, info, startTcIdx, blockInfo.dealTcSize, dStartIdx, dDealSize); + inputQue1.EnQue(scoreUb); + inputQue1.DeQue(); + PipeBarrier(); + LocalTensor scoreLocal = tmpBuff1.Get(); + DataCopy(scoreLocal, + scoreUb, + blockInfo.dealTcSize * (uint32_t)COMP::coff * constInfo_.cmpRatio * + dDealSize); + inputQue1.FreeTensor(scoreUb); + + LocalTensor apeUb = inputQue1.AllocTensor(); + CopyInApe(apeUb, dStartIdx, dDealSize); + inputQue1.EnQue(apeUb); + inputQue1.DeQue(); + PipeBarrier(); + AddApeToScore(scoreLocal, apeUb, blockInfo.dealTcSize, dDealSize); + inputQue1.FreeTensor(apeUb); + + LocalTensor kvUb = inputQue1.AllocTensor(); + OverLapKv( + kvUb, info, startTcIdx, blockInfo.dealTcSize, dStartIdx, dDealSize); + inputQue1.EnQue(kvUb); + inputQue1.DeQue(); + PipeBarrier(); + LocalTensor kvLocal = tmpBuff2.Get(); + DataCopy(kvLocal, + kvUb, + blockInfo.dealTcSize * (uint32_t)COMP::coff * constInfo_.cmpRatio * + dDealSize); + inputQue1.FreeTensor(kvUb); + + UpdateState( + kvLocal, scoreLocal, startTcIdx, blockInfo, dStartIdx, dDealSize); + + if (blockInfo.compressTcSize > 0) { + LocalTensor tmpUb = kvLocal[BUFFER_SIZE_BYTE_32K / sizeof(T)]; + PipeBarrier(); + SoftmaxDN(scoreLocal, tmpUb, blockInfo.compressTcSize, dDealSize); + + LocalTensor comporessedUb = outputQue1.AllocTensor(); + PipeBarrier(); + KvMulReduceScore(kvLocal, + scoreLocal, + comporessedUb, + tmpUb, + blockInfo.compressTcSize, + dDealSize); + + outputQue1.EnQue(comporessedUb); + outputQue1.DeQue(); + CopyOutVec1Res( + info, comporessedUb, blockInfo.compressTcSize, dStartIdx, dDealSize); + outputQue1.FreeTensor(comporessedUb); + } + + compressedCnt_ += blockInfo.compressTcSize; + startTcIdx += blockInfo.dealTcSize; + } +} + +template +__aicore__ inline void CompressorBlockVector::ComputeVec1( + const RunInfo& info) { + // 计算当前VecCore的任务量 + uint32_t dealTcStartIdx = 0; + uint32_t dealTcSize = 128 / constInfo_.cmpRatio; + if (dealTcSize > info.dealTcNum) { + dealTcSize = info.dealTcNum; + } + if (GetBlockIdx() % 2 == 1) { + dealTcStartIdx = dealTcSize; + dealTcSize = info.dealTcNum - dealTcSize; + } + if (dealTcSize == 0) { + return; + } + + // 刷新当前VecCore的起始bIdx和sIdx + uint32_t curBStart = info.bStart; + uint32_t curSStart = info.sStart; + uint32_t curCompressedCnt = 0; + if (GetBlockIdx() % 2 == 1) { + BlockInfo blockInfo(info.bStart, info.sStart, 0); + blockInfo.dealSeqSize = dealTcStartIdx * constInfo_.cmpRatio; + while (blockInfo.dealSeqSize > 0) { + UpdateBlockInfo(blockInfo); + curCompressedCnt += blockInfo.compressTcSize; + } + // 因为需要获取本次完成后的bIdx和sIdx, 所以这里再调用一次 + UpdateBlockInfo(blockInfo); + curBStart = blockInfo.bIdx; + curSStart = blockInfo.sIdx; + } + + // 计算headDim和Tc方向切分大小 + constexpr uint32_t BASE_BLOCK_ELEMENT_NUM = BUFFER_SIZE_BYTE_32K / sizeof(T); + uint32_t maxDealColNum = + BASE_BLOCK_ELEMENT_NUM / (constInfo_.cmpRatio * (uint32_t)COMP::coff); + + uint32_t tcSplitSize = 0; + uint32_t dSplitSize = 0; + uint32_t dLoopCount = 0; + if (maxDealColNum < constInfo_.dBaseSize) { + tcSplitSize = 1; + dLoopCount = (constInfo_.dBaseSize + maxDealColNum - 1) / maxDealColNum; + dSplitSize = constInfo_.dBaseSize / dLoopCount; + } else { + dSplitSize = constInfo_.dBaseSize; + dLoopCount = 1; + tcSplitSize = maxDealColNum / constInfo_.dBaseSize; + } + + // 切块循环 + for (uint32_t dLoopIdx = 0; dLoopIdx < dLoopCount; dLoopIdx++) { + BlockInfo blockInfo(curBStart, curSStart, 0); + uint32_t actDealTcSize = tcSplitSize; + compressedCnt_ = curCompressedCnt; + for (uint32_t tcIdx = 0; tcIdx < dealTcSize; tcIdx += tcSplitSize) { + if (tcIdx + tcSplitSize > dealTcSize) { + actDealTcSize = dealTcSize - tcIdx; + } + // 处理单个切块 + blockInfo.dealSeqSize = actDealTcSize * constInfo_.cmpRatio; + DealVec1BaseBlock( + info, blockInfo, tcIdx, dLoopIdx * dSplitSize, dSplitSize); + } + } +} + +template +__aicore__ inline void CompressorBlockVector::ComputeVec2( + const XllmKernelCompressor::RunInfo& info) { + SplitCoreV2(info); + uint32_t vec2DealM = v2TcEndIdx - v2TcStartIdx; + uint32_t loopCount = (vec2DealM + v2MBaseSize - 1) / v2MBaseSize; + for (uint32_t v2LoopIdx = 0, dealSize = v2MBaseSize; v2LoopIdx < loopCount; + ++v2LoopIdx) { + if (v2LoopIdx == loopCount - 1) { + dealSize = vec2DealM - v2LoopIdx * v2MBaseSize; + } + DealVec2BaseBlock(info, v2TcStartIdx + v2LoopIdx * v2MBaseSize, dealSize); + } + v2TcStartIdx = 0; + v2TcEndIdx = 0; +} + +template +__aicore__ inline void CompressorBlockVector::DealVec2BaseBlock( + const XllmKernelCompressor::RunInfo& info, + uint32_t startRow, + uint32_t dealRowCount) { + uint32_t computeSize = dealRowCount * constInfo_.headDim; + int64_t inGmOffset = startRow * constInfo_.headDim; + // CopyIn + LocalTensor vec1ResUb = inputQue1.AllocTensor(); + DataCopy(vec1ResUb, vec2InputGm_[inGmOffset], computeSize); + inputQue1.EnQue(vec1ResUb); + inputQue1.DeQue(); + + // RmsNorm + LocalTensor normResUb = tmpBuff1.Get(); + LocalTensor tempLocal = tmpBuff2.Get(); + PipeBarrier(); + MultRowRmsNorm( + normResUb, vec1ResUb, normWeightUb, tempLocal, info, dealRowCount); + inputQue1.FreeTensor(vec1ResUb); + + // rope: 只对后RD进行rope; 将normResUb每行前headDim - + // ropeHeadDim个元素cast到X_T,然后再与rope后的结果组合存到outputUb + LocalTensor outputUb = outputQue1.AllocTensor(); + PipeBarrier(); + CalRope(info, outputUb, normResUb, startRow - v2TcStartIdx, dealRowCount); + PipeBarrier(); + // CopyOut + outputQue1.EnQue(outputUb); + outputQue1.DeQue(); + CopyFinalResultOut(info, outputUb, startRow - v2TcStartIdx, dealRowCount); + outputQue1.FreeTensor(outputUb); +} + +template +__aicore__ inline void CompressorBlockVector::MultRowRmsNorm( + LocalTensor& normResUb, + LocalTensor& vec1ResUb, + LocalTensor& normWeightUb, + LocalTensor& tempLocal, + const XllmKernelCompressor::RunInfo& info, + uint32_t dealRowCount) { + RmsNormParam rmsNormParams = {constInfo_.reciprocalD, + constInfo_.normEps, + dealRowCount, + constInfo_.headDim}; + RmsNorm(normResUb, vec1ResUb, normWeightUb, tempLocal, rmsNormParams); +} + +template +__aicore__ inline void CompressorBlockVector::CalRope( + const XllmKernelCompressor::RunInfo& info, + LocalTensor& outputUb, + LocalTensor& normResUb, + uint32_t startRow, + uint32_t dealRowCount) { + uint32_t bStartIdx = OutputBStartIdx; + uint32_t sStartIdx = OutputSStartIdx; + uint64_t globalScStart = 0; + CalcGlobalScStart(0, 0, bStartIdx, sStartIdx, globalScStart); + uint32_t totalSize = dealRowCount * constInfo_.headDim; + uint32_t dealScSize = dealRowCount; + uint32_t curDealScSize = 0; + + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + curDealScSize = dealRowCount; + uint32_t computeSize = curDealScSize * constInfo_.ropeHeadDim; + uint64_t SinCosOffset = globalScStart * constInfo_.ropeHeadDim; + // sin与cos各占一半, 实际分别最多只会用8K,总占用16K + LocalTensor cosUb = inputQue1.AllocTensor(); + LocalTensor sinUb = cosUb[BUFFER_SIZE_BYTE_8K / sizeof(X_T)]; + DataCopy(cosUb, ropeCosGm_[SinCosOffset], computeSize); + DataCopy(sinUb, ropeSinGm_[SinCosOffset], computeSize); + inputQue1.EnQue(sinUb); + inputQue1.DeQue(); + + LocalTensor ropeCosFp32Local = tmpBuff2.Get(); + LocalTensor ropeSinFp32Local = + ropeCosFp32Local[BUFFER_SIZE_BYTE_16K / sizeof(T)] + .template ReinterpretCast(); + LocalTensor tempLocal = + ropeSinFp32Local[BUFFER_SIZE_BYTE_16K / sizeof(T)] + .template ReinterpretCast(); + PipeBarrier(); + Cast(ropeCosFp32Local, cosUb, RoundMode::CAST_NONE, computeSize); + Cast(ropeSinFp32Local, sinUb, RoundMode::CAST_NONE, computeSize); + PipeBarrier(); + inputQue1.FreeTensor(sinUb); + RotaryPosEmb(normResUb, + normResUb, + ropeCosFp32Local, + ropeSinFp32Local, + tempLocal, + gatherOffsetCastUb, + curDealScSize, + constInfo_.ropeHeadDim, + constInfo_.headDim, + constInfo_.headDim - constInfo_.ropeHeadDim); + PipeBarrier(); + while (dealScSize > 0) { + UpdateOutputIdx(bStartIdx, sStartIdx, dealScSize, curDealScSize); + } + } else { + // 处理BSH有效数据在内存上不连续 (可能存在pad) + uint32_t ubProcessedCount = 0; + uint32_t preOutputBStartIdx = 0; + uint32_t preOutputSStartIdx = 0; + while (dealScSize > 0) { + // 逐batch计算写出索引 + preOutputBStartIdx = bStartIdx; + preOutputSStartIdx = sStartIdx; + UpdateOutputIdx(bStartIdx, sStartIdx, dealScSize, curDealScSize); + if (curDealScSize) { + uint32_t computeSize = curDealScSize * constInfo_.ropeHeadDim; + uint64_t SinCosOffset = globalScStart * constInfo_.ropeHeadDim; + // sin与cos各占一半, 实际分别最多只会用8K,总占用16K + LocalTensor cosUb = inputQue1.AllocTensor(); + LocalTensor sinUb = cosUb[BUFFER_SIZE_BYTE_8K / sizeof(X_T)]; + DataCopy(cosUb, ropeCosGm_[SinCosOffset], computeSize); + DataCopy(sinUb, ropeSinGm_[SinCosOffset], computeSize); + inputQue1.EnQue(sinUb); + inputQue1.DeQue(); + + LocalTensor ropeCosFp32Local = tmpBuff2.Get(); + LocalTensor ropeSinFp32Local = + ropeCosFp32Local[BUFFER_SIZE_BYTE_16K / sizeof(T)] + .template ReinterpretCast(); + LocalTensor tempLocal = + ropeSinFp32Local[BUFFER_SIZE_BYTE_16K / sizeof(T)] + .template ReinterpretCast(); + + PipeBarrier(); + Cast(ropeCosFp32Local, cosUb, RoundMode::CAST_NONE, computeSize); + Cast(ropeSinFp32Local, sinUb, RoundMode::CAST_NONE, computeSize); + PipeBarrier(); + inputQue1.FreeTensor(sinUb); + + RotaryPosEmb( + normResUb[(dealRowCount - dealScSize - curDealScSize) * + constInfo_.headDim], + normResUb[(dealRowCount - dealScSize - curDealScSize) * + constInfo_.headDim], + ropeCosFp32Local, + ropeSinFp32Local, + tempLocal, + gatherOffsetCastUb, + curDealScSize, + constInfo_.ropeHeadDim, + constInfo_.headDim, + constInfo_.headDim - constInfo_.ropeHeadDim); + PipeBarrier(); + } + CalcGlobalScStart(preOutputBStartIdx, + preOutputSStartIdx, + bStartIdx, + sStartIdx, + globalScStart); + ubProcessedCount += curDealScSize; + } + } + Cast(outputUb, normResUb, RoundMode::CAST_RINT, totalSize); + PipeBarrier(); +} + +template +__aicore__ inline void CompressorBlockVector::SplitCoreV2( + const XllmKernelCompressor::RunInfo& info) { + // 累积N个基本块数据后做vec2,N=2,传入的RunInfo包含该组核处理的数据块的bStart、bEnd、sStart、sEnd以及dealTcCount; + // 每组核切M方向将C1/V1后的数据分8 * 2个vec核上进行V2计算 + // 每次进行v2计算都会根据当前情况将workspace中的每组核处理的数据重新分到当前组的vec核 + + // Input: + // syncAll前每组cube核处理的实际数据块在batch及s方向的起止idx及实际数据量(m方向) + // Output: 每个vec核的处理数据块在m方向的起止位置及输出到Gm上的起始位置 + uint32_t coreNum = constInfo_.dBasicBlockNum * 2; // 组中有多少个vec核:16 + usedCoreNum = coreNum; + uint32_t currCoreIdx = GetBlockIdx(); // 当前vec核ID + uint32_t curVecCoreGroupIdx = currCoreIdx / coreNum; // 当前vec核所在组ID + vec1ResGmStart = curVecCoreGroupIdx * constInfo_.nSize * + constInfo_.tcBaseSize * constInfo_.headDim; + // 1.计算总vec2基本块数量 + uint64_t totalBaseNum = info.dealScSize; // 当前组核累积的实际数据量 + // 2.每个vec核上分到的数据量 + uint32_t avgBaseNum = 1; + if (totalBaseNum > coreNum) { + avgBaseNum = (totalBaseNum + coreNum - 1) / coreNum; + } else { + usedCoreNum = totalBaseNum; + } + if (currCoreIdx % coreNum >= usedCoreNum) { + return; + } + // 3.计算每个vec核的起始结束位置 + uint32_t accumBaseNum = 0; // 当前累积的基本块数 + uint32_t targetBaseNum = (currCoreIdx % coreNum + 1) * + avgBaseNum; // 当前vec核目标要达到的基本块数量 + uint32_t targetStartBaseNum = + targetBaseNum - avgBaseNum; // 分当前vec核时前面已经完成分核的基本块数量 + bool setStart = false; + for (uint32_t i = 0; i < totalBaseNum; ++i) { + if (accumBaseNum >= totalBaseNum) { + return; + } + accumBaseNum += 1; + if (!setStart && (accumBaseNum > targetStartBaseNum)) { + v2TcStartIdx = i; + setStart = true; + } + if (setStart && + (accumBaseNum >= targetBaseNum || i == (totalBaseNum - 1))) { + // 更新当前核的End分核信息 + v2TcEndIdx = i + 1; + GetScIdxInfo(info.bStart, + info.scStart, + info.dealScSize, + v2TcStartIdx, + v2TcEndIdx, + OutputBStartIdx, + OutputSStartIdx, + OutputSize); + return; + } + } +} + +template +__aicore__ inline void CompressorBlockVector::CalcGlobalScStart( + uint32_t bStart, + uint32_t scStart, + uint32_t bEnd, + uint32_t scEnd, + uint64_t& globalScStart) { + for (uint32_t bIdx = bStart; bIdx < bEnd; ++bIdx) { + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + curActSeqLength_ = GetSeqLength(bIdx); + curStartPos_ = GetStartPos(bIdx); + globalScStart += GetScSize(); + } else { + curActSeqLength_ = constInfo_.sSize; + curStartPos_ = GetStartPos(bIdx); + globalScStart += + (curActSeqLength_ + constInfo_.cmpRatio - 1) / constInfo_.cmpRatio; + } + } + globalScStart -= scStart; + globalScStart += scEnd; +} + +template +__aicore__ inline void CompressorBlockVector::UpdateOutputIdx( + uint32_t& outputBStart, + uint32_t& outputSStart, + uint32_t& dealScSize, + uint32_t& curDealScSize) { + curActSeqLength_ = GetSeqLength(outputBStart); + curStartPos_ = GetStartPos(outputBStart); + uint32_t curBatchScSize = + (curStartPos_ + curActSeqLength_) / constInfo_.cmpRatio - + curStartPos_ / constInfo_.cmpRatio; + uint32_t curBatchRemainScSize = curBatchScSize - outputSStart; + curDealScSize = + curBatchRemainScSize > dealScSize ? dealScSize : curBatchRemainScSize; + dealScSize -= curDealScSize; + outputSStart += curDealScSize; + if (outputSStart == curBatchScSize) { + outputBStart++; + outputSStart = 0; + } +} + +template +__aicore__ inline void CompressorBlockVector::CopyFinalResultOut( + const XllmKernelCompressor::RunInfo& info, + const LocalTensor& cmpKvOutUb, + uint32_t startRow, + uint32_t dealRowCount) { + uint64_t globalScStart = 0; + CalcGlobalScStart(0, 0, OutputBStartIdx, OutputSStartIdx, globalScStart); + uint64_t outOffset = globalScStart * constInfo_.headDim; + uint32_t copySize = dealRowCount * constInfo_.headDim; + + uint32_t dealScSize = dealRowCount; + uint32_t curDealScSize = 0; + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + DataCopy(cmpKvOutGm_[outOffset], cmpKvOutUb, copySize); + while (dealScSize > 0) { + UpdateOutputIdx( + OutputBStartIdx, OutputSStartIdx, dealScSize, curDealScSize); + } + } else { + // 处理BSH有效数据在内存上不连续(可能存在pad) + uint32_t ubProcessedCount = 0; + uint32_t preOutputBStartIdx = 0; + uint32_t preOutputSStartIdx = 0; + while (dealScSize > 0) { + // 逐batch计算写出索引 + preOutputBStartIdx = OutputBStartIdx; + preOutputSStartIdx = OutputSStartIdx; + UpdateOutputIdx( + OutputBStartIdx, OutputSStartIdx, dealScSize, curDealScSize); + DataCopy(cmpKvOutGm_[globalScStart * constInfo_.headDim], + cmpKvOutUb[ubProcessedCount * constInfo_.headDim], + curDealScSize * constInfo_.headDim); + CalcGlobalScStart(preOutputBStartIdx, + preOutputSStartIdx, + OutputBStartIdx, + OutputSStartIdx, + globalScStart); + ubProcessedCount += curDealScSize; + } + } +} +} // namespace XllmKernelCompressor +#endif // COMPRESSOR_BLOCK_VECTOR_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_block_vec_perf.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_block_vec_perf.h new file mode 100644 index 0000000000..c35aaf5b28 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_block_vec_perf.h @@ -0,0 +1,1976 @@ +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved. + * This file is a part of the CANN Open Software. + * Licensed under CANN Open Software License Agreement Version 1.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 compressor_block_vec_perf.h + * \brief + */ + +#ifndef COMPRESSOR_BLOCK_VEC_PERF_H +#define COMPRESSOR_BLOCK_VEC_PERF_H + +#include "arch32.h" +#include "compressor/op_kernel/compressor_comm.h" +#include "compressor/op_kernel/compressor_tools.h" + +using namespace AscendC; + +namespace XllmKernelCompressor { +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +template +class CompressorBlockVectorPerf { + public: + static constexpr bool X_DTYPE = COMP::xDtype == X_DTYPE::BF16; + static constexpr uint64_t BLOCK_VEC_BASE_BUFFER_SIZE = 32 * 1024; // 32k + static constexpr uint32_t DATABLOCK_BYTES = 32; + static constexpr float FLOAT_ZERO = 0; + // =================================类型定义区================================= + // 中间计算数据类型为float,高精度模式 + using T = float; + using X_T = typename AscendC::Conditional::type; + + __aicore__ inline CompressorBlockVectorPerf(){}; + // =================================设置参数================================= + __aicore__ inline void InitParams(const ConstInfo& constInfo, + const CompressorTools& tools); + __aicore__ inline void Init(__gm__ uint8_t* x, + __gm__ uint8_t* wKv, + __gm__ uint8_t* wGate, + __gm__ uint8_t* kvState, + __gm__ uint8_t* scoreState, + __gm__ uint8_t* ape, + __gm__ uint8_t* normWeight, + __gm__ uint8_t* ropeSin, + __gm__ uint8_t* ropeCos, + __gm__ uint8_t* kvBlockTable, + __gm__ uint8_t* scoreBlockTable, + __gm__ uint8_t* cuSeqlens, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* startPos, + __gm__ uint8_t* cmpKvOut); + // =================================资源管理================================= + __aicore__ inline void InitBuffers(TPipe* pipe); + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + // =================================执行计算================================= + __aicore__ inline void ComputeVec1(const XllmKernelCompressor::RunInfo& info); + __aicore__ inline uint32_t GetBasicNum(); + __aicore__ inline uint32_t GetScSize(); + __aicore__ inline void GetScIdxInfo(uint32_t bStart, + uint32_t scStart, + uint32_t dealScSize, + uint32_t v2TcStart, + uint32_t v2TcEnd, + uint32_t& outputBStart, + uint32_t& outputSStart, + uint32_t& outputScSize); + __aicore__ inline void CalcScEndIdx(uint32_t bStart, + uint32_t scStart, + uint32_t dealScSize, + uint32_t& bEnd, + uint32_t& scEnd); + __aicore__ inline void InitVec1GlobalTensor(GlobalTensor preMm1ResGm, + GlobalTensor curMm1ResGm, + GlobalTensor vec1ResGm, + GlobalTensor vec2InputGm); + __aicore__ inline void ComputeVec2( + const XllmKernelCompressor::Vec2RunInfo& info); + __aicore__ inline void WriteToCacheState( + const GlobalTensor& state, + const GlobalTensor& blockTableGm, + const LocalTensor& input, + uint32_t batchIdx, + uint32_t startSeqIdx, + uint32_t endSeqIdx, + uint32_t dStart, + uint32_t dDealSize); + __aicore__ inline void ReadFromCacheState( + const LocalTensor& output, + const GlobalTensor& state, + const GlobalTensor& blockTableGm, + uint32_t batchIdx, + uint32_t startSeqIdx, + uint32_t endSeqIdx, + uint32_t dStart, + uint32_t dDealSize); + + protected: + GlobalTensor vec1ResGm_; + GlobalTensor vec2InputGm_; + GlobalTensor preMm1ResGm_; + GlobalTensor curMm1ResGm_; + + private: + __aicore__ inline uint32_t GetSeqUsed(uint32_t bIdx); + __aicore__ inline uint32_t GetStartPos(uint32_t bIdx); + __aicore__ inline uint32_t GetSeqLength(uint32_t bIdx); + __aicore__ inline uint32_t GetBsLength(uint32_t index); + __aicore__ inline void CalcGlobalScStart(uint32_t bStart, + uint32_t scStart, + uint32_t bEnd, + uint32_t scEnd, + uint64_t& globalScStart); + __aicore__ inline void UpdateOutputIdx(uint32_t& outputBStart, + uint32_t& outputSStart, + uint32_t& dealScSize, + uint32_t& curDealScSize); + __aicore__ inline void DealVec1BaseBlock( + const RunInfo& info, + CompressorVec1SliceIterator& sliceIterstor, + uint32_t dStartIdx, + uint32_t dDealSize); + // __aicore__ inline void UpdateBlockInfo(VecBlockInfo &blockInfo); + __aicore__ inline void CopyInApe(const LocalTensor& apeUb, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void AddApeToScore(const LocalTensor& scoreLocal, + const LocalTensor& apeUb, + uint32_t tcDealSize, + uint32_t dDealSize); + __aicore__ inline void DataCopyAlignUbToUb(const LocalTensor dstLocal, + const LocalTensor srcLocal, + uint32_t copyRowCount, + uint32_t copyColCount, + uint32_t srcSingleRowCount, + uint32_t dstSingleRowCount); + __aicore__ inline void DataCopyAlignGmToUb(const LocalTensor dstLocal, + const GlobalTensor srcGm, + uint32_t copyRowCount, + uint32_t copyColCount, + uint32_t srcSingleRowCount, + uint32_t dstSingleRowCount); + __aicore__ inline void OverLap(const LocalTensor dstLocal, + const LocalTensor srcLocal, + const Vec1SliceInfo& sliceInfo, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void FromWokrSpaceToUb(const LocalTensor dstLocal, + const Vec1SliceInfo& sliceInfo, + const SeqCntInfo& seqCntInfo, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void UpdateState(const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const Vec1SliceInfo& sliceInfo, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void SoftmaxDN(const LocalTensor& scoreLocal, + const LocalTensor& tmpUb, + uint32_t tcDealSize, + uint32_t dDealSize); + __aicore__ inline void KvMulReduceScore(const LocalTensor& kvLocal, + const LocalTensor& scoreLocal, + const LocalTensor& dstLocal, + const LocalTensor& tmpUb, + uint32_t tcDealSize, + uint32_t dDealSize); + __aicore__ inline void CopyOutVec1Res(const RunInfo& info, + const LocalTensor comporessedUb, + uint32_t compressTcSize, + uint32_t dStartIdx, + uint32_t dDealSize); + + __aicore__ inline void SplitCoreV2( + const XllmKernelCompressor::Vec2RunInfo& info); + __aicore__ inline void CopyFinalResultOut( + const XllmKernelCompressor::Vec2RunInfo& info, + const LocalTensor& cmpKvOutUb, + uint32_t startRow, + uint32_t dealRowCount); + __aicore__ inline void DealVec2BaseBlock( + const XllmKernelCompressor::Vec2RunInfo& info, + uint32_t startRow, + uint32_t dealRowCount); + __aicore__ inline void MultRowRmsNorm( + const LocalTensor& normResUb, + const LocalTensor& vec1ResUb, + const LocalTensor& normWeightUb, + const LocalTensor& tempLocal, + const XllmKernelCompressor::Vec2RunInfo& info, + uint32_t dealRowCount); + __aicore__ inline void CalRope(const XllmKernelCompressor::Vec2RunInfo& info, + const LocalTensor& outputUb, + const LocalTensor& normResUb, + uint32_t startRow, + uint32_t dealRowCount); + __aicore__ inline void SaveLeftFirst(const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const Vec1SliceInfo& sliceInfo, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void SaveState(const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const Vec1SliceInfo& sliceInfo, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void ReadState(const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const Vec1SliceInfo& sliceInfo, + uint32_t dStartIdx, + uint32_t dDealSize); + // static constexpr uint64_t SYNC_INPUT_BUF1_FLAG = 2; + // static constexpr uint64_t SYNC_INPUT_BUF1_PONG_FLAG = 3; + uint32_t cmpRatio_ = 0U; + uint32_t coff_ = 0U; + uint32_t curStartPos_ = 0; + uint32_t curActSeqLength_ = 0; + uint32_t compressedCnt_ = 0; + uint32_t v1SplitSize_ = 0; + uint32_t v1ScLoopTimes_ = 0; + uint32_t v1DLoopTimes_ = 0; + uint32_t dealTcNum_ = 0; + bool apeIsLoad_ = false; + bool isExistSeqUsed = false; + bool isExistStartPos = false; + // vec2 + uint32_t v2MBaseSize = 16; // Tc块数量:32 * 1024 / (512 * 4) + uint32_t v2TcStartIdx = 0U; + uint32_t v2TcEndIdx = 0U; + uint32_t mmResColSize_ = 128; + int64_t vec1ResGmStart = 0U; + uint32_t usedCoreNum = 16; + uint32_t OutputBStartIdx, OutputSStartIdx, OutputSize; + uint32_t mmResBaseOffset_ = 0; + CompressorTools tools_; + ConstInfo constInfo_ = {}; + MSplitInfo mSplitInfo = {}; + GlobalTensor startPosGm_; + GlobalTensor cuSeqlensGm_; + GlobalTensor sequsedGm_; + GlobalTensor kvBlockTableGm_; + GlobalTensor scoreBlockTableGm_; + GlobalTensor kvStateGm_; + GlobalTensor scoreStateGm_; + GlobalTensor apeGm_; + GlobalTensor normWeightGm_; + GlobalTensor ropeSinGm_; + GlobalTensor ropeCosGm_; + GlobalTensor cmpKvOutGm_; + + // ================================Local + // Buffer区==================================== TBuf + // mm1ResUb; + LocalTensor mm1ResTensor; + LocalTensor leftStateTensor; + LocalTensor rightStateTensor; + LocalTensor normWeightUb; + LocalTensor apeUb; + LocalTensor gatherOffsetCastUb; + // 临时tbuf + TBuf tmpBuff1; + TBuf tmpBuff2; + TBuf gatherOffsetBuf; + TBuf apeBuf; + // in queue + TQue inputQue1; + TQue inputQue2; + TBuf normWeightBuf; + // out queue + TQue outputQue1; +}; + +template +__aicore__ inline void CompressorBlockVectorPerf::InitParams( + const ConstInfo& constInfo, + const CompressorTools& tools) { + this->constInfo_ = constInfo; + this->tools_ = tools; + // constexpr uint64_t ROPE_BUFFER_IN_QUE_SIZE = BUFFER_SIZE_BYTE_2K; + // uint32_t v2MMax = ROPE_BUFFER_IN_QUE_SIZE / (constInfo_.ropeHeadDim * + // sizeof(X_T)); + v2MBaseSize = + BLOCK_VEC_BASE_BUFFER_SIZE / (constInfo_.headDim * sizeof(float)); + // if (v2MBaseSize > v2MMax) { + // v2MBaseSize = v2MMax; + // } +} + +template +__aicore__ inline void CompressorBlockVectorPerf::Init( + __gm__ uint8_t* x, + __gm__ uint8_t* wKv, + __gm__ uint8_t* wGate, + __gm__ uint8_t* kvState, + __gm__ uint8_t* scoreState, + __gm__ uint8_t* ape, + __gm__ uint8_t* normWeight, + __gm__ uint8_t* ropeSin, + __gm__ uint8_t* ropeCos, + __gm__ uint8_t* kvBlockTable, + __gm__ uint8_t* scoreBlockTable, + __gm__ uint8_t* cuSeqlens, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* startPos, + __gm__ uint8_t* cmpKvOut) { + kvBlockTableGm_.SetGlobalBuffer((__gm__ int32_t*)kvBlockTable); + scoreBlockTableGm_.SetGlobalBuffer((__gm__ int32_t*)scoreBlockTable); + kvStateGm_.SetGlobalBuffer((__gm__ T*)kvState); + scoreStateGm_.SetGlobalBuffer((__gm__ T*)scoreState); + apeGm_.SetGlobalBuffer((__gm__ T*)ape); + normWeightGm_.SetGlobalBuffer((__gm__ X_T*)normWeight); + ropeSinGm_.SetGlobalBuffer((__gm__ X_T*)ropeSin); + ropeCosGm_.SetGlobalBuffer((__gm__ X_T*)ropeCos); + cmpKvOutGm_.SetGlobalBuffer((__gm__ X_T*)cmpKvOut); + isExistSeqUsed = (seqUsed != nullptr); + isExistStartPos = (startPos != nullptr); + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + cuSeqlensGm_.SetGlobalBuffer((__gm__ int32_t*)cuSeqlens); + } + if (isExistSeqUsed) { + sequsedGm_.SetGlobalBuffer((__gm__ int32_t*)seqUsed); + } + if (isExistStartPos) { + startPosGm_.SetGlobalBuffer((__gm__ int32_t*)startPos); + } +} + +template +__aicore__ inline void CompressorBlockVectorPerf::InitBuffers( + TPipe* pipe) { + pipe->InitBuffer(inputQue1, 1, BUFFER_SIZE_BYTE_32K); + pipe->InitBuffer(tmpBuff1, BUFFER_SIZE_BYTE_32K); + pipe->InitBuffer(tmpBuff2, BUFFER_SIZE_BYTE_64K); + pipe->InitBuffer(outputQue1, 1, BUFFER_SIZE_BYTE_16K); + pipe->InitBuffer(inputQue2, 1, BUFFER_SIZE_BYTE_2K); + pipe->InitBuffer(normWeightBuf, BUFFER_SIZE_BYTE_4K); + pipe->InitBuffer(gatherOffsetBuf, BUFFER_SIZE_BYTE_2K); + pipe->InitBuffer(apeBuf, BUFFER_SIZE_BYTE_32K); + normWeightUb = normWeightBuf.Get(); + apeUb = apeBuf.Get(); + LocalTensor normweightInUb = inputQue2.AllocTensor(); + LocalTensor gatherOffsetUb = gatherOffsetBuf.Get(); + DataCopy(normweightInUb, + normWeightGm_, + constInfo_.headDim); // 获取normWeight,常驻 + inputQue2.EnQue(normweightInUb); + inputQue2.DeQue(); + Cast(normWeightUb, normweightInUb, RoundMode::CAST_NONE, constInfo_.headDim); + inputQue2.FreeTensor(normweightInUb); + if constexpr (COMP::rotaryMode == + XllmKernelCompressor::ROTARY_MODE::INTERLEAVE) { + SetGatherSrcOffset(gatherOffsetUb, constInfo_.headDim); + } + gatherOffsetCastUb = gatherOffsetUb.ReinterpretCast(); + PipeBarrier(); +} + +template +__aicore__ inline void CompressorBlockVectorPerf::AllocEventID() { + // SetFlag(SYNC_INPUT_BUF1_FLAG); + // SetFlag(SYNC_INPUT_BUF1_PONG_FLAG); +} + +template +__aicore__ inline void CompressorBlockVectorPerf::FreeEventID() { + // WaitFlag(SYNC_INPUT_BUF1_FLAG); + // WaitFlag(SYNC_INPUT_BUF1_PONG_FLAG); +} + +template +__aicore__ inline void CompressorBlockVectorPerf::InitVec1GlobalTensor( + GlobalTensor preMm1ResGm, + GlobalTensor curMm1ResGm, + GlobalTensor vec1ResGm, + GlobalTensor vec2InputGm) { + // this->preMm1KvResGm_ = preMm1KVResGm; + // this->curMm1KvResGm_ = curMm1KvResGm; + // this->preMm1ScoreResGm_ = preMm1ScoreResGm; + // this->curMm1ScoreResGm_ = curMm1ScoreResGm; + this->preMm1ResGm_ = preMm1ResGm; + this->curMm1ResGm_ = curMm1ResGm; + this->vec1ResGm_ = vec1ResGm; + this->vec2InputGm_ = vec2InputGm; +} + +template +__aicore__ inline uint32_t CompressorBlockVectorPerf::GetSeqUsed( + uint32_t bIdx) { + if (isExistSeqUsed) { + return (uint32_t)sequsedGm_.GetValue(bIdx); + } else { + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + return (uint32_t)(cuSeqlensGm_.GetValue(bIdx + 1) - + cuSeqlensGm_.GetValue(bIdx)); + } else { + return constInfo_.sSize; + } + } +} + +template +__aicore__ inline uint32_t CompressorBlockVectorPerf::GetStartPos( + uint32_t bIdx) { + if (isExistStartPos) { + return startPosGm_.GetValue(bIdx); + } + return 0; +} + +// TODO 使用这种方式获取seq的约束为顺序访问,随机访问不可用 +template +__aicore__ inline uint32_t CompressorBlockVectorPerf::GetSeqLength( + uint32_t bIdx) { + if (isExistSeqUsed) { + return sequsedGm_.GetValue(bIdx); + } else if (COMP::xLayout == X_LAYOUT::TH) { + return cuSeqlensGm_.GetValue(bIdx + 1) - cuSeqlensGm_.GetValue(bIdx); + } else { + return constInfo_.sSize; + } +} + +template +__aicore__ inline uint32_t CompressorBlockVectorPerf::GetBsLength( + uint32_t index) { + if (COMP::xLayout == X_LAYOUT::TH) { + return cuSeqlensGm_.GetValue(index); + } else { + return index * constInfo_.sSize; + } +} + +template +__aicore__ inline uint32_t CompressorBlockVectorPerf::GetBasicNum() { + // 获取 m方向上对应基本单元Tc的个数 + uint32_t curBasicNum = 0; + uint32_t headSize = 0; + if (curStartPos_ % constInfo_.cmpRatio != 0) { + headSize = constInfo_.cmpRatio - curStartPos_ % constInfo_.cmpRatio; + headSize = headSize > curActSeqLength_ ? curActSeqLength_ : headSize; + curBasicNum++; + } + // 加上中间整块及尾块 + curBasicNum += (curActSeqLength_ - headSize + constInfo_.cmpRatio - 1) / + constInfo_.cmpRatio; + return curBasicNum; +} + +template +__aicore__ inline uint32_t CompressorBlockVectorPerf::GetScSize() { + uint32_t curBasicNum = + (curStartPos_ + curActSeqLength_) / constInfo_.cmpRatio - + curStartPos_ / constInfo_.cmpRatio; + return curBasicNum; +} + +// 根据计算Tc开始结束索引 +template +__aicore__ inline void CompressorBlockVectorPerf::CalcScEndIdx( + uint32_t bStart, + uint32_t scStart, + uint32_t dealScSize, + uint32_t& bEnd, + uint32_t& scEnd) { + uint32_t accScSize = 0; + for (int bIdx = bStart; bIdx < constInfo_.batchSize; ++bIdx) { + bEnd = bIdx; + // 计算起始batch的剩余块 + if (bIdx == bStart) { + curActSeqLength_ = GetSeqLength(bIdx); + curStartPos_ = GetStartPos(bIdx); + accScSize += GetScSize() - scStart; + // printf("[GetEndIdx] bIdx:%u accScSize:%u dealScSize:%u headSize:%u + // curStartPos_:%u curActSeqLength_:%u \n", bIdx, accScSize, dealScSize, + // headSize, curStartPos_, curActSeqLength_); + if (accScSize >= dealScSize) { + scEnd = scStart + dealScSize; + return; + } + } else { + curActSeqLength_ = GetSeqLength(bIdx); + curStartPos_ = GetStartPos(bIdx); + uint32_t curBasicNum = GetScSize(); + uint32_t curBasicNumEnd = dealScSize - accScSize; + + // printf("[GetEndIdx] accScSize:%u curBasicNum:%u dealScSize:%u\n", + // accScSize, curBasicNum, dealScSize); + if (accScSize + curBasicNum >= dealScSize) { + scEnd = curBasicNumEnd; + return; + } + accScSize += curBasicNum; + } + } +} + +// 根据sc的开始索引计算vec输出时的b、sc的索引 +template +__aicore__ inline void CompressorBlockVectorPerf::GetScIdxInfo( + uint32_t bStart, + uint32_t scStart, + uint32_t dealScSize, + uint32_t v2TcStart, + uint32_t v2TcEnd, + uint32_t& outputBStart, + uint32_t& outputSStart, + uint32_t& outputScSize) { + outputScSize = v2TcEnd - v2TcStart; + uint32_t scEnd = 0; + uint32_t bEnd = 0; + CalcScEndIdx(bStart, scStart, v2TcStart, bEnd, scEnd); + outputSStart = scEnd; + outputBStart = bEnd; + // 处理跳batch + curActSeqLength_ = GetSeqLength(bEnd); + curStartPos_ = GetStartPos(bEnd); + uint32_t curScSize = GetScSize(); + if (curScSize == scEnd) { + outputSStart = 0; + outputBStart++; + } +} + +template +__aicore__ inline void CompressorBlockVectorPerf::CopyInApe( + const LocalTensor& apeUb, + uint32_t dStartIdx, + uint32_t dDealSize) { + LocalTensor apeUbTmp = inputQue1.AllocTensor(); + + uint32_t copyRowCount = constInfo_.cmpRatio; + uint32_t copyColCount = dDealSize; + uint32_t dstSingleRowCount = ((uint32_t)COMP::coff) * dDealSize; + uint32_t srcSingleRowCount = ((uint32_t)COMP::coff) * constInfo_.headDim; + + uint32_t gmOffset = (constInfo_.aiCoreIdx % constInfo_.dBasicBlockNum) * + constInfo_.dBaseSize + + dStartIdx; + uint32_t dstUbOffset = 0; + if constexpr (COMP::coff == COFF::OVERLAP) { + DataCopyAlignGmToUb(apeUbTmp[dstUbOffset], + apeGm_[gmOffset], + copyRowCount, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); + + gmOffset += constInfo_.headDim; + dstUbOffset += dDealSize; + } + DataCopyAlignGmToUb(apeUbTmp[dstUbOffset], + apeGm_[gmOffset], + copyRowCount, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); + inputQue1.EnQue(apeUbTmp); + inputQue1.DeQue(); + DataCopy(apeUb, + apeUbTmp, + ((uint32_t)COMP::coff) * dDealSize * constInfo_.cmpRatio); + inputQue1.FreeTensor(apeUbTmp); +} + +template +__aicore__ inline void CompressorBlockVectorPerf::AddApeToScore( + const LocalTensor& scoreLocal, + const LocalTensor& apeUb, + uint32_t tcDealSize, + uint32_t dDealSize) { + uint32_t ReduceSize = COMP::coff == COFF::OVERLAP ? 2 * constInfo_.cmpRatio + : constInfo_.cmpRatio; + uint32_t rCnt = ReduceSize * dDealSize; + for (uint32_t r = 0; r < tcDealSize; r++) { + Add(scoreLocal[r * rCnt], scoreLocal[r * rCnt], apeUb, rCnt); + } +} + +template +__aicore__ inline void CompressorBlockVectorPerf::DataCopyAlignUbToUb( + const LocalTensor dstLocal, + const LocalTensor srcLocal, + uint32_t copyRowCount, + uint32_t copyColCount, + uint32_t srcSingleRowCount, + uint32_t dstSingleRowCount) { + if (copyRowCount == 0) { + return; + } + DataCopyParams intriParams; + intriParams.blockCount = copyRowCount; + intriParams.blockLen = copyColCount / (32 / sizeof(T)); + intriParams.dstStride = (dstSingleRowCount - copyColCount) / (32 / sizeof(T)); + intriParams.srcStride = (srcSingleRowCount - copyColCount) / (32 / sizeof(T)); + DataCopy(dstLocal, srcLocal, intriParams); +} + +template +__aicore__ inline void CompressorBlockVectorPerf::DataCopyAlignGmToUb( + const LocalTensor dstLocal, + const GlobalTensor srcGm, + uint32_t copyRowCount, + uint32_t copyColCount, + uint32_t srcSingleRowCount, + uint32_t dstSingleRowCount) { + if (copyRowCount == 0) { + return; + } + DataCopyParams intriParams; + intriParams.blockCount = copyRowCount; + intriParams.blockLen = copyColCount / (32 / sizeof(T)); + intriParams.dstStride = (dstSingleRowCount - copyColCount) / (32 / sizeof(T)); + intriParams.srcStride = (srcSingleRowCount - copyColCount) / (32 / sizeof(T)); + DataCopy(dstLocal, srcGm, intriParams); +} + +template +__aicore__ inline void CompressorBlockVectorPerf::OverLap( + const LocalTensor dstLocal, + const LocalTensor srcLocal, + const Vec1SliceInfo& sliceInfo, + uint32_t dStartIdx, + uint32_t dDealSize) { + // Ub data layout after overlap when r = 4 and coff = 2: + // Tc0_seq01: |--- --D_L--- -|------D_R-----| + // Tc0_seq02: |--- --D_L--- -|------D_R-----| + // Tc0_seq03: |--- --D_L--- -|------D_R-----| + // Tc0_seq04: |--- --D_L--- -|------D_R-----| + // Tc1_seq01: |--- --D_L--- -|------D_R-----| + // Tc1_seq02: |--- --D_L--- -|------D_R-----| + // Tc1_seq03: |--- --D_L--- -|------D_R-----| + // Tc1_seq04: |--- --D_L--- -|------D_R-----| + uint32_t srcSingleRowElemNum = dDealSize; // 2: kv和score各一份 + uint32_t copyRowCount = sliceInfo.dealTcSize * constInfo_.cmpRatio - + sliceInfo.headHolderSeqCnt - + sliceInfo.tailHolderSeqCnt; + uint32_t copyColCount = dDealSize; + uint32_t srcSingleRowCount = srcSingleRowElemNum; + uint32_t dstSingleRowCount = + ((uint32_t)COMP::coff) * dDealSize; // left和right在seq方向是交错存储的 + uint32_t srcLocalOffset = sliceInfo.dealedSeqCnt * srcSingleRowElemNum; + + uint32_t dstUbOffset = + sliceInfo.dealedTcCnt * constInfo_.cmpRatio * dstSingleRowCount; + if constexpr (COMP::coff == COFF::OVERLAP) { + // 左侧首块 + uint32_t preSrcLocalOffset = + sliceInfo.preDealedSeqCnt * srcSingleRowElemNum; + uint32_t preDstUbOffset = (sliceInfo.dealedTcCnt * constInfo_.cmpRatio + + sliceInfo.preHeadHolderSeqCnt) * + dstSingleRowCount; + DataCopyAlignUbToUb(dstLocal[preDstUbOffset], + srcLocal[preSrcLocalOffset], + sliceInfo.preValidSeqCnt, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); + + // 左侧剩余块 + preSrcLocalOffset += sliceInfo.preValidSeqCnt * srcSingleRowElemNum; + preDstUbOffset += + (sliceInfo.preValidSeqCnt + sliceInfo.preTailHolderSeqCnt + + sliceInfo.headHolderSeqCnt) * + dstSingleRowCount; + DataCopyAlignUbToUb(dstLocal[preDstUbOffset], + srcLocal[preSrcLocalOffset], + copyRowCount - sliceInfo.lastTcSeqCnt, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); + dstUbOffset += dDealSize; + srcLocalOffset += BUFFER_SIZE_BYTE_16K / sizeof(T); + } + dstUbOffset += sliceInfo.headHolderSeqCnt * dstSingleRowCount; + DataCopyAlignUbToUb(dstLocal[dstUbOffset], + srcLocal[srcLocalOffset], + copyRowCount, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); +} + +// template +// __aicore__ inline void +// CompressorBlockVectorPerf::OverLap(LocalTensor dstLocal, +// const Vec1SliceInfo &sliceInfo, uint32_t dStartIdx, uint32_t dDealSize) +// { +// // Ub data layout after overlap when r = 4 and coff = 2: +// // Tc0_seq01: |--- --D_L--- -|------D_R-----| +// // Tc0_seq02: |--- --D_L--- -|------D_R-----| +// // Tc0_seq03: |--- --D_L--- -|------D_R-----| +// // Tc0_seq04: |--- --D_L--- -|------D_R-----| +// // Tc1_seq01: |--- --D_L--- -|------D_R-----| +// // Tc1_seq02: |--- --D_L--- -|------D_R-----| +// // Tc1_seq03: |--- --D_L--- -|------D_R-----| +// // Tc1_seq04: |--- --D_L--- -|------D_R-----| +// uint32_t srcSingleRowElemNum = constInfo_.dBaseSize * 2; // 2: +// kv和score各一份 uint32_t copyRowCount = sliceInfo.dealTcSize * +// constInfo_.cmpRatio - sliceInfo.headHolderSeqCnt - +// sliceInfo.tailHolderSeqCnt; uint32_t copyColCount = dDealSize; uint32_t +// srcSingleRowCount = srcSingleRowElemNum; uint32_t dstSingleRowCount = +// ((uint32_t)COMP::coff) * dDealSize; // left和right在seq方向是交错存储的 +// uint32_t srcGmOffset = sliceInfo.dealedSeqCnt * srcSingleRowElemNum + +// dStartIdx; + +// uint32_t dstUbOffset = 0; +// if constexpr (COMP::coff == COFF::OVERLAP) { +// // 左侧首块 +// uint32_t preSrcGmOffset = sliceInfo.preDealedSeqCnt * +// srcSingleRowElemNum + constInfo_.dBaseSize + dStartIdx; uint32_t +// preDstUbOffset = sliceInfo.preHeadHolderSeqCnt * dstSingleRowCount; +// DataCopyAlignGmToUb(dstLocal[preDstUbOffset], +// preMm1ResGm_[preSrcGmOffset], +// sliceInfo.preValidSeqCnt, copyColCount, srcSingleRowCount, +// dstSingleRowCount); + +// // 左侧剩余块 +// preSrcGmOffset += sliceInfo.preValidSeqCnt * srcSingleRowElemNum; +// preDstUbOffset += (sliceInfo.preValidSeqCnt + +// sliceInfo.preTailHolderSeqCnt + sliceInfo.headHolderSeqCnt) * +// dstSingleRowCount; DataCopyAlignGmToUb(dstLocal[preDstUbOffset], +// preMm1ResGm_[preSrcGmOffset], +// copyRowCount - sliceInfo.lastTcSeqCnt, copyColCount, +// srcSingleRowCount, dstSingleRowCount); +// dstUbOffset += dDealSize; +// } +// dstUbOffset += sliceInfo.headHolderSeqCnt * dstSingleRowCount; +// DataCopyAlignGmToUb(dstLocal[dstUbOffset], curMm1ResGm_[srcGmOffset], +// copyRowCount, copyColCount, srcSingleRowCount, dstSingleRowCount); +// } + +template +__aicore__ inline void CompressorBlockVectorPerf::FromWokrSpaceToUb( + const LocalTensor dstLocal, + const Vec1SliceInfo& sliceInfo, + const SeqCntInfo& seqCntInfo, + uint32_t dStartIdx, + uint32_t dDealSize) { + // Ub data layout after overlap when r = 4 and coff = 2: + // Tc0_seq01: |--- --D_L--- -|------D_R-----| + // Tc0_seq02: |--- --D_L--- -|------D_R-----| + // Tc0_seq03: |--- --D_L--- -|------D_R-----| + // Tc0_seq04: |--- --D_L--- -|------D_R-----| + // Tc1_seq01: |--- --D_L--- -|------D_R-----| + // Tc1_seq02: |--- --D_L--- -|------D_R-----| + // Tc1_seq03: |--- --D_L--- -|------D_R-----| + // Tc1_seq04: |--- --D_L--- -|------D_R-----| + uint32_t srcSingleRowElemNum = + constInfo_.dBaseSize * 2; // 2: kv和score各一份 + uint32_t copyRowCount = sliceInfo.dealTcSize * constInfo_.cmpRatio - + sliceInfo.headHolderSeqCnt - + sliceInfo.tailHolderSeqCnt; + uint32_t copyColCount = dDealSize; + uint32_t srcSingleRowCount = srcSingleRowElemNum; + uint32_t dstSingleRowCount = dDealSize; // left和right在seq方向是交错存储的 + uint32_t srcGmOffset = + sliceInfo.dealedSeqCnt * srcSingleRowElemNum + dStartIdx; + + uint32_t dstUbOffset = 0; + if constexpr (COMP::coff == COFF::OVERLAP) { + uint32_t preSrcGmOffset = + sliceInfo.preDealedSeqCnt * srcSingleRowElemNum + dStartIdx; + DataCopyAlignGmToUb(dstLocal[dstUbOffset], + preMm1ResGm_[preSrcGmOffset], + seqCntInfo.preDealedSeqCnt, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); + dstUbOffset += BUFFER_SIZE_BYTE_16K / sizeof(T); + } + DataCopyAlignGmToUb(dstLocal[dstUbOffset], + curMm1ResGm_[srcGmOffset], + seqCntInfo.dealedSeqCnt, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); +} + +// template +// __aicore__ inline void +// CompressorBlockVectorPerf::FromWokrSpaceToUb(LocalTensor &dstLocal, +// const GlobalTensor &srcGm, +// uint32_t +// dealedSeqCnt, +// uint32_t seqCnt, +// uint32_t +// dDealSize, +// uint32_t +// loopTimes, +// uint32_t +// gmStride) +// { +// uint32_t copyRowCount = loopTimes; +// uint32_t copyColCount = dDealSize * seqCnt; +// uint32_t srcSingleRowCount = gmStride; +// uint32_t dstSingleRowCount = dDealSize; // +// left和right在seq方向是交错存储的 uint32_t srcGmOffset = dealedSeqCnt * +// srcSingleRowCount; + +// DataCopyAlignGmToUb(dstLocal, srcGm[srcGmOffset], +// copyRowCount, copyColCount, srcSingleRowCount, +// dstSingleRowCount); +// } + +template +__aicore__ inline void CompressorBlockVectorPerf::ReadFromCacheState( + const LocalTensor& output, + const GlobalTensor& state, + const GlobalTensor& blockTableGm, + uint32_t batchIdx, + uint32_t startSeqIdx, + uint32_t endSeqIdx, + uint32_t dStart, + uint32_t dDealSize) { + uint32_t coff = static_cast(COMP::coff); + uint64_t blockTablebaseOffset = batchIdx * constInfo_.maxBlockNumPerBatch; + uint32_t curSeqIdx = startSeqIdx; + uint32_t copyFinishRowCnt = 0; + uint32_t seqCnt = endSeqIdx - startSeqIdx; + while (copyFinishRowCnt < seqCnt) { + uint64_t blockIdOffset = curSeqIdx / constInfo_.blockSize; + uint64_t remainRowCnt = curSeqIdx % constInfo_.blockSize; + uint64_t idInBlockTable = + blockTableGm.GetValue(blockTablebaseOffset + blockIdOffset); + uint32_t copyRowCnt = constInfo_.blockSize - remainRowCnt; + if (copyFinishRowCnt + copyRowCnt > seqCnt) { + copyRowCnt = seqCnt - copyFinishRowCnt; + } + // printf("idInBlockTable=%d, remainRowCnt=%d, dBasicBlockNum=%d, + // aiCoreIdx=%d, curSeqIdx=%d, seqCnt=%d, endSeqIdx=%d, startSeqIdx=%d, + // copyFinishRowCnt=%d\n", + // idInBlockTable, remainRowCnt, constInfo_.dBasicBlockNum, + // constInfo_.aiCoreIdx, curSeqIdx, seqCnt, endSeqIdx, startSeqIdx, + // copyFinishRowCnt); + if (idInBlockTable == 0) { + // print error log + } + uint64_t stateOffset = + idInBlockTable * constInfo_.blockSize * coff * constInfo_.headDim + + remainRowCnt * coff * constInfo_.headDim + + (constInfo_.aiCoreIdx % constInfo_.dBasicBlockNum) * + constInfo_.dBaseSize + + dStart; + + DataCopyParams copyParams; + copyParams.blockCount = copyRowCnt; + copyParams.blockLen = dDealSize / (32 / sizeof(T)); + copyParams.dstStride = (coff * dDealSize - dDealSize) / (32 / sizeof(T)); + copyParams.srcStride = + (coff * constInfo_.headDim - dDealSize) / (32 / sizeof(T)); + // printf("stateOffset=%d, copyRowCnt=%d, dDealSize=%d, dstStride=%d, + // srcStride=%d\n", + // stateOffset, copyRowCnt, dDealSize, (coff * constInfo_.headDim - + // dDealSize), (coff * dDealSize - dDealSize)); + DataCopy(output[copyFinishRowCnt * coff * dDealSize], + state[stateOffset], + copyParams); + // AscendC::DumpTensor(state[stateOffset], 120, 64); + // AscendC::DumpTensor(output, 121, 64); + + copyFinishRowCnt += copyRowCnt; + curSeqIdx += copyRowCnt; + } +} + +template +__aicore__ inline void CompressorBlockVectorPerf::WriteToCacheState( + const GlobalTensor& state, + const GlobalTensor& blockTableGm, + const LocalTensor& input, + uint32_t batchIdx, + uint32_t startSeqIdx, + uint32_t endSeqIdx, + uint32_t dStart, + uint32_t dDealSize) { + uint32_t coff = static_cast(COMP::coff); + uint64_t blockTablebaseOffset = batchIdx * constInfo_.maxBlockNumPerBatch; + uint32_t curSeqIdx = startSeqIdx; + uint32_t copyFinishRowCnt = 0; + uint32_t seqCnt = endSeqIdx - startSeqIdx; + while (copyFinishRowCnt < seqCnt) { + uint64_t blockIdOffset = curSeqIdx / constInfo_.blockSize; + uint64_t remainRowCnt = curSeqIdx % constInfo_.blockSize; + uint64_t idInBlockTable = + blockTableGm.GetValue(blockTablebaseOffset + blockIdOffset); + uint32_t copyRowCnt = constInfo_.blockSize - remainRowCnt; + if (copyFinishRowCnt + copyRowCnt > seqCnt) { + copyRowCnt = seqCnt - copyFinishRowCnt; + } + // printf("idInBlockTable=%d, remainRowCnt=%d, dBasicBlockNum=%d, + // aiCoreIdx=%d, curSeqIdx=%d, seqCnt=%d, endSeqIdx=%d, startSeqIdx=%d, + // copyFinishRowCnt=%d\n", + // idInBlockTable, remainRowCnt, constInfo_.dBasicBlockNum, + // constInfo_.aiCoreIdx, curSeqIdx, seqCnt, endSeqIdx, startSeqIdx, + // copyFinishRowCnt); + + if (idInBlockTable != 0) { // 32 + uint64_t stateOffset = + idInBlockTable * constInfo_.blockSize * coff * constInfo_.headDim + + remainRowCnt * coff * constInfo_.headDim + + (constInfo_.aiCoreIdx % constInfo_.dBasicBlockNum) * + constInfo_.dBaseSize + + dStart; + + DataCopyParams copyParams; + copyParams.blockCount = copyRowCnt; + copyParams.blockLen = dDealSize / (32 / sizeof(T)); + copyParams.dstStride = + (coff * constInfo_.headDim - dDealSize) / (32 / sizeof(T)); + copyParams.srcStride = (coff * dDealSize - dDealSize) / (32 / sizeof(T)); + // printf("stateOffset=%d, copyRowCnt=%d, dDealSize=%d, dstStride=%d, + // srcStride=%d\n", + // stateOffset, copyRowCnt, dDealSize, (coff * constInfo_.headDim - + // dDealSize), (coff * dDealSize - dDealSize)); + DataCopy(state[stateOffset], + input[copyFinishRowCnt * coff * dDealSize], + copyParams); + // AscendC::DumpTensor(state[stateOffset], 110, 64); + } + + copyFinishRowCnt += copyRowCnt; + curSeqIdx += copyRowCnt; + } +} + +template +__aicore__ inline void CompressorBlockVectorPerf::SaveLeftFirst( + const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const Vec1SliceInfo& sliceInfo, + uint32_t dStartIdx, + uint32_t dDealSize) { + uint32_t coff = static_cast(COMP::coff); + uint32_t preBIdx = sliceInfo.preBIdx; + // 左边为上一个batch或者最后一个batch的数据 + // if (blockInfo.bIdx == 0) { + // // 左边为最后一个batch的数据 + // preBIdx = constInfo_.batchSize - 1; + // } else { + // //左边为上一个batch数据 + // preBIdx = blockInfo.bIdx - 1; + // } + + uint32_t bSeqUsed = GetSeqUsed(preBIdx); + uint32_t bStartPos = GetStartPos(preBIdx); + + uint32_t endIdxInBlock = (bStartPos + bSeqUsed) % constInfo_.cmpRatio; + if (endIdxInBlock == 0) { + endIdxInBlock = constInfo_.cmpRatio; + } + + uint32_t copySeqCnt = (endIdxInBlock > bSeqUsed) ? bSeqUsed : endIdxInBlock; + uint64_t endSeqIdx = bStartPos + bSeqUsed; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = (endIdxInBlock - copySeqCnt) * coff * dDealSize; + // printf("--SaveLeftFirst-----srcBaseOffset=%d, endIdxInBlock=%d, + // copySeqCnt=%d\n", srcBaseOffset, endIdxInBlock, copySeqCnt); + WriteToCacheState(kvStateGm_, + kvBlockTableGm_, + kvLocal[srcBaseOffset], + preBIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + WriteToCacheState(scoreStateGm_, + scoreBlockTableGm_, + scoreLocal[srcBaseOffset], + preBIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); +} + +template +__aicore__ inline void CompressorBlockVectorPerf::SaveState( + const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const Vec1SliceInfo& sliceInfo, + uint32_t dStartIdx, + uint32_t dDealSize) { + if constexpr (COMP::coff == COFF::OVERLAP) { + uint32_t coff = static_cast(COMP::coff); + // 存右边 + if (sliceInfo.sIdx + sliceInfo.validSeqCnt == sliceInfo.bSeqUsed) { + uint32_t copySeqCnt = constInfo_.cmpRatio - sliceInfo.tailHolderSeqCnt; + if (sliceInfo.validSeqCnt < copySeqCnt) { + copySeqCnt = sliceInfo.validSeqCnt; + } else { + if (sliceInfo.tailHolderSeqCnt > 0) { + if (sliceInfo.validSeqCnt - copySeqCnt > constInfo_.cmpRatio) { + copySeqCnt += constInfo_.cmpRatio; + } else { + copySeqCnt += sliceInfo.validSeqCnt - copySeqCnt; + } + } + } + uint64_t endSeqIdx = + sliceInfo.bStartPos + sliceInfo.sIdx + sliceInfo.validSeqCnt; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = + (sliceInfo.headHolderSeqCnt + sliceInfo.validSeqCnt - copySeqCnt) * + coff * dDealSize; + // printf("headHolderSeqCnt=%d, validSeqCnt=%d, copySeqCnt=%d, + // tailHolderSeqCnt=%d\n", sliceInfo.headHolderSeqCnt, + // sliceInfo.validSeqCnt, copySeqCnt, sliceInfo.tailHolderSeqCnt); + // printf("--srcStride=%d--\n", (srcBaseOffset + dDealSize)); + WriteToCacheState(kvStateGm_, + kvBlockTableGm_, + kvLocal[srcBaseOffset + dDealSize], + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx + constInfo_.headDim, + dDealSize); + WriteToCacheState(scoreStateGm_, + scoreBlockTableGm_, + scoreLocal[srcBaseOffset + dDealSize], + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx + constInfo_.headDim, + dDealSize); + } else if (sliceInfo.sIdx + sliceInfo.validSeqCnt + constInfo_.cmpRatio > + sliceInfo.bSeqUsed) { + uint32_t copySeqCnt = constInfo_.cmpRatio; + if (copySeqCnt > sliceInfo.validSeqCnt) { + copySeqCnt = sliceInfo.validSeqCnt; + } + uint64_t endSeqIdx = + sliceInfo.bStartPos + sliceInfo.sIdx + sliceInfo.validSeqCnt; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = + (sliceInfo.headHolderSeqCnt + sliceInfo.validSeqCnt - copySeqCnt) * + coff * dDealSize; + WriteToCacheState(kvStateGm_, + kvBlockTableGm_, + kvLocal[srcBaseOffset + dDealSize], + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx + constInfo_.headDim, + dDealSize); + WriteToCacheState(scoreStateGm_, + scoreBlockTableGm_, + scoreLocal[srcBaseOffset + dDealSize], + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx + constInfo_.headDim, + dDealSize); + } + + // 存左边 + if (sliceInfo.dealTcSize == 1) { + // 左边尾块和首块是同一块 + if (sliceInfo.sIdx == 0) { + SaveLeftFirst(kvLocal, scoreLocal, sliceInfo, dStartIdx, dDealSize); + } else { + if (sliceInfo.tailHolderSeqCnt > 0) { + // 左边为本batch数据 + uint32_t copySeqCnt = constInfo_.cmpRatio; + if (sliceInfo.sIdx < copySeqCnt) { + copySeqCnt = sliceInfo.sIdx; + } + uint64_t endSeqIdx = + sliceInfo.bStartPos + sliceInfo.sIdx + sliceInfo.validSeqCnt - + (constInfo_.cmpRatio - sliceInfo.tailHolderSeqCnt); + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = + (sliceInfo.headHolderSeqCnt + sliceInfo.validSeqCnt + + sliceInfo.tailHolderSeqCnt - copySeqCnt) * + coff * dDealSize; + WriteToCacheState(kvStateGm_, + kvBlockTableGm_, + kvLocal[srcBaseOffset], + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + WriteToCacheState(scoreStateGm_, + scoreBlockTableGm_, + scoreLocal[srcBaseOffset], + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } + } else { + // 存左边第一块 + if (sliceInfo.sIdx == 0) { + SaveLeftFirst(kvLocal, scoreLocal, sliceInfo, dStartIdx, dDealSize); + } + + // 存左边最后一块 + if (sliceInfo.tailHolderSeqCnt > 0) { + // 左边为本batch数据 + uint32_t copySeqCnt = constInfo_.cmpRatio; + if (sliceInfo.validSeqCnt - + (constInfo_.cmpRatio - sliceInfo.tailHolderSeqCnt) < + copySeqCnt) { + copySeqCnt = sliceInfo.validSeqCnt - + (constInfo_.cmpRatio - sliceInfo.tailHolderSeqCnt); + } + uint64_t endSeqIdx = sliceInfo.bStartPos + sliceInfo.sIdx + + sliceInfo.validSeqCnt - + (constInfo_.cmpRatio - sliceInfo.tailHolderSeqCnt); + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = + (sliceInfo.headHolderSeqCnt + sliceInfo.validSeqCnt + + sliceInfo.tailHolderSeqCnt - copySeqCnt) * + coff * dDealSize; + WriteToCacheState(kvStateGm_, + kvBlockTableGm_, + kvLocal[srcBaseOffset], + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + WriteToCacheState(scoreStateGm_, + scoreBlockTableGm_, + scoreLocal[srcBaseOffset], + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } + } else { + if (sliceInfo.tailHolderSeqCnt > 0) { // 仅尾块不满时需要存到state上 + uint32_t copySeqCnt = constInfo_.cmpRatio - sliceInfo.tailHolderSeqCnt; + if (copySeqCnt > sliceInfo.validSeqCnt) { + copySeqCnt = sliceInfo.validSeqCnt; + } + uint64_t srcBaseOffset = + (sliceInfo.headHolderSeqCnt + sliceInfo.validSeqCnt - copySeqCnt) * + dDealSize; + uint64_t endSeqIdx = + sliceInfo.bStartPos + sliceInfo.sIdx + sliceInfo.validSeqCnt; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + WriteToCacheState(kvStateGm_, + kvBlockTableGm_, + kvLocal[srcBaseOffset], + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + WriteToCacheState(scoreStateGm_, + scoreBlockTableGm_, + scoreLocal[srcBaseOffset], + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } +} + +template +__aicore__ inline void CompressorBlockVectorPerf::ReadState( + const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const Vec1SliceInfo& sliceInfo, + uint32_t dStartIdx, + uint32_t dDealSize) { + // 没有需要压缩的块时, 不需要读state的信息 + if (sliceInfo.compressTcSize == 0) { + return; + } + + if constexpr (COMP::coff == XllmKernelCompressor::COFF::OVERLAP) { + float SOFTMAX_MIN_NUM = (float)(-1.0 / 0.0); + // 填充右边 + if (sliceInfo.headHolderSeqCnt > 0) { + // 整个batch的第一块 + uint32_t copySeqCnt = sliceInfo.bStartPos % constInfo_.cmpRatio; + uint64_t endSeqIdx = sliceInfo.bStartPos; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = 0; + // printf("--headHolderSeqCnt=%d, validSeqCnt=%d, copySeqCnt=%d, + // tailHolderSeqCnt=%d\n", sliceInfo.headHolderSeqCnt, + // sliceInfo.validSeqCnt, copySeqCnt, sliceInfo.tailHolderSeqCnt); + ReadFromCacheState(kvLocal[dDealSize], + kvStateGm_, + kvBlockTableGm_, + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx + constInfo_.headDim, + dDealSize); + ReadFromCacheState(scoreLocal[dDealSize], + scoreStateGm_, + scoreBlockTableGm_, + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx + constInfo_.headDim, + dDealSize); + } + + // 填充左边 + if (sliceInfo.compressTcSize == 1) { + if (sliceInfo.sIdx == 0) { + // 右边为整个batch的第一块 + if (sliceInfo.bStartPos < constInfo_.cmpRatio) { + // 无历史数据 + // dDealSize必须为64 + Duplicate(kvLocal, + FLOAT_ZERO, + dDealSize, + constInfo_.cmpRatio, + 1, + 2 * dDealSize / 8); + Duplicate(scoreLocal, + SOFTMAX_MIN_NUM, + dDealSize, + constInfo_.cmpRatio, + 1, + 2 * dDealSize / 8); + } else { + // 存在前一个压缩组, 左侧数据全部在state中 + uint32_t copySeqCnt = constInfo_.cmpRatio; + uint64_t endSeqIdx = + sliceInfo.bStartPos / constInfo_.cmpRatio * constInfo_.cmpRatio; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = 0; + // printf("-1-headHolderSeqCnt=%d, validSeqCnt=%d, copySeqCnt=%d, + // tailHolderSeqCnt=%d\n", sliceInfo.headHolderSeqCnt, + // sliceInfo.validSeqCnt, copySeqCnt, sliceInfo.tailHolderSeqCnt); + ReadFromCacheState(kvLocal, + kvStateGm_, + kvBlockTableGm_, + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + ReadFromCacheState(scoreLocal, + scoreStateGm_, + scoreBlockTableGm_, + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } else if (sliceInfo.sIdx == + (constInfo_.cmpRatio - + (sliceInfo.bStartPos % constInfo_.cmpRatio))) { + // 右边为本次需要压缩的第二个压缩组 + if ((sliceInfo.bStartPos % constInfo_.cmpRatio) > 0) { + uint32_t copySeqCnt = sliceInfo.bStartPos % constInfo_.cmpRatio; + uint64_t endSeqIdx = sliceInfo.bStartPos; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = 0; + ReadFromCacheState(kvLocal, + kvStateGm_, + kvBlockTableGm_, + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + ReadFromCacheState(scoreLocal, + scoreStateGm_, + scoreBlockTableGm_, + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } + } else { + if (sliceInfo.sIdx == 0) { + if (sliceInfo.bStartPos < constInfo_.cmpRatio) { + // 无历史数据 + // dDealSize必须为64 + Duplicate(kvLocal, + FLOAT_ZERO, + dDealSize, + constInfo_.cmpRatio, + 1, + 2 * dDealSize / 8); + Duplicate(scoreLocal, + SOFTMAX_MIN_NUM, + dDealSize, + constInfo_.cmpRatio, + 1, + 2 * dDealSize / 8); + } else { + uint32_t copySeqCnt = + constInfo_.cmpRatio + sliceInfo.bStartPos % constInfo_.cmpRatio; + uint64_t endSeqIdx = sliceInfo.bStartPos; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = 0; + ReadFromCacheState(kvLocal, + kvStateGm_, + kvBlockTableGm_, + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + ReadFromCacheState(scoreLocal, + scoreStateGm_, + scoreBlockTableGm_, + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } + } + } else { + // 需要压缩时, 首块如果头部有占位行, 必然需要从state拷贝数据 + if (sliceInfo.headHolderSeqCnt > 0) { + // 整个batch的第一块 + uint32_t copySeqCnt = sliceInfo.bStartPos % constInfo_.cmpRatio; + uint64_t endSeqIdx = sliceInfo.bStartPos; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = 0; + // PRINTF("copySeqCnt:%d, bIdx:%d, startSeqIdx:%d, endSeqIdx:%d, + // dStartIdx:%d dDealSize:%d\n", + // copySeqCnt, sliceInfo.bIdx, startSeqIdx, endSeqIdx, dStartIdx, + // dDealSize); + ReadFromCacheState(kvLocal, + kvStateGm_, + kvBlockTableGm_, + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + ReadFromCacheState(scoreLocal, + scoreStateGm_, + scoreBlockTableGm_, + sliceInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } +} + +template +__aicore__ inline void CompressorBlockVectorPerf::UpdateState( + const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const Vec1SliceInfo& sliceInfo, + uint32_t dStartIdx, + uint32_t dDealSize) { + event_t eventId_V_MTE3 = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_MTE3)); + event_t eventId_MTE3_MTE2 = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE3_MTE2)); + event_t eventId_MTE3_V = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE3_V)); + event_t eventId_MTE2_V = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + + SetFlag(eventId_V_MTE3); + WaitFlag(eventId_V_MTE3); + SaveState(kvLocal, scoreLocal, sliceInfo, dStartIdx, dDealSize); + SetFlag(eventId_MTE3_MTE2); + SetFlag(eventId_MTE3_V); + WaitFlag(eventId_MTE3_MTE2); + WaitFlag(eventId_MTE3_V); + ReadState(kvLocal, scoreLocal, sliceInfo, dStartIdx, dDealSize); + SetFlag(eventId_MTE2_V); + WaitFlag(eventId_MTE2_V); +} + +template +__aicore__ inline void CompressorBlockVectorPerf::SoftmaxDN( + const LocalTensor& scoreLocal, + const LocalTensor& tmpUb, + uint32_t tcDealSize, + uint32_t dDealSize) { + float minValue = -2e38; + uint32_t ReduceSize = COMP::coff == COFF::OVERLAP ? 2 * constInfo_.cmpRatio + : constInfo_.cmpRatio; + uint32_t rCnt = ReduceSize * dDealSize; + for (uint32_t r = 0; r < tcDealSize; r++) { + ColumnSoftMax(scoreLocal[r * rCnt], + scoreLocal[r * rCnt], + tmpUb[r * rCnt], + ReduceSize, + dDealSize); + } +} + +template +__aicore__ inline void CompressorBlockVectorPerf::KvMulReduceScore( + const LocalTensor& kvLocal, + const LocalTensor& scoreLocal, + const LocalTensor& dstLocal, + const LocalTensor& tmpUb, + uint32_t tcDealSize, + uint32_t dDealSize) { + uint32_t ReduceSize = COMP::coff == COFF::OVERLAP ? 2 * constInfo_.cmpRatio + : constInfo_.cmpRatio; + uint32_t rCnt = ReduceSize * dDealSize; + Mul(kvLocal, kvLocal, scoreLocal, tcDealSize * rCnt); + PipeBarrier(); + for (uint32_t r = 0; r < tcDealSize; r++) { + ColumnSum(dstLocal[r * dDealSize], + kvLocal[r * rCnt], + tmpUb[r * rCnt], + ReduceSize, + dDealSize); + } +} + +template +__aicore__ inline void CompressorBlockVectorPerf::CopyOutVec1Res( + const RunInfo& info, + const LocalTensor comporessedUb, + uint32_t compressTcSize, + uint32_t dStartIdx, + uint32_t dDealSize) { + uint64_t outGmOffset = + info.vec1ResOffset + compressedCnt_ * constInfo_.headDim + dStartIdx; + // PRINTF("CopyOutVec1Res outGmOffset:%llu, info.vec1ResOffset:%d, + // compressedCnt_:%d, dStartIdx:%d, compressTcSize:%d\n", + // outGmOffset, info.vec1ResOffset, compressedCnt_, dStartIdx, + // compressTcSize); + DataCopyParams copyParams; + copyParams.blockCount = compressTcSize; + copyParams.blockLen = dDealSize / (32 / sizeof(T)); + copyParams.dstStride = (constInfo_.headDim - dDealSize) / (32 / sizeof(T)); + copyParams.srcStride = 0; + DataCopy(vec1ResGm_[outGmOffset], comporessedUb, copyParams); +} + +template +__aicore__ inline void CompressorBlockVectorPerf::DealVec1BaseBlock( + const RunInfo& info, + CompressorVec1SliceIterator& sliceIterstor, + uint32_t dStartIdx, + uint32_t dDealSize) { + // PRINTF("DealVec1BaseBlock Start. blockInfo.dealSeqSize:%d\n", + // blockInfo.dealSeqSize); + Vec1SliceInfo sliceInfo = sliceIterstor.GetSlice(); + CompressorVec1SliceIterator tempSliceIterstor(tools_); + Vec1SliceInfo tempSliceInfo{}; + tempSliceIterstor.SetMaxBatchSize(constInfo_.batchSize); + + tempSliceIterstor.template Reset( + sliceInfo.bIdx, sliceInfo.sIdx, sliceInfo.dealedSeqCnt, 0U); + tempSliceIterstor.SetNeedDealTcSize(sliceIterstor.GetNeedDealTcSize()); + SeqCntInfo seqCntInfo = tempSliceIterstor.FullIteratorSlice(); + + LocalTensor scoreUb = inputQue1.AllocTensor(); + FromWokrSpaceToUb(scoreUb, + sliceInfo, + seqCntInfo, + dStartIdx + constInfo_.dBaseSize, + dDealSize); + // FromWokrSpaceToUb(scoreUb, curMm1ScoreResGm_, sliceInfo.dealedSeqCnt, + // seqCntInfo.curSeqCnt, dDealSize, 1, xx); if constexpr (COMP::coff == + // COFF::OVERLAP) { FromWokrSpaceToUb(scoreUb[BUFFER_SIZE_BYTE_16K / + // sizeof(T)], preMm1ScoreResGm_, sliceInfo.preDealedSeqCnt, + // seqCntInfo.preSeqCnt, dDealSize, 1, xx); + // } + inputQue1.EnQue(scoreUb); + inputQue1.DeQue(); + LocalTensor scoreLocal = tmpBuff1.Get(); + tempSliceIterstor.template Reset( + sliceInfo.bIdx, sliceInfo.sIdx, 0U, 0U); + tempSliceIterstor.SetNeedDealTcSize(sliceIterstor.GetNeedDealTcSize()); + while (!tempSliceIterstor.IsEnd()) { + tempSliceInfo = tempSliceIterstor.GetSlice(); + OverLap(scoreLocal, scoreUb, tempSliceInfo, dStartIdx, dDealSize); + tempSliceIterstor.IteratorSlice(); + } + PipeBarrier(); + inputQue1.FreeTensor(scoreUb); + + LocalTensor kvUb = inputQue1.AllocTensor(); + FromWokrSpaceToUb(kvUb, sliceInfo, seqCntInfo, dStartIdx, dDealSize); + // FromWokrSpaceToUb(kvUb, curMm1KvResGm_, sliceInfo.dealedSeqCnt, + // seqCntInfo.curSeqCnt, dDealSize, 1, xx); if constexpr (COMP::coff == + // COFF::OVERLAP) { + // FromWokrSpaceToUb(kvUb[BUFFER_SIZE_BYTE_16K / sizeof(T)], + // preMm1KvResGm_, sliceInfo.preDealedSeqCnt, seqCntInfo.preSeqCnt, + // dDealSize, 1, xx); + // } + inputQue1.EnQue(kvUb); + inputQue1.DeQue(); + LocalTensor kvLocal = tmpBuff2.Get(); + tempSliceIterstor.template Reset( + sliceInfo.bIdx, sliceInfo.sIdx, 0U, 0U); + tempSliceIterstor.SetNeedDealTcSize(sliceIterstor.GetNeedDealTcSize()); + while (!tempSliceIterstor.IsEnd()) { + tempSliceInfo = tempSliceIterstor.GetSlice(); + OverLap(kvLocal, kvUb, tempSliceInfo, dStartIdx, dDealSize); + tempSliceIterstor.IteratorSlice(); + } + PipeBarrier(); + inputQue1.FreeTensor(kvUb); + + while (!sliceIterstor.IsEnd()) { + sliceInfo = sliceIterstor.GetSlice(); + uint32_t ubOffset = sliceInfo.dealedTcCnt * constInfo_.cmpRatio * + ((uint32_t)COMP::coff) * dDealSize; + // PRINTF("DealVec1BaseBlock bIdx:%d sIdx:%d headHolderSeqCnt:%d + // validSeqCnt:%d tailHolderSeqCnt:%d dealSeqSize:%d compressTcSize:%d\n", + // blockInfo.bIdx, blockInfo.sIdx, blockInfo.headHolderSeqCnt, + // blockInfo.validSeqCnt, blockInfo.tailHolderSeqCnt, + // blockInfo.dealSeqSize, blockInfo.compressTcSize); + + // LocalTensor scoreUb = inputQue1.AllocTensor(); + // OverLap(scoreUb, sliceInfo, dStartIdx + constInfo_.dBaseSize, dDealSize); + // inputQue1.EnQue(scoreUb); + // inputQue1.DeQue(); + // PipeBarrier(); + // LocalTensor scoreLocal = tmpBuff1.Get(); + // DataCopy(scoreLocal, scoreUb, sliceInfo.dealTcSize * (uint32_t)COMP::coff + // * constInfo_.cmpRatio * dDealSize); inputQue1.FreeTensor(scoreUb); + + // DumpTensorForDim2(scoreLocal, 3, 128 * 64); + // PipeBarrier(); + AddApeToScore(scoreLocal[ubOffset], + apeUb, + sliceInfo.dealTcSize, + dDealSize); // VEC,pengchen + PipeBarrier(); + // DumpTensorForDim2(scoreLocal, 5, 128 * 64); + + // DumpTensorForDim2(kvLocal, 6, 128 * 64); + + // LocalTensor kvUb = inputQue1.AllocTensor(); + // OverLap(kvUb, sliceInfo, dStartIdx, dDealSize); + // inputQue1.EnQue(kvUb); + // inputQue1.DeQue(); + // PipeBarrier(); + // LocalTensor kvLocal = tmpBuff2.Get(); + // DataCopy(kvLocal, kvUb, sliceInfo.dealTcSize * (uint32_t)COMP::coff * + // constInfo_.cmpRatio * dDealSize); inputQue1.FreeTensor(kvUb); + + UpdateState(kvLocal[ubOffset], + scoreLocal[ubOffset], + sliceInfo, + dStartIdx, + dDealSize); // TODO:MTE2\MTE3, shasha + + // UpdateState(kvLocal, scoreLocal, startTcIdx, blockInfo, dStartIdx, + // dDealSize); // TODO:MTE2\MTE3, shasha DumpTensorForDim2(kvLocal, 7, 128 * + // 64); DumpTensorForDim2(scoreLocal, 8, 128 * 64); + + if (sliceInfo.compressTcSize > 0) { + LocalTensor tmpUb = kvLocal[BUFFER_SIZE_BYTE_32K / sizeof(T)]; + PipeBarrier(); + SoftmaxDN(scoreLocal[ubOffset], + tmpUb, + sliceInfo.compressTcSize, + dDealSize); // TODO:VEC, yixiao + // DumpTensorForDim2(scoreLocal, 9, 128 * 64, 128, 64); + + LocalTensor comporessedUb = outputQue1.AllocTensor(); + PipeBarrier(); + KvMulReduceScore(kvLocal[ubOffset], + scoreLocal[ubOffset], + comporessedUb, + tmpUb, + sliceInfo.compressTcSize, + dDealSize); // VEC, pengchen + PipeBarrier(); + // DumpTensorForDim2(comporessedUb, 10, 64); + outputQue1.EnQue(comporessedUb); + outputQue1.DeQue(); + CopyOutVec1Res( + info, comporessedUb, sliceInfo.compressTcSize, dStartIdx, dDealSize); + outputQue1.FreeTensor(comporessedUb); + } + sliceIterstor.IteratorSlice(); + compressedCnt_ += sliceInfo.compressTcSize; + } +} + +template +__aicore__ inline void CompressorBlockVectorPerf::ComputeVec1( + const RunInfo& info) { + // DumpTensorForDim2(mm1ResTensor, 2, 128 * 256); + + CompressorVec1SliceIterator sliceIterstor(tools_); + sliceIterstor.SetMaxBatchSize(constInfo_.batchSize); + sliceIterstor.template Reset(info.bStart, info.sStart, 0U, 0U); + Vec1SliceInfo sliceInfo = sliceIterstor.GetSlice(); + + // printf("bIdx:%d, sIdx:%d, bSeqUsed:%d, bStartPos:%d, headHolderSeqCnt:%d, + // validSeqCnt:%d, tailHolderSeqCnt:%d, " + // "dealSeqCnt:%d, dealTcSize:%d, compressTcSize:%d\n", + // sliceInfo.bIdx, sliceInfo.sIdx, sliceInfo.bSeqUsed, + // sliceInfo.bStartPos, sliceInfo.headHolderSeqCnt, + // sliceInfo.validSeqCnt, sliceInfo.tailHolderSeqCnt, + // sliceInfo.dealSeqCnt, sliceInfo.dealTcSize, + // sliceInfo.compressTcSize); + + // printf("preBIdx:%d, preSIdx:%d, preBSeqUsed:%d, preBStartPos:%d, + // preHeadHolderSeqCnt:%d, preValidSeqCnt:%d, " + // "preTailHolderSeqCnt:%d, lastTcSeqCnt:%d, dealedSeqCnt:%d, + // preDealedSeqCnt:%d, sliceInfo.dealedTcCnt:%d\n", sliceInfo.preBIdx, + // sliceInfo.preSIdx, sliceInfo.preBSeqUsed, sliceInfo.preBStartPos, + // sliceInfo.preHeadHolderSeqCnt, sliceInfo.preValidSeqCnt, + // sliceInfo.preTailHolderSeqCnt, sliceInfo.lastTcSeqCnt, + // sliceInfo.dealedSeqCnt, sliceInfo.preDealedSeqCnt, + // sliceInfo.dealedTcCnt); + // 计算当前VecCore的任务量 + uint32_t dealSeqStartIdx = 0; + uint32_t dealTcSize = CeilDivT(info.dealTcNum, 2U); + uint32_t curBStart = info.bStart; + uint32_t curSStart = info.sStart; + uint32_t curCompressedCnt = 0; + // 刷新当前VecCore的起始bIdx和sIdx + if (GetBlockIdx() % 2 == 1) { + sliceIterstor.SetNeedDealTcSize(dealTcSize); + dealTcSize = info.dealTcNum - dealTcSize; + if (dealTcSize == 0) { + return; + } + while (!sliceIterstor.IsEnd()) { + sliceInfo = sliceIterstor.GetSlice(); + sliceIterstor.IteratorSlice(); + curCompressedCnt += sliceInfo.compressTcSize; + } + sliceInfo = sliceIterstor.GetSlice(); + dealSeqStartIdx = sliceInfo.dealedSeqCnt; + curBStart = sliceInfo.bIdx; + curSStart = sliceInfo.sIdx; + } + // 计算headDim和Tc方向切分大小 + constexpr uint32_t BASE_BLOCK_ELEMENT_NUM = BUFFER_SIZE_BYTE_32K / sizeof(T); + uint32_t maxDealColNum = + BASE_BLOCK_ELEMENT_NUM / (constInfo_.cmpRatio * (uint32_t)COMP::coff); + + // TODO:修改切D逻辑,后续不在核内切D + uint32_t tcSplitSize = 0; + uint32_t dSplitSize = 0; + uint32_t dLoopCount = 0; + + // 切块逻辑 + { + if (maxDealColNum < constInfo_.dBaseSize) { + tcSplitSize = 1; + dLoopCount = (constInfo_.dBaseSize + maxDealColNum - 1) / maxDealColNum; + dSplitSize = constInfo_.dBaseSize / dLoopCount; + } else { + dSplitSize = constInfo_.dBaseSize; + dLoopCount = constInfo_.dBaseSize / dSplitSize; + tcSplitSize = maxDealColNum / constInfo_.dBaseSize; + } + } + + // 切块循环 + for (uint32_t dLoopIdx = 0; dLoopIdx < dLoopCount; dLoopIdx++) { + CopyInApe(apeUb, dLoopIdx * dSplitSize, dSplitSize); + + sliceIterstor.Reset(curBStart, curSStart, dealSeqStartIdx, 0U); + // sliceIterstor.SetNeedDealTcSize(dealTcSize); + uint32_t actDealTcSize = tcSplitSize; + compressedCnt_ = curCompressedCnt; + for (uint32_t tcIdx = 0; tcIdx < dealTcSize; tcIdx += tcSplitSize) { + if (tcIdx + tcSplitSize > dealTcSize) { + actDealTcSize = dealTcSize - tcIdx; + } + // 处理单个切块 + sliceIterstor.SetNeedDealTcSize(actDealTcSize); + sliceIterstor.SetDealedTcCnt(0U); + DealVec1BaseBlock(info, sliceIterstor, dLoopIdx * dSplitSize, dSplitSize); + } + } + + // DumpTensorForDim2(vec1ResGm_[info.vec1ResOffset + curCompressedCnt * + // constInfo_.headDim], 101, 128); +} + +template +__aicore__ inline void CompressorBlockVectorPerf::ComputeVec2( + const XllmKernelCompressor::Vec2RunInfo& info) { + // DumpTensorForDim2(vec2InputGm_, 401, 32 * constInfo_.headDim); + SplitCoreV2(info); + uint32_t vec2DealM = v2TcEndIdx - v2TcStartIdx; + uint32_t loopCount = (vec2DealM + v2MBaseSize - 1) / v2MBaseSize; + for (uint32_t v2LoopIdx = 0, dealSize = v2MBaseSize; v2LoopIdx < loopCount; + ++v2LoopIdx) { + if (v2LoopIdx == loopCount - 1) { + dealSize = vec2DealM - v2LoopIdx * v2MBaseSize; + } + DealVec2BaseBlock(info, v2TcStartIdx + v2LoopIdx * v2MBaseSize, dealSize); + } + v2TcStartIdx = 0; + v2TcEndIdx = 0; +} + +template +__aicore__ inline void CompressorBlockVectorPerf::DealVec2BaseBlock( + const XllmKernelCompressor::Vec2RunInfo& info, + uint32_t startRow, + uint32_t dealRowCount) { + uint32_t computeSize = dealRowCount * constInfo_.headDim; + int64_t inGmOffset = startRow * constInfo_.headDim; + // CopyIn + LocalTensor vec1ResUb = inputQue1.AllocTensor(); + DataCopy(vec1ResUb, vec2InputGm_[inGmOffset], computeSize); + // DumpTensorForDim2(vec1ResUb, 201, computeSize); + inputQue1.EnQue(vec1ResUb); + inputQue1.DeQue(); + + // RmsNorm + // DumpTensorForDim2(normWeightUb, 202, constInfo_.headDim); + + LocalTensor normResUb = tmpBuff1.Get(); + LocalTensor tempLocal = tmpBuff2.Get(); + // DumpTensor(ropeSinLocal_, 100420, computeSize); + PipeBarrier(); + MultRowRmsNorm( + normResUb, vec1ResUb, normWeightUb, tempLocal, info, dealRowCount); + inputQue1.FreeTensor(vec1ResUb); + + // rope: 只对后RD进行rope; 将normResUb每行前headDim - + // ropeHeadDim个元素cast到X_T,然后再与rope后的结果组合存到outputUb + LocalTensor outputUb = outputQue1.AllocTensor(); + PipeBarrier(); + CalRope(info, outputUb, normResUb, startRow - v2TcStartIdx, dealRowCount); + PipeBarrier(); + // DumpTensorForDim2(outputUb, 204, computeSize); + // CopyOut + outputQue1.EnQue(outputUb); + outputQue1.DeQue(); + CopyFinalResultOut(info, outputUb, startRow - v2TcStartIdx, dealRowCount); + outputQue1.FreeTensor(outputUb); +} + +template +__aicore__ inline void CompressorBlockVectorPerf::MultRowRmsNorm( + const LocalTensor& normResUb, + const LocalTensor& vec1ResUb, + const LocalTensor& normWeightUb, + const LocalTensor& tempLocal, + const XllmKernelCompressor::Vec2RunInfo& info, + uint32_t dealRowCount) { + RmsNormParam rmsNormParams = {constInfo_.reciprocalD, + constInfo_.normEps, + dealRowCount, + constInfo_.headDim}; + RmsNorm(normResUb, vec1ResUb, normWeightUb, tempLocal, rmsNormParams); +} + +template +__aicore__ inline void CompressorBlockVectorPerf::CalRope( + const XllmKernelCompressor::Vec2RunInfo& info, + const LocalTensor& outputUb, + const LocalTensor& normResUb, + uint32_t startRow, + uint32_t dealRowCount) { + uint64_t globalScStart = 0; + CalcGlobalScStart(0, 0, OutputBStartIdx, OutputSStartIdx, globalScStart); + uint64_t SinCosOffset = globalScStart * constInfo_.ropeHeadDim; + uint32_t computeSize = dealRowCount * constInfo_.ropeHeadDim; + uint32_t totalSize = dealRowCount * constInfo_.headDim; + + // sin与cos各占一半, 实际分别最多只会用8K,总占用16K + LocalTensor cosUb = inputQue1.AllocTensor(); + LocalTensor sinUb = cosUb[BUFFER_SIZE_BYTE_8K / sizeof(X_T)]; + DataCopy( + cosUb, ropeCosGm_[SinCosOffset], computeSize); // TODO:ropeCosGm_上的偏移 + DataCopy( + sinUb, ropeSinGm_[SinCosOffset], computeSize); // TODO:ropeSinGm_上的偏移 + inputQue1.EnQue(sinUb); + inputQue1.DeQue(); + + LocalTensor ropeCosFp32Local = tmpBuff2.Get(); + LocalTensor ropeSinFp32Local = + ropeCosFp32Local[BUFFER_SIZE_BYTE_16K / sizeof(T)] + .template ReinterpretCast(); + LocalTensor tempLocal = ropeSinFp32Local[BUFFER_SIZE_BYTE_16K / sizeof(T)] + .template ReinterpretCast(); + // DumpTensor(ropeSinLocal_, 100421, computeSize); + PipeBarrier(); + Cast(ropeCosFp32Local, cosUb, RoundMode::CAST_NONE, computeSize); + Cast(ropeSinFp32Local, sinUb, RoundMode::CAST_NONE, computeSize); + PipeBarrier(); + inputQue1.FreeTensor(sinUb); + + RotaryPosEmb(normResUb, + normResUb, + ropeCosFp32Local, + ropeSinFp32Local, + tempLocal, + gatherOffsetCastUb, + dealRowCount, + constInfo_.ropeHeadDim, + constInfo_.headDim, + constInfo_.headDim - constInfo_.ropeHeadDim); + PipeBarrier(); + Cast(outputUb, normResUb, RoundMode::CAST_RINT, totalSize); + PipeBarrier(); +} + +template +__aicore__ inline void CompressorBlockVectorPerf::SplitCoreV2( + const XllmKernelCompressor::Vec2RunInfo& info) { + // 累积N个基本块数据后做vec2,N=2,传入的RunInfo包含该组核处理的数据块的bStart、bEnd、sStart、sEnd以及dealTcCount; + // 每组核切M方向将C1/V1后的数据分8 * 2个vec核上进行V2计算 + // 每次进行v2计算都会根据当前情况将workspace中的每组核处理的数据重新分到当前组的vec核 + + // Input: + // syncAll前每组cube核处理的实际数据块在batch及s方向的起止idx及实际数据量(m方向) + // Output: 每个vec核的处理数据块在m方向的起止位置及输出到Gm上的起始位置 + uint32_t coreNum = constInfo_.dBasicBlockNum * 2; // 组中有多少个vec核:16 + usedCoreNum = coreNum; + uint32_t currCoreIdx = GetBlockIdx(); // 当前vec核ID + uint32_t curVecCoreGroupIdx = currCoreIdx / coreNum; // 当前vec核所在组ID + vec1ResGmStart = curVecCoreGroupIdx * constInfo_.nSize * + constInfo_.tcBaseSize * constInfo_.headDim; + // 1.计算总vec2基本块数量 + // uint64_t totalBaseNum = (constInfo_.coreGroupNum * constInfo_.nSize * + // constInfo_.tcBaseSize + v2MBaseSize - 1) / v2MBaseSize; // + // TODO:不是按照实际数据量计算,暂时按照m方向完整基本块计算数据量 + uint64_t totalBaseNum = info.dealScSize; // 当前组核累积的实际数据量 + // 2.每个vec核上分到的数据量 + uint32_t avgBaseNum = 1; + if (totalBaseNum > coreNum) { + avgBaseNum = (totalBaseNum + coreNum - 1) / coreNum; + // uint32_t remainder = totalBaseNum % coreNum; + // avgBaseNum = (currCoreIdx % coreNum) < remainder ? avgBaseNum + 1 : + // avgBaseNum; + } else { + usedCoreNum = totalBaseNum; + } + if (currCoreIdx % coreNum >= usedCoreNum) { + return; + } + // 3.计算每个vec核的起始结束位置 + uint32_t accumBaseNum = 0; // 当前累积的基本块数 + uint32_t targetBaseNum = (currCoreIdx % coreNum + 1) * + avgBaseNum; // 当前vec核目标要达到的基本块数量 + uint32_t targetStartBaseNum = + targetBaseNum - avgBaseNum; // 分当前vec核时前面已经完成分核的基本块数量 + bool setStart = false; + for (uint32_t i = 0; i < totalBaseNum; ++i) { + if (accumBaseNum >= totalBaseNum) { + return; + } + accumBaseNum += 1; + if (!setStart && (accumBaseNum > targetStartBaseNum)) { + v2TcStartIdx = i; + setStart = true; + } + if (setStart && + (accumBaseNum >= targetBaseNum || i == (totalBaseNum - 1))) { + // 更新当前核的End分核信息 + v2TcEndIdx = i + 1; + GetScIdxInfo(info.bStart, + info.bCompressedId, + info.dealScSize, + v2TcStartIdx, + v2TcEndIdx, + OutputBStartIdx, + OutputSStartIdx, + OutputSize); + return; + } + } +} + +template +__aicore__ inline void CompressorBlockVectorPerf::CalcGlobalScStart( + uint32_t bStart, + uint32_t scStart, + uint32_t bEnd, + uint32_t scEnd, + uint64_t& globalScStart) { + for (uint32_t bIdx = bStart; bIdx < bEnd; ++bIdx) { + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + curActSeqLength_ = GetSeqLength(bIdx); + curStartPos_ = GetStartPos(bIdx); + globalScStart += GetScSize(); + } else { + curActSeqLength_ = constInfo_.sSize; + globalScStart += + (curActSeqLength_ + constInfo_.cmpRatio - 1) / constInfo_.cmpRatio; + } + } + globalScStart -= scStart; + globalScStart += scEnd; +} + +template +__aicore__ inline void CompressorBlockVectorPerf::UpdateOutputIdx( + uint32_t& outputBStart, + uint32_t& outputSStart, + uint32_t& dealScSize, + uint32_t& curDealScSize) { + curActSeqLength_ = GetSeqLength(outputBStart); + curStartPos_ = GetStartPos(outputBStart); + uint32_t curBatchScSize = + (curStartPos_ + curActSeqLength_) / constInfo_.cmpRatio - + curStartPos_ / constInfo_.cmpRatio; + uint32_t curBatchRemainScSize = curBatchScSize - outputSStart; + curDealScSize = + curBatchRemainScSize > dealScSize ? dealScSize : curBatchRemainScSize; + dealScSize -= curDealScSize; + outputSStart += curDealScSize; + if (outputSStart == curBatchScSize) { + outputBStart++; + outputSStart = 0; + } +} + +template +__aicore__ inline void CompressorBlockVectorPerf::CopyFinalResultOut( + const XllmKernelCompressor::Vec2RunInfo& info, + const LocalTensor& cmpKvOutUb, + uint32_t startRow, + uint32_t dealRowCount) { + uint64_t globalScStart = 0; + CalcGlobalScStart(0, 0, OutputBStartIdx, OutputSStartIdx, globalScStart); + uint64_t outOffset = globalScStart * constInfo_.headDim; + uint32_t copySize = dealRowCount * constInfo_.headDim; + + uint32_t dealScSize = dealRowCount; + uint32_t curDealScSize = 0; + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + DataCopy(cmpKvOutGm_[outOffset], cmpKvOutUb, copySize); + while (dealScSize > 0) { + UpdateOutputIdx( + OutputBStartIdx, OutputSStartIdx, dealScSize, curDealScSize); + } + } else { + // 处理BSH有效数据在内存上不连续(可能存在pad) + uint32_t ubProcessedCount = 0; + uint32_t preOutputBStartIdx = 0; + uint32_t preOutputSStartIdx = 0; + while (dealScSize > 0) { + // 逐batch计算写出索引 + preOutputBStartIdx = OutputBStartIdx; + preOutputSStartIdx = OutputSStartIdx; + UpdateOutputIdx( + OutputBStartIdx, OutputSStartIdx, dealScSize, curDealScSize); + DataCopy(cmpKvOutGm_[globalScStart * constInfo_.headDim], + cmpKvOutUb[ubProcessedCount * constInfo_.headDim], + curDealScSize * constInfo_.headDim); + CalcGlobalScStart(preOutputBStartIdx, + preOutputSStartIdx, + OutputBStartIdx, + OutputSStartIdx, + globalScStart); + ubProcessedCount += curDealScSize; + } + } +} +} // namespace XllmKernelCompressor +#endif // COMPRESSOR_BLOCK_VECTOR_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_vector_comm.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_vector_comm.h new file mode 100644 index 0000000000..cfac58ad27 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/compressor_vector_comm.h @@ -0,0 +1,432 @@ +/** + * 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 compressor_vector_comm.h + * \brief 存放各种vector的公共组件 + */ + +#ifndef COMPRESSOR_VECTOR_COMM_H +#define COMPRESSOR_VECTOR_COMM_H + +#include "compressor/op_kernel/compressor_comm.h" +namespace XllmKernelCompressor { + +struct MatRpeatParam { + uint32_t row; + uint32_t col; + uint32_t dtypeMask; + uint32_t loopTimes; + uint32_t colRemain; + uint8_t repeatStride; +}; + +struct RmsNormParam { + float reciprocal; + float epsilon; + uint32_t row; + uint32_t col; + float scale; + uint16_t isScaleEnable; +}; + +/** + * @brief ColumnSum 对矩阵按列进行求和 + * @param dstLocal 输出tensor [1, col],支持和shareTmpUb是同一块空间 + * @param srcLocal 输入tensor [row, col] + * @param shareTmpUb 临时buffer 内部需要的空间为 [ceil(row / 2) * col * + * sizeof(float)] + * @param row 行数 + * @param col 列数 + */ +__aicore__ inline void ColumnSum(const LocalTensor& dstLocal, + const LocalTensor& srcLocal, + const LocalTensor& shareTmpUb, + uint32_t row, + uint32_t col) { + // 行数为1时,直接将srcLocal复制到dstLocal + if (unlikely(row == 1)) { + DataCopy(dstLocal, srcLocal, row * col); + PipeBarrier(); + return; + } + for (uint32_t mask = MAX_R << 1; mask > 1; mask >>= 1) { + if (row & mask) { + // 将输入对半求和后放进临时空间 + Add(shareTmpUb, + srcLocal, + srcLocal[mask * col / 2], + mask * col / 2); // 2:对矩阵按列做计算 + PipeBarrier(); + // 将余量加到前一半上 + if (unlikely(row > mask)) { + if ((row - mask) > (mask >> 1)) { + Add(shareTmpUb, + shareTmpUb, + srcLocal[mask * col], + mask * col / 2); // 2:对矩阵按列做计算 + PipeBarrier(); + Add(shareTmpUb, + shareTmpUb, + srcLocal[(mask + (mask >> 1)) * col], + (row - mask - (mask >> 1)) * col); + PipeBarrier(); + } else { + Add(shareTmpUb, shareTmpUb, srcLocal[mask * col], (row - mask) * col); + PipeBarrier(); + } + } + // 每次将后一半行加到前一半上 + for (uint32_t i = mask >> 2; i > 1; i >>= 1) { + Add(shareTmpUb, shareTmpUb, shareTmpUb[i * col], i * col); + PipeBarrier(); + } + if (mask == 2) { // 2:最后一次矩阵运算处理 + DataCopy(dstLocal, shareTmpUb, col); + } else { + Add(dstLocal, shareTmpUb, shareTmpUb[col], col); + } + PipeBarrier(); + break; + } + } +} + +/** + * @brief ColumnMax 对矩阵按列进行求最大值 + * @param dstLocal 输出tensor [1, col],支持和shareTmpUb是同一块空间 + * @param srcLocal 输入tensor [row, col] + * @param shareTmpUb 临时buffer 内部需要的空间为 [ceil(row / 2) * col * + * sizeof(float)] + * @param row 行数 + * @param col 列数 + */ +__aicore__ inline void ColumnMax(const LocalTensor& dstLocal, + const LocalTensor& srcLocal, + const LocalTensor& shareTmpUb, + uint32_t row, + uint32_t col) { + // 行数为1时,直接将srcLocal复制到dstLocal + if (unlikely(row == 1)) { + DataCopy(dstLocal, srcLocal, row * col); + PipeBarrier(); + return; + } + for (uint32_t mask = MAX_R << 1; mask > 1; mask >>= 1) { + if (row & mask) { + // 将输入对半求最大值后放进临时空间 + Max(shareTmpUb, + srcLocal, + srcLocal[mask * col / 2], + mask * col / 2); // 2:对矩阵按列做计算 + PipeBarrier(); + // 将余量和前一半求最大值后加到前一半上 + if (unlikely(row > mask)) { + if ((row - mask) > (mask >> 1)) { + Max(shareTmpUb, + shareTmpUb, + srcLocal[mask * col], + mask * col / 2); // 2:对矩阵按列做计算 + PipeBarrier(); + Max(shareTmpUb, + shareTmpUb, + srcLocal[(mask + (mask >> 1)) * col], + (row - mask - (mask >> 1)) * col); + PipeBarrier(); + } else { + Max(shareTmpUb, shareTmpUb, srcLocal[mask * col], (row - mask) * col); + PipeBarrier(); + } + } + // 每次将后一半行和前一半最大值后加到前一半上 + for (uint32_t i = mask >> 2; i > 1; i >>= 1) { + Max(shareTmpUb, shareTmpUb, shareTmpUb[i * col], i * col); + PipeBarrier(); + } + if (mask == 2) { // 2:最后一次矩阵运算处理 + DataCopy(dstLocal, shareTmpUb, col); + } else { + Max(dstLocal, shareTmpUb, shareTmpUb[col], col); + } + PipeBarrier(); + break; + } + } +} + +/** + * @brief MatSubVec 矩阵逐行减向量 + * @param dstLocal 输出tensor [row, col] + * @param src0Local 输入tensor [row, col] + * @param src1Local 输入tensor [1, col] + * @param repeatParam 描述待处理数据的排布,包括 + row 行数 + col 列数 + dtypeMask 一次迭代参与计算元素数 + loopTimes 循环次数 + colRemain 剩余列数 + repeatStride 循环步长(内存中实际列长度) + */ +__aicore__ inline void MatSubVec(const LocalTensor& dstLocal, + const LocalTensor& src0Local, + const LocalTensor& src1Local, + const MatRpeatParam& repeatParam) { + for (uint32_t row = 0; row < repeatParam.row; row += REPEAT_MAX_NUM) { + uint32_t repeatRowTimes = Std::min(repeatParam.row - row, REPEAT_MAX_NUM); + uint32_t offset = 0; + for (uint32_t i = 0; i < repeatParam.loopTimes; i++) { + Sub(dstLocal[row * repeatParam.col + offset], + src0Local[row * repeatParam.col + offset], + src1Local[offset], + repeatParam.dtypeMask, + repeatRowTimes, + {1, 1, 1, repeatParam.repeatStride, repeatParam.repeatStride, 0}); + offset += repeatParam.dtypeMask; + } + if (repeatParam.colRemain > 0) { + Sub(dstLocal[row * repeatParam.col + offset], + src0Local[row * repeatParam.col + offset], + src1Local[offset], + repeatParam.colRemain, + repeatRowTimes, + {1, 1, 1, repeatParam.repeatStride, repeatParam.repeatStride, 0}); + } + } +} + +/** + * @brief MatDivVec 矩阵逐行除以向量 + * @param dstLocal 输出tensor [row, col] + * @param src0Local 输入tensor [row, col] + * @param src1Local 输入tensor [1, col] + * @param repeatParam 描述待处理数据的排布,包括 + row 行数 + col 列数 + dtypeMask 一次迭代参与计算元素数 + loopTimes 循环次数 + colRemain 剩余列数 + repeatStride 循环步长(内存中实际列长度) + */ +__aicore__ inline void MatDivVec(const LocalTensor& dstLocal, + const LocalTensor& src0Local, + const LocalTensor& src1Local, + const MatRpeatParam& repeatParam) { + for (uint32_t row = 0; row < repeatParam.row; row += REPEAT_MAX_NUM) { + uint32_t repeatRowTimes = Std::min(repeatParam.row - row, REPEAT_MAX_NUM); + uint32_t offset = 0; + for (uint32_t i = 0; i < repeatParam.loopTimes; i++) { + Div(dstLocal[row * repeatParam.col + offset], + src0Local[row * repeatParam.col + offset], + src1Local[offset], + repeatParam.dtypeMask, + repeatRowTimes, + {1, 1, 1, repeatParam.repeatStride, repeatParam.repeatStride, 0}); + offset += repeatParam.dtypeMask; + } + if (repeatParam.colRemain > 0) { + Div(dstLocal[row * repeatParam.col + offset], + src0Local[row * repeatParam.col + offset], + src1Local[offset], + repeatParam.colRemain, + repeatRowTimes, + {1, 1, 1, repeatParam.repeatStride, repeatParam.repeatStride, 0}); + } + } +} + +/** + * @brief MatMulVec 矩阵逐行乘以向量 + * @param dstLocal 输出tensor [row, col] + * @param src0Local 输入tensor [row, col] + * @param src1Local 输入tensor [1, col] + * @param repeatParam 描述待处理数据的排布,包括 + row 行数 + col 列数 + dtypeMask 一次迭代参与计算元素数 + loopTimes 循环次数 + colRemain 剩余列数 + repeatStride 循环步长(内存中实际列长度) + */ +__aicore__ inline void MatMulVec(const LocalTensor& dstLocal, + const LocalTensor& src0Local, + const LocalTensor& src1Local, + const MatRpeatParam& repeatParam) { + for (uint32_t row = 0; row < repeatParam.row; row += REPEAT_MAX_NUM) { + uint32_t repeatRowTimes = Std::min(repeatParam.row - row, REPEAT_MAX_NUM); + uint32_t offset = 0; + for (uint32_t i = 0; i < repeatParam.loopTimes; i++) { + Mul(dstLocal[row * repeatParam.col + offset], + src0Local[row * repeatParam.col + offset], + src1Local[offset], + repeatParam.dtypeMask, + repeatRowTimes, + {1, 1, 1, repeatParam.repeatStride, repeatParam.repeatStride, 0}); + offset += repeatParam.dtypeMask; + } + if (repeatParam.colRemain > 0) { + Mul(dstLocal[row * repeatParam.col + offset], + src0Local[row * repeatParam.col + offset], + src1Local[offset], + repeatParam.colRemain, + repeatRowTimes, + {1, 1, 1, repeatParam.repeatStride, repeatParam.repeatStride, 0}); + } + } +} + +/** + * @brief RowSum 矩阵对每行求和 + * @param dstLocal 输出tensor [1, row] + * @param srcLocal 输入tensor [row, col] + * @param shareTmpUb 临时buffer 内部需要的空间为 [row, + col],支持和srcLocal是同一块空间 + * @param repeatParam 描述待处理数据的排布,包括 + row 行数 + col 列数 + dtypeMask 一次迭代参与计算元素数 + loopTimes 循环次数 + colRemain 剩余列数 + repeatStride 循环步长(内存中实际列长度) + */ +__aicore__ inline void RowSum(const LocalTensor& dstLocal, + const LocalTensor& srcLocal, + const LocalTensor& shareTmpUb, + const MatRpeatParam& repeatParam) { + uint32_t blockCount = repeatParam.loopTimes; + if (blockCount > 0 && repeatParam.colRemain > 0) { + Add(shareTmpUb, + srcLocal, + srcLocal[blockCount * repeatParam.dtypeMask], + repeatParam.colRemain, + repeatParam.row, + {1, + 1, + 1, + repeatParam.repeatStride, + repeatParam.repeatStride, + repeatParam.repeatStride}); + AscendC::PipeBarrier(); + } + + for (uint32_t loopCount = blockCount >> 1; loopCount > 0; + loopCount = blockCount >> 1) { + blockCount = (blockCount + 1) >> 1; + for (uint32_t i = 0; i < loopCount; i++) { + Add(shareTmpUb[i * repeatParam.dtypeMask], + srcLocal[i * repeatParam.dtypeMask], + srcLocal[(i + blockCount) * repeatParam.dtypeMask], + repeatParam.dtypeMask, + repeatParam.row, + {1, + 1, + 1, + repeatParam.repeatStride, + repeatParam.repeatStride, + repeatParam.repeatStride}); + } + AscendC::PipeBarrier(); + } + + WholeReduceSum(dstLocal, + shareTmpUb, + (repeatParam.col < repeatParam.dtypeMask) + ? repeatParam.col + : repeatParam.dtypeMask, + repeatParam.row, + 1, + 1, + repeatParam.repeatStride); +} + +/** + * @brief RowDivs 矩阵每行除以对应元素 + * @param dstLocal 输出tensor [row, col] + * @param src0Local 输入tensor [row, col] + * @param src1Local 输入tensor [row, + 1],需要扩展到一个datablock中(实际内存需要为[row, FP32_BLOCK_ELEMENT_NUM]) + * @param repeatParam 描述待处理数据的排布,包括 + row 行数 + col 列数 + dtypeMask 一次迭代参与计算元素数 + loopTimes 循环次数 + colRemain 剩余列数 + repeatStride 循环步长(内存中实际列长度) + */ +__aicore__ inline void RowDivs(const LocalTensor& dstLocal, + const LocalTensor& src0Local, + const LocalTensor& src1Local, + const MatRpeatParam& repeatParam) { + for (uint32_t row = 0; row < repeatParam.row; row += REPEAT_MAX_NUM) { + uint32_t repeatRowTimes = Std::min(repeatParam.row - row, REPEAT_MAX_NUM); + uint32_t offset = 0; + for (uint32_t i = 0; i < repeatParam.loopTimes; i++) { + Div(dstLocal[row * repeatParam.col + offset], + src0Local[row * repeatParam.col + offset], + src1Local, + repeatParam.dtypeMask, + repeatRowTimes, + {1, 1, 0, repeatParam.repeatStride, repeatParam.repeatStride, 1}); + offset += repeatParam.dtypeMask; + } + if (repeatParam.colRemain > 0) { + Div(dstLocal[row * repeatParam.col + offset], + src0Local[row * repeatParam.col + offset], + src1Local, + repeatParam.colRemain, + repeatRowTimes, + {1, 1, 0, repeatParam.repeatStride, repeatParam.repeatStride, 1}); + } + } +} + +/** + * @brief RowMuls 矩阵每行乘以相同元素 + * @param dstLocal 输出tensor [row, col] + * @param src0Local 输入tensor [row, col] + * @param src1Local 输入tensor [row, + 1],需要扩展到一个datablock中(实际内存需要为[row, FP32_BLOCK_ELEMENT_NUM]) + * @param repeatParam 描述待处理数据的排布,包括 + row 行数 + col 列数 + dtypeMask 一次迭代参与计算元素数 + loopTimes 循环次数 + colRemain 剩余列数 + repeatStride 循环步长(内存中实际列长度) + */ +__aicore__ inline void RowMuls(const LocalTensor& dstLocal, + const LocalTensor& src0Local, + const LocalTensor& src1Local, + const MatRpeatParam& repeatParam) { + for (uint32_t row = 0; row < repeatParam.row; row += REPEAT_MAX_NUM) { + uint32_t repeatRowTimes = Std::min(repeatParam.row - row, REPEAT_MAX_NUM); + uint32_t offset = 0; + for (uint32_t i = 0; i < repeatParam.loopTimes; i++) { + Mul(dstLocal[row * repeatParam.col + offset], + src0Local[row * repeatParam.col + offset], + src1Local, + repeatParam.dtypeMask, + repeatRowTimes, + {1, 1, 0, repeatParam.repeatStride, repeatParam.repeatStride, 1}); + offset += repeatParam.dtypeMask; + } + if (repeatParam.colRemain > 0) { + Mul(dstLocal[row * repeatParam.col + offset], + src0Local[row * repeatParam.col + offset], + src1Local, + repeatParam.colRemain, + repeatRowTimes, + {1, 1, 0, repeatParam.repeatStride, repeatParam.repeatStride, 1}); + } + } +} + +} // namespace XllmKernelCompressor +#endif // COMPRESSOR_VECTOR_COMM_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/rms_norm.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/rms_norm.h new file mode 100644 index 0000000000..bab8e22b65 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/rms_norm.h @@ -0,0 +1,89 @@ +/** + * 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 rms_norm.h + * \brief + */ + +#ifndef RMS_NORM_H +#define RMS_NORM_H + +#include "compressor/op_kernel/compressor_comm.h" +#include "compressor_vector_comm.h" + +namespace XllmKernelCompressor { +/** + * @brief RmsNorm 对矩阵进行rmsnorm + * @param dstLocal 输出tensor [row, col],支持和srcLocal是同一块空间 + * @param srcLocal 输入tensor [row, col] + * @param gammaLocal 系数gamma [1, col] + * @param shareTmpUb 临时buffer 内部需要的空间为 [(row * col + row) * + sizeof(float)] + * @param rmsNormParams rms所需系数,包括 + reciprocal rmsnorm系数reciprocal + epsilon rmsnorm系数epsilon + row 处理的行数 + col 列数 + */ +template +__aicore__ inline void RmsNorm(const LocalTensor& dstLocal, + const LocalTensor& srcLocal, + const LocalTensor& gammaLocal, + const LocalTensor& shareTmpUb, + const RmsNormParam& rmsNormParams) { + uint64_t cnt = rmsNormParams.row * rmsNormParams.col; + LocalTensor temp1Local = shareTmpUb.ReinterpretCast(); + LocalTensor temp2Local = temp1Local[cnt]; + + // temp1Local = srcLocal ^ 2 + Mul(temp1Local, srcLocal, srcLocal, cnt); + PipeBarrier(); + + MatRpeatParam repeatParams = { + rmsNormParams.row, // row + rmsNormParams.col, // col + FP32_REPEAT_ELEMENT_NUM, // dtypeMask + rmsNormParams.col / FP32_REPEAT_ELEMENT_NUM, // loopTimes + rmsNormParams.col % FP32_REPEAT_ELEMENT_NUM, // colsRemain + static_cast(rmsNormParams.col / + FP32_BLOCK_ELEMENT_NUM), // repeatStride + }; + + // temp2Local[row] = Sum(temp1Local) + RowSum(temp2Local, temp1Local, temp1Local, repeatParams); + PipeBarrier(); + + // temp2Local[row] = temp2Local[row] * reciprocal(1/N) + Muls(temp2Local, temp2Local, rmsNormParams.reciprocal, rmsNormParams.row); + PipeBarrier(); + + // temp2Local[row] = temp2Local[row] + epsilon + Adds(temp2Local, temp2Local, rmsNormParams.epsilon, rmsNormParams.row); + PipeBarrier(); + + // temp2Local[row] = Sqrt(temp2Local[row]) + Sqrt(temp2Local, temp2Local, rmsNormParams.row); + PipeBarrier(); + + // temp1Local[row, 8] = brc(temp2Local[row, 1]) + Brcb(temp1Local, temp2Local, CeilDivT(rmsNormParams.row, BRCB_NUM), {1, 8}); + PipeBarrier(); + + // dstLocal = srcLocal / temp1Local(sum) + RowDivs(dstLocal, srcLocal, temp1Local, repeatParams); + PipeBarrier(); + + // dstLocal = dstLocal * gammaLocal + MatMulVec(dstLocal, dstLocal, gammaLocal, repeatParams); +} +} // namespace XllmKernelCompressor +#endif // MLA_PROLOG_RMS_NORM_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/rope.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/rope.h new file mode 100644 index 0000000000..7a4778b99b --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/rope.h @@ -0,0 +1,186 @@ +/** + * 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 rope.h + * \brief + */ + +#ifndef ROPE_H +#define ROPE_H + +#include "compressor/op_kernel/compressor_comm.h" +#include "compressor_vector_comm.h" + +namespace XllmKernelCompressor { + +/** + * @brief SetGatherSrcOffset 计算用于interleave模式的offset + * @param gatherOffsetLocal 输出tensor + * [count],数据类型需要为int64_t,使用时要转换 + * @param count offset的元素个数,一般为列数 + */ +template +__aicore__ inline void SetGatherSrcOffset( + const LocalTensor& gatherOffsetLocal, + uint32_t count) { + for (uint32_t i = 0; i < 8; i++) { + gatherOffsetLocal.SetValue(i, i ^ 1); + } + + event_t eventId_S_V = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); + SetFlag(eventId_S_V); + WaitFlag(eventId_S_V); + + int32_t scalarValue = 8; + while (scalarValue < count) { + int32_t nextValue = scalarValue * 2; + PipeBarrier(); + if (nextValue < count) { + Adds(gatherOffsetLocal[scalarValue], + gatherOffsetLocal, + scalarValue, + scalarValue); + } else { + Adds(gatherOffsetLocal[scalarValue], + gatherOffsetLocal, + scalarValue, + count - scalarValue); + break; + } + scalarValue = nextValue; + } + PipeBarrier(); + Muls(gatherOffsetLocal, + gatherOffsetLocal, + static_cast(sizeof(T)), + count); +} + +/** + * @brief RotaryPosEmb 同时做row行的RotaryPosEmb,每一行的元素为col + * @param dstLocal 输出tensor [row, actualCol],支持和srcLocal是同一块空间 + * @param srcLocal 输入tensor [row, actualCol] + * @param cosLocal cos系数tensor [row, col] + * @param sinLocal sin系数tensor [row, col] + * @param shareTmpUb 临时buffer 内部需要的空间为 [row * col * sizeof(float)] + * @param gatherOffsetcastLocal + * 用于interleave模式的offset,数据类型需要为uint64_t + * @param row 待处理的行数 + * @param col 待处理的列数 + * @param actualCol 实际列数 + * @param baseAddr 计算基地址 + */ +template +__aicore__ inline void RotaryPosEmb( + const LocalTensor& dstLocal, + const LocalTensor& srcLocal, + const LocalTensor& cosLocal, + const LocalTensor& sinLocal, + const LocalTensor& shareTmpUb, + const LocalTensor& gatherOffsetcastLocal, + uint32_t row, + uint32_t col, + uint32_t actualCol, + uint64_t baseAddr) { + uint64_t cnt = row * col; + uint32_t half_col = col >> 1; + uint64_t rsvdCnt = 0; + LocalTensor reArrLocal = shareTmpUb.ReinterpretCast(); + if constexpr (MODE == ROTARY_MODE::HALF) { + DataCopy( + reArrLocal, + srcLocal[baseAddr + half_col], + {static_cast(row), + static_cast(CeilDivT(half_col, FP32_BLOCK_ELEMENT_NUM)), + static_cast( + CeilDivT(actualCol - half_col, FP32_BLOCK_ELEMENT_NUM)), + static_cast(CeilDivT(half_col, FP32_BLOCK_ELEMENT_NUM))}); + DataCopy( + reArrLocal[half_col], + srcLocal[baseAddr], + {static_cast(row), + static_cast(CeilDivT(half_col, FP32_BLOCK_ELEMENT_NUM)), + static_cast( + CeilDivT(actualCol - half_col, FP32_BLOCK_ELEMENT_NUM)), + static_cast(CeilDivT(half_col, FP32_BLOCK_ELEMENT_NUM))}); + PipeBarrier(); + Muls(reArrLocal, + reArrLocal, + float(-1), + half_col, + row, + {1, + 1, + static_cast( + CeilDivT(static_cast(col), FP32_BLOCK_ELEMENT_NUM)), + static_cast( + CeilDivT(static_cast(col), FP32_BLOCK_ELEMENT_NUM))}); + } else if constexpr (MODE == ROTARY_MODE::INTERLEAVE) { + for (uint32_t i = 0; i < row; i++) { + Gather(reArrLocal[i * col], + srcLocal[i * actualCol + baseAddr], + gatherOffsetcastLocal, + 0, + col); + } + PipeBarrier(); + uint32_t repeatTimes = cnt / FP32_REPEAT_ELEMENT_NUM; + uint32_t remainder = cnt % FP32_REPEAT_ELEMENT_NUM; + uint64_t fullMask = 0x5555555555555555; + uint64_t partialMask = 0x55; + SetVectorMask(0, fullMask); + Muls(reArrLocal, + reArrLocal, + float(-1), + MASK_PLACEHOLDER, + repeatTimes, + {1, 1, FP32_BLOCK_ELEMENT_NUM, FP32_BLOCK_ELEMENT_NUM}); + + if (unlikely(remainder > 0)) { + SetVectorMask(0, partialMask); + Muls(reArrLocal[repeatTimes * FP32_REPEAT_ELEMENT_NUM], + reArrLocal[repeatTimes * FP32_REPEAT_ELEMENT_NUM], + float(-1), + MASK_PLACEHOLDER, + remainder / FP32_BLOCK_ELEMENT_NUM, + {1, 1, 1, 1}); + } + ResetMask(); + } + + PipeBarrier(); + BinaryRepeatParams computeParams{ + 1, + 1, + 1, + static_cast(CeilDivT(actualCol, FP32_BLOCK_ELEMENT_NUM)), + static_cast(CeilDivT(actualCol, FP32_BLOCK_ELEMENT_NUM)), + static_cast(CeilDivT(col, FP32_BLOCK_ELEMENT_NUM))}; + Mul(dstLocal[baseAddr], + srcLocal[baseAddr], + cosLocal, + col, + row, + computeParams); + Mul(reArrLocal, reArrLocal, sinLocal, cnt); + PipeBarrier(); + Add(dstLocal[baseAddr], + dstLocal[baseAddr], + reArrLocal, + col, + row, + computeParams); +} +} // namespace XllmKernelCompressor + +#endif diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/soft_max.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/soft_max.h new file mode 100644 index 0000000000..d71c06c799 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch32/soft_max.h @@ -0,0 +1,61 @@ +/** + * 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 soft_max.h + * \brief + */ + +#ifndef SOFT_MAX_H +#define SOFT_MAX_H + +#include "compressor/op_kernel/compressor_comm.h" +#include "compressor_vector_comm.h" + +namespace XllmKernelCompressor { +/** + * @brief ColumnSoftMax 对矩阵按列进行SoftMax + * @param dstLocal 输出tensor [row, col],支持和srcLocal是同一块空间 + * @param srcLocal 输入tensor [row, col] + * @param shareTmpUb 临时buffer 内部需要的空间为 [floor(row / 2) * col * + * sizeof(float)] + * @param row 行数 + * @param col 列数 + */ +__aicore__ inline void ColumnSoftMax(const LocalTensor& dstLocal, + const LocalTensor& srcLocal, + const LocalTensor& shareTmpUb, + uint32_t row, + uint32_t col) { + uint32_t dtypeMask = FP32_REPEAT_ELEMENT_NUM; + uint32_t dLoop = col / dtypeMask; + uint32_t dRemain = col % dtypeMask; + uint8_t repeatStride = col / FP32_BLOCK_ELEMENT_NUM; + ColumnMax(shareTmpUb, srcLocal, shareTmpUb, row, col); + PipeBarrier(); + MatSubVec(dstLocal, + srcLocal, + shareTmpUb, + {row, col, dtypeMask, dLoop, dRemain, repeatStride}); + PipeBarrier(); + Exp(dstLocal, dstLocal, row * col); + PipeBarrier(); + ColumnSum(shareTmpUb, dstLocal, shareTmpUb, row, col); + PipeBarrier(); + MatDivVec(dstLocal, + dstLocal, + shareTmpUb, + {row, col, dtypeMask, dLoop, dRemain, repeatStride}); +} + +} // namespace XllmKernelCompressor + +#endif diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/compressor_block_cube.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/compressor_block_cube.h new file mode 100644 index 0000000000..248f513224 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/compressor_block_cube.h @@ -0,0 +1,765 @@ +/** + * 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 compressor_block_cube.h + * \brief + */ + +#ifndef COMPRESSOR_BLOCK_CUBE_H +#define COMPRESSOR_BLOCK_CUBE_H + +#include "compressor/op_kernel/compressor_comm.h" + +using namespace AscendC; + +namespace XllmKernelCompressor { + +constexpr FixpipeConfig CFG_ROW_MAJOR_UB = { + CO2Layout::ROW_MAJOR, + true}; // ROW_MAJOR: 使能NZ2ND,输出数据格式为ND格式; true: + // 用于用户指定目的地址的位置是否是UB + +template +class CompressorBlockCube { + public: + __aicore__ inline CompressorBlockCube(){}; + __aicore__ inline void InitParams(const ConstInfo& constInfo); + __aicore__ inline void Init(__gm__ uint8_t* x, + __gm__ uint8_t* wKv, + __gm__ uint8_t* wGate, + __gm__ uint8_t* kvState, + __gm__ uint8_t* scoreState, + __gm__ uint8_t* ape, + __gm__ uint8_t* normWeight, + __gm__ uint8_t* ropeSin, + __gm__ uint8_t* ropeCos, + __gm__ uint8_t* kvBlockTable, + __gm__ uint8_t* scoreBlockTable, + __gm__ uint8_t* cuSeqlens, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* startPos, + __gm__ uint8_t* cmpKvOut); + __aicore__ inline void InitBuffers(TPipe* pipe); + __aicore__ inline void AllocEventID(TPipe* pipe); + __aicore__ inline void FreeEventID(TPipe* pipe); + __aicore__ inline void ComputeMm1(const RunInfo& info); + + private: + using T = float; + using X_T = typename AscendC:: + Conditional::type; + + __aicore__ inline uint32_t GetSeqUsed(uint32_t bIdx); + __aicore__ inline uint32_t GetStartPos(uint32_t bIdx); + __aicore__ inline uint32_t GetTIdxByBatch(uint32_t bIdx); + __aicore__ inline void CopyWeightGmToL1(const RunInfo& info, + LocalTensor wL1Tensor, + uint32_t hIdx, + uint32_t kBase, + uint32_t nLoopIdx); + __aicore__ inline void CopyXGmToL1(const RunInfo& info, + LocalTensor xL1Tensor, + uint32_t hIdx, + uint32_t kBase, + uint32_t mStart, + uint32_t mDealSize, + bool isLastM); + __aicore__ inline void LoadAToL0(LocalTensor aL0Tensor, + LocalTensor xL1Tensor, + uint32_t mStart, + uint32_t mDealSize, + uint32_t kBase, + uint32_t mSize, + bool isRightLeft); + __aicore__ inline void LoadBToL0(LocalTensor bL0Tensor, + LocalTensor wL1Tensor, + uint32_t nStart, + uint32_t nDealSize, + uint32_t nBase, + uint32_t kBase); + __aicore__ inline void MatrixMmad(LocalTensor cL0Tensor, + LocalTensor aL0Tensor, + LocalTensor bL0Tensor, + uint32_t mActSize, + uint32_t nDealSize, + uint32_t kActSize, + bool isInitL0C); + __aicore__ inline void CopyL0CDataToUb(LocalTensor ubTensor, + LocalTensor cL0Tensor, + uint32_t vecCoreIdx, + uint32_t mSizeAlign, + uint32_t nSizeAlign, + uint32_t nIdx); + + ConstInfo constInfo_ = {}; + + // GM + GlobalTensor xGm_; + GlobalTensor wkvGm_; + GlobalTensor wgateGm_; + GlobalTensor cuSeqlensGm_; + GlobalTensor sequsedGm_; + GlobalTensor startPosGm_; + bool isExistSeqUsed = false; + bool isExistStartPos = false; + + // =================================L1 Buffer================================= + static constexpr uint32_t L1_X_SIZE = 128 * 1024; + static constexpr uint32_t L1_W_SIZE = 64 * 1024; + // L1 Buffer + TBuf xBufL1; + TBuf wBufL1; + // =================================L0 Buffer================================= + // L0 buffer size + 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; + // L0_A + TBuf tmpBufL0A; + // L0_B + TBuf tmpBufL0B; + // L0_C + TBuf tmpBufL0C; + // =================================Event&Buffer ID=========================== + // mte2 <> mte1 EventID + static constexpr uint32_t X_EVENT0 = EVENT_ID0; + static constexpr uint32_t X_EVENT1 = EVENT_ID1; + uint32_t xBufId = 0; + static constexpr uint32_t W_EVENT0 = EVENT_ID2; + static constexpr uint32_t W_EVENT1 = EVENT_ID3; + uint32_t wBufId = 0; + static constexpr uint32_t M_LOCK_EVENT0 = EVENT_ID4; + static constexpr uint32_t M_LOCK_EVENT1 = EVENT_ID5; + uint32_t mLockId = 0; + static constexpr uint32_t N_LOCK_EVENT0 = EVENT_ID6; + static constexpr uint32_t N_LOCK_EVENT1 = EVENT_ID7; + uint32_t nLockId = 0; + // mte1 <> mmad EventID + static constexpr uint32_t L0AB_EVENT0 = EVENT_ID3; + static constexpr uint32_t L0AB_EVENT1 = EVENT_ID4; + uint32_t l0abBufId = 0; + // mmad <> fixpipe EventID + static constexpr uint32_t L0C_EVENT0 = EVENT_ID0; + static constexpr uint32_t L0C_EVENT1 = EVENT_ID1; + static constexpr uint32_t L0C_EVENT2 = EVENT_ID2; + static constexpr uint32_t L0C_EVENT3 = EVENT_ID3; + uint32_t l0cBufId = 0; + + // =================================UB Buffer=========================== + TBuf mm1ResUb; + LocalTensor mm1ResTensor; + + // =================================Loop====================================== + uint32_t curBIdx_ = 0; + uint32_t curSIdx_ = 0; +}; + +template +__aicore__ inline void CompressorBlockCube::InitParams( + const ConstInfo& constInfo) { + this->constInfo_ = constInfo; +} + +template +__aicore__ inline void CompressorBlockCube::Init( + __gm__ uint8_t* x, + __gm__ uint8_t* wKv, + __gm__ uint8_t* wGate, + __gm__ uint8_t* kvState, + __gm__ uint8_t* scoreState, + __gm__ uint8_t* ape, + __gm__ uint8_t* normWeight, + __gm__ uint8_t* ropeSin, + __gm__ uint8_t* ropeCos, + __gm__ uint8_t* kvBlockTable, + __gm__ uint8_t* scoreBlockTable, + __gm__ uint8_t* cuSeqlens, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* startPos, + __gm__ uint8_t* cmpKvOut) { + xGm_.SetGlobalBuffer((__gm__ X_T*)x); + wkvGm_.SetGlobalBuffer((__gm__ X_T*)wKv); + wgateGm_.SetGlobalBuffer((__gm__ X_T*)wGate); + isExistSeqUsed = (seqUsed != nullptr); + isExistStartPos = (startPos != nullptr); + if (isExistStartPos) { + startPosGm_.SetGlobalBuffer((__gm__ int32_t*)startPos); + } + if (isExistSeqUsed) { + sequsedGm_.SetGlobalBuffer((__gm__ int32_t*)seqUsed); + } + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + cuSeqlensGm_.SetGlobalBuffer((__gm__ int32_t*)cuSeqlens); + } +} + +template +__aicore__ inline void CompressorBlockCube::InitBuffers(TPipe* pipe) { + // L1 + pipe->InitBuffer(xBufL1, L1_X_SIZE * 2); + pipe->InitBuffer(wBufL1, L1_W_SIZE * 2); + + // L0 + pipe->InitBuffer(tmpBufL0A, L0A_PP_SIZE * 2); + pipe->InitBuffer(tmpBufL0B, L0B_PP_SIZE * 2); + pipe->InitBuffer(tmpBufL0C, L0C_PP_SIZE * 4); + + // UB + pipe->InitBuffer(mm1ResUb, 128 * 1024); + mm1ResTensor = mm1ResUb.Get(); +} + +template +__aicore__ inline void CompressorBlockCube::AllocEventID(TPipe* pipe) { + SetFlag(X_EVENT0); + SetFlag(X_EVENT1); + SetFlag(W_EVENT0); + SetFlag(W_EVENT1); + SetFlag(M_LOCK_EVENT0); + SetFlag(M_LOCK_EVENT1); + SetFlag(N_LOCK_EVENT0); + SetFlag(N_LOCK_EVENT1); + + SetFlag(L0AB_EVENT0); + SetFlag(L0AB_EVENT1); + + SetFlag(L0C_EVENT0); + SetFlag(L0C_EVENT1); + SetFlag(L0C_EVENT2); + SetFlag(L0C_EVENT3); +} + +template +__aicore__ inline void CompressorBlockCube::FreeEventID(TPipe* pipe) { + WaitFlag(X_EVENT0); + WaitFlag(X_EVENT1); + WaitFlag(W_EVENT0); + WaitFlag(W_EVENT1); + WaitFlag(M_LOCK_EVENT0); + WaitFlag(M_LOCK_EVENT1); + WaitFlag(N_LOCK_EVENT0); + WaitFlag(N_LOCK_EVENT1); + + WaitFlag(L0AB_EVENT0); + WaitFlag(L0AB_EVENT1); + + WaitFlag(L0C_EVENT0); + WaitFlag(L0C_EVENT1); + WaitFlag(L0C_EVENT2); + WaitFlag(L0C_EVENT3); +} + +template +__aicore__ inline void CompressorBlockCube::CopyWeightGmToL1( + const RunInfo& info, + LocalTensor wL1Tensor, + uint32_t hIdx, + uint32_t kBase, + uint32_t nLoopIdx) { + // hIdx: hidden_size轴的索引ID + // kBase: hidden_size轴单次往L1搬运的长度, 128 + // nLoopIdx: D方向L1搬运的循环ID, 0/1 + // coff=1时, nLoopIdx=0, 搬运wkv nBase, nLoopIdx=1, 搬运wgate nBase + if constexpr (COMP::coff == COFF::OVERLAP) { + // coff=2时, constInfo_.dBaseSize = 64, wkv和wgate在D轴各占一半 + // nLoopIdx=0, 搬运coffIdx=0的数据; nLoopIdx=1, 搬运coffIdx=1的数据 + uint64_t coffIdx = nLoopIdx; + uint64_t dIdx = + constInfo_.aiCoreIdx % constInfo_.dBasicBlockNum * constInfo_.dBaseSize; + uint64_t gmOffset = coffIdx * constInfo_.headDim * constInfo_.hSize + + dIdx * constInfo_.hSize + hIdx; + uint32_t wkvUbOffset = nLoopIdx * (kBase * 2 * constInfo_.dBaseSize); + uint32_t wgateUbOffset = + wkvUbOffset + constInfo_.dBaseSize * (32 / sizeof(X_T)); + CopySingleMatrixNDToNZ(wL1Tensor[wkvUbOffset], + wkvGm_[gmOffset], + constInfo_.dBaseSize, + kBase, + constInfo_.hSize, + 2 * constInfo_.dBaseSize); + CopySingleMatrixNDToNZ(wL1Tensor[wgateUbOffset], + wgateGm_[gmOffset], + constInfo_.dBaseSize, + kBase, + constInfo_.hSize, + 2 * constInfo_.dBaseSize); + } else { + // coff=1时, constInfo_.dBaseSize = 128, nLoopIdx=0, 搬运wkv nBase, + // nLoopIdx=1, 搬运wgate nBase + uint64_t dIdx = + constInfo_.aiCoreIdx % constInfo_.dBasicBlockNum * constInfo_.dBaseSize; + uint64_t gmOffset = dIdx * constInfo_.hSize + hIdx; + uint32_t ubOffset = nLoopIdx * kBase * constInfo_.dBaseSize; + if (nLoopIdx == 0) { + CopySingleMatrixNDToNZ(wL1Tensor[ubOffset], + wkvGm_[gmOffset], + constInfo_.dBaseSize, + kBase, + constInfo_.hSize, + constInfo_.dBaseSize); + } else { + CopySingleMatrixNDToNZ(wL1Tensor[ubOffset], + wgateGm_[gmOffset], + constInfo_.dBaseSize, + kBase, + constInfo_.hSize, + constInfo_.dBaseSize); + } + } +} + +template +__aicore__ inline uint32_t CompressorBlockCube::GetSeqUsed( + uint32_t bIdx) { + if (isExistSeqUsed) { + return (uint32_t)sequsedGm_.GetValue(bIdx); + } else { + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + return (uint32_t)(cuSeqlensGm_.GetValue(bIdx + 1) - + cuSeqlensGm_.GetValue(bIdx)); + } else { + return constInfo_.sSize; + } + } +} + +template +__aicore__ inline uint32_t CompressorBlockCube::GetStartPos( + uint32_t bIdx) { + if (isExistStartPos) { + return (uint32_t)startPosGm_.GetValue(bIdx); + } + return 0; +} + +template +__aicore__ inline uint32_t CompressorBlockCube::GetTIdxByBatch( + uint32_t bIdx) { + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + return (uint32_t)(cuSeqlensGm_.GetValue(bIdx)); + } else { + return constInfo_.sSize * bIdx; + } +} + +template +__aicore__ inline void CompressorBlockCube::CopyXGmToL1( + const RunInfo& info, + LocalTensor xL1Tensor, + uint32_t hIdx, + uint32_t kBase, + uint32_t mStart, + uint32_t mDealSize, + bool isLastM) { + uint32_t bStartPos; + uint32_t bSeqUsed; + bool copyLastCmpBlock = false; + if constexpr (COMP::coff == COFF::OVERLAP) { + if (mStart == 0) { + curBIdx_ = info.bStart; + curSIdx_ = info.sStart; + // update cur idx + if (curSIdx_ == 0) { + if (curBIdx_ == 0) { + copyLastCmpBlock = true; + } else { + // 取上一个batch的尾 + // S=0时向前取B + do { + curBIdx_ = + (curBIdx_ - 1 + constInfo_.batchSize) % constInfo_.batchSize; + bStartPos = GetStartPos(curBIdx_); + bSeqUsed = GetSeqUsed(curBIdx_); + } while (bSeqUsed == 0); + + curSIdx_ = + bStartPos + bSeqUsed == 0 + ? 0 + : max(Trunc(bStartPos + bSeqUsed - 1, constInfo_.cmpRatio), + bStartPos) - + bStartPos; + } + } else { + curSIdx_ = + curSIdx_ < constInfo_.cmpRatio ? 0 : curSIdx_ - constInfo_.cmpRatio; + } + } + if (isLastM) { + mDealSize = mDealSize + constInfo_.cmpRatio; + } + } else { + if (mStart == 0) { + curBIdx_ = info.bStart; + curSIdx_ = info.sStart; + } + } + + uint32_t ubOffset = mStart * (32 / sizeof(X_T)); + uint32_t mSizeFinish = 0; + if (copyLastCmpBlock) { + uint32_t lastBIdx = constInfo_.batchSize; + // S=0时向前取B + do { + lastBIdx = (lastBIdx - 1 + constInfo_.batchSize) % constInfo_.batchSize; + bStartPos = GetStartPos(lastBIdx); + bSeqUsed = GetSeqUsed(lastBIdx); + } while (bSeqUsed == 0); + + uint32_t copySeqCnt = (bStartPos + bSeqUsed) % constInfo_.cmpRatio; + if (copySeqCnt == 0) { + copySeqCnt = constInfo_.cmpRatio; + } + if (bSeqUsed < copySeqCnt) { + copySeqCnt = bSeqUsed; + } + uint64_t tmpSeqId = bSeqUsed - copySeqCnt; + uint32_t rOffset = (bStartPos + bSeqUsed - copySeqCnt) % + constInfo_.cmpRatio * (32 / sizeof(X_T)); + uint64_t sIdx = GetTIdxByBatch(lastBIdx) + tmpSeqId; + uint64_t gmOffset = sIdx * constInfo_.hSize + hIdx; + uint32_t nValue = copySeqCnt; + uint32_t dValue = kBase; + uint32_t srcDValue = constInfo_.hSize; + uint32_t dstNzC0Stride = + (info.dealTcNum * constInfo_.cmpRatio + 15) / 16 * 16; + if constexpr (COMP::coff == COFF::OVERLAP) { + dstNzC0Stride = + (info.dealTcNum * constInfo_.cmpRatio + constInfo_.cmpRatio + 15) / + 16 * 16; + } + CopySingleMatrixNDToNZ(xL1Tensor[ubOffset + rOffset], + xGm_[gmOffset], + nValue, + dValue, + srcDValue, + dstNzC0Stride); + + ubOffset += constInfo_.cmpRatio * (32 / sizeof(X_T)); + mSizeFinish += constInfo_.cmpRatio; + } + + while (mSizeFinish < mDealSize) { + if (curBIdx_ > info.bEnd) { + break; + } + uint32_t bSeqUsed = GetSeqUsed(curBIdx_); + uint32_t bStartPos = GetStartPos(curBIdx_); + + // 如果S=0,直接到下一个B + if (bSeqUsed == 0) { + curBIdx_++; + curSIdx_ = 0; + continue; + } + + uint32_t headHolderCnt = (bStartPos + curSIdx_) % constInfo_.cmpRatio; + uint32_t canCopyCnt = bSeqUsed - curSIdx_; + if (mSizeFinish + headHolderCnt + canCopyCnt > mDealSize) { + canCopyCnt = mDealSize - (mSizeFinish + headHolderCnt); + } + uint32_t tailHolderCnt = + constInfo_.cmpRatio - + (bStartPos + curSIdx_ + canCopyCnt) % constInfo_.cmpRatio; + if (tailHolderCnt == constInfo_.cmpRatio) { + tailHolderCnt = 0; + } + if (canCopyCnt == 0) { + continue; + } + + // 跳过batch头部的预留行 + ubOffset += headHolderCnt * (32 / sizeof(X_T)); + + uint64_t sIdx = GetTIdxByBatch(curBIdx_) + curSIdx_; + uint64_t gmOffset = sIdx * constInfo_.hSize + hIdx; + uint32_t nValue = canCopyCnt; + uint32_t dValue = kBase; + uint32_t srcDValue = constInfo_.hSize; + uint32_t dstNzC0Stride = + (info.dealTcNum * constInfo_.cmpRatio + 15) / 16 * 16; + if constexpr (COMP::coff == COFF::OVERLAP) { + dstNzC0Stride = + (info.dealTcNum * constInfo_.cmpRatio + constInfo_.cmpRatio + 15) / + 16 * 16; + } + CopySingleMatrixNDToNZ(xL1Tensor[ubOffset], + xGm_[gmOffset], + nValue, + dValue, + srcDValue, + dstNzC0Stride); + ubOffset += (canCopyCnt + tailHolderCnt) * (32 / sizeof(X_T)); + + curSIdx_ += canCopyCnt; + if (curSIdx_ == bSeqUsed) { + curBIdx_++; + curSIdx_ = 0; + } + + mSizeFinish += headHolderCnt + canCopyCnt + tailHolderCnt; + } +} + +template +__aicore__ inline void CompressorBlockCube::LoadAToL0( + LocalTensor aL0Tensor, + LocalTensor xL1Tensor, + uint32_t mStart, + uint32_t mDealSize, + uint32_t kBase, + uint32_t mSize, + bool isRightLeft) { + if constexpr (COMP::coff == COFF::OVERLAP) { + if (isRightLeft) { + mStart += constInfo_.cmpRatio; + } + mSize += constInfo_.cmpRatio; + } + uint32_t xTensorOffset = mStart * (32 / sizeof(X_T)); + LoadData2DParamsV2 loadData2DParamsV2; + loadData2DParamsV2.mStartPosition = 0; + loadData2DParamsV2.kStartPosition = 0; + loadData2DParamsV2.mStep = (mDealSize + 15) / 16; + loadData2DParamsV2.kStep = kBase / 16; + loadData2DParamsV2.srcStride = (mSize + 15) / 16; + loadData2DParamsV2.dstStride = loadData2DParamsV2.mStep; + loadData2DParamsV2.ifTranspose = false; + LoadData(aL0Tensor, xL1Tensor[xTensorOffset], loadData2DParamsV2); +} + +template +__aicore__ inline void CompressorBlockCube::LoadBToL0( + LocalTensor bL0Tensor, + LocalTensor wL1Tensor, + uint32_t nStart, + uint32_t nDealSize, + uint32_t nBase, + uint32_t kBase) { + uint64_t wTensorOffset = (nStart / nBase) * (nBase * kBase); + LoadData2DParams loadData2DParams; + loadData2DParams.startIndex = 0; + loadData2DParams.repeatTimes = (nBase / 16) * (kBase / 16); + loadData2DParams.srcStride = 1; + loadData2DParams.dstGap = 0; + loadData2DParams.ifTranspose = false; + LoadData(bL0Tensor, wL1Tensor[wTensorOffset], loadData2DParams); +} + +template +__aicore__ inline void CompressorBlockCube::MatrixMmad( + LocalTensor cL0Tensor, + LocalTensor aL0Tensor, + LocalTensor bL0Tensor, + uint32_t mActSize, + uint32_t nDealSize, + uint32_t kActSize, + bool isInitL0C) { + MmadParams mmadParams; + mmadParams.m = (mActSize + 15) / 16 * 16; + if (mmadParams.m == 1) { + mmadParams.m = 16; + } + mmadParams.n = nDealSize; + mmadParams.k = kActSize; + mmadParams.cmatrixInitVal = isInitL0C; + mmadParams.cmatrixSource = false; + Mmad(cL0Tensor, aL0Tensor, bL0Tensor, mmadParams); +} + +template +__aicore__ inline void CompressorBlockCube::CopyL0CDataToUb( + LocalTensor ubTensor, + LocalTensor cL0Tensor, + uint32_t vecCoreIdx, + uint32_t mSizeAlign, + uint32_t nSizeAlign, + uint32_t nIdx) { + if constexpr (COMP::coff == COFF::OVERLAP) { + FixpipeParamsC310 fixpipeParams; // L0C->UB + fixpipeParams.nSize = nSizeAlign; // L0C上的结果矩阵N方向的size大小; + // 为什么要8个元素对齐(32B对齐) // 128 + fixpipeParams.mSize = mSizeAlign; // when enable NZ2ND/NZ2DN, + // L0C->UB时mSize*sizeof(T)必须为32的倍数 + fixpipeParams.srcStride = mSizeAlign; + fixpipeParams.dstStride = + nSizeAlign; // UB的排布是kv|score, coff=2时, 各占64,正好128 + fixpipeParams.dualDstCtl = 0; + fixpipeParams.subBlockId = vecCoreIdx; + fixpipeParams.params.ndNum = 1; + fixpipeParams.params.srcNdStride = 0; + fixpipeParams.params.dstNdStride = 0; + Fixpipe( + ubTensor[nIdx * 128 * 128], + cL0Tensor, + fixpipeParams); // 将matmul结果从L0C搬运到UB + } else { + FixpipeParamsC310 fixpipeParams; // L0C->UB + fixpipeParams.nSize = nSizeAlign; // L0C上的结果矩阵N方向的size大小; + // 为什么要8个元素对齐(32B对齐) // 128 + fixpipeParams.mSize = mSizeAlign; // when enable NZ2ND/NZ2DN, + // L0C->UB时mSize*sizeof(T)必须为32的倍数 + fixpipeParams.srcStride = mSizeAlign; + fixpipeParams.dstStride = + 2 * nSizeAlign; // UB的排布是kv|score, 所以N轴需要乘2, 256 + fixpipeParams.dualDstCtl = 0; + fixpipeParams.subBlockId = vecCoreIdx; + fixpipeParams.params.ndNum = 1; + fixpipeParams.params.srcNdStride = 0; + fixpipeParams.params.dstNdStride = 0; + Fixpipe( + ubTensor[nIdx * nSizeAlign], + cL0Tensor, + fixpipeParams); // 将matmul结果从L0C搬运到UB + } +} + +template +__aicore__ inline void CompressorBlockCube::ComputeMm1( + const RunInfo& info) { + static constexpr uint32_t K_SIZE = 256; + static constexpr uint32_t K_L1_BASE = 128; + static constexpr uint32_t N_L1_BASE = 128; + static constexpr uint32_t M_L1_BASE = 128; + static constexpr uint32_t K_L1_LOOP = K_SIZE / K_L1_BASE; + + uint32_t nSize = constInfo_.dBaseSize * 2 * ((uint32_t)COMP::coff); + uint32_t mSize = info.dealTcNum * constInfo_.cmpRatio; + bool needMLock = (mSize > M_L1_BASE); + + uint32_t hSize = constInfo_.hSize; + for (uint32_t h = 0; h < hSize; h += K_SIZE) { + for (uint32_t kL1Idx = 0; kL1Idx < K_L1_LOOP; kL1Idx++) { + WaitFlag(X_EVENT0 + xBufId); + WaitFlag(W_EVENT0 + wBufId); + + LocalTensor xL1Tensor = xBufL1.GetWithOffset( + (L1_X_SIZE / sizeof(X_T)), xBufId * L1_X_SIZE); + LocalTensor wL1Tensor = wBufL1.GetWithOffset( + (L1_W_SIZE / sizeof(X_T)), wBufId * L1_W_SIZE); + for (uint32_t nL1 = 0; nL1 < nSize; nL1 += N_L1_BASE) { + // nLockId = nL1 / N_L1_BASE + WaitFlag(N_LOCK_EVENT0 + nLockId); + CopyWeightGmToL1(info, + wL1Tensor, + h + kL1Idx * K_L1_BASE, + K_L1_BASE, + nL1 / N_L1_BASE); + SetFlag(N_LOCK_EVENT0 + nLockId); + WaitFlag(N_LOCK_EVENT0 + nLockId); + for (uint32_t mL1 = 0; mL1 < mSize; mL1 += M_L1_BASE) { + uint32_t mDealSize = M_L1_BASE; + bool isLastM = (mL1 + M_L1_BASE >= mSize); + if (isLastM) { + mDealSize = mSize - mL1; + } + + if (nL1 == 0) { + mLockId = mL1 / M_L1_BASE; + if (needMLock) { + WaitFlag(M_LOCK_EVENT0 + mLockId); + } + // 当Coff=2时,mL1为最后一块时,需要多拷贝一个cmpRatio + CopyXGmToL1(info, + xL1Tensor, + h + kL1Idx * K_L1_BASE, + K_L1_BASE, + mL1, + mDealSize, + isLastM); + + // m轴可以一次拷贝时, 不需要m轴的拷贝锁;同步替换成大锁 + if (needMLock) { + SetFlag(M_LOCK_EVENT0 + mLockId); + WaitFlag(M_LOCK_EVENT0 + mLockId); + } else { + SetFlag(X_EVENT0 + xBufId); + WaitFlag(X_EVENT0 + xBufId); + } + } + + { + // 获取L0C + l0cBufId = + (nL1 / N_L1_BASE) * 2 + + (mL1 / + M_L1_BASE); // 2: m方向最多两块, 两块用不满时, 第二块L0C空着 + WaitFlag(L0C_EVENT0 + l0cBufId); + LocalTensor cL0Tensor = tmpBufL0C.GetWithOffset( + (L0C_PP_SIZE / sizeof(T)), l0cBufId * L0C_PP_SIZE); + { + WaitFlag(L0AB_EVENT0 + l0abBufId); + LocalTensor aL0Tensor = tmpBufL0A.GetWithOffset( + (L0A_PP_SIZE / sizeof(X_T)), l0abBufId * L0A_PP_SIZE); + LocalTensor bL0Tensor = tmpBufL0B.GetWithOffset( + (L0B_PP_SIZE / sizeof(X_T)), l0abBufId * L0B_PP_SIZE); + // 当Coff=2时,nL1=0时计算的是pre数据,nL1=N_L1_BASE时计算的是cur数据 + uint32_t K_L0_BASE = K_L1_BASE; + LoadAToL0(aL0Tensor, + xL1Tensor, + mL1, + mDealSize, + K_L0_BASE, + mSize, + (nL1 > 0)); + uint32_t N_L0_BASE = N_L1_BASE; + LoadBToL0( + bL0Tensor, wL1Tensor, nL1, N_L0_BASE, N_L0_BASE, K_L0_BASE); + SetFlag(L0AB_EVENT0 + l0abBufId); + WaitFlag(L0AB_EVENT0 + l0abBufId); + MatrixMmad(cL0Tensor, + aL0Tensor, + bL0Tensor, + mDealSize, + N_L0_BASE, + K_L0_BASE, + (h == 0) && (kL1Idx == 0)); + SetFlag(L0AB_EVENT0 + l0abBufId); + l0abBufId = (l0abBufId + 1) % 2; + } + if ((h + K_SIZE >= hSize) && (kL1Idx + 1 == K_L1_LOOP)) { + SetFlag(L0C_EVENT0 + l0cBufId); + WaitFlag(L0C_EVENT0 + l0cBufId); + uint32_t mSizeAlign = (mDealSize + 15) / 16 * 16; + uint32_t nSizeAlign = N_L1_BASE; + uint32_t nIdx = nL1 / N_L1_BASE; + CopyL0CDataToUb(mm1ResTensor, + cL0Tensor, + (mL1 == 0) ? 0 : 1, + mSizeAlign, + nSizeAlign, + nIdx); + } + SetFlag(L0C_EVENT0 + l0cBufId); + } + + if (nL1 + N_L1_BASE >= nSize) { + if (needMLock) { + mLockId = mL1 / M_L1_BASE; + SetFlag(M_LOCK_EVENT0 + mLockId); + } + } + } + SetFlag(N_LOCK_EVENT0 + nLockId); + nLockId = (nLockId + 1) % 2; + } + + SetFlag(X_EVENT0 + xBufId); + xBufId = (xBufId + 1) % 2; + SetFlag(W_EVENT0 + wBufId); + wBufId = (wBufId + 1) % 2; + } + } +} + +} // namespace XllmKernelCompressor + +#endif // COMPRESSOR_BLOCK_CUBE_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/compressor_block_vec.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/compressor_block_vec.h new file mode 100644 index 0000000000..fbdf717255 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/compressor_block_vec.h @@ -0,0 +1,1793 @@ +/** + * 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 compressor_block_vec.h + * \brief + */ + +#ifndef COMPRESSOR_BLOCK_VEC_H +#define COMPRESSOR_BLOCK_VEC_H + +#include "compressor/op_kernel/compressor_comm.h" +#include "kernel_operator.h" +#include "kernel_operator_list_tensor_intf.h" +#include "kernel_tiling/kernel_tiling.h" +#include "vf/vf_add.h" +#include "vf/vf_mul.h" +#include "vf/vf_rms_norm.h" +#include "vf/vf_rope.h" +#include "vf/vf_softmax.h" + +using namespace AscendC; + +namespace XllmKernelCompressor { +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +template +class CompressorBlockVector { + public: + static constexpr bool X_DTYPE = COMP::xDtype == X_DTYPE::BF16; + static constexpr uint64_t BLOCK_VEC_BASE_BUFFER_SIZE = 32 * 1024; // 32k + static constexpr uint32_t DATABLOCK_BYTES = 32; + static constexpr float FLOAT_ZERO = 0; + // =================================类型定义区================================= + // 中间计算数据类型为float,高精度模式 + using T = float; + using X_T = typename AscendC::Conditional::type; + + __aicore__ inline CompressorBlockVector(){}; + // =================================设置参数================================= + __aicore__ inline void InitParams(const ConstInfo& constInfo); + __aicore__ inline void Init(__gm__ uint8_t* x, + __gm__ uint8_t* wKv, + __gm__ uint8_t* wGate, + __gm__ uint8_t* kvState, + __gm__ uint8_t* scoreState, + __gm__ uint8_t* ape, + __gm__ uint8_t* normWeight, + __gm__ uint8_t* ropeSin, + __gm__ uint8_t* ropeCos, + __gm__ uint8_t* kvBlockTable, + __gm__ uint8_t* scoreBlockTable, + __gm__ uint8_t* cuSeqlens, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* startPos, + __gm__ uint8_t* cmpKvOut); + // =================================资源管理================================= + __aicore__ inline void InitBuffers(TPipe* pipe); + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + // =================================执行计算================================= + __aicore__ inline void ComputeVec1(const XllmKernelCompressor::RunInfo& info); + __aicore__ inline uint32_t GetBasicNum(); + __aicore__ inline uint32_t GetScSize(); + __aicore__ inline void GetScIdxInfo(uint32_t bStart, + uint32_t scStart, + uint32_t dealScSize, + uint32_t v2TcStart, + uint32_t v2TcEnd, + uint32_t& outputBStart, + uint32_t& outputSStart, + uint32_t& outputScSize); + __aicore__ inline void CalcScEndIdx(uint32_t bStart, + uint32_t scStart, + uint32_t dealScSize, + uint32_t& bEnd, + uint32_t& scEnd); + __aicore__ inline void InitVec1GlobalTensor(GlobalTensor preMm1ResGm, + GlobalTensor curMm1ResGm, + GlobalTensor vec1ResGm, + GlobalTensor vec2InputGm); + __aicore__ inline void ComputeVec2(const XllmKernelCompressor::RunInfo& info); + __aicore__ inline void WriteToCacheState( + const GlobalTensor& state, + const GlobalTensor& blockTableGm, + const LocalTensor& input, + uint32_t batchIdx, + uint32_t startSeqIdx, + uint32_t endSeqIdx, + uint32_t dStart, + uint32_t dDealSize); + __aicore__ inline void ReadFromCacheState( + const LocalTensor& output, + const GlobalTensor& state, + const GlobalTensor& blockTableGm, + uint32_t batchIdx, + uint32_t startSeqIdx, + uint32_t endSeqIdx, + uint32_t dStart, + uint32_t dDealSize); + __aicore__ inline void ProcessSingleBatch(uint32_t batchIdx, + uint64_t batchStartSeqIdx, + uint64_t batchEndSeqIdx, + uint32_t dLoop, + uint32_t dealDSize, + LocalTensor& mmResRight, + LocalTensor& mmResLeft); + + protected: + GlobalTensor vec1ResGm_; + GlobalTensor vec2InputGm_; + GlobalTensor preMm1ResGm_; + GlobalTensor curMm1ResGm_; + + private: + __aicore__ inline uint32_t GetSeqUsed(uint32_t bIdx); + __aicore__ inline uint32_t GetStartPos(uint32_t bIdx); + __aicore__ inline uint32_t GetSeqLength(uint32_t bIdx); + __aicore__ inline uint32_t GetBsLength(uint32_t index); + __aicore__ inline void CalcGlobalScStart(uint32_t bStart, + uint32_t scStart, + uint32_t bEnd, + uint32_t scEnd, + uint64_t& globalScStart); + __aicore__ inline void UpdateOutputIdx(uint32_t& outputBStart, + uint32_t& outputSStart, + uint32_t& dealScSize, + uint32_t& curDealScSize); + __aicore__ inline void DealVec1BaseBlock(const RunInfo& info, + BlockInfo& blockInfo, + uint32_t startTcIdx, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void UpdateBlockInfo(BlockInfo& blockInfo); + __aicore__ inline void CopyInApe(LocalTensor apeUb, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void AddApeToScore(LocalTensor& scoreLocal, + LocalTensor& apeUb, + uint32_t tcDealSize, + uint32_t dDealSize); + __aicore__ inline void DataCopyAlignUbToUb(LocalTensor dstLocal, + LocalTensor srcLocal, + uint32_t copyRowCount, + uint32_t copyColCount, + uint32_t srcSingleRowCount, + uint32_t dstSingleRowCount); + __aicore__ inline void DataCopyAlignGmToUb(LocalTensor dstLocal, + GlobalTensor srcGm, + uint32_t copyRowCount, + uint32_t copyColCount, + uint32_t srcSingleRowCount, + uint32_t dstSingleRowCount); + __aicore__ inline void OverLapScore(LocalTensor scoreLocal, + uint32_t tcStartIdx, + uint32_t tcDealSize, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void OverLapKv(LocalTensor kvLocal, + uint32_t tcStartIdx, + uint32_t tcDealSize, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void UpdateState(LocalTensor kvLocal, + LocalTensor scoreLocal, + uint32_t startTcIdx, + const BlockInfo& blockInfo, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void SoftmaxDN(LocalTensor& scoreLocal, + uint32_t tcDealSize, + uint32_t dDealSize); + __aicore__ inline void KvMulReduceScore(LocalTensor& kvLocal, + LocalTensor& scoreLocal, + LocalTensor& dstLocal, + uint32_t tcDealSize, + uint32_t dDealSize); + __aicore__ inline void CopyOutVec1Res(const RunInfo& info, + LocalTensor comporessedUb, + uint32_t compressTcSize, + uint32_t dStartIdx, + uint32_t dDealSize); + + __aicore__ inline void SplitCoreV2(const XllmKernelCompressor::RunInfo& info); + __aicore__ inline void CopyFinalResultOut( + const XllmKernelCompressor::RunInfo& info, + const LocalTensor& cmpKvOutUb, + uint32_t startRow, + uint32_t dealRowCount); + __aicore__ inline void DealVec2BaseBlock( + const XllmKernelCompressor::RunInfo& info, + uint32_t startRow, + uint32_t dealRowCount); + __aicore__ inline void RmsNorm(LocalTensor& vec1ResUb, + LocalTensor& normWeightUb, + LocalTensor& normResUb, + const XllmKernelCompressor::RunInfo& info, + uint32_t dealRowCount); + __aicore__ inline void CalRope(const XllmKernelCompressor::RunInfo& info, + LocalTensor& outputUb, + LocalTensor& normResUb, + uint32_t startRow, + uint32_t dealRowCount); + __aicore__ inline void SaveLeftFirst(const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const BlockInfo& blockInfo, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void SaveState(const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const BlockInfo& blockInfo, + uint32_t dStartIdx, + uint32_t dDealSize); + __aicore__ inline void ReadState(const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const BlockInfo& blockInfo, + uint32_t dStartIdx, + uint32_t dDealSize); + // static constexpr uint64_t SYNC_INPUT_BUF1_FLAG = 2; + // static constexpr uint64_t SYNC_INPUT_BUF1_PONG_FLAG = 3; + uint32_t cmpRatio_ = 0U; + uint32_t coff_ = 0U; + uint32_t curStartPos_ = 0; + uint32_t curActSeqLength_ = 0; + uint32_t compressedCnt_ = 0; + // vec2 + uint32_t v2MBaseSize = 16; // Tc块数量:32 * 1024 / (512 * 4) + uint32_t v2TcStartIdx = 0U; + uint32_t v2TcEndIdx = 0U; + uint32_t mmResColSize_ = 128; + int64_t vec1ResGmStart = 0U; + uint32_t usedCoreNum = 16; + uint32_t OutputBStartIdx, OutputSStartIdx, OutputSize; + uint32_t mmResBaseOffset_ = 0; + ConstInfo constInfo_ = {}; + MSplitInfo mSplitInfo = {}; + GlobalTensor startPosGm_; + GlobalTensor sequsedGm_; + GlobalTensor cuSeqlensGm_; + GlobalTensor kvBlockTableGm_; + GlobalTensor scoreBlockTableGm_; + GlobalTensor kvStateGm_; + GlobalTensor scoreStateGm_; + GlobalTensor apeGm_; + GlobalTensor normWeightGm_; + GlobalTensor ropeSinGm_; + GlobalTensor ropeCosGm_; + GlobalTensor cmpKvOutGm_; + bool isExistSeqUsed = false; + bool isExistStartPos = false; + + // ================================Local + // Buffer区==================================== + TBuf mm1ResUb; + LocalTensor mm1ResTensor; + LocalTensor leftStateTensor; + LocalTensor rightStateTensor; + LocalTensor normWeightUb; + // 临时tbuf + TBuf tmpBuff1; + TBuf tmpBuff2; + // in queue + TQue inputQue1; + TQue inputQue2; + TBuf normWeightBuf; + // out queue + TQue outputQue1; +}; + +template +__aicore__ inline void CompressorBlockVector::InitParams( + const ConstInfo& constInfo) { + this->constInfo_ = constInfo; + v2MBaseSize = + BLOCK_VEC_BASE_BUFFER_SIZE / (constInfo_.headDim * sizeof(float)); +} + +template +__aicore__ inline void CompressorBlockVector::Init( + __gm__ uint8_t* x, + __gm__ uint8_t* wKv, + __gm__ uint8_t* wGate, + __gm__ uint8_t* kvState, + __gm__ uint8_t* scoreState, + __gm__ uint8_t* ape, + __gm__ uint8_t* normWeight, + __gm__ uint8_t* ropeSin, + __gm__ uint8_t* ropeCos, + __gm__ uint8_t* kvBlockTable, + __gm__ uint8_t* scoreBlockTable, + __gm__ uint8_t* cuSeqlens, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* startPos, + __gm__ uint8_t* cmpKvOut) { + kvBlockTableGm_.SetGlobalBuffer((__gm__ int32_t*)kvBlockTable); + scoreBlockTableGm_.SetGlobalBuffer((__gm__ int32_t*)scoreBlockTable); + kvStateGm_.SetGlobalBuffer((__gm__ T*)kvState); + scoreStateGm_.SetGlobalBuffer((__gm__ T*)scoreState); + apeGm_.SetGlobalBuffer((__gm__ T*)ape); + normWeightGm_.SetGlobalBuffer((__gm__ X_T*)normWeight); + ropeSinGm_.SetGlobalBuffer((__gm__ X_T*)ropeSin); + ropeCosGm_.SetGlobalBuffer((__gm__ X_T*)ropeCos); + cmpKvOutGm_.SetGlobalBuffer((__gm__ X_T*)cmpKvOut); + isExistSeqUsed = (seqUsed != nullptr); + isExistStartPos = (startPos != nullptr); + if (isExistSeqUsed) { + sequsedGm_.SetGlobalBuffer((__gm__ int32_t*)seqUsed); + } + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + cuSeqlensGm_.SetGlobalBuffer((__gm__ int32_t*)cuSeqlens); + } + if (isExistStartPos) { + startPosGm_.SetGlobalBuffer((__gm__ int32_t*)startPos); + } +} + +template +__aicore__ inline void CompressorBlockVector::InitBuffers(TPipe* pipe) { + // UB + pipe->InitBuffer(mm1ResUb, 128 * 1024); + mm1ResTensor = mm1ResUb.Get(); + if constexpr (COMP::coff == COFF::OVERLAP) { + leftStateTensor = mm1ResTensor; // 64K + rightStateTensor = mm1ResTensor[128 * 128]; // 64K + } else { + leftStateTensor = mm1ResTensor; // 0K + rightStateTensor = mm1ResTensor; // 128K + } + pipe->InitBuffer(inputQue1, 1, BUFFER_SIZE_BYTE_32K); + pipe->InitBuffer(tmpBuff1, BUFFER_SIZE_BYTE_32K); + pipe->InitBuffer(tmpBuff2, BUFFER_SIZE_BYTE_32K); + pipe->InitBuffer(outputQue1, 1, BUFFER_SIZE_BYTE_16K); + pipe->InitBuffer(inputQue2, 2, BUFFER_SIZE_BYTE_2K); + pipe->InitBuffer(normWeightBuf, BUFFER_SIZE_BYTE_1K); + normWeightUb = normWeightBuf.Get(); + LocalTensor normweightInUb = inputQue2.AllocTensor(); + DataCopy(normweightInUb, + normWeightGm_, + constInfo_.headDim); // 获取normWeight,常驻 + inputQue2.EnQue(normweightInUb); + inputQue2.DeQue(); + DataCopy(normWeightUb, normweightInUb, constInfo_.headDim); + inputQue2.FreeTensor(normweightInUb); +} + +template +__aicore__ inline void CompressorBlockVector::AllocEventID() { + // SetFlag(SYNC_INPUT_BUF1_FLAG); + // SetFlag(SYNC_INPUT_BUF1_PONG_FLAG); +} + +template +__aicore__ inline void CompressorBlockVector::FreeEventID() { + // WaitFlag(SYNC_INPUT_BUF1_FLAG); + // WaitFlag(SYNC_INPUT_BUF1_PONG_FLAG); +} + +template +__aicore__ inline void CompressorBlockVector::InitVec1GlobalTensor( + GlobalTensor preMm1ResGm, + GlobalTensor curMm1ResGm, + GlobalTensor vec1ResGm, + GlobalTensor vec2InputGm) { + this->preMm1ResGm_ = preMm1ResGm; + this->curMm1ResGm_ = curMm1ResGm; + this->vec1ResGm_ = vec1ResGm; + this->vec2InputGm_ = vec2InputGm; +} + +template +__aicore__ inline uint32_t CompressorBlockVector::GetSeqUsed( + uint32_t bIdx) { + if (isExistSeqUsed) { + return (uint32_t)sequsedGm_.GetValue(bIdx); + } else { + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + return (uint32_t)(cuSeqlensGm_.GetValue(bIdx + 1) - + cuSeqlensGm_.GetValue(bIdx)); + } else { + return constInfo_.sSize; + } + } +} + +template +__aicore__ inline uint32_t CompressorBlockVector::GetStartPos( + uint32_t bIdx) { + if (isExistStartPos) { + return startPosGm_.GetValue(bIdx); + } + return 0; +} + +template +__aicore__ inline uint32_t CompressorBlockVector::GetSeqLength( + uint32_t bIdx) { + if (isExistSeqUsed) { + return sequsedGm_.GetValue(bIdx); + } else if (COMP::xLayout == X_LAYOUT::TH) { + return cuSeqlensGm_.GetValue(bIdx + 1) - cuSeqlensGm_.GetValue(bIdx); + } else { + if (isExistSeqUsed) { + return sequsedGm_.GetValue(bIdx); + } + return constInfo_.sSize; + } +} + +template +__aicore__ inline uint32_t CompressorBlockVector::GetBsLength( + uint32_t index) { + if (COMP::xLayout == X_LAYOUT::TH) { + return cuSeqlensGm_.GetValue(index); + } else { + return index * constInfo_.sSize; + } +} + +template +__aicore__ inline uint32_t CompressorBlockVector::GetBasicNum() { + // 获取 m方向上对应基本单元Tc的个数 + uint32_t curBasicNum = 0; + uint32_t headSize = 0; + if (curStartPos_ % constInfo_.cmpRatio != 0) { + headSize = constInfo_.cmpRatio - curStartPos_ % constInfo_.cmpRatio; + headSize = headSize > curActSeqLength_ ? curActSeqLength_ : headSize; + curBasicNum++; + } + // 加上中间整块及尾块 + curBasicNum += (curActSeqLength_ - headSize + constInfo_.cmpRatio - 1) / + constInfo_.cmpRatio; + return curBasicNum; +} + +template +__aicore__ inline uint32_t CompressorBlockVector::GetScSize() { + uint32_t curBasicNum = + (curStartPos_ + curActSeqLength_) / constInfo_.cmpRatio - + curStartPos_ / constInfo_.cmpRatio; + return curBasicNum; +} + +// 根据计算Tc开始结束索引 +template +__aicore__ inline void CompressorBlockVector::CalcScEndIdx( + uint32_t bStart, + uint32_t scStart, + uint32_t dealScSize, + uint32_t& bEnd, + uint32_t& scEnd) { + uint32_t accScSize = 0; + for (int bIdx = bStart; bIdx < constInfo_.batchSize; ++bIdx) { + bEnd = bIdx; + + curActSeqLength_ = GetSeqLength(bIdx); + curStartPos_ = GetStartPos(bIdx); + // 计算起始batch的剩余块 + if (bIdx == bStart) { + accScSize += GetScSize() - scStart; // 需要减去本batch已经处理完的sc + if (accScSize >= dealScSize) { + scEnd = scStart + dealScSize; + return; + } + } else { + uint32_t curBasicNum = GetScSize(); + uint32_t curBasicNumEnd = dealScSize - accScSize; + + if (accScSize + curBasicNum >= dealScSize) { + scEnd = curBasicNumEnd; + return; + } + accScSize += curBasicNum; + } + } +} + +// 根据sc的开始索引计算vec输出时的b、sc的索引 +template +__aicore__ inline void CompressorBlockVector::GetScIdxInfo( + uint32_t bStart, + uint32_t scStart, + uint32_t dealScSize, + uint32_t v2TcStart, + uint32_t v2TcEnd, + uint32_t& outputBStart, + uint32_t& outputSStart, + uint32_t& outputScSize) { + outputScSize = v2TcEnd - v2TcStart; + uint32_t scEnd = 0; + uint32_t bEnd = 0; + CalcScEndIdx(bStart, scStart, v2TcStart, bEnd, scEnd); + outputSStart = scEnd; + outputBStart = bEnd; + // 处理跳batch + curActSeqLength_ = GetSeqLength(bEnd); + curStartPos_ = GetStartPos(bEnd); + uint32_t curScSize = GetScSize(); + if (curScSize == scEnd) { + outputSStart = 0; + outputBStart++; + } +} + +template +__aicore__ inline void CompressorBlockVector::CopyInApe( + LocalTensor apeUb, + uint32_t dStartIdx, + uint32_t dDealSize) { + uint32_t copyRowCount = constInfo_.cmpRatio; + uint32_t copyColCount = dDealSize; + uint32_t dstSingleRowCount = ((uint32_t)COMP::coff) * dDealSize; + uint32_t srcSingleRowCount = ((uint32_t)COMP::coff) * constInfo_.headDim; + + uint32_t gmOffset = (constInfo_.aiCoreIdx % constInfo_.dBasicBlockNum) * + constInfo_.dBaseSize + + dStartIdx; + uint32_t dstUbOffset = 0; + if constexpr (COMP::coff == COFF::OVERLAP) { + DataCopyAlignGmToUb(apeUb[dstUbOffset], + apeGm_[gmOffset], + copyRowCount, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); + + gmOffset += constInfo_.headDim; + dstUbOffset += dDealSize; + } + DataCopyAlignGmToUb(apeUb[dstUbOffset], + apeGm_[gmOffset], + copyRowCount, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); +} + +template +__aicore__ inline void CompressorBlockVector::AddApeToScore( + LocalTensor& scoreLocal, + LocalTensor& apeUb, + uint32_t tcDealSize, + uint32_t dDealSize) { + for (uint16_t i = 0; i < tcDealSize; i++) { + LocalTensor dstLocal = scoreLocal[i * dDealSize * constInfo_.cmpRatio * + ((uint32_t)COMP::coff)]; + AddVF(dstLocal, + apeUb, + 0, + ((uint32_t)COMP::coff), + dDealSize, + constInfo_.cmpRatio); + } +} + +template +__aicore__ inline void CompressorBlockVector::DataCopyAlignUbToUb( + LocalTensor dstLocal, + LocalTensor srcLocal, + uint32_t copyRowCount, + uint32_t copyColCount, + uint32_t srcSingleRowCount, + uint32_t dstSingleRowCount) { + DataCopyParams intriParams; + intriParams.blockCount = copyRowCount; + intriParams.blockLen = copyColCount / (32 / sizeof(T)); + intriParams.dstStride = (dstSingleRowCount - copyColCount) / (32 / sizeof(T)); + intriParams.srcStride = (srcSingleRowCount - copyColCount) / (32 / sizeof(T)); + DataCopy(dstLocal, srcLocal, intriParams); +} + +template +__aicore__ inline void CompressorBlockVector::DataCopyAlignGmToUb( + LocalTensor dstLocal, + GlobalTensor srcGm, + uint32_t copyRowCount, + uint32_t copyColCount, + uint32_t srcSingleRowCount, + uint32_t dstSingleRowCount) { + DataCopyParams intriParams; + intriParams.blockCount = copyRowCount; + intriParams.blockLen = copyColCount / (32 / sizeof(T)); + intriParams.dstStride = (dstSingleRowCount - copyColCount) / (32 / sizeof(T)); + intriParams.srcStride = (srcSingleRowCount - copyColCount) / (32 / sizeof(T)); + DataCopy(dstLocal, srcGm, intriParams); +} + +template +__aicore__ inline void CompressorBlockVector::OverLapScore( + LocalTensor scoreLocal, + uint32_t tcStartIdx, + uint32_t tcDealSize, + uint32_t dStartIdx, + uint32_t dDealSize) { + // scoreUb data layout after overlap when r = 4 and coff = 2: + // Tc0_seq01: |--- --D_L--- -|------D_R-----| + // Tc0_seq02: |--- --D_L--- -|------D_R-----| + // Tc0_seq03: |--- --D_L--- -|------D_R-----| + // Tc0_seq04: |--- --D_L--- -|------D_R-----| + // Tc1_seq01: |--- --D_L--- -|------D_R-----| + // Tc1_seq02: |--- --D_L--- -|------D_R-----| + // Tc1_seq03: |--- --D_L--- -|------D_R-----| + // Tc1_seq04: |--- --D_L--- -|------D_R-----| + uint32_t srcSingleRowElemNum = + constInfo_.dBaseSize * 2; // 2: kv和score各一份 + uint32_t copyRowCount = tcDealSize * constInfo_.cmpRatio; + uint32_t copyColCount = dDealSize; + uint32_t srcSingleRowCount = srcSingleRowElemNum; + uint32_t dstSingleRowCount = + ((uint32_t)COMP::coff) * dDealSize; // left和right在seq方向是交错存储的 + uint32_t srcScoreUbOffset = + (tcStartIdx * constInfo_.cmpRatio) * srcSingleRowElemNum + + constInfo_.dBaseSize + dStartIdx; + + uint32_t dstUbOffset = 0; + if constexpr (COMP::coff == COFF::OVERLAP) { + DataCopyAlignUbToUb(scoreLocal[dstUbOffset], + leftStateTensor[srcScoreUbOffset], + copyRowCount, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); + dstUbOffset += dDealSize; + } + DataCopyAlignUbToUb(scoreLocal[dstUbOffset], + rightStateTensor[srcScoreUbOffset], + copyRowCount, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); +} + +template +__aicore__ inline void CompressorBlockVector::OverLapKv( + LocalTensor kvLocal, + uint32_t tcStartIdx, + uint32_t tcDealSize, + uint32_t dStartIdx, + uint32_t dDealSize) { + // kvUb data layout after overlap when r = 4 and coff = 2: + // Tc0_seq01: |--- --D_L--- -|------D_R-----| + // Tc0_seq02: |--- --D_L--- -|------D_R-----| + // Tc0_seq03: |--- --D_L--- -|------D_R-----| + // Tc0_seq04: |--- --D_L--- -|------D_R-----| + // Tc1_seq01: |--- --D_L--- -|------D_R-----| + // Tc1_seq02: |--- --D_L--- -|------D_R-----| + // Tc1_seq03: |--- --D_L--- -|------D_R-----| + // Tc1_seq04: |--- --D_L--- -|------D_R-----| + uint32_t srcSingleRowElemNum = + constInfo_.dBaseSize * 2; // 2: kv和score各一份 + uint32_t copyRowCount = tcDealSize * constInfo_.cmpRatio; + uint32_t copyColCount = dDealSize; + uint32_t srcSingleRowCount = srcSingleRowElemNum; + uint32_t dstSingleRowCount = + ((uint32_t)COMP::coff) * dDealSize; // left和right在seq方向是交错存储的 + uint32_t srcScoreUbOffset = + (tcStartIdx * constInfo_.cmpRatio) * srcSingleRowElemNum + dStartIdx; + + uint32_t dstUbOffset = 0; + if constexpr (COMP::coff == COFF::OVERLAP) { + DataCopyAlignUbToUb(kvLocal[dstUbOffset], + leftStateTensor[srcScoreUbOffset], + copyRowCount, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); + dstUbOffset += dDealSize; + } + DataCopyAlignUbToUb(kvLocal[dstUbOffset], + rightStateTensor[srcScoreUbOffset], + copyRowCount, + copyColCount, + srcSingleRowCount, + dstSingleRowCount); +} + +template +__aicore__ inline void CompressorBlockVector::ReadFromCacheState( + const LocalTensor& output, + const GlobalTensor& state, + const GlobalTensor& blockTableGm, + uint32_t batchIdx, + uint32_t startSeqIdx, + uint32_t endSeqIdx, + uint32_t dStart, + uint32_t dDealSize) { + uint32_t coff = static_cast(COMP::coff); + uint64_t blockTablebaseOffset = batchIdx * constInfo_.maxBlockNumPerBatch; + uint32_t curSeqIdx = startSeqIdx; + uint32_t copyFinishRowCnt = 0; + uint32_t seqCnt = endSeqIdx - startSeqIdx; + while (copyFinishRowCnt < seqCnt) { + uint64_t blockIdOffset = curSeqIdx / constInfo_.blockSize; + uint64_t remainRowCnt = curSeqIdx % constInfo_.blockSize; + uint64_t idInBlockTable = + blockTableGm.GetValue(blockTablebaseOffset + blockIdOffset); + uint32_t copyRowCnt = constInfo_.blockSize - remainRowCnt; + if (copyFinishRowCnt + copyRowCnt > seqCnt) { + copyRowCnt = seqCnt - copyFinishRowCnt; + } + + uint64_t stateOffset = + idInBlockTable * constInfo_.blockSize * coff * constInfo_.headDim + + remainRowCnt * coff * constInfo_.headDim + + (constInfo_.aiCoreIdx % constInfo_.dBasicBlockNum) * + constInfo_.dBaseSize + + dStart; + + DataCopyParams copyParams; + copyParams.blockCount = copyRowCnt; + copyParams.blockLen = dDealSize / (32 / sizeof(T)); + copyParams.dstStride = (coff * dDealSize - dDealSize) / (32 / sizeof(T)); + copyParams.srcStride = + (coff * constInfo_.headDim - dDealSize) / (32 / sizeof(T)); + DataCopy(output[copyFinishRowCnt * coff * dDealSize], + state[stateOffset], + copyParams); + + copyFinishRowCnt += copyRowCnt; + curSeqIdx += copyRowCnt; + } +} + +template +__aicore__ inline void CompressorBlockVector::WriteToCacheState( + const GlobalTensor& state, + const GlobalTensor& blockTableGm, + const LocalTensor& input, + uint32_t batchIdx, + uint32_t startSeqIdx, + uint32_t endSeqIdx, + uint32_t dStart, + uint32_t dDealSize) { + uint32_t coff = static_cast(COMP::coff); + uint64_t blockTablebaseOffset = batchIdx * constInfo_.maxBlockNumPerBatch; + uint32_t curSeqIdx = startSeqIdx; + uint32_t copyFinishRowCnt = 0; + uint32_t seqCnt = endSeqIdx - startSeqIdx; + while (copyFinishRowCnt < seqCnt) { + uint64_t blockIdOffset = curSeqIdx / constInfo_.blockSize; + uint64_t remainRowCnt = curSeqIdx % constInfo_.blockSize; + uint64_t idInBlockTable = + blockTableGm.GetValue(blockTablebaseOffset + blockIdOffset); + uint32_t copyRowCnt = constInfo_.blockSize - remainRowCnt; + if (copyFinishRowCnt + copyRowCnt > seqCnt) { + copyRowCnt = seqCnt - copyFinishRowCnt; + } + + if (idInBlockTable != 0) { // 32 + uint64_t stateOffset = + idInBlockTable * constInfo_.blockSize * coff * constInfo_.headDim + + remainRowCnt * coff * constInfo_.headDim + + (constInfo_.aiCoreIdx % constInfo_.dBasicBlockNum) * + constInfo_.dBaseSize + + dStart; + + DataCopyParams copyParams; + copyParams.blockCount = copyRowCnt; + copyParams.blockLen = dDealSize / (32 / sizeof(T)); + copyParams.dstStride = + (coff * constInfo_.headDim - dDealSize) / (32 / sizeof(T)); + copyParams.srcStride = (coff * dDealSize - dDealSize) / (32 / sizeof(T)); + DataCopy(state[stateOffset], + input[copyFinishRowCnt * coff * dDealSize], + copyParams); + } + + copyFinishRowCnt += copyRowCnt; + curSeqIdx += copyRowCnt; + } +} + +template +__aicore__ inline void CompressorBlockVector::SaveLeftFirst( + const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const BlockInfo& blockInfo, + uint32_t dStartIdx, + uint32_t dDealSize) { + uint32_t coff = static_cast(COMP::coff); + uint32_t preBIdx = 0; + // 左边为上一个batch或者最后一个batch的数据 + preBIdx = (blockInfo.bIdx - 1 + constInfo_.batchSize) % constInfo_.batchSize; + + uint32_t bSeqUsed = GetSeqUsed(preBIdx); + uint32_t bStartPos = GetStartPos(preBIdx); + // S=0时,跳B + while (bSeqUsed == 0) { + preBIdx = (preBIdx - 1 + constInfo_.batchSize) % constInfo_.batchSize; + bSeqUsed = GetSeqUsed(preBIdx); + bStartPos = GetStartPos(preBIdx); + } + + uint32_t endIdxInBlock = (bStartPos + bSeqUsed) % constInfo_.cmpRatio; + if (endIdxInBlock == 0) { + endIdxInBlock = constInfo_.cmpRatio; + } + + uint32_t copySeqCnt = (endIdxInBlock > bSeqUsed) ? bSeqUsed : endIdxInBlock; + uint64_t endSeqIdx = bStartPos + bSeqUsed; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = (endIdxInBlock - copySeqCnt) * coff * dDealSize; + WriteToCacheState(kvStateGm_, + kvBlockTableGm_, + kvLocal[srcBaseOffset], + preBIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + WriteToCacheState(scoreStateGm_, + scoreBlockTableGm_, + scoreLocal[srcBaseOffset], + preBIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); +} + +template +__aicore__ inline void CompressorBlockVector::SaveState( + const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const BlockInfo& blockInfo, + uint32_t dStartIdx, + uint32_t dDealSize) { + if (COMP::coff == COFF::OVERLAP) { + uint32_t coff = static_cast(COMP::coff); + // 存右边 + if (blockInfo.sIdx + blockInfo.validSeqCnt == blockInfo.bSeqUsed) { + uint32_t copySeqCnt = constInfo_.cmpRatio - blockInfo.tailHolderSeqCnt; + if (blockInfo.validSeqCnt < copySeqCnt) { + copySeqCnt = blockInfo.validSeqCnt; + } else { + if (blockInfo.tailHolderSeqCnt > 0) { + if (blockInfo.validSeqCnt - copySeqCnt > constInfo_.cmpRatio) { + copySeqCnt += constInfo_.cmpRatio; + } else { + copySeqCnt += blockInfo.validSeqCnt - copySeqCnt; + } + } + } + uint64_t endSeqIdx = + blockInfo.bStartPos + blockInfo.sIdx + blockInfo.validSeqCnt; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = + (blockInfo.headHolderSeqCnt + blockInfo.validSeqCnt - copySeqCnt) * + coff * dDealSize; + WriteToCacheState(kvStateGm_, + kvBlockTableGm_, + kvLocal[srcBaseOffset + dDealSize], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx + constInfo_.headDim, + dDealSize); + WriteToCacheState(scoreStateGm_, + scoreBlockTableGm_, + scoreLocal[srcBaseOffset + dDealSize], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx + constInfo_.headDim, + dDealSize); + } else if (blockInfo.sIdx + blockInfo.validSeqCnt + constInfo_.cmpRatio > + blockInfo.bSeqUsed) { + uint32_t copySeqCnt = constInfo_.cmpRatio; + if (copySeqCnt > blockInfo.validSeqCnt) { + copySeqCnt = blockInfo.validSeqCnt; + } + uint64_t endSeqIdx = + blockInfo.bStartPos + blockInfo.sIdx + blockInfo.validSeqCnt; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = + (blockInfo.headHolderSeqCnt + blockInfo.validSeqCnt - copySeqCnt) * + coff * dDealSize; + WriteToCacheState(kvStateGm_, + kvBlockTableGm_, + kvLocal[srcBaseOffset + dDealSize], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx + constInfo_.headDim, + dDealSize); + WriteToCacheState(scoreStateGm_, + scoreBlockTableGm_, + scoreLocal[srcBaseOffset + dDealSize], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx + constInfo_.headDim, + dDealSize); + } + + // 存左边 + if (blockInfo.dealTcSize == 1) { + // 左边尾块和首块是同一块 + if (blockInfo.sIdx == 0) { + SaveLeftFirst(kvLocal, scoreLocal, blockInfo, dStartIdx, dDealSize); + } else { + if (blockInfo.tailHolderSeqCnt > 0) { + // 左边为本batch数据 + uint32_t copySeqCnt = constInfo_.cmpRatio; + if (blockInfo.sIdx < copySeqCnt) { + copySeqCnt = blockInfo.sIdx; + } + uint64_t endSeqIdx = + blockInfo.bStartPos + blockInfo.sIdx + blockInfo.validSeqCnt - + (constInfo_.cmpRatio - blockInfo.tailHolderSeqCnt); + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = + (blockInfo.headHolderSeqCnt + blockInfo.validSeqCnt + + blockInfo.tailHolderSeqCnt - copySeqCnt) * + coff * dDealSize; + WriteToCacheState(kvStateGm_, + kvBlockTableGm_, + kvLocal[srcBaseOffset], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + WriteToCacheState(scoreStateGm_, + scoreBlockTableGm_, + scoreLocal[srcBaseOffset], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } + } else { + // 存左边第一块 + if (blockInfo.sIdx == 0) { + SaveLeftFirst(kvLocal, scoreLocal, blockInfo, dStartIdx, dDealSize); + } + + // 存左边最后一块 + if (blockInfo.tailHolderSeqCnt > 0) { + // 左边为本batch数据 + uint32_t copySeqCnt = constInfo_.cmpRatio; + if (blockInfo.validSeqCnt - + (constInfo_.cmpRatio - blockInfo.tailHolderSeqCnt) < + copySeqCnt) { + copySeqCnt = blockInfo.validSeqCnt - + (constInfo_.cmpRatio - blockInfo.tailHolderSeqCnt); + } + uint64_t endSeqIdx = blockInfo.bStartPos + blockInfo.sIdx + + blockInfo.validSeqCnt - + (constInfo_.cmpRatio - blockInfo.tailHolderSeqCnt); + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = + (blockInfo.headHolderSeqCnt + blockInfo.validSeqCnt + + blockInfo.tailHolderSeqCnt - copySeqCnt) * + coff * dDealSize; + WriteToCacheState(kvStateGm_, + kvBlockTableGm_, + kvLocal[srcBaseOffset], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + WriteToCacheState(scoreStateGm_, + scoreBlockTableGm_, + scoreLocal[srcBaseOffset], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } + } else { + if (blockInfo.tailHolderSeqCnt > 0) { // 仅尾块不满时需要存到state上 + uint32_t copySeqCnt = constInfo_.cmpRatio - blockInfo.tailHolderSeqCnt; + if (copySeqCnt > blockInfo.validSeqCnt) { + copySeqCnt = blockInfo.validSeqCnt; + } + uint64_t srcBaseOffset = + (blockInfo.headHolderSeqCnt + blockInfo.validSeqCnt - copySeqCnt) * + dDealSize; + uint64_t endSeqIdx = + blockInfo.bStartPos + blockInfo.sIdx + blockInfo.validSeqCnt; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + WriteToCacheState(kvStateGm_, + kvBlockTableGm_, + kvLocal[srcBaseOffset], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + WriteToCacheState(scoreStateGm_, + scoreBlockTableGm_, + scoreLocal[srcBaseOffset], + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } +} + +template +__aicore__ inline void CompressorBlockVector::ReadState( + const LocalTensor kvLocal, + const LocalTensor scoreLocal, + const BlockInfo& blockInfo, + uint32_t dStartIdx, + uint32_t dDealSize) { + // 没有需要压缩的块时, 不需要读state的信息 + if (blockInfo.compressTcSize == 0) { + return; + } + + if (COMP::coff == XllmKernelCompressor::COFF::OVERLAP) { + float SOFTMAX_MIN_NUM = static_cast(-1.0 / 0.0); + // 填充右边 + if (blockInfo.headHolderSeqCnt > 0) { + // 整个batch的第一块 + uint32_t copySeqCnt = blockInfo.bStartPos % constInfo_.cmpRatio; + uint64_t endSeqIdx = blockInfo.bStartPos; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = 0; + ReadFromCacheState(kvLocal[dDealSize], + kvStateGm_, + kvBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx + constInfo_.headDim, + dDealSize); + ReadFromCacheState(scoreLocal[dDealSize], + scoreStateGm_, + scoreBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx + constInfo_.headDim, + dDealSize); + } + + // 填充左边 + if (blockInfo.compressTcSize == 1) { + if (blockInfo.sIdx == 0) { + // 右边为整个batch的第一块 + if (blockInfo.bStartPos < constInfo_.cmpRatio) { + // 无历史数据 + // dDealSize必须为64 + Duplicate(kvLocal, + FLOAT_ZERO, + dDealSize, + constInfo_.cmpRatio, + 1, + 2 * dDealSize / 8); + Duplicate(scoreLocal, + SOFTMAX_MIN_NUM, + dDealSize, + constInfo_.cmpRatio, + 1, + 2 * dDealSize / 8); + } else { + // 存在前一个压缩组, 左侧数据全部在state中 + uint32_t copySeqCnt = constInfo_.cmpRatio; + uint64_t endSeqIdx = + blockInfo.bStartPos / constInfo_.cmpRatio * constInfo_.cmpRatio; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = 0; + ReadFromCacheState(kvLocal, + kvStateGm_, + kvBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + ReadFromCacheState(scoreLocal, + scoreStateGm_, + scoreBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } else if (blockInfo.sIdx == + (constInfo_.cmpRatio - + (blockInfo.bStartPos % constInfo_.cmpRatio))) { + // 右边为本次需要压缩的第二个压缩组 + if ((blockInfo.bStartPos % constInfo_.cmpRatio) > 0) { + uint32_t copySeqCnt = blockInfo.bStartPos % constInfo_.cmpRatio; + uint64_t endSeqIdx = blockInfo.bStartPos; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = 0; + ReadFromCacheState(kvLocal, + kvStateGm_, + kvBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + ReadFromCacheState(scoreLocal, + scoreStateGm_, + scoreBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } + } else { + if (blockInfo.sIdx == 0) { + if (blockInfo.bStartPos < constInfo_.cmpRatio) { + // 无历史数据 + // dDealSize必须为64 + Duplicate(kvLocal, + FLOAT_ZERO, + dDealSize, + constInfo_.cmpRatio, + 1, + 2 * dDealSize / 8); + Duplicate(scoreLocal, + SOFTMAX_MIN_NUM, + dDealSize, + constInfo_.cmpRatio, + 1, + 2 * dDealSize / 8); + } else { + uint32_t copySeqCnt = + constInfo_.cmpRatio + blockInfo.bStartPos % constInfo_.cmpRatio; + uint64_t endSeqIdx = blockInfo.bStartPos; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = 0; + ReadFromCacheState(kvLocal, + kvStateGm_, + kvBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + ReadFromCacheState(scoreLocal, + scoreStateGm_, + scoreBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } + } + } else { + // 需要压缩时, 首块如果头部有占位行, 必然需要从state拷贝数据 + if (blockInfo.headHolderSeqCnt > 0) { + // 整个batch的第一块 + uint32_t copySeqCnt = blockInfo.bStartPos % constInfo_.cmpRatio; + uint64_t endSeqIdx = blockInfo.bStartPos; + uint64_t startSeqIdx = endSeqIdx - copySeqCnt; + uint64_t srcBaseOffset = 0; + ReadFromCacheState(kvLocal, + kvStateGm_, + kvBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + ReadFromCacheState(scoreLocal, + scoreStateGm_, + scoreBlockTableGm_, + blockInfo.bIdx, + startSeqIdx, + endSeqIdx, + dStartIdx, + dDealSize); + } + } +} + +template +__aicore__ inline void CompressorBlockVector::UpdateState( + LocalTensor kvLocal, + LocalTensor scoreLocal, + uint32_t startTcIdx, + const BlockInfo& blockInfo, + uint32_t dStartIdx, + uint32_t dDealSize) { + event_t eventId_V_MTE3 = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_MTE3)); + event_t eventId_MTE3_MTE2 = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE3_MTE2)); + event_t eventId_MTE3_V = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE3_V)); + event_t eventId_MTE2_V = + static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + + SetFlag(eventId_V_MTE3); + WaitFlag(eventId_V_MTE3); + SaveState(kvLocal, scoreLocal, blockInfo, dStartIdx, dDealSize); + SetFlag(eventId_MTE3_MTE2); + SetFlag(eventId_MTE3_V); + WaitFlag(eventId_MTE3_MTE2); + WaitFlag(eventId_MTE3_V); + ReadState(kvLocal, scoreLocal, blockInfo, dStartIdx, dDealSize); + SetFlag(eventId_MTE2_V); + WaitFlag(eventId_MTE2_V); +} + +template +__aicore__ inline void CompressorBlockVector::SoftmaxDN( + LocalTensor& scoreLocal, + uint32_t tcDealSize, + uint32_t dDealSize) { + float minValue = -2e38; + uint32_t ReduceSize = COMP::coff == COFF::OVERLAP ? 2 * constInfo_.cmpRatio + : constInfo_.cmpRatio; + FaVectorApi::SoftmaxDnVF(scoreLocal, + scoreLocal, + dDealSize, + ReduceSize, + tcDealSize, + minValue, + dDealSize); +} + +template +__aicore__ inline void CompressorBlockVector::KvMulReduceScore( + LocalTensor& kvLocal, + LocalTensor& scoreLocal, + LocalTensor& dstLocal, + uint32_t tcDealSize, + uint32_t dDealSize) { + MulReduceSumbaseVF(kvLocal, + scoreLocal, + dstLocal, + (uint32_t)COMP::coff, + constInfo_.cmpRatio, + 0, + dDealSize, + tcDealSize * constInfo_.cmpRatio); +} + +template +__aicore__ inline void CompressorBlockVector::CopyOutVec1Res( + const RunInfo& info, + LocalTensor comporessedUb, + uint32_t compressTcSize, + uint32_t dStartIdx, + uint32_t dDealSize) { + uint64_t outGmOffset = + info.vec1ResOffset + compressedCnt_ * constInfo_.headDim + dStartIdx; + DataCopyParams copyParams; + copyParams.blockCount = compressTcSize; + copyParams.blockLen = dDealSize / (32 / sizeof(T)); + copyParams.dstStride = (constInfo_.headDim - dDealSize) / (32 / sizeof(T)); + copyParams.srcStride = 0; + DataCopy(vec1ResGm_[outGmOffset], comporessedUb, copyParams); +} + +template +__aicore__ inline void CompressorBlockVector::UpdateBlockInfo( + BlockInfo& blockInfo) { + if (!blockInfo.isFirst) { + blockInfo.sIdx += blockInfo.validSeqCnt; + if (blockInfo.sIdx == blockInfo.bSeqUsed) { + blockInfo.sIdx = 0; + do { + if (blockInfo.bIdx > constInfo_.batchSize) { + break; + } + blockInfo.bIdx++; + blockInfo.bSeqUsed = GetSeqUsed(blockInfo.bIdx); + blockInfo.bStartPos = GetStartPos(blockInfo.bIdx); + } while (blockInfo.bSeqUsed == 0); + } + if (blockInfo.dealSeqSize == 0) { + return; + } + } else { + if (blockInfo.dealSeqSize == 0) { + return; + } + blockInfo.bSeqUsed = GetSeqUsed(blockInfo.bIdx); + // 如果S=0,跳B + while (blockInfo.bSeqUsed == 0) { + if (blockInfo.bIdx > constInfo_.batchSize) { + break; + } + blockInfo.bIdx++; + blockInfo.bSeqUsed = GetSeqUsed(blockInfo.bIdx); + } + blockInfo.bStartPos = GetStartPos(blockInfo.bIdx); + blockInfo.isFirst = false; + } + + // 计算头部占位行数、有效数据行数、尾部占位行数 + blockInfo.headHolderSeqCnt = + (blockInfo.bStartPos + blockInfo.sIdx) % constInfo_.cmpRatio; + blockInfo.validSeqCnt = blockInfo.bSeqUsed - blockInfo.sIdx; + if (blockInfo.headHolderSeqCnt + blockInfo.validSeqCnt > + blockInfo.dealSeqSize) { + blockInfo.validSeqCnt = blockInfo.dealSeqSize - blockInfo.headHolderSeqCnt; + } + blockInfo.tailHolderSeqCnt = + constInfo_.cmpRatio - + (blockInfo.bStartPos + blockInfo.sIdx + blockInfo.validSeqCnt) % + constInfo_.cmpRatio; + if (blockInfo.tailHolderSeqCnt == constInfo_.cmpRatio) { + blockInfo.tailHolderSeqCnt = 0; + } + + // 计算本次可以处理的Tc个数 + blockInfo.dealTcSize = (blockInfo.headHolderSeqCnt + blockInfo.validSeqCnt + + blockInfo.tailHolderSeqCnt) / + constInfo_.cmpRatio; + + // 因为是一个batch的数据, 只有最后一个压缩块才可能不需要压缩, + // 此时blockInfo.tailHolderSeqCnt > 0 + blockInfo.compressTcSize = blockInfo.dealTcSize; + if (blockInfo.tailHolderSeqCnt > 0) { + blockInfo.compressTcSize = + blockInfo.dealTcSize - 1; // 最后一个压缩块不满时,其不需要压缩 + } + + // 更新剩余未处理的行数 + blockInfo.dealSeqSize -= blockInfo.headHolderSeqCnt + blockInfo.validSeqCnt + + blockInfo.tailHolderSeqCnt; +} + +template +__aicore__ inline void CompressorBlockVector::DealVec1BaseBlock( + const RunInfo& info, + BlockInfo& blockInfo, + uint32_t startTcIdx, + uint32_t dStartIdx, + uint32_t dDealSize) { + while (blockInfo.dealSeqSize > 0) { + UpdateBlockInfo(blockInfo); + + LocalTensor scoreLocal = tmpBuff1.Get(); + PipeBarrier(); + OverLapScore( + scoreLocal, startTcIdx, blockInfo.dealTcSize, dStartIdx, dDealSize); + + LocalTensor apeUb = inputQue1.AllocTensor(); + CopyInApe(apeUb, dStartIdx, dDealSize); + inputQue1.EnQue(apeUb); + inputQue1.DeQue(); + + PipeBarrier(); + AddApeToScore(scoreLocal, apeUb, blockInfo.dealTcSize, dDealSize); + inputQue1.FreeTensor(apeUb); + + LocalTensor kvLocal = tmpBuff2.Get(); + OverLapKv(kvLocal, startTcIdx, blockInfo.dealTcSize, dStartIdx, dDealSize); + + UpdateState( + kvLocal, scoreLocal, startTcIdx, blockInfo, dStartIdx, dDealSize); + + if (blockInfo.compressTcSize > 0) { + PipeBarrier(); + SoftmaxDN(scoreLocal, blockInfo.compressTcSize, dDealSize); + + LocalTensor comporessedUb = outputQue1.AllocTensor(); + PipeBarrier(); + KvMulReduceScore(kvLocal, + scoreLocal, + comporessedUb, + blockInfo.compressTcSize, + dDealSize); + outputQue1.EnQue(comporessedUb); + outputQue1.DeQue(); + CopyOutVec1Res( + info, comporessedUb, blockInfo.compressTcSize, dStartIdx, dDealSize); + outputQue1.FreeTensor(comporessedUb); + } + + compressedCnt_ += blockInfo.compressTcSize; + startTcIdx += blockInfo.dealTcSize; + } +} + +template +__aicore__ inline void CompressorBlockVector::ComputeVec1( + const RunInfo& info) { + // 计算当前VecCore的任务量 + uint32_t dealTcStartIdx = 0; + uint32_t dealTcSize = 128 / constInfo_.cmpRatio; + if (dealTcSize > info.dealTcNum) { + dealTcSize = info.dealTcNum; + } + if (GetBlockIdx() % 2 == 1) { + dealTcStartIdx = dealTcSize; + dealTcSize = info.dealTcNum - dealTcSize; + } + if (dealTcSize == 0) { + return; + } + + // 刷新当前VecCore的起始bIdx和sIdx + uint32_t curBStart = info.bStart; + uint32_t curSStart = info.sStart; + uint32_t curCompressedCnt = 0; + if (GetBlockIdx() % 2 == 1) { + BlockInfo blockInfo(info.bStart, info.sStart, 0); + blockInfo.dealSeqSize = dealTcStartIdx * constInfo_.cmpRatio; + while (blockInfo.dealSeqSize > 0) { + UpdateBlockInfo(blockInfo); + curCompressedCnt += blockInfo.compressTcSize; + } + // 因为需要获取本次完成后的bIdx和sIdx, 所以这里再调用一次 + UpdateBlockInfo(blockInfo); + curBStart = blockInfo.bIdx; + curSStart = blockInfo.sIdx; + } + + // 计算headDim和Tc方向切分大小 + constexpr uint32_t BASE_BLOCK_ELEMENT_NUM = BUFFER_SIZE_BYTE_32K / sizeof(T); + uint32_t maxDealColNum = + BASE_BLOCK_ELEMENT_NUM / (constInfo_.cmpRatio * (uint32_t)COMP::coff); + + uint32_t tcSplitSize = 0; + uint32_t dSplitSize = 0; + uint32_t dLoopCount = 0; + if (maxDealColNum < constInfo_.dBaseSize) { + tcSplitSize = 1; + dLoopCount = (constInfo_.dBaseSize + maxDealColNum - 1) / maxDealColNum; + dSplitSize = constInfo_.dBaseSize / dLoopCount; + } else { + dSplitSize = constInfo_.dBaseSize; + dLoopCount = 1; + tcSplitSize = maxDealColNum / constInfo_.dBaseSize; + } + + // 切块循环 + for (uint32_t dLoopIdx = 0; dLoopIdx < dLoopCount; dLoopIdx++) { + BlockInfo blockInfo(curBStart, curSStart, 0); + uint32_t actDealTcSize = tcSplitSize; + compressedCnt_ = curCompressedCnt; + for (uint32_t tcIdx = 0; tcIdx < dealTcSize; tcIdx += tcSplitSize) { + if (tcIdx + tcSplitSize > dealTcSize) { + actDealTcSize = dealTcSize - tcIdx; + } + // 处理单个切块 + blockInfo.dealSeqSize = actDealTcSize * constInfo_.cmpRatio; + DealVec1BaseBlock( + info, blockInfo, tcIdx, dLoopIdx * dSplitSize, dSplitSize); + } + } +} + +template +__aicore__ inline void CompressorBlockVector::ComputeVec2( + const XllmKernelCompressor::RunInfo& info) { + SplitCoreV2(info); + uint32_t vec2DealM = v2TcEndIdx - v2TcStartIdx; + uint32_t loopCount = (vec2DealM + v2MBaseSize - 1) / v2MBaseSize; + for (uint32_t v2LoopIdx = 0, dealSize = v2MBaseSize; v2LoopIdx < loopCount; + ++v2LoopIdx) { + if (v2LoopIdx == loopCount - 1) { + dealSize = vec2DealM - v2LoopIdx * v2MBaseSize; + } + DealVec2BaseBlock(info, v2TcStartIdx + v2LoopIdx * v2MBaseSize, dealSize); + } + v2TcStartIdx = 0; + v2TcEndIdx = 0; +} + +template +__aicore__ inline void CompressorBlockVector::DealVec2BaseBlock( + const XllmKernelCompressor::RunInfo& info, + uint32_t startRow, + uint32_t dealRowCount) { + uint32_t computeSize = dealRowCount * constInfo_.headDim; + int64_t inGmOffset = startRow * constInfo_.headDim; + // CopyIn + LocalTensor vec1ResUb = inputQue1.AllocTensor(); + DataCopy(vec1ResUb, vec2InputGm_[inGmOffset], computeSize); + inputQue1.EnQue(vec1ResUb); + inputQue1.DeQue(); + + // RmsNorm + LocalTensor normResUb = tmpBuff2.Get(); + PipeBarrier(); + RmsNorm(vec1ResUb, normWeightUb, normResUb, info, dealRowCount); + inputQue1.FreeTensor(vec1ResUb); + + // rope: 只对后RD进行rope; 将normResUb每行前headDim - + // ropeHeadDim个元素cast到X_T,然后再与rope后的结果组合存到outputUb + LocalTensor outputUb = outputQue1.AllocTensor(); + PipeBarrier(); + CalRope(info, outputUb, normResUb, startRow - v2TcStartIdx, dealRowCount); + PipeBarrier(); + // CopyOut + outputQue1.EnQue(outputUb); + outputQue1.DeQue(); + CopyFinalResultOut(info, outputUb, startRow - v2TcStartIdx, dealRowCount); + outputQue1.FreeTensor(outputUb); +} + +template +__aicore__ inline void CompressorBlockVector::RmsNorm( + LocalTensor& vec1ResUb, + LocalTensor& normWeightUb, + LocalTensor& normResUb, + const XllmKernelCompressor::RunInfo& info, + uint32_t dealRowCount) { + uint32_t row = 1; + uint32_t col = constInfo_.headDim; + float reciprocal = 1.0f / col; + float epsilon = constInfo_.normEps; + for (uint32_t i = 0; i < dealRowCount; ++i) { + RmsNormVF(normResUb[i * col], + vec1ResUb[i * col], + normWeightUb, + reciprocal, + epsilon, + row, + col); + } +} + +template +__aicore__ inline void CompressorBlockVector::CalRope( + const XllmKernelCompressor::RunInfo& info, + LocalTensor& outputUb, + LocalTensor& normResUb, + uint32_t startRow, + uint32_t dealRowCount) { + uint32_t normNum = constInfo_.headDim - constInfo_.ropeHeadDim; + // 将normal部分cast成X_T + uint64_t mask = REPEAT_BLOCK_BYTE / sizeof(T); // 每个迭代处理64个元素 + uint8_t repeatTime = normNum / mask; // norm部分迭代次数,rope部分不做处理 + for (uint32_t i = 0; i < dealRowCount; i++) { + Cast(outputUb[i * constInfo_.headDim], + normResUb[i * constInfo_.headDim], + RoundMode::CAST_ROUND, + mask, + repeatTime, + {1, 1, 4, 8}); + } + + uint32_t bStartIdx = OutputBStartIdx; + uint32_t sStartIdx = OutputSStartIdx; + uint64_t globalScStart = 0; + CalcGlobalScStart(0, 0, bStartIdx, sStartIdx, globalScStart); + uint32_t dealScSize = dealRowCount; + uint32_t curDealScSize = 0; + uint32_t ubProcessedCount = 0; + uint32_t preOutputBStartIdx = 0; + uint32_t preOutputSStartIdx = 0; + while (dealScSize > 0) { + preOutputBStartIdx = bStartIdx; + preOutputSStartIdx = sStartIdx; + UpdateOutputIdx(bStartIdx, sStartIdx, dealScSize, curDealScSize); + + uint32_t computeSize = curDealScSize * constInfo_.ropeHeadDim; + int64_t SinCosOffset = globalScStart * constInfo_.ropeHeadDim; + LocalTensor tmpRopeInUb = tmpBuff1.Get(); + uint32_t offset = computeSize * sizeof(T); + LocalTensor tmpRopeOutUb = + tmpBuff1.GetWithOffset(computeSize, offset); + offset += computeSize * sizeof(X_T); + + // 分离rope部分 + DataCopyParams ropeCopyParams; + ropeCopyParams.blockCount = static_cast(curDealScSize); + ropeCopyParams.blockLen = static_cast( + constInfo_.ropeHeadDim * sizeof(T) / DATABLOCK_BYTES); + ropeCopyParams.srcStride = + static_cast(normNum * sizeof(T) / DATABLOCK_BYTES); + ropeCopyParams.dstStride = 0; + DataCopy(tmpRopeInUb, + normResUb[normNum + (dealRowCount - dealScSize - curDealScSize) * + constInfo_.headDim], + ropeCopyParams); + + // sin与cos各占一半, 实际分别最多只会用8K,总占用16K + LocalTensor sinUb = inputQue1.AllocTensor(); + LocalTensor cosUb = + sinUb[BLOCK_VEC_BASE_BUFFER_SIZE / 2 / sizeof(X_T)]; + DataCopy(sinUb, ropeSinGm_[SinCosOffset], computeSize); + DataCopy(cosUb, ropeCosGm_[SinCosOffset], computeSize); + inputQue1.EnQue(sinUb); + inputQue1.DeQue(); + + if constexpr (COMP::rotaryMode == ROTARY_MODE::INTERLEAVE) { + PipeBarrier(); + InterleaveModeVF(sinUb, + cosUb, + tmpRopeInUb, + tmpRopeOutUb, + constInfo_.ropeHeadDim, + curDealScSize, + 1); + PipeBarrier(); + } else { + PipeBarrier(); + HalfAlignVF(sinUb, + cosUb, + tmpRopeInUb, + tmpRopeOutUb, + constInfo_.ropeHeadDim, + curDealScSize, + 1); + PipeBarrier(); + } + inputQue1.FreeTensor(sinUb); + // normal部分和rope拼接,并搬到outputub + ropeCopyParams.blockCount = curDealScSize; + ropeCopyParams.blockLen = static_cast( + constInfo_.ropeHeadDim * sizeof(X_T) / DATABLOCK_BYTES); + ropeCopyParams.srcStride = 0; + ropeCopyParams.dstStride = + static_cast(normNum * sizeof(X_T) / DATABLOCK_BYTES); + DataCopy(outputUb[normNum + (dealRowCount - dealScSize - curDealScSize) * + constInfo_.headDim], + tmpRopeOutUb, + ropeCopyParams); + + CalcGlobalScStart(preOutputBStartIdx, + preOutputSStartIdx, + bStartIdx, + sStartIdx, + globalScStart); + ubProcessedCount += curDealScSize; + } +} + +template +__aicore__ inline void CompressorBlockVector::SplitCoreV2( + const XllmKernelCompressor::RunInfo& info) { + // 累积N个基本块数据后做vec2,N=2,传入的RunInfo包含该组核处理的数据块的bStart、bEnd、sStart、sEnd以及dealTcCount; + // 每组核切M方向将C1/V1后的数据分8 * 2个vec核上进行V2计算 + // 每次进行v2计算都会根据当前情况将workspace中的每组核处理的数据重新分到当前组的vec核 + + // Input: + // syncAll前每组cube核处理的实际数据块在batch及s方向的起止idx及实际数据量(m方向) + // Output: 每个vec核的处理数据块在m方向的起止位置及输出到Gm上的起始位置 + uint32_t coreNum = constInfo_.dBasicBlockNum * 2; // 组中有多少个vec核:16 + usedCoreNum = coreNum; + uint32_t currCoreIdx = GetBlockIdx(); // 当前vec核ID + uint32_t curVecCoreGroupIdx = currCoreIdx / coreNum; // 当前vec核所在组ID + vec1ResGmStart = curVecCoreGroupIdx * constInfo_.nSize * + constInfo_.tcBaseSize * constInfo_.headDim; + // 1.计算总vec2基本块数量 + uint64_t totalBaseNum = info.dealScSize; // 当前组核累积的实际数据量 + // 2.每个vec核上分到的数据量 + uint32_t avgBaseNum = 1; + if (totalBaseNum > coreNum) { + avgBaseNum = (totalBaseNum + coreNum - 1) / coreNum; + } else { + usedCoreNum = totalBaseNum; + } + if (currCoreIdx % coreNum >= usedCoreNum) { + return; + } + // 3.计算每个vec核的起始结束位置 + uint32_t accumBaseNum = 0; // 当前累积的基本块数 + uint32_t targetBaseNum = (currCoreIdx % coreNum + 1) * + avgBaseNum; // 当前vec核目标要达到的基本块数量 + uint32_t targetStartBaseNum = + targetBaseNum - avgBaseNum; // 分当前vec核时前面已经完成分核的基本块数量 + bool setStart = false; + for (uint32_t i = 0; i < totalBaseNum; ++i) { + if (accumBaseNum >= totalBaseNum) { + return; + } + accumBaseNum += 1; + if (!setStart && (accumBaseNum > targetStartBaseNum)) { + v2TcStartIdx = i; + setStart = true; + } + if (setStart && + (accumBaseNum >= targetBaseNum || i == (totalBaseNum - 1))) { + // 更新当前核的End分核信息 + v2TcEndIdx = i + 1; + GetScIdxInfo(info.bStart, + info.scStart, + info.dealScSize, + v2TcStartIdx, + v2TcEndIdx, + OutputBStartIdx, + OutputSStartIdx, + OutputSize); + return; + } + } +} + +template +__aicore__ inline void CompressorBlockVector::CalcGlobalScStart( + uint32_t bStart, + uint32_t scStart, + uint32_t bEnd, + uint32_t scEnd, + uint64_t& globalScStart) { + for (uint32_t bIdx = bStart; bIdx < bEnd; ++bIdx) { + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + curActSeqLength_ = GetSeqLength(bIdx); + curStartPos_ = GetStartPos(bIdx); + globalScStart += GetScSize(); + } else { + curActSeqLength_ = constInfo_.sSize; + globalScStart += + (curActSeqLength_ + constInfo_.cmpRatio - 1) / constInfo_.cmpRatio; + } + } + globalScStart -= scStart; + globalScStart += scEnd; +} + +template +__aicore__ inline void CompressorBlockVector::UpdateOutputIdx( + uint32_t& outputBStart, + uint32_t& outputSStart, + uint32_t& dealScSize, + uint32_t& curDealScSize) { + curActSeqLength_ = GetSeqLength(outputBStart); + curStartPos_ = GetStartPos(outputBStart); + uint32_t curBatchScSize = + (curStartPos_ + curActSeqLength_) / constInfo_.cmpRatio - + curStartPos_ / constInfo_.cmpRatio; + uint32_t curBatchRemainScSize = curBatchScSize - outputSStart; + curDealScSize = + curBatchRemainScSize > dealScSize ? dealScSize : curBatchRemainScSize; + dealScSize -= curDealScSize; + outputSStart += curDealScSize; + if (outputSStart == curBatchScSize) { + outputBStart++; + outputSStart = 0; + } +} + +template +__aicore__ inline void CompressorBlockVector::CopyFinalResultOut( + const XllmKernelCompressor::RunInfo& info, + const LocalTensor& cmpKvOutUb, + uint32_t startRow, + uint32_t dealRowCount) { + uint64_t globalScStart = 0; + CalcGlobalScStart(0, 0, OutputBStartIdx, OutputSStartIdx, globalScStart); + uint64_t outOffset = globalScStart * constInfo_.headDim; + uint32_t copySize = dealRowCount * constInfo_.headDim; + + uint32_t dealScSize = dealRowCount; + uint32_t curDealScSize = 0; + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + DataCopy(cmpKvOutGm_[outOffset], cmpKvOutUb, copySize); + while (dealScSize > 0) { + UpdateOutputIdx( + OutputBStartIdx, OutputSStartIdx, dealScSize, curDealScSize); + } + } else { + // 处理BSH有效数据在内存上不连续(可能存在pad) + uint32_t ubProcessedCount = 0; + uint32_t preOutputBStartIdx = 0; + uint32_t preOutputSStartIdx = 0; + while (dealScSize > 0) { + // 逐batch计算写出索引 + preOutputBStartIdx = OutputBStartIdx; + preOutputSStartIdx = OutputSStartIdx; + UpdateOutputIdx( + OutputBStartIdx, OutputSStartIdx, dealScSize, curDealScSize); + DataCopy(cmpKvOutGm_[globalScStart * constInfo_.headDim], + cmpKvOutUb[ubProcessedCount * constInfo_.headDim], + curDealScSize * constInfo_.headDim); + CalcGlobalScStart(preOutputBStartIdx, + preOutputSStartIdx, + OutputBStartIdx, + OutputSStartIdx, + globalScStart); + ubProcessedCount += curDealScSize; + } + } +} +} // namespace XllmKernelCompressor +#endif // COMPRESSOR_BLOCK_VECTOR_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_add.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_add.h new file mode 100644 index 0000000000..e2f899ddc4 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_add.h @@ -0,0 +1,75 @@ +/** + * 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 vf_add.h + * \brief + */ + +#ifndef VF_ADD_H +#define VF_ADD_H + +#include "kernel_operator.h" +using namespace AscendC; +constexpr uint32_t FLOAT_REP_SIZE = 64; +constexpr uint32_t BTYEALIGNSIZE = 32; +constexpr uint32_t REGSIZE = 256; +constexpr uint32_t HALFCORED = 128; + +/*apeOffset —— ape的偏移 + loopCnt —— r行循环次数 + count —— regtensor上的元素数 + + +*/ +template +__simd_vf__ void AddVFImpl(__ubuf__ T* inputAddr, + __ubuf__ T* apeAddr, + const uint16_t coreSplitD, + const uint16_t loopCnt) { + MicroAPI::RegTensor vreg0; + MicroAPI::RegTensor vregape0; + MicroAPI::MaskReg mask = + MicroAPI::CreateMask(); + for (uint16_t loop = 0; loop < loopCnt; loop++) { + MicroAPI::LoadAlign(vreg0, inputAddr + loop * FLOAT_REP_SIZE); + MicroAPI::LoadAlign(vregape0, apeAddr + loop * FLOAT_REP_SIZE); + MicroAPI::Add(vreg0, vreg0, vregape0, mask); + MicroAPI::StoreAlign(inputAddr + loop * FLOAT_REP_SIZE, vreg0, mask); + } +} + +/** + * @brief AddVF 输入与apt相加 + * @param rightLocal 输出tensor [] + * @param leftLocal 输入tensor [row, col] + * @param aptLocal apt输入tensor [r] + * @param apeIdx ape起始位置 + * @param d coff*d为ape的D轴大小 + * @param coreSplitD scoreleft大小,coff*coreSplitD为总大小 + * @param coreSplitS 核间d轴切分大小 + */ +template +__aicore__ inline void AddVF(LocalTensor& scoreLocal, + LocalTensor& apeLocal, + uint16_t apeIdx, + const uint16_t coff, + const uint16_t coreSplitD, + uint32_t coreSplitS) { + uint16_t loopCnt = coff * coreSplitD * coreSplitS / FLOAT_REP_SIZE; + + __ubuf__ T* scoreAddr = (__ubuf__ T*)scoreLocal.GetPhyAddr(); + __ubuf__ T* apeAddr = (__ubuf__ T*)apeLocal.GetPhyAddr() + apeIdx; + + AddVFImpl(scoreAddr, apeAddr, coreSplitD, loopCnt); +} + +#endif diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_mul.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_mul.h new file mode 100644 index 0000000000..1848ccb944 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_mul.h @@ -0,0 +1,154 @@ +/** + * 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 vf_mul.h + * \brief + */ + +#ifndef VF_MUL_H +#define VF_MUL_H +#include "kernel_operator.h" +using namespace AscendC; + +constexpr uint32_t FLOATBYTE = 4; +constexpr uint32_t baseD32 = 32; +constexpr uint32_t baseD64 = 64; +constexpr uint32_t baseD128 = 128; + +template +__simd_vf__ void MulReduceSumbase32VFImpl(__ubuf__ T* kvAddr, + __ubuf__ T* scoreAddr, + __ubuf__ T* outputAddr, + const uint16_t coff, + const uint16_t r, + const uint16_t scLoopCnt, + const uint16_t baseD) { + MicroAPI::RegTensor vreg0; + MicroAPI::RegTensor vreg1; + MicroAPI::RegTensor vregSum; + MicroAPI::MaskReg maskHalf = + MicroAPI::CreateMask(); + uint32_t count = baseD; + for (uint16_t scLoop = 0; scLoop < scLoopCnt; scLoop++) { + MicroAPI::Duplicate(vregSum, 0, maskHalf); + for (uint16_t rLoop = 0; rLoop < coff * r; rLoop++) { + MicroAPI::LoadAlign(vreg0, kvAddr + rLoop * baseD); + MicroAPI::LoadAlign(vreg1, scoreAddr + rLoop * baseD); + MicroAPI::Mul(vreg0, vreg0, vreg1, maskHalf); + MicroAPI::Add(vregSum, vregSum, vreg0, maskHalf); + } + MicroAPI::StoreAlign(outputAddr + scLoop * baseD, vregSum, maskHalf); + } +} + +template +__simd_vf__ void MulReduceSumbase64VFImpl(__ubuf__ T* kvAddr, + __ubuf__ T* scoreAddr, + __ubuf__ T* outputAddr, + const uint16_t coff, + const uint16_t r, + const uint16_t scLoopCnt, + const uint16_t baseD) { + MicroAPI::RegTensor vreg0; + MicroAPI::RegTensor vreg1; + MicroAPI::RegTensor vregMul; + MicroAPI::RegTensor vregSum; + MicroAPI::MaskReg mask = + MicroAPI::CreateMask(); + uint32_t offset = 0; + for (uint16_t scLoop = 0; scLoop < scLoopCnt; scLoop++) { + MicroAPI::Duplicate(vregSum, 0, mask); + for (uint16_t rLoop = 0; rLoop < coff * r; rLoop++) { + MicroAPI::LoadAlign(vreg0, kvAddr + offset); + MicroAPI::LoadAlign(vreg1, scoreAddr + offset); + MicroAPI::Mul(vregMul, vreg0, vreg1, mask); + MicroAPI::Add(vregSum, vregSum, vregMul, mask); + offset += baseD; + } + MicroAPI::StoreAlign(outputAddr + scLoop * baseD, vregSum, mask); + } +} + +template +__simd_vf__ void MulReduceSumbase128VFImpl(__ubuf__ T* kvAddr, + __ubuf__ T* scoreAddr, + __ubuf__ T* outputAddr, + const uint16_t coff, + const uint16_t r, + const uint16_t scLoopCnt, + const uint16_t baseD) { + MicroAPI::RegTensor vreg00; + MicroAPI::RegTensor vreg01; + MicroAPI::RegTensor vreg10; + MicroAPI::RegTensor vreg11; + MicroAPI::RegTensor vregMul0; + MicroAPI::RegTensor vregMul1; + MicroAPI::RegTensor vregSum0; + MicroAPI::RegTensor vregSum1; + MicroAPI::MaskReg mask = + MicroAPI::CreateMask(); + uint32_t offset = 0; + for (uint32_t scLoop = 0; scLoop < scLoopCnt; scLoop++) { + MicroAPI::Duplicate(vregSum0, 0, mask); + MicroAPI::Duplicate(vregSum1, 0, mask); + for (uint32_t rLoop = 0; rLoop < coff * r; rLoop++) { + MicroAPI::LoadAlign(vreg00, kvAddr + offset); + MicroAPI::LoadAlign(vreg01, kvAddr + offset + baseD64); + MicroAPI::LoadAlign(vreg10, scoreAddr + offset); + MicroAPI::LoadAlign(vreg11, scoreAddr + offset + baseD64); + MicroAPI::Mul(vregMul0, vreg00, vreg10, mask); + MicroAPI::Mul(vregMul1, vreg01, vreg11, mask); + MicroAPI::Add(vregSum0, vregSum0, vregMul0, mask); + MicroAPI::Add(vregSum1, vregSum1, vregMul1, mask); + offset += baseD; + } + MicroAPI::StoreAlign(outputAddr + scLoop * baseD, vregSum0, mask); + MicroAPI::StoreAlign(outputAddr + baseD64 + scLoop * baseD, vregSum1, mask); + } +} + +/** + * @brief MulReduceSumbaseVF 包含mul和reducesum + * @param outputLocal 输出tensor [] + * @param r s方向的最小块 + * @param sc r个sc + * @param baseD 核内d轴切分大小 + * @param baseS 行数, + */ + +template +__aicore__ inline void MulReduceSumbaseVF(LocalTensor& kvLocal, + LocalTensor& scoreLocal, + LocalTensor& outputLocal, + const uint16_t coff, + const uint16_t r, + uint32_t outIdx, + const uint16_t baseD, + const uint32_t baseS) { + uint32_t scLoopCnt = baseS / r; + + __ubuf__ T* kvAddr = (__ubuf__ T*)kvLocal.GetPhyAddr(); + __ubuf__ T* scoreAddr = (__ubuf__ T*)scoreLocal.GetPhyAddr(); + __ubuf__ T* outputAddr = (__ubuf__ T*)outputLocal.GetPhyAddr() + outIdx; + if (baseD == baseD32) { + MulReduceSumbase32VFImpl( + kvAddr, scoreAddr, outputAddr, coff, r, scLoopCnt, baseD); + } else if (baseD == baseD64) { + MulReduceSumbase64VFImpl( + kvAddr, scoreAddr, outputAddr, coff, r, scLoopCnt, baseD); + } else if (baseD == baseD128) { + MulReduceSumbase128VFImpl( + kvAddr, scoreAddr, outputAddr, coff, r, scLoopCnt, baseD); + } +} + +#endif \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_rms_norm.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_rms_norm.h new file mode 100644 index 0000000000..3f154762d0 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_rms_norm.h @@ -0,0 +1,122 @@ +/** + * 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 vf_rms_norm.h + * \brief + */ + +#ifndef VF_RMS_NORM_H +#define VF_RMS_NORM_H +#include "kernel_tensor.h" + +// repeatTimes——D轴的分块数 +template +__simd_vf__ void RmsNormVFImpl(__ubuf__ T* inputBuf, + __ubuf__ GammaType* gammaBuf, + __ubuf__ T* outputBuf, + uint32_t repeatTimes, + float reciprocal, + float epsilon) { + MicroAPI::RegTensor vregSum; + MicroAPI::RegTensor vregSumReduce; + MicroAPI::RegTensor vregDiv; + MicroAPI::RegTensor vregSquareRoot; + + MicroAPI::MaskReg maskAll = + MicroAPI::CreateMask(); + MicroAPI::MaskReg maskFirst = + MicroAPI::CreateMask(); + + static constexpr MicroAPI::CastTrait castTraitB162B32 = { + MicroAPI::RegLayout::ZERO, + MicroAPI::SatMode::UNKNOWN, + MicroAPI::MaskMergeMode::ZEROING, + RoundMode::UNKNOWN}; + + MicroAPI::Duplicate(vregSum, 0.0f); + + for (uint32_t i = 0; i < repeatTimes; ++i) { + MicroAPI::RegTensor vregX; + MicroAPI::RegTensor vregXSquare; + uint64_t loopOffset = i * FLOAT_REP_SIZE; + + MicroAPI::LoadAlign( + vregX, inputBuf + loopOffset); + MicroAPI::Mul(vregXSquare, vregX, vregX, maskAll); + MicroAPI::Add(vregSum, vregXSquare, vregSum, maskAll); + } + + MicroAPI:: + Reduce( + vregSumReduce, vregSum, maskAll); + MicroAPI::Muls( + vregSumReduce, vregSumReduce, reciprocal, maskFirst); + MicroAPI::Adds( + vregSumReduce, vregSumReduce, epsilon, maskFirst); + MicroAPI::Sqrt(vregSquareRoot, vregSumReduce, maskFirst); + MicroAPI::Duplicate( + vregDiv, vregSquareRoot, maskAll); + + for (uint32_t i = 0; i < repeatTimes; ++i) { + MicroAPI::RegTensor vregX; + MicroAPI::RegTensor vregGamma; + MicroAPI::RegTensor vregGammaCast; + uint16_t loopOffset = i * FLOAT_REP_SIZE; + + MicroAPI::LoadAlign( + vregX, inputBuf + loopOffset); + MicroAPI::LoadAlign( + vregGamma, gammaBuf + loopOffset); + MicroAPI::Cast( + vregGammaCast, vregGamma, maskAll); + + MicroAPI::Div(vregX, vregX, vregDiv, maskAll); + MicroAPI::Mul(vregX, vregX, vregGammaCast, maskAll); + + MicroAPI::StoreAlign( + outputBuf + loopOffset, vregX, maskAll); + } +} + +/** + * @brief RmsNormVF 对一行进行rmsnorm + * @param outputLocal 输出tensor [row, col],row目前均为1 + * @param inputLocal 输入tensor [row, col] + * @param gammaLocal gamma参数tensor [row, col] + * @param rmsNormParams rmsNrom计算所需系数,包括 + row 行数 1 + col 列数,对应headSizeCq或headSizeCkv + reciprocal ,1/N + epsilon,防止除零极小数 + */ +template +__aicore__ inline void RmsNormVF(LocalTensor outputLocal, + const LocalTensor inputLocal, + const LocalTensor gammaLocal, + float reciprocal, + float epsilon, + uint32_t row, + uint32_t col) { + uint32_t cnt = row * col; + uint32_t repeatTimes = (cnt + FLOAT_REP_SIZE - 1) / FLOAT_REP_SIZE; + + __ubuf__ T* inputBuf = (__ubuf__ T*)inputLocal.GetPhyAddr(); + __ubuf__ GammaType* gammaBuf = (__ubuf__ GammaType*)gammaLocal.GetPhyAddr(); + __ubuf__ T* outputBuf = (__ubuf__ T*)outputLocal.GetPhyAddr(); + + RmsNormVFImpl( + inputBuf, gammaBuf, outputBuf, repeatTimes, reciprocal, epsilon); +} + +#endif \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_rope.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_rope.h new file mode 100644 index 0000000000..2a7228fae8 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_rope.h @@ -0,0 +1,365 @@ +/** + * 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 vf_rope.h + * \brief + */ + +#ifndef VF_ROPE_H +#define VF_ROPE_H + +#include "compressor/op_kernel/compressor_comm.h" +#include "kernel_operator.h" + +using namespace AscendC; + +__aicore__ inline constexpr uint32_t GetVRegSize() { +#if __CCE_AICORE__ == 310 + return VECTOR_REG_WIDTH; +#else + return 256U; +#endif +} + +__aicore__ inline constexpr uint32_t GetUbBlockSize() { return 32U; } + +constexpr MicroAPI::CastTrait castTraitB162B32 = { + MicroAPI::RegLayout::ZERO, + MicroAPI::SatMode::UNKNOWN, + MicroAPI::MaskMergeMode::ZEROING, + RoundMode::UNKNOWN, +}; + +constexpr MicroAPI::CastTrait castTraitB322B16 = { + MicroAPI::RegLayout::ZERO, + MicroAPI::SatMode::NO_SAT, + MicroAPI::MaskMergeMode::ZEROING, + RoundMode::CAST_RINT, +}; + +constexpr uint32_t VL_FLOAT32_SIZE = GetVRegSize() / sizeof(float); +constexpr uint32_t BLOCK_TYPE_SIZE = GetUbBlockSize(); +constexpr uint32_t HALF_INTERLEAVE_COEF = 2; + +// load 2个对齐的Tensor 到寄存器中 +template +__aicore__ inline void LoadTwoTensorForDtypeT(__local_mem__ T* src1, + __local_mem__ T* src2, + MicroAPI::RegTensor& dst1, + MicroAPI::RegTensor& dst2, + MicroAPI::MaskReg& dst1Preg, + MicroAPI::MaskReg& dst2Preg, + uint32_t src1Offset, + uint32_t src2Offset) { + if constexpr (IsSameType::value) { + MicroAPI::RegTensor xFp16Q; + MicroAPI::RegTensor xFp16R; + MicroAPI::DataCopy( + xFp16Q, ((__local_mem__ half*)(src1) + (src1Offset))); + MicroAPI::DataCopy( + xFp16R, ((__local_mem__ half*)(src2) + (src2Offset))); + Cast(dst1, xFp16Q, dst1Preg); + Cast(dst2, xFp16R, dst2Preg); + } else if constexpr (IsSameType::value) { + MicroAPI::RegTensor xFp16Q; + MicroAPI::RegTensor xFp16R; + MicroAPI::DataCopy( + xFp16Q, ((__local_mem__ bfloat16_t*)(src1) + (src1Offset))); + MicroAPI::DataCopy( + xFp16R, ((__local_mem__ bfloat16_t*)(src2) + (src2Offset))); + Cast(dst1, xFp16Q, dst1Preg); + Cast(dst2, xFp16R, dst2Preg); + } else { + MicroAPI::DataCopy(dst1, ((__local_mem__ float*)(src1) + (src1Offset))); + MicroAPI::DataCopy(dst2, ((__local_mem__ float*)(src2) + (src2Offset))); + } +} + +// load 对齐的 bfloat16,float16,bfloat32类型的 input(ub中)数据到 +// float32类型的dst(寄存器)中 +template +__aicore__ inline void LoadOneTensorForDtypeT(__local_mem__ T* input, + MicroAPI::RegTensor& dst, + MicroAPI::MaskReg& preg, + uint32_t offset) { + if constexpr (IsSameType::value) { + MicroAPI::RegTensor xFp16; + MicroAPI::DataCopy( + xFp16, ((__local_mem__ half*)(input) + (offset))); + MicroAPI::Cast(dst, xFp16, preg); + } else if constexpr (IsSameType::value) { + MicroAPI::RegTensor xBf16; + MicroAPI::DataCopy( + xBf16, ((__local_mem__ bfloat16_t*)(input) + (offset))); + Cast(dst, xBf16, preg); + } else { + MicroAPI::DataCopy(dst, ((__local_mem__ float*)(input) + (offset))); + } +} + +// store +// 对齐的float32类型的src(寄存器)数据到output(ub)中,output数据类型支持bfloat16,float16,bfloat32,int32_t,int16_t,int8_t,uint8_t +template +__aicore__ inline void StoreOneTensorForDtypeT(__local_mem__ T* output, + MicroAPI::RegTensor& src, + MicroAPI::MaskReg& preg, + uint32_t offset) { + if constexpr (IsSameType::value) { + MicroAPI::RegTensor yFp16; + MicroAPI::Cast(yFp16, src, preg); + MicroAPI::DataCopy( + ((__local_mem__ half*)output + offset), yFp16, preg); + } else if constexpr (IsSameType::value) { + MicroAPI::RegTensor xBf16; + MicroAPI::Cast(xBf16, src, preg); + MicroAPI::DataCopy( + ((__local_mem__ bfloat16_t*)output + offset), xBf16, preg); + } +} + +template +__aicore__ inline void HalfAlignVF(const LocalTensor& sinTensor, + const LocalTensor& cosTensor, + const LocalTensor& inTensor, + const LocalTensor& outTensor, + uint32_t dLen, + uint16_t currSNum, + uint16_t currDNum) { + __local_mem__ ROPET* sinUb = (__local_mem__ ROPET*)sinTensor.GetPhyAddr(); + __local_mem__ ROPET* cosUb = (__local_mem__ ROPET*)cosTensor.GetPhyAddr(); + __local_mem__ T* inUb = (__local_mem__ T*)inTensor.GetPhyAddr(); + __local_mem__ ROPET* outUb = (__local_mem__ ROPET*)outTensor.GetPhyAddr(); + uint32_t halfD = dLen / HALF_INTERLEAVE_COEF; + + uint32_t dAlign = XllmKernelCompressor::Align( + dLen, static_cast(BLOCK_TYPE_SIZE / sizeof(T))); + uint32_t halfDAlign = XllmKernelCompressor::Align( + halfD, static_cast(BLOCK_TYPE_SIZE / sizeof(T))); + uint16_t repeatTimes = XllmKernelCompressor::CeilDivT(halfD, VL_FLOAT32_SIZE); + __local_mem__ T* currInUb; + __local_mem__ ROPET* currOutUb; + __local_mem__ ROPET* currSinUb; + __local_mem__ ROPET* currCosUb; + + __VEC_SCOPE__ { + MicroAPI::RegTensor vregIn; + MicroAPI::RegTensor vregHalfIn; + MicroAPI::RegTensor vregSin; + MicroAPI::RegTensor vregHalfSin; + MicroAPI::RegTensor vregCos; + MicroAPI::RegTensor vregHalfCos; + MicroAPI::RegTensor vregOut; + MicroAPI::RegTensor vregHalfOut; + MicroAPI::MaskReg preg; + for (uint16_t sIdx = 0; sIdx < currSNum; sIdx++) { + currSinUb = sinUb + sIdx * dAlign; + currCosUb = cosUb + sIdx * dAlign; + for (uint16_t row = 0; row < currDNum; row++) { + currInUb = inUb + (sIdx * currDNum + row) * dAlign; + currOutUb = outUb + (sIdx * currDNum + row) * dAlign; + uint32_t updateCnt = halfD; + for (uint16_t i = 0; i < repeatTimes; i++) { + preg = MicroAPI::UpdateMask(updateCnt); + uint32_t offset = i * VL_FLOAT32_SIZE; + uint32_t halfOffset = offset + halfDAlign; + LoadTwoTensorForDtypeT(currInUb, + currInUb, + vregIn, + vregHalfIn, + preg, + preg, + offset, + halfOffset); + LoadTwoTensorForDtypeT(currSinUb, + currSinUb, + vregSin, + vregHalfSin, + preg, + preg, + offset, + halfOffset); + LoadTwoTensorForDtypeT(currCosUb, + currCosUb, + vregCos, + vregHalfCos, + preg, + preg, + offset, + halfOffset); + + MicroAPI::Mul(vregSin, vregSin, vregHalfIn, preg); + MicroAPI::Mul(vregHalfOut, vregHalfSin, vregIn, preg); + MicroAPI::Mul(vregCos, vregCos, vregIn, preg); + MicroAPI::Sub(vregOut, vregCos, vregSin, preg); + MicroAPI::Mul(vregHalfCos, vregHalfCos, vregHalfIn, preg); + MicroAPI::Add(vregHalfOut, vregHalfOut, vregHalfCos, preg); + + StoreOneTensorForDtypeT(currOutUb, vregOut, preg, offset); + StoreOneTensorForDtypeT( + currOutUb, vregHalfOut, preg, halfOffset); + } + } + } + } +} + +template +__aicore__ inline void InterleaveModeVF(const LocalTensor& sinTensor, + const LocalTensor& cosTensor, + const LocalTensor& inTensor, + const LocalTensor& outTensor, + uint32_t dLen, + uint16_t currSNum, + uint16_t currDNum) { + __local_mem__ ROPET* sinUb = (__local_mem__ ROPET*)sinTensor.GetPhyAddr(); + __local_mem__ ROPET* cosUb = (__local_mem__ ROPET*)cosTensor.GetPhyAddr(); + __local_mem__ T* inUb = (__local_mem__ T*)inTensor.GetPhyAddr(); + __local_mem__ ROPET* outUb = (__local_mem__ ROPET*)outTensor.GetPhyAddr(); + uint16_t repeatTimes = + dLen / + VL_FLOAT32_SIZE; //(每个寄存器256字节,最多存放数据256/4=64element,因此需要使用寄存器的数量) + uint32_t dAlignLen = XllmKernelCompressor::Align( + dLen, static_cast(BLOCK_TYPE_SIZE / sizeof(T))); + // Dlen(8对齐、32/4)RD=64 + uint16_t loopNum = repeatTimes / 2; //(开两个寄存器) + uint32_t tailNum = dLen - loopNum * 2 * VL_FLOAT32_SIZE; //(尾块数据数) + uint16_t tailTwoVL = tailNum / VL_FLOAT32_SIZE; + uint16_t tailOneVL = (tailTwoVL == 1 && tailNum > 0) ? 0 : 1; + uint32_t tailLen = tailNum % VL_FLOAT32_SIZE; + __local_mem__ T* currInUb; + __local_mem__ ROPET* currOutUb; + __local_mem__ ROPET* currSinUb; + __local_mem__ ROPET* currCosUb; + __local_mem__ ROPET* tailSinUb; + __local_mem__ ROPET* tailCosUb; + + __VEC_SCOPE__ { + MicroAPI::RegTensor vregFormerCos; + MicroAPI::RegTensor vregLatterCos; + MicroAPI::RegTensor vregFormerSin; + MicroAPI::RegTensor vregLatterSin; + MicroAPI::RegTensor vregFormerIn; + MicroAPI::RegTensor vregLatterIn; + MicroAPI::RegTensor vregOdd; + MicroAPI::RegTensor vregEven; + MicroAPI::RegTensor vregFormerOut; + MicroAPI::RegTensor vregLatterOut; + MicroAPI::MaskReg pregLoop; + MicroAPI::MaskReg pregTail; + for (uint16_t sIdx = 0; sIdx < currSNum; sIdx++) { // sc轴 + currSinUb = sinUb + sIdx * dAlignLen; + currCosUb = cosUb + sIdx * dAlignLen; + for (uint16_t idxD = 0; idxD < currDNum; idxD++) { // D轴 + uint32_t updateCnt = dLen; + currInUb = + inUb + + (sIdx * currDNum + idxD) * + dAlignLen; // 将后64个element取出,因此对于SC轴上的每行数据, + currOutUb = + outUb + + (sIdx * currDNum + idxD) * + dAlignLen; // 将数据64个element输出到sc轴上每行的最后64位上, + pregLoop = MicroAPI::CreateMask(); + for (uint16_t i = 0; i < loopNum; i++) { // 循环次数 + uint32_t evenOffSet = (i * 2) * VL_FLOAT32_SIZE; // 前64个element + uint32_t oddOffset = evenOffSet + VL_FLOAT32_SIZE; // 后64个element + // 数据拷贝,两个寄存器分别拷贝 + LoadOneTensorForDtypeT( + currInUb, vregFormerIn, pregLoop, evenOffSet); + LoadOneTensorForDtypeT( + currInUb, vregLatterIn, pregLoop, oddOffset); + LoadOneTensorForDtypeT( + currCosUb, vregFormerCos, pregLoop, evenOffSet); + LoadOneTensorForDtypeT( + currCosUb, vregLatterCos, pregLoop, oddOffset); + LoadOneTensorForDtypeT( + currSinUb, vregFormerSin, pregLoop, evenOffSet); + LoadOneTensorForDtypeT( + currSinUb, vregLatterSin, pregLoop, oddOffset); + MicroAPI::Mul(vregFormerCos, vregFormerCos, vregFormerIn, pregLoop); + MicroAPI::Mul(vregLatterCos, vregLatterCos, vregLatterIn, pregLoop); + MicroAPI::DeInterleave( + vregEven, vregOdd, vregFormerIn, vregLatterIn); + // 解交织,将前64个和后64个数据的奇数位数据和偶数位数据分别拿出来,并进行拼接EVEN存放奇数位数据,ODD存放偶数位数据 + MicroAPI::Muls(vregOdd, vregOdd, float(-1.0), pregLoop); + MicroAPI::Interleave( + vregFormerIn, vregLatterIn, vregOdd, vregEven); + // 交织生成与sin相乘的数据 + MicroAPI::Mul(vregFormerSin, vregFormerSin, vregFormerIn, pregLoop); + MicroAPI::Add(vregFormerCos, vregFormerCos, vregFormerSin, pregLoop); + MicroAPI::Mul(vregLatterSin, vregLatterSin, vregLatterIn, pregLoop); + MicroAPI::Add(vregLatterCos, vregLatterCos, vregLatterSin, pregLoop); + // 拷贝输出数据 + StoreOneTensorForDtypeT( + currOutUb, vregFormerCos, pregLoop, evenOffSet); // 前64个元素 + StoreOneTensorForDtypeT( + currOutUb, vregLatterCos, pregLoop, oddOffset); // 后64个元素 + } + + currInUb = inUb + (sIdx * currDNum + idxD) * dAlignLen + + (loopNum * 2 * VL_FLOAT32_SIZE); + currOutUb = outUb + (sIdx * currDNum + idxD) * dAlignLen + + (loopNum * 2 * VL_FLOAT32_SIZE); + tailSinUb = currSinUb + loopNum * 2 * VL_FLOAT32_SIZE; + tailCosUb = currCosUb + loopNum * 2 * VL_FLOAT32_SIZE; + // 尾块大于VL时,读取一个VL,读取尾块 + for (uint16_t i = 0; i < tailTwoVL; i++) { + uint32_t updateCnt = tailLen; + pregTail = MicroAPI::UpdateMask(updateCnt); + LoadOneTensorForDtypeT(currInUb, vregFormerIn, pregLoop, 0); + LoadOneTensorForDtypeT( + currInUb, vregLatterIn, pregTail, VL_FLOAT32_SIZE); + LoadOneTensorForDtypeT(tailCosUb, vregFormerCos, pregLoop, 0); + LoadOneTensorForDtypeT( + tailCosUb, vregLatterCos, pregTail, VL_FLOAT32_SIZE); + LoadOneTensorForDtypeT(tailSinUb, vregFormerSin, pregLoop, 0); + LoadOneTensorForDtypeT( + tailSinUb, vregLatterSin, pregTail, VL_FLOAT32_SIZE); + MicroAPI::Mul(vregFormerCos, vregFormerCos, vregFormerIn, pregLoop); + MicroAPI::Mul(vregLatterCos, vregLatterCos, vregLatterIn, pregTail); + MicroAPI::DeInterleave( + vregEven, vregOdd, vregFormerIn, vregLatterIn); + MicroAPI::Muls(vregOdd, vregOdd, float(-1.0), pregLoop); + MicroAPI::Interleave( + vregFormerIn, vregLatterIn, vregOdd, vregEven); + MicroAPI::Mul(vregFormerSin, vregFormerSin, vregFormerIn, pregLoop); + MicroAPI::Add(vregFormerCos, vregFormerCos, vregFormerSin, pregLoop); + MicroAPI::Mul(vregLatterSin, vregLatterSin, vregLatterIn, pregTail); + MicroAPI::Add(vregLatterCos, vregLatterCos, vregLatterSin, pregTail); + StoreOneTensorForDtypeT(currOutUb, vregFormerCos, pregLoop, 0); + StoreOneTensorForDtypeT( + currOutUb, vregLatterCos, pregTail, VL_FLOAT32_SIZE); + } + + // 尾块小于VL时,只读取VL + for (uint16_t i = 0; i < tailOneVL; i++) { + uint32_t updateCnt = tailLen; + pregTail = MicroAPI::UpdateMask(updateCnt); + LoadOneTensorForDtypeT(currInUb, vregFormerIn, pregTail, 0); + LoadOneTensorForDtypeT(tailCosUb, vregFormerCos, pregTail, 0); + LoadOneTensorForDtypeT(tailSinUb, vregFormerSin, pregTail, 0); + MicroAPI::Mul(vregFormerCos, vregFormerCos, vregFormerIn, pregTail); + MicroAPI::DeInterleave( + vregEven, vregOdd, vregFormerIn, vregLatterIn); + MicroAPI::Muls(vregOdd, vregOdd, float(-1.0), pregTail); + MicroAPI::Interleave( + vregFormerIn, vregLatterIn, vregOdd, vregEven); + MicroAPI::Mul(vregFormerSin, vregFormerSin, vregFormerIn, pregTail); + MicroAPI::Add(vregFormerCos, vregFormerCos, vregFormerSin, pregTail); + StoreOneTensorForDtypeT(currOutUb, vregFormerCos, pregTail, 0); + } + } + } + } +} + +#endif \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_softmax.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_softmax.h new file mode 100644 index 0000000000..3df829df53 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/arch35/vf/vf_softmax.h @@ -0,0 +1,1393 @@ +/** + * 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 vf_softmax.h + * \brief + */ + +#ifndef VF_SOFTMAX_H +#define VF_SOFTMAX_H +#include "kernel_tensor.h" +namespace FaVectorApi { +using AscendC::LocalTensor; +using namespace AscendC; +using namespace MicroAPI; + +template +__simd_vf__ inline void SoftmaxDndBase128(__ubuf__ T* x_softmax, + __ubuf__ float* input_x_local_UB, + const uint32_t RowSize, + const uint32_t ReduceSize, + const uint32_t vScRealSize, + const T minValue) { + RegTensor vreg_x_sum_0_0; + RegTensor vreg_x_sum_1_0; + RegTensor vreg_x_sum_2_0; + RegTensor vreg_x_sum_3_0; + RegTensor vreg_x_sum_0_1; + RegTensor vreg_x_sum_1_1; + RegTensor vreg_x_sum_2_1; + RegTensor vreg_x_sum_3_1; + RegTensor vreg_x_sum_0_2; + RegTensor vreg_x_sum_1_2; + RegTensor vreg_x_sum_2_2; + RegTensor vreg_x_sum_3_2; + RegTensor vreg_x_sum_0_3; + RegTensor vreg_x_sum_1_3; + RegTensor vreg_x_sum_2_3; + RegTensor vreg_x_sum_3_3; + + RegTensor vreg_x_exp_0_0; + RegTensor vreg_x_exp_1_0; + RegTensor vreg_x_exp_2_0; + RegTensor vreg_x_exp_3_0; + RegTensor vreg_x_exp_0_1; + RegTensor vreg_x_exp_1_1; + RegTensor vreg_x_exp_2_1; + RegTensor vreg_x_exp_3_1; + RegTensor vreg_x_exp_0_2; + RegTensor vreg_x_exp_1_2; + RegTensor vreg_x_exp_2_2; + RegTensor vreg_x_exp_3_2; + RegTensor vreg_x_exp_0_3; + RegTensor vreg_x_exp_1_3; + RegTensor vreg_x_exp_2_3; + RegTensor vreg_x_exp_3_3; + + RegTensor vreg_x_f32_0_0; + RegTensor vreg_x_f32_1_0; + RegTensor vreg_x_f32_2_0; + RegTensor vreg_x_f32_3_0; + RegTensor vreg_x_f32_0_1; + RegTensor vreg_x_f32_1_1; + RegTensor vreg_x_f32_2_1; + RegTensor vreg_x_f32_3_1; + RegTensor vreg_x_f32_0_2; + RegTensor vreg_x_f32_1_2; + RegTensor vreg_x_f32_2_2; + RegTensor vreg_x_f32_3_2; + RegTensor vreg_x_f32_0_3; + RegTensor vreg_x_f32_1_3; + RegTensor vreg_x_f32_2_3; + RegTensor vreg_x_f32_3_3; + + RegTensor vreg_x_softmax_0_0; + RegTensor vreg_x_softmax_1_0; + RegTensor vreg_x_softmax_2_0; + RegTensor vreg_x_softmax_3_0; + RegTensor vreg_x_softmax_0_1; + RegTensor vreg_x_softmax_1_1; + RegTensor vreg_x_softmax_2_1; + RegTensor vreg_x_softmax_3_1; + MaskReg preg_all; + MaskReg preg_136; + preg_all = CreateMask(); + uint32_t sreg_92 = static_cast(128ULL); + preg_136 = UpdateMask(sreg_92); + RegTensor src0_0, src1_0, src2_0, src3_0, src0_1, src1_1, src2_1, + src3_1, src0_2, src1_2, src2_2, src3_2, src0_3, src1_3, src2_3, src3_3; + RegTensor max0_0, max1_0, max2_0, max3_0, max0_1, max1_1, max2_1, + max3_1, max0_2, max1_2, max2_2, max3_2, max0_3, max1_3, max2_3, max3_3; + RegTensor vreg_min; + + __ubuf__ float* src_ub0_0 = input_x_local_UB; + __ubuf__ float* src_ub0_1 = input_x_local_UB + RowSize / 2; + __ubuf__ float* src_ub0_2 = input_x_local_UB + RowSize; + __ubuf__ float* src_ub0_3 = input_x_local_UB + RowSize + RowSize / 2; + __ubuf__ float* src_ub1_0 = src_ub0_0 + ReduceSize * RowSize; + __ubuf__ float* src_ub1_1 = src_ub0_0 + ReduceSize * RowSize + RowSize / 2; + __ubuf__ float* src_ub1_2 = src_ub0_0 + ReduceSize * RowSize + RowSize; + __ubuf__ float* src_ub1_3 = + src_ub0_0 + ReduceSize * RowSize + RowSize + RowSize / 2; + __ubuf__ float* src_ub2_0 = src_ub0_0 + ReduceSize * RowSize * 2; + __ubuf__ float* src_ub2_1 = + src_ub0_0 + ReduceSize * RowSize * 2 + RowSize / 2; + __ubuf__ float* src_ub2_2 = src_ub0_0 + ReduceSize * RowSize * 2 + RowSize; + __ubuf__ float* src_ub2_3 = + src_ub0_0 + ReduceSize * RowSize * 2 + RowSize + RowSize / 2; + __ubuf__ float* src_ub3_0 = src_ub0_0 + ReduceSize * RowSize * 3; + __ubuf__ float* src_ub3_1 = + src_ub0_0 + ReduceSize * RowSize * 3 + RowSize / 2; + __ubuf__ float* src_ub3_2 = src_ub0_0 + ReduceSize * RowSize * 3 + RowSize; + __ubuf__ float* src_ub3_3 = + src_ub0_0 + ReduceSize * RowSize * 3 + RowSize + RowSize / 2; + + __ubuf__ float* x_softmax_0_0 = x_softmax; + __ubuf__ float* x_softmax_0_1 = x_softmax + RowSize / 2; + __ubuf__ float* x_softmax_1_0 = x_softmax + (ReduceSize * RowSize); + __ubuf__ float* x_softmax_1_1 = + x_softmax + (ReduceSize * RowSize) + RowSize / 2; + __ubuf__ float* x_softmax_2_0 = x_softmax + (ReduceSize * RowSize * 2); + __ubuf__ float* x_softmax_2_1 = + x_softmax + (ReduceSize * RowSize * 2) + RowSize / 2; + __ubuf__ float* x_softmax_3_0 = x_softmax + (ReduceSize * RowSize * 3); + __ubuf__ float* x_softmax_3_1 = + x_softmax + (ReduceSize * RowSize * 3) + RowSize / 2; + + for (uint16_t iter_sc = 0; iter_sc < uint16_t(vScRealSize / 4); ++iter_sc) { + Duplicate(max0_0, minValue); + Duplicate(max1_0, minValue); + Duplicate(max2_0, minValue); + Duplicate(max3_0, minValue); + Duplicate(max0_1, minValue); + Duplicate(max1_1, minValue); + Duplicate(max2_1, minValue); + Duplicate(max3_1, minValue); + Duplicate(max0_2, minValue); + Duplicate(max1_2, minValue); + Duplicate(max2_2, minValue); + Duplicate(max3_2, minValue); + Duplicate(max0_3, minValue); + Duplicate(max1_3, minValue); + Duplicate(max2_3, minValue); + Duplicate(max3_3, minValue); + + Duplicate( + vreg_x_sum_0_0, 0, preg_all); + Duplicate( + vreg_x_sum_1_0, 0, preg_all); + Duplicate( + vreg_x_sum_2_0, 0, preg_all); + Duplicate( + vreg_x_sum_3_0, 0, preg_all); + Duplicate( + vreg_x_sum_0_1, 0, preg_all); + Duplicate( + vreg_x_sum_1_1, 0, preg_all); + Duplicate( + vreg_x_sum_2_1, 0, preg_all); + Duplicate( + vreg_x_sum_3_1, 0, preg_all); + Duplicate( + vreg_x_sum_0_2, 0, preg_all); + Duplicate( + vreg_x_sum_1_2, 0, preg_all); + Duplicate( + vreg_x_sum_2_2, 0, preg_all); + Duplicate( + vreg_x_sum_3_2, 0, preg_all); + Duplicate( + vreg_x_sum_0_3, 0, preg_all); + Duplicate( + vreg_x_sum_1_3, 0, preg_all); + Duplicate( + vreg_x_sum_2_3, 0, preg_all); + Duplicate( + vreg_x_sum_3_3, 0, preg_all); + for (uint16_t iter_m = 0; iter_m < uint16_t(ReduceSize / 2); ++iter_m) { + LoadAlign(src0_0, + src_ub0_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src0_1, + src_ub0_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src0_2, + src_ub0_2 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src0_3, + src_ub0_3 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + LoadAlign(src1_0, + src_ub1_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src1_1, + src_ub1_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src1_2, + src_ub1_2 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src1_3, + src_ub1_3 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + LoadAlign(src2_0, + src_ub2_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src2_1, + src_ub2_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src2_2, + src_ub2_2 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src2_3, + src_ub2_3 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + LoadAlign(src3_0, + src_ub3_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src3_1, + src_ub3_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src3_2, + src_ub3_2 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src3_3, + src_ub3_3 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + Max(max0_0, max0_0, src0_0, preg_all); + Max(max0_1, max0_1, src0_1, preg_all); + Max(max0_2, max0_2, src0_2, preg_all); + Max(max0_3, max0_3, src0_3, preg_all); + Max(max1_0, max1_0, src1_0, preg_all); + Max(max1_1, max1_1, src1_1, preg_all); + Max(max1_2, max1_2, src1_2, preg_all); + Max(max1_3, max1_3, src1_3, preg_all); + Max(max2_0, max2_0, src2_0, preg_all); + Max(max2_1, max2_1, src2_1, preg_all); + Max(max2_2, max2_2, src2_2, preg_all); + Max(max2_3, max2_3, src2_3, preg_all); + Max(max3_0, max3_0, src3_0, preg_all); + Max(max3_1, max3_1, src3_1, preg_all); + Max(max3_2, max3_2, src3_2, preg_all); + Max(max3_3, max3_3, src3_3, preg_all); + } + Max(max0_0, max0_0, max0_2, preg_all); + Max(max0_1, max0_1, max0_3, preg_all); + Max(max1_0, max1_0, max1_2, preg_all); + Max(max1_1, max1_1, max1_3, preg_all); + Max(max2_0, max2_0, max2_2, preg_all); + Max(max2_1, max2_1, max2_3, preg_all); + Max(max3_0, max3_0, max3_2, preg_all); + Max(max3_1, max3_1, max3_3, preg_all); + + for (uint16_t iter_m = 0; iter_m < uint16_t(ReduceSize / 2); ++iter_m) { + LoadAlign(vreg_x_f32_0_0, + src_ub0_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_0_1, + src_ub0_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_0_2, + src_ub0_2 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_0_3, + src_ub0_3 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + LoadAlign(vreg_x_f32_1_0, + src_ub1_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_1_1, + src_ub1_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_1_2, + src_ub1_2 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_1_3, + src_ub1_3 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + LoadAlign(vreg_x_f32_2_0, + src_ub2_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_2_1, + src_ub2_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_2_2, + src_ub2_2 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_2_3, + src_ub2_3 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + LoadAlign(vreg_x_f32_3_0, + src_ub3_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_3_1, + src_ub3_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_3_2, + src_ub3_2 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_3_3, + src_ub3_3 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + FusedExpSub(vreg_x_exp_0_0, vreg_x_f32_0_0, max0_0, preg_all); + FusedExpSub(vreg_x_exp_0_1, vreg_x_f32_0_1, max0_1, preg_all); + FusedExpSub(vreg_x_exp_0_2, vreg_x_f32_0_2, max0_0, preg_all); + FusedExpSub(vreg_x_exp_0_3, vreg_x_f32_0_3, max0_1, preg_all); + FusedExpSub(vreg_x_exp_1_0, vreg_x_f32_1_0, max1_0, preg_all); + FusedExpSub(vreg_x_exp_1_1, vreg_x_f32_1_1, max1_1, preg_all); + FusedExpSub(vreg_x_exp_1_2, vreg_x_f32_1_2, max1_0, preg_all); + FusedExpSub(vreg_x_exp_1_3, vreg_x_f32_1_3, max1_1, preg_all); + FusedExpSub(vreg_x_exp_2_0, vreg_x_f32_2_0, max2_0, preg_all); + FusedExpSub(vreg_x_exp_2_1, vreg_x_f32_2_1, max2_1, preg_all); + FusedExpSub(vreg_x_exp_2_2, vreg_x_f32_2_2, max2_0, preg_all); + FusedExpSub(vreg_x_exp_2_3, vreg_x_f32_2_3, max2_1, preg_all); + FusedExpSub(vreg_x_exp_3_0, vreg_x_f32_3_0, max3_0, preg_all); + FusedExpSub(vreg_x_exp_3_1, vreg_x_f32_3_1, max3_1, preg_all); + FusedExpSub(vreg_x_exp_3_2, vreg_x_f32_3_2, max3_0, preg_all); + FusedExpSub(vreg_x_exp_3_3, vreg_x_f32_3_3, max3_1, preg_all); + + Add(vreg_x_sum_0_0, vreg_x_exp_0_0, vreg_x_sum_0_0, preg_all); + Add(vreg_x_sum_0_1, vreg_x_exp_0_1, vreg_x_sum_0_1, preg_all); + Add(vreg_x_sum_0_2, vreg_x_exp_0_2, vreg_x_sum_0_2, preg_all); + Add(vreg_x_sum_0_3, vreg_x_exp_0_3, vreg_x_sum_0_3, preg_all); + Add(vreg_x_sum_1_0, vreg_x_exp_1_0, vreg_x_sum_1_0, preg_all); + Add(vreg_x_sum_1_1, vreg_x_exp_1_1, vreg_x_sum_1_1, preg_all); + Add(vreg_x_sum_1_2, vreg_x_exp_1_2, vreg_x_sum_1_2, preg_all); + Add(vreg_x_sum_1_3, vreg_x_exp_1_3, vreg_x_sum_1_3, preg_all); + Add(vreg_x_sum_2_0, vreg_x_exp_2_0, vreg_x_sum_2_0, preg_all); + Add(vreg_x_sum_2_1, vreg_x_exp_2_1, vreg_x_sum_2_1, preg_all); + Add(vreg_x_sum_2_2, vreg_x_exp_2_2, vreg_x_sum_2_2, preg_all); + Add(vreg_x_sum_2_3, vreg_x_exp_2_3, vreg_x_sum_2_3, preg_all); + Add(vreg_x_sum_3_0, vreg_x_exp_3_0, vreg_x_sum_3_0, preg_all); + Add(vreg_x_sum_3_1, vreg_x_exp_3_1, vreg_x_sum_3_1, preg_all); + Add(vreg_x_sum_3_2, vreg_x_exp_3_2, vreg_x_sum_3_2, preg_all); + Add(vreg_x_sum_3_3, vreg_x_exp_3_3, vreg_x_sum_3_3, preg_all); + + StoreAlign( + ((__ubuf__ T*&)src_ub0_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_0_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub0_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_0_1, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub0_2 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_0_2, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub0_3 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_0_3, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub1_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_1_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub1_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_1_1, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub1_2 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_1_2, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub1_3 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_1_3, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub2_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_2_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub2_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_2_1, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub2_2 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_2_2, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub2_3 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_2_3, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub3_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_3_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub3_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_3_1, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub3_2 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_3_2, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub3_3 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_3_3, + preg_all); + } + Add(vreg_x_sum_0_0, vreg_x_sum_0_0, vreg_x_sum_0_2, preg_all); + Add(vreg_x_sum_0_1, vreg_x_sum_0_1, vreg_x_sum_0_3, preg_all); + Add(vreg_x_sum_1_0, vreg_x_sum_1_0, vreg_x_sum_1_2, preg_all); + Add(vreg_x_sum_1_1, vreg_x_sum_1_1, vreg_x_sum_1_3, preg_all); + Add(vreg_x_sum_2_0, vreg_x_sum_2_0, vreg_x_sum_2_2, preg_all); + Add(vreg_x_sum_2_1, vreg_x_sum_2_1, vreg_x_sum_2_3, preg_all); + Add(vreg_x_sum_3_0, vreg_x_sum_3_0, vreg_x_sum_3_2, preg_all); + Add(vreg_x_sum_3_1, vreg_x_sum_3_1, vreg_x_sum_3_3, preg_all); + + LocalMemBar(); + for (uint16_t iter_m = 0; iter_m < ReduceSize; ++iter_m) { + LoadAlign( + vreg_x_exp_0_0, + src_ub0_0 + iter_m * RowSize + ReduceSize * RowSize * iter_sc * 4); + LoadAlign( + vreg_x_exp_0_1, + src_ub0_1 + iter_m * RowSize + ReduceSize * RowSize * iter_sc * 4); + LoadAlign( + vreg_x_exp_1_0, + src_ub1_0 + iter_m * RowSize + ReduceSize * RowSize * iter_sc * 4); + LoadAlign( + vreg_x_exp_1_1, + src_ub1_1 + iter_m * RowSize + ReduceSize * RowSize * iter_sc * 4); + LoadAlign( + vreg_x_exp_2_0, + src_ub2_0 + iter_m * RowSize + ReduceSize * RowSize * iter_sc * 4); + LoadAlign( + vreg_x_exp_2_1, + src_ub2_1 + iter_m * RowSize + ReduceSize * RowSize * iter_sc * 4); + LoadAlign( + vreg_x_exp_3_0, + src_ub3_0 + iter_m * RowSize + ReduceSize * RowSize * iter_sc * 4); + LoadAlign( + vreg_x_exp_3_1, + src_ub3_1 + iter_m * RowSize + ReduceSize * RowSize * iter_sc * 4); + + Div(vreg_x_softmax_0_0, vreg_x_exp_0_0, vreg_x_sum_0_0, preg_all); + Div(vreg_x_softmax_0_1, vreg_x_exp_0_1, vreg_x_sum_0_1, preg_all); + Div(vreg_x_softmax_1_0, vreg_x_exp_1_0, vreg_x_sum_1_0, preg_all); + Div(vreg_x_softmax_1_1, vreg_x_exp_1_1, vreg_x_sum_1_1, preg_all); + Div(vreg_x_softmax_2_0, vreg_x_exp_2_0, vreg_x_sum_2_0, preg_all); + Div(vreg_x_softmax_2_1, vreg_x_exp_2_1, vreg_x_sum_2_1, preg_all); + Div(vreg_x_softmax_3_0, vreg_x_exp_3_0, vreg_x_sum_3_0, preg_all); + Div(vreg_x_softmax_3_1, vreg_x_exp_3_1, vreg_x_sum_3_1, preg_all); + + StoreAlign( + ((__ubuf__ T*&)x_softmax_0_0 + iter_m * RowSize + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_softmax_0_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)x_softmax_0_1 + iter_m * RowSize + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_softmax_0_1, + preg_all); + StoreAlign( + ((__ubuf__ T*&)x_softmax_1_0 + iter_m * RowSize + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_softmax_1_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)x_softmax_1_1 + iter_m * RowSize + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_softmax_1_1, + preg_all); + StoreAlign( + ((__ubuf__ T*&)x_softmax_2_0 + iter_m * RowSize + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_softmax_2_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)x_softmax_2_1 + iter_m * RowSize + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_softmax_2_1, + preg_all); + StoreAlign( + ((__ubuf__ T*&)x_softmax_3_0 + iter_m * RowSize + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_softmax_3_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)x_softmax_3_1 + iter_m * RowSize + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_softmax_3_1, + preg_all); + } + } + // 尾块处理 + for (uint16_t iter_sc = 0; iter_sc < uint16_t(vScRealSize % 4); ++iter_sc) { + Duplicate(max0_0, minValue); + Duplicate(max0_1, minValue); + Duplicate(max0_2, minValue); + Duplicate(max0_3, minValue); + + Duplicate( + vreg_x_sum_0_0, 0, preg_all); + Duplicate( + vreg_x_sum_0_1, 0, preg_all); + Duplicate( + vreg_x_sum_0_2, 0, preg_all); + Duplicate( + vreg_x_sum_0_3, 0, preg_all); + for (uint16_t iter_m = 0; iter_m < uint16_t(ReduceSize / 2); ++iter_m) { + LoadAlign(src0_0, + src_ub0_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + LoadAlign(src0_1, + src_ub0_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + LoadAlign(src0_2, + src_ub0_2 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + LoadAlign(src0_3, + src_ub0_3 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + + Max(max0_0, max0_0, src0_0, preg_all); + Max(max0_1, max0_1, src0_1, preg_all); + Max(max0_2, max0_2, src0_2, preg_all); + Max(max0_3, max0_3, src0_3, preg_all); + } + Max(max0_0, max0_0, max0_2, preg_all); + Max(max0_1, max0_1, max0_3, preg_all); + + for (uint16_t iter_m = 0; iter_m < ReduceSize / 2; ++iter_m) { + LoadAlign(vreg_x_f32_0_0, + src_ub0_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + LoadAlign(vreg_x_f32_0_1, + src_ub0_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + LoadAlign(vreg_x_f32_0_2, + src_ub0_2 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + LoadAlign(vreg_x_f32_0_3, + src_ub0_3 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + + FusedExpSub(vreg_x_exp_0_0, vreg_x_f32_0_0, max0_0, preg_all); + FusedExpSub(vreg_x_exp_0_1, vreg_x_f32_0_1, max0_1, preg_all); + FusedExpSub(vreg_x_exp_0_2, vreg_x_f32_0_2, max0_0, preg_all); + FusedExpSub(vreg_x_exp_0_3, vreg_x_f32_0_3, max0_1, preg_all); + + Add(vreg_x_sum_0_0, vreg_x_exp_0_0, vreg_x_sum_0_0, preg_all); + Add(vreg_x_sum_0_1, vreg_x_exp_0_1, vreg_x_sum_0_1, preg_all); + Add(vreg_x_sum_0_2, vreg_x_exp_0_2, vreg_x_sum_0_2, preg_all); + Add(vreg_x_sum_0_3, vreg_x_exp_0_3, vreg_x_sum_0_3, preg_all); + + StoreAlign( + ((__ubuf__ T*&)src_ub0_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)), + vreg_x_exp_0_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub0_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)), + vreg_x_exp_0_1, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub0_2 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)), + vreg_x_exp_0_2, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub0_3 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)), + vreg_x_exp_0_3, + preg_all); + } + Add(vreg_x_sum_0_0, vreg_x_sum_0_0, vreg_x_sum_0_2, preg_all); + Add(vreg_x_sum_0_1, vreg_x_sum_0_1, vreg_x_sum_0_3, preg_all); + + LocalMemBar(); + for (uint16_t iter_m = 0; iter_m < ReduceSize; ++iter_m) { + LoadAlign(vreg_x_exp_0_0, + src_ub0_0 + iter_m * RowSize + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + LoadAlign(vreg_x_exp_0_1, + src_ub0_1 + iter_m * RowSize + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + + Div(vreg_x_softmax_0_0, vreg_x_exp_0_0, vreg_x_sum_0_0, preg_all); + Div(vreg_x_softmax_0_1, vreg_x_exp_0_1, vreg_x_sum_0_1, preg_all); + + StoreAlign( + ((__ubuf__ T*&)x_softmax_0_0 + iter_m * RowSize + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)), + vreg_x_softmax_0_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)x_softmax_0_1 + iter_m * RowSize + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)), + vreg_x_softmax_0_1, + preg_all); + } + } +} + +template +__simd_vf__ inline void SoftmaxDndBase64(__ubuf__ T* x_softmax, + __ubuf__ float* input_x_local_UB, + const uint32_t RowSize, + const uint32_t ReduceSize, + const uint32_t vScRealSize, + const T minValue) { + RegTensor vreg_x_sum_0_0; + RegTensor vreg_x_sum_1_0; + RegTensor vreg_x_sum_2_0; + RegTensor vreg_x_sum_3_0; + RegTensor vreg_x_sum_0_1; + RegTensor vreg_x_sum_1_1; + RegTensor vreg_x_sum_2_1; + RegTensor vreg_x_sum_3_1; + + RegTensor vreg_x_exp_0_0; + RegTensor vreg_x_exp_1_0; + RegTensor vreg_x_exp_2_0; + RegTensor vreg_x_exp_3_0; + RegTensor vreg_x_exp_0_1; + RegTensor vreg_x_exp_1_1; + RegTensor vreg_x_exp_2_1; + RegTensor vreg_x_exp_3_1; + + RegTensor vreg_x_f32_0_0; + RegTensor vreg_x_f32_1_0; + RegTensor vreg_x_f32_2_0; + RegTensor vreg_x_f32_3_0; + RegTensor vreg_x_f32_0_1; + RegTensor vreg_x_f32_1_1; + RegTensor vreg_x_f32_2_1; + RegTensor vreg_x_f32_3_1; + + RegTensor vreg_x_softmax_0; + RegTensor vreg_x_softmax_1; + RegTensor vreg_x_softmax_2; + RegTensor vreg_x_softmax_3; + MaskReg preg_all; + MaskReg preg_136; + preg_all = CreateMask(); + uint32_t sreg_92 = static_cast(128ULL); + preg_136 = UpdateMask(sreg_92); + RegTensor src0_0, src1_0, src2_0, src3_0, src0_1, src1_1, src2_1, + src3_1; + RegTensor max0_0, max1_0, max2_0, max3_0, max0_1, max1_1, max2_1, + max3_1; + RegTensor vreg_min; + + __ubuf__ float* src_ub0_0 = input_x_local_UB; + __ubuf__ float* src_ub0_1 = input_x_local_UB + RowSize; + __ubuf__ float* src_ub1_0 = src_ub0_0 + ReduceSize * RowSize; + __ubuf__ float* src_ub1_1 = src_ub0_0 + ReduceSize * RowSize + RowSize; + __ubuf__ float* src_ub2_0 = src_ub0_0 + ReduceSize * RowSize * 2; + __ubuf__ float* src_ub2_1 = src_ub0_0 + ReduceSize * RowSize * 2 + RowSize; + __ubuf__ float* src_ub3_0 = src_ub0_0 + ReduceSize * RowSize * 3; + __ubuf__ float* src_ub3_1 = src_ub0_0 + ReduceSize * RowSize * 3 + RowSize; + + __ubuf__ float* x_softmax_0 = x_softmax; + __ubuf__ float* x_softmax_1 = x_softmax + (ReduceSize * RowSize); + __ubuf__ float* x_softmax_2 = x_softmax + (ReduceSize * RowSize * 2); + __ubuf__ float* x_softmax_3 = x_softmax + (ReduceSize * RowSize * 3); + + for (uint16_t iter_sc = 0; iter_sc < uint16_t(vScRealSize / 4); ++iter_sc) { + Duplicate(max0_0, minValue); + Duplicate(max1_0, minValue); + Duplicate(max2_0, minValue); + Duplicate(max3_0, minValue); + Duplicate(max0_1, minValue); + Duplicate(max1_1, minValue); + Duplicate(max2_1, minValue); + Duplicate(max3_1, minValue); + + Duplicate( + vreg_x_sum_0_0, 0, preg_all); + Duplicate( + vreg_x_sum_1_0, 0, preg_all); + Duplicate( + vreg_x_sum_2_0, 0, preg_all); + Duplicate( + vreg_x_sum_3_0, 0, preg_all); + Duplicate( + vreg_x_sum_0_1, 0, preg_all); + Duplicate( + vreg_x_sum_1_1, 0, preg_all); + Duplicate( + vreg_x_sum_2_1, 0, preg_all); + Duplicate( + vreg_x_sum_3_1, 0, preg_all); + for (uint16_t iter_m = 0; iter_m < uint16_t(ReduceSize / 2); ++iter_m) { + LoadAlign(src0_0, + src_ub0_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src0_1, + src_ub0_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + LoadAlign(src1_0, + src_ub1_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src1_1, + src_ub1_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + LoadAlign(src2_0, + src_ub2_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src2_1, + src_ub2_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + LoadAlign(src3_0, + src_ub3_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src3_1, + src_ub3_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + Max(max0_0, max0_0, src0_0, preg_all); + Max(max0_1, max0_1, src0_1, preg_all); + Max(max1_0, max1_0, src1_0, preg_all); + Max(max1_1, max1_1, src1_1, preg_all); + Max(max2_0, max2_0, src2_0, preg_all); + Max(max2_1, max2_1, src2_1, preg_all); + Max(max3_0, max3_0, src3_0, preg_all); + Max(max3_1, max3_1, src3_1, preg_all); + } + Max(max0_0, max0_0, max0_1, preg_all); + Max(max1_0, max1_0, max1_1, preg_all); + Max(max2_0, max2_0, max2_1, preg_all); + Max(max3_0, max3_0, max3_1, preg_all); + + for (uint16_t iter_m = 0; iter_m < uint16_t(ReduceSize / 2); ++iter_m) { + LoadAlign(vreg_x_f32_0_0, + src_ub0_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_0_1, + src_ub0_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + LoadAlign(vreg_x_f32_1_0, + src_ub1_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_1_1, + src_ub1_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + LoadAlign(vreg_x_f32_2_0, + src_ub2_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_2_1, + src_ub2_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + LoadAlign(vreg_x_f32_3_0, + src_ub3_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_3_1, + src_ub3_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + FusedExpSub(vreg_x_exp_0_0, vreg_x_f32_0_0, max0_0, preg_all); + FusedExpSub(vreg_x_exp_0_1, vreg_x_f32_0_1, max0_0, preg_all); + FusedExpSub(vreg_x_exp_1_0, vreg_x_f32_1_0, max1_0, preg_all); + FusedExpSub(vreg_x_exp_1_1, vreg_x_f32_1_1, max1_0, preg_all); + FusedExpSub(vreg_x_exp_2_0, vreg_x_f32_2_0, max2_0, preg_all); + FusedExpSub(vreg_x_exp_2_1, vreg_x_f32_2_1, max2_0, preg_all); + FusedExpSub(vreg_x_exp_3_0, vreg_x_f32_3_0, max3_0, preg_all); + FusedExpSub(vreg_x_exp_3_1, vreg_x_f32_3_1, max3_0, preg_all); + + Add(vreg_x_sum_0_0, vreg_x_exp_0_0, vreg_x_sum_0_0, preg_all); + Add(vreg_x_sum_0_1, vreg_x_exp_0_1, vreg_x_sum_0_1, preg_all); + Add(vreg_x_sum_1_0, vreg_x_exp_1_0, vreg_x_sum_1_0, preg_all); + Add(vreg_x_sum_1_1, vreg_x_exp_1_1, vreg_x_sum_1_1, preg_all); + Add(vreg_x_sum_2_0, vreg_x_exp_2_0, vreg_x_sum_2_0, preg_all); + Add(vreg_x_sum_2_1, vreg_x_exp_2_1, vreg_x_sum_2_1, preg_all); + Add(vreg_x_sum_3_0, vreg_x_exp_3_0, vreg_x_sum_3_0, preg_all); + Add(vreg_x_sum_3_1, vreg_x_exp_3_1, vreg_x_sum_3_1, preg_all); + + StoreAlign( + ((__ubuf__ T*&)src_ub0_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_0_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub0_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_0_1, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub1_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_1_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub1_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_1_1, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub2_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_2_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub2_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_2_1, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub3_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_3_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub3_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_3_1, + preg_all); + } + Add(vreg_x_sum_0_0, vreg_x_sum_0_0, vreg_x_sum_0_1, preg_all); + Add(vreg_x_sum_1_0, vreg_x_sum_1_0, vreg_x_sum_1_1, preg_all); + Add(vreg_x_sum_2_0, vreg_x_sum_2_0, vreg_x_sum_2_1, preg_all); + Add(vreg_x_sum_3_0, vreg_x_sum_3_0, vreg_x_sum_3_1, preg_all); + + LocalMemBar(); + for (uint16_t iter_m = 0; iter_m < ReduceSize; ++iter_m) { + LoadAlign( + vreg_x_exp_0_0, + src_ub0_0 + iter_m * RowSize + ReduceSize * RowSize * iter_sc * 4); + LoadAlign( + vreg_x_exp_1_0, + src_ub1_0 + iter_m * RowSize + ReduceSize * RowSize * iter_sc * 4); + LoadAlign( + vreg_x_exp_2_0, + src_ub2_0 + iter_m * RowSize + ReduceSize * RowSize * iter_sc * 4); + LoadAlign( + vreg_x_exp_3_0, + src_ub3_0 + iter_m * RowSize + ReduceSize * RowSize * iter_sc * 4); + + Div(vreg_x_softmax_0, vreg_x_exp_0_0, vreg_x_sum_0_0, preg_all); + Div(vreg_x_softmax_1, vreg_x_exp_1_0, vreg_x_sum_1_0, preg_all); + Div(vreg_x_softmax_2, vreg_x_exp_2_0, vreg_x_sum_2_0, preg_all); + Div(vreg_x_softmax_3, vreg_x_exp_3_0, vreg_x_sum_3_0, preg_all); + + StoreAlign( + ((__ubuf__ T*&)x_softmax_0 + iter_m * RowSize + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_softmax_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)x_softmax_1 + iter_m * RowSize + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_softmax_1, + preg_all); + StoreAlign( + ((__ubuf__ T*&)x_softmax_2 + iter_m * RowSize + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_softmax_2, + preg_all); + StoreAlign( + ((__ubuf__ T*&)x_softmax_3 + iter_m * RowSize + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_softmax_3, + preg_all); + } + } + // 尾块处理 + for (uint16_t iter_sc = 0; iter_sc < uint16_t(vScRealSize % 4); ++iter_sc) { + Duplicate(max0_0, minValue); + Duplicate(max0_1, minValue); + + Duplicate( + vreg_x_sum_0_0, 0, preg_all); + Duplicate( + vreg_x_sum_0_1, 0, preg_all); + for (uint16_t iter_m = 0; iter_m < uint16_t(ReduceSize / 2); ++iter_m) { + LoadAlign(src0_0, + src_ub0_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + LoadAlign(src0_1, + src_ub0_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + + Max(max0_0, max0_0, src0_0, preg_all); + Max(max0_1, max0_1, src0_1, preg_all); + } + Max(max0_0, max0_0, max0_1, preg_all); + + for (uint16_t iter_m = 0; iter_m < ReduceSize / 2; ++iter_m) { + LoadAlign(vreg_x_f32_0_0, + src_ub0_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + LoadAlign(vreg_x_f32_0_1, + src_ub0_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + + FusedExpSub(vreg_x_exp_0_0, vreg_x_f32_0_0, max0_0, preg_all); + FusedExpSub(vreg_x_exp_0_1, vreg_x_f32_0_1, max0_0, preg_all); + + Add(vreg_x_sum_0_0, vreg_x_exp_0_0, vreg_x_sum_0_0, preg_all); + Add(vreg_x_sum_0_1, vreg_x_exp_0_1, vreg_x_sum_0_1, preg_all); + + StoreAlign( + ((__ubuf__ T*&)src_ub0_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)), + vreg_x_exp_0_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub0_1 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)), + vreg_x_exp_0_1, + preg_all); + } + Add(vreg_x_sum_0_0, vreg_x_sum_0_0, vreg_x_sum_0_1, preg_all); + + LocalMemBar(); + for (uint16_t iter_m = 0; iter_m < ReduceSize; ++iter_m) { + LoadAlign(vreg_x_exp_0_0, + src_ub0_0 + iter_m * RowSize + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + Div(vreg_x_softmax_0, vreg_x_exp_0_0, vreg_x_sum_0_0, preg_all); + + StoreAlign( + ((__ubuf__ T*&)x_softmax_0 + iter_m * RowSize + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)), + vreg_x_softmax_0, + preg_all); + } + } +} + +template +__simd_vf__ inline void SoftmaxDndBase32(__ubuf__ T* x_softmax, + __ubuf__ float* input_x_local_UB, + const uint32_t RowSize, + const uint32_t ReduceSize, + const uint32_t vScRealSize, + const T minValue) { + RegTensor vreg_x_sum_0_0; + RegTensor vreg_x_sum_1_0; + RegTensor vreg_x_sum_2_0; + RegTensor vreg_x_sum_3_0; + RegTensor vreg_x_sum_0_1; + RegTensor vreg_x_sum_1_1; + RegTensor vreg_x_sum_2_1; + RegTensor vreg_x_sum_3_1; + + RegTensor vreg_x_exp_0_0; + RegTensor vreg_x_exp_1_0; + RegTensor vreg_x_exp_2_0; + RegTensor vreg_x_exp_3_0; + RegTensor vreg_x_exp_0_1; + RegTensor vreg_x_exp_1_1; + RegTensor vreg_x_exp_2_1; + RegTensor vreg_x_exp_3_1; + + RegTensor vreg_x_f32_0_0; + RegTensor vreg_x_f32_1_0; + RegTensor vreg_x_f32_2_0; + RegTensor vreg_x_f32_3_0; + RegTensor vreg_x_f32_0_1; + RegTensor vreg_x_f32_1_1; + RegTensor vreg_x_f32_2_1; + RegTensor vreg_x_f32_3_1; + + RegTensor vreg_x_softmax_0; + RegTensor vreg_x_softmax_1; + RegTensor vreg_x_softmax_2; + RegTensor vreg_x_softmax_3; + + MaskReg preg_LHalf; + MaskReg preg_HHalf; + MaskReg preg_all; + MaskReg preg_136; + preg_all = CreateMask(); + preg_LHalf = CreateMask(); + Not(preg_HHalf, preg_LHalf, preg_all); + uint32_t sreg_92 = static_cast(128ULL); + preg_136 = UpdateMask(sreg_92); + RegTensor max0, max1, max2, max3; + RegTensor src0_0, src1_0, src2_0, src3_0, src0_1, src1_1, src2_1, + src3_1; + RegTensor max0_0, max1_0, max2_0, max3_0, max0_1, max1_1, max2_1, + max3_1; + RegTensor vreg_min; + + __ubuf__ float* src_ub0_0 = input_x_local_UB; + __ubuf__ float* src_ub0_1 = input_x_local_UB + RowSize * 2; + __ubuf__ float* src_ub1_0 = src_ub0_0 + ReduceSize * RowSize; + __ubuf__ float* src_ub1_1 = src_ub0_0 + ReduceSize * RowSize + RowSize * 2; + __ubuf__ float* src_ub2_0 = src_ub0_0 + ReduceSize * RowSize * 2; + __ubuf__ float* src_ub2_1 = + src_ub0_0 + ReduceSize * RowSize * 2 + RowSize * 2; + __ubuf__ float* src_ub3_0 = src_ub0_0 + ReduceSize * RowSize * 3; + __ubuf__ float* src_ub3_1 = + src_ub0_0 + ReduceSize * RowSize * 3 + RowSize * 2; + + __ubuf__ float* x_softmax_0 = x_softmax; + __ubuf__ float* x_softmax_1 = x_softmax + (ReduceSize * RowSize); + __ubuf__ float* x_softmax_2 = x_softmax + (ReduceSize * RowSize * 2); + __ubuf__ float* x_softmax_3 = x_softmax + (ReduceSize * RowSize * 3); + + for (uint16_t iter_sc = 0; iter_sc < uint16_t(vScRealSize / 4); ++iter_sc) { + Duplicate(max0, minValue); + Duplicate(max1, minValue); + Duplicate(max2, minValue); + Duplicate(max3, minValue); + Duplicate(max0_0, minValue); + Duplicate(max1_0, minValue); + Duplicate(max2_0, minValue); + Duplicate(max3_0, minValue); + Duplicate(max0_1, minValue); + Duplicate(max1_1, minValue); + Duplicate(max2_1, minValue); + Duplicate(max3_1, minValue); + + Duplicate( + vreg_x_sum_0_0, 0, preg_all); + Duplicate( + vreg_x_sum_1_0, 0, preg_all); + Duplicate( + vreg_x_sum_2_0, 0, preg_all); + Duplicate( + vreg_x_sum_3_0, 0, preg_all); + Duplicate( + vreg_x_sum_0_1, 0, preg_all); + Duplicate( + vreg_x_sum_1_1, 0, preg_all); + Duplicate( + vreg_x_sum_2_1, 0, preg_all); + Duplicate( + vreg_x_sum_3_1, 0, preg_all); + for (uint16_t iter_m = 0; iter_m < uint16_t(ReduceSize / 4); ++iter_m) { + LoadAlign(src0_0, + src_ub0_0 + iter_m * RowSize * 4 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src0_1, + src_ub0_1 + iter_m * RowSize * 4 + + ReduceSize * RowSize * iter_sc * 4); + + LoadAlign(src1_0, + src_ub1_0 + iter_m * RowSize * 4 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src1_1, + src_ub1_1 + iter_m * RowSize * 4 + + ReduceSize * RowSize * iter_sc * 4); + + LoadAlign(src2_0, + src_ub2_0 + iter_m * RowSize * 4 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src2_1, + src_ub2_1 + iter_m * RowSize * 4 + + ReduceSize * RowSize * iter_sc * 4); + + LoadAlign(src3_0, + src_ub3_0 + iter_m * RowSize * 4 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(src3_1, + src_ub3_1 + iter_m * RowSize * 4 + + ReduceSize * RowSize * iter_sc * 4); + + Max(max0_0, max0_0, src0_0, preg_all); + Max(max0_1, max0_1, src0_1, preg_all); + Max(max1_0, max1_0, src1_0, preg_all); + Max(max1_1, max1_1, src1_1, preg_all); + Max(max2_0, max2_0, src2_0, preg_all); + Max(max2_1, max2_1, src2_1, preg_all); + Max(max3_0, max3_0, src3_0, preg_all); + Max(max3_1, max3_1, src3_1, preg_all); + } + Max(max0, max0_0, max0_1, preg_all); + Max(max1, max1_0, max1_1, preg_all); + Max(max2, max2_0, max2_1, preg_all); + Max(max3, max3_0, max3_1, preg_all); + + Squeeze( + max0_0, max0, preg_LHalf); + Squeeze( + max0_1, max0, preg_HHalf); + Max(max0, max0_0, max0_1, preg_LHalf); + + Squeeze( + max1_0, max1, preg_LHalf); + Squeeze( + max1_1, max1, preg_HHalf); + Max(max1, max1_0, max1_1, preg_LHalf); + + Squeeze( + max2_0, max2, preg_LHalf); + Squeeze( + max2_1, max2, preg_HHalf); + Max(max2, max2_0, max2_1, preg_LHalf); + + Squeeze( + max3_0, max3, preg_LHalf); + Squeeze( + max3_1, max3, preg_HHalf); + Max(max3, max3_0, max3_1, preg_LHalf); + + for (uint16_t iter_m = 0; iter_m < uint16_t(ReduceSize / 2); ++iter_m) { + LoadAlign(vreg_x_f32_0_0, + src_ub0_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_0_1, + (src_ub0_0 + RowSize) + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + LoadAlign(vreg_x_f32_1_0, + src_ub1_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_1_1, + (src_ub1_0 + RowSize) + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + LoadAlign(vreg_x_f32_2_0, + src_ub2_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_2_1, + (src_ub2_0 + RowSize) + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + LoadAlign(vreg_x_f32_3_0, + src_ub3_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + LoadAlign(vreg_x_f32_3_1, + (src_ub3_0 + RowSize) + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4); + + FusedExpSub(vreg_x_exp_0_0, vreg_x_f32_0_0, max0, preg_all); + FusedExpSub(vreg_x_exp_0_1, vreg_x_f32_0_1, max0, preg_all); + FusedExpSub(vreg_x_exp_1_0, vreg_x_f32_1_0, max1, preg_all); + FusedExpSub(vreg_x_exp_1_1, vreg_x_f32_1_1, max1, preg_all); + FusedExpSub(vreg_x_exp_2_0, vreg_x_f32_2_0, max2, preg_all); + FusedExpSub(vreg_x_exp_2_1, vreg_x_f32_2_1, max2, preg_all); + FusedExpSub(vreg_x_exp_3_0, vreg_x_f32_3_0, max3, preg_all); + FusedExpSub(vreg_x_exp_3_1, vreg_x_f32_3_1, max3, preg_all); + + Add(vreg_x_sum_0_0, vreg_x_exp_0_0, vreg_x_sum_0_0, preg_all); + Add(vreg_x_sum_0_1, vreg_x_exp_0_1, vreg_x_sum_0_1, preg_all); + Add(vreg_x_sum_1_0, vreg_x_exp_1_0, vreg_x_sum_1_0, preg_all); + Add(vreg_x_sum_1_1, vreg_x_exp_1_1, vreg_x_sum_1_1, preg_all); + Add(vreg_x_sum_2_0, vreg_x_exp_2_0, vreg_x_sum_2_0, preg_all); + Add(vreg_x_sum_2_1, vreg_x_exp_2_1, vreg_x_sum_2_1, preg_all); + Add(vreg_x_sum_3_0, vreg_x_exp_3_0, vreg_x_sum_3_0, preg_all); + Add(vreg_x_sum_3_1, vreg_x_exp_3_1, vreg_x_sum_3_1, preg_all); + + StoreAlign( + ((__ubuf__ T*&)src_ub0_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_0_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub0_0 + RowSize + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_0_1, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub1_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_1_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub1_0 + RowSize + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_1_1, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub2_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_2_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub2_0 + RowSize + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_2_1, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub3_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_3_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub3_0 + RowSize + iter_m * RowSize * 2 + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_exp_3_1, + preg_all); + } + Add(vreg_x_sum_0_0, vreg_x_sum_0_0, vreg_x_sum_0_1, preg_all); + Add(vreg_x_sum_1_0, vreg_x_sum_1_0, vreg_x_sum_1_1, preg_all); + Add(vreg_x_sum_2_0, vreg_x_sum_2_0, vreg_x_sum_2_1, preg_all); + Add(vreg_x_sum_3_0, vreg_x_sum_3_0, vreg_x_sum_3_1, preg_all); + + LocalMemBar(); + for (uint16_t iter_m = 0; iter_m < ReduceSize; ++iter_m) { + LoadAlign( + vreg_x_exp_0_0, + src_ub0_0 + iter_m * RowSize + ReduceSize * RowSize * iter_sc * 4); + LoadAlign( + vreg_x_exp_1_0, + src_ub1_0 + iter_m * RowSize + ReduceSize * RowSize * iter_sc * 4); + LoadAlign( + vreg_x_exp_2_0, + src_ub2_0 + iter_m * RowSize + ReduceSize * RowSize * iter_sc * 4); + LoadAlign( + vreg_x_exp_3_0, + src_ub3_0 + iter_m * RowSize + ReduceSize * RowSize * iter_sc * 4); + + Div(vreg_x_softmax_0, vreg_x_exp_0_0, vreg_x_sum_0_0, preg_all); + Div(vreg_x_softmax_1, vreg_x_exp_1_0, vreg_x_sum_1_0, preg_all); + Div(vreg_x_softmax_2, vreg_x_exp_2_0, vreg_x_sum_2_0, preg_all); + Div(vreg_x_softmax_3, vreg_x_exp_3_0, vreg_x_sum_3_0, preg_all); + + StoreAlign( + ((__ubuf__ T*&)x_softmax_0 + iter_m * RowSize + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_softmax_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)x_softmax_1 + iter_m * RowSize + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_softmax_1, + preg_all); + StoreAlign( + ((__ubuf__ T*&)x_softmax_2 + iter_m * RowSize + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_softmax_2, + preg_all); + StoreAlign( + ((__ubuf__ T*&)x_softmax_3 + iter_m * RowSize + + ReduceSize * RowSize * iter_sc * 4), + vreg_x_softmax_3, + preg_all); + } + } + // 尾块处理 + for (uint16_t iter_sc = 0; iter_sc < uint16_t(vScRealSize % 4); ++iter_sc) { + Duplicate(max0, minValue); + Duplicate(max0_0, minValue); + Duplicate(max0_1, minValue); + + Duplicate( + vreg_x_sum_0_0, 0, preg_all); + Duplicate( + vreg_x_sum_0_1, 0, preg_all); + for (uint16_t iter_m = 0; iter_m < uint16_t(ReduceSize / 4); ++iter_m) { + LoadAlign(src0_0, + src_ub0_0 + iter_m * RowSize * 4 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + LoadAlign(src0_1, + src_ub0_1 + iter_m * RowSize * 4 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + + Max(max0_0, max0_0, src0_0, preg_all); + Max(max0_1, max0_1, src0_1, preg_all); + } + Max(max0, max0_0, max0_1, preg_all); + + Squeeze( + max0_0, max0, preg_LHalf); + Squeeze( + max0_1, max0, preg_HHalf); + Max(max0, max0_0, max0_1, preg_LHalf); + + for (uint16_t iter_m = 0; iter_m < uint16_t(ReduceSize / 2); ++iter_m) { + LoadAlign(vreg_x_f32_0_0, + src_ub0_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + LoadAlign(vreg_x_f32_0_1, + (src_ub0_0 + RowSize) + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + + FusedExpSub(vreg_x_exp_0_0, vreg_x_f32_0_0, max0, preg_all); + FusedExpSub(vreg_x_exp_0_1, vreg_x_f32_0_1, max0, preg_all); + + Add(vreg_x_sum_0_0, vreg_x_exp_0_0, vreg_x_sum_0_0, preg_all); + Add(vreg_x_sum_0_1, vreg_x_exp_0_1, vreg_x_sum_0_1, preg_all); + + StoreAlign( + ((__ubuf__ T*&)src_ub0_0 + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)), + vreg_x_exp_0_0, + preg_all); + StoreAlign( + ((__ubuf__ T*&)src_ub0_0 + RowSize + iter_m * RowSize * 2 + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)), + vreg_x_exp_0_1, + preg_all); + } + Add(vreg_x_sum_0_0, vreg_x_sum_0_0, vreg_x_sum_0_1, preg_all); + + LocalMemBar(); + for (uint16_t iter_m = 0; iter_m < ReduceSize; ++iter_m) { + LoadAlign(vreg_x_exp_0_0, + src_ub0_0 + iter_m * RowSize + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)); + + Div(vreg_x_softmax_0, vreg_x_exp_0_0, vreg_x_sum_0_0, preg_all); + + StoreAlign( + ((__ubuf__ T*&)x_softmax_0 + iter_m * RowSize + + ReduceSize * RowSize * (iter_sc + vScRealSize / 4 * 4)), + vreg_x_softmax_0, + preg_LHalf); + } + } +} + +/* + * @ingroup ProcessVec1Vf + * @brief compute max = reducemax, exp(x-max)/sum(exp(x-max)) + * @param [out] dstTensor, output LocalTensor + * @param [in] srcTensor, input LocalTensor + * @param [in] RowSize, input rows + * @param [in] vScBaseSize, input columns, should be 256 bytes aligned, the + * value is originN aligned to 64 + * @param [in] vScRealSize, input origin columns, support range: 0 < originN <= + * 128 + * @param [in] scale, scale value + * @param [in] minValue, minimum value + */ + +template +__aicore__ inline void SoftmaxDnVF(const LocalTensor& dstTensor, + const LocalTensor& srcTensor, + const uint32_t RowSize, + const uint32_t ReduceSize, + const uint32_t vScRealSize, + const T minValue, + const uint32_t dDealSize) { + __ubuf__ T* x_softmax = (__ubuf__ T*)dstTensor.GetPhyAddr(); + __ubuf__ T* input_x_local_UB = (__ubuf__ T*)srcTensor.GetPhyAddr(); + if (dDealSize == 64) { + SoftmaxDndBase64(x_softmax, + input_x_local_UB, + RowSize, + ReduceSize, + vScRealSize, + minValue); + } else if (dDealSize == 32) { + SoftmaxDndBase32(x_softmax, + input_x_local_UB, + RowSize, + ReduceSize, + vScRealSize, + minValue); + } else { + SoftmaxDndBase128(x_softmax, + input_x_local_UB, + RowSize, + ReduceSize, + vScRealSize, + minValue); + } +} +} // namespace FaVectorApi +#endif // VF_SOFTMAX_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_comm.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_comm.h new file mode 100644 index 0000000000..f5e4e93441 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_comm.h @@ -0,0 +1,304 @@ +/** + * 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 compressor_comm.h + * \brief + */ + +#ifndef COMPRESSOR_COMM_H +#define COMPRESSOR_COMM_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" + +using namespace AscendC; + +namespace XllmKernelCompressor { +template +__aicore__ inline T CeilDivT(T num1, T num2) { + if (num2 == 0) { + return static_cast(0); + } + return (num1 + num2 - 1) / num2; +} + +template +__aicore__ inline T Align(T num, T rnd) { + return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd) * (rnd))); +} + +template +__aicore__ inline T Trunc(T num, T rnd) { + return ((rnd) == 0) ? 0 : (((num) / (rnd) * (rnd))); +} + +enum class X_LAYOUT : std::uint8_t { + BSH = static_cast(0), + TH = static_cast(1) +}; + +enum class X_DTYPE : std::uint8_t { + BF16 = static_cast(0), + FP16 = static_cast(1) +}; + +enum class COFF : std::uint8_t { + DISABLE = static_cast(1), + OVERLAP = static_cast(2) +}; + +enum class ROTARY_MODE : std::uint8_t { + HALF = static_cast(1), + INTERLEAVE = static_cast(2) +}; + +enum class TEMPLATE_ID : uint8_t { NORMAL = 0, EMPTY_X = 1, PERF = 2 }; + +template +struct COMPType { + static constexpr X_LAYOUT xLayout = X_L; + static constexpr X_DTYPE xDtype = X_T; + static constexpr COFF coff = C; + static constexpr ROTARY_MODE rotaryMode = Rotary_Mode; +}; + +struct ConstInfo { + // 整个AICORE的任务信息, 左闭右开区间[ (bStart, s2Start), (bEnd, s2End) ) + uint32_t bStart = 0U; + uint32_t sStart = 0U; + uint32_t bEnd = 0U; + uint32_t sEnd = 0U; + + // 分核相关 + uint32_t usedCoreNum = 0; + uint32_t dBaseSize = 0; + uint32_t mBaseSize = 0; + uint32_t tcSize = 0; + uint32_t tcBaseSize = 0; + uint32_t tcBasicBlockNum = 0; + uint32_t dBasicBlockNum = 0; + uint32_t coreGroupNum = 0; + uint32_t singleCoreDealTcBasicNum = 0; + uint32_t dIdx = 0; + uint32_t bIdxOfLastTc = 0; + uint32_t sIdxOfLastTc = 0; + + // shape及参数 + uint32_t batchSize = 0; + uint32_t hSize = 0; + uint32_t sSize = 0; + uint32_t headDim = 0; + uint32_t ropeHeadDim = 0; + uint32_t cmpRatio = 0; + float normEps = 1e-6; + float reciprocalD = 0; + + uint32_t curGroupIdx = 0; + uint32_t tailGroupIdx = 0; + uint32_t tailBasicBlockNum = 0; + uint32_t realDealBasicBlockNum = 0; + + // pageAttention + uint32_t blockNum = 0; + uint32_t blockSize = 0; + uint32_t maxBlockNumPerBatch = 0; + + // workSpace + uint32_t preMm1ResSize = 0; + uint32_t curMm1ResSize = 0; + uint32_t vec1ResSize = 0; + + uint32_t aiCoreIdx = 0; + uint32_t nSize = 0; +}; + +struct RunInfo { + bool isValid = false; + + // 增加字段 + uint32_t dealTcNum = 0; + // 右边相关信息 + uint32_t bStart = 0; + uint32_t sStart = 0; + uint32_t dealSeqCnt = 0; + // 左边相关信息 + uint32_t preBStart = 0; + uint32_t preSStart = 0; + uint32_t preDealSeqCnt = 0; // 左边需要处理的s大小 + uint32_t preFirstSeqCnt = 0; // 左边首块大小 + + uint32_t bEnd = 0; + uint32_t sEnd = 0; + uint32_t bStartSeqIdx = 0; + uint32_t bEndSeqIdx = 0; + + // v2分核信息 sc是左闭右开 + uint32_t scStart = 0; + uint32_t scEnd = 0; + uint32_t dealScSize = 0; + + // vec1Res offset + uint64_t vec1ResOffset = 0; +}; + +struct Vec2RunInfo { + // uint32_t bStart = 0; + uint32_t sStart = 0; + uint32_t bEnd = 0; + uint32_t sEnd = 0; + // v2分核信息 sc是左闭右开 + uint32_t scStart = 0; + uint32_t scEnd = 0; + // uint32_t dealScSize = 0; + + // 增加字段 + uint32_t bStart = 0; + uint32_t compressedId = 0; + uint32_t bCompressedId = 0; + uint32_t dealScSize = 0; +}; + +struct MSplitInfo { + uint32_t vecStartB = 0U; + uint32_t vecStartS = 0U; + uint32_t vecEndB = 0U; + uint32_t vecEndS = 0U; + uint32_t dealTcNum = 0U; + // vec1Res offset + uint64_t vec1StartOffset = 0; + uint64_t vec1ResOffset = 0; +}; + +struct BlockInfo { + __aicore__ inline BlockInfo(uint32_t bIdx, + uint32_t sIdx, + uint32_t dealSeqSize) + : bIdx(bIdx), sIdx(sIdx), dealSeqSize(dealSeqSize){}; + uint32_t bIdx = 0U; + uint32_t sIdx = 0U; + uint32_t dealSeqSize = 0; + + uint32_t isFirst = true; + uint32_t bSeqUsed = 0U; + uint32_t bStartPos = 0U; + uint32_t headHolderSeqCnt = 0U; + uint32_t validSeqCnt = 0U; + uint32_t tailHolderSeqCnt = 0U; + uint32_t dealTcSize = 0U; + uint32_t tailValidSeqCnt = 0U; + uint32_t compressTcSize = 0U; +}; + +// BUFFER的字节数 +inline constexpr uint32_t BUFFER_SIZE_BYTE_32B = 32; +inline constexpr uint32_t BUFFER_SIZE_BYTE_64B = 64; +inline constexpr uint32_t BUFFER_SIZE_BYTE_256B = 256; +inline constexpr uint32_t BUFFER_SIZE_BYTE_512B = 512; +inline constexpr uint32_t BUFFER_SIZE_BYTE_1K = 1024; +inline constexpr uint32_t BUFFER_SIZE_BYTE_2K = 2048; +inline constexpr uint32_t BUFFER_SIZE_BYTE_4K = 4096; +inline constexpr uint32_t BUFFER_SIZE_BYTE_8K = 8192; +inline constexpr uint32_t BUFFER_SIZE_BYTE_16K = 16384; +inline constexpr uint32_t BUFFER_SIZE_BYTE_32K = 32768; +inline constexpr uint32_t BUFFER_SIZE_BYTE_64K = 65536; + +// BLOCK和REPEAT的字节数 +inline constexpr uint64_t BYTE_BLOCK = 32UL; +inline constexpr uint32_t REPEAT_BLOCK_BYTE = 256U; +// BLOCK和REPEAT的FP32元素数 +inline constexpr uint32_t FP32_BLOCK_ELEMENT_NUM = + BYTE_BLOCK / sizeof(float); // 8 +inline constexpr uint32_t FP32_REPEAT_ELEMENT_NUM = + REPEAT_BLOCK_BYTE / sizeof(float); // 64 +inline constexpr uint32_t REPEAT_STRIDE_NUM = + REPEAT_BLOCK_BYTE / BYTE_BLOCK; // 8 +inline constexpr uint32_t REPEAT_MAX_NUM = 255; +inline constexpr uint32_t BRCB_NUM = 8; +inline constexpr uint32_t MAX_R = 256; + +template +__aicore__ inline void CopySingleMatrixNDToNZ(LocalTensor l1Tensor, + const GlobalTensor gmTensor, + uint32_t nValue, + uint32_t dValue, + uint32_t srcDValue, + uint32_t dstNzC0Stride) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nValue; // nd矩阵的行数 + if constexpr (IsSameType::value) { + constexpr uint32_t HALF_SIZE_DIVISOR = 2; + nd2nzPara.dValue = dValue / HALF_SIZE_DIVISOR; + nd2nzPara.srcDValue = srcDValue / HALF_SIZE_DIVISOR; + } else { + nd2nzPara.dValue = dValue; // ND columns + nd2nzPara.srcDValue = srcDValue; // ND row stride + } + nd2nzPara.dstNzC0Stride = dstNzC0Stride; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(l1Tensor, gmTensor, nd2nzPara); +} +template +__aicore__ inline void DumpTensorForDim2(GlobalTensor tensor, + uint32_t desc, + uint32_t dumpSize, + uint32_t row, + uint32_t col) { + uint32_t array2[] = {static_cast(row), static_cast(col)}; + AscendC::ShapeInfo shapeInfo(2, array2); + // AscendC::DumpTensor(tensor, desc, dumpSize, shapeInfo); +} + +template +__aicore__ inline void DumpTensorForDim2(LocalTensor tensor, + uint32_t desc, + uint32_t dumpSize, + uint32_t row, + uint32_t col) { + uint32_t array2[] = {static_cast(row), static_cast(col)}; + AscendC::ShapeInfo shapeInfo(2, array2); + // AscendC::DumpTensor(tensor, desc, dumpSize, shapeInfo); +} + +template +__aicore__ inline void DumpTensorForDim2(LocalTensor tensor, + uint32_t desc, + uint32_t dumpSize) { + uint32_t col = 32 / sizeof(T); + uint32_t array2[] = {static_cast(dumpSize / col), + static_cast(col)}; + AscendC::ShapeInfo shapeInfo(2, array2); + // AscendC::DumpTensor(tensor, desc, dumpSize, shapeInfo); +} + +template +__aicore__ inline void DumpTensorForDim2(GlobalTensor tensor, + uint32_t desc, + uint32_t dumpSize) { + uint32_t col = 32 / sizeof(T); + uint32_t array2[] = {static_cast(dumpSize / col), + static_cast(col)}; + AscendC::ShapeInfo shapeInfo(2, array2); + // AscendC::DumpTensor(tensor, desc, dumpSize, shapeInfo); +} + +} // namespace XllmKernelCompressor +#endif \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_kernel.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_kernel.h new file mode 100644 index 0000000000..cd978349d9 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_kernel.h @@ -0,0 +1,747 @@ +/** + * 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 compressor_kernel.h + * \brief + */ + +#ifndef COMPRESSOR_KERNEL_H +#define COMPRESSOR_KERNEL_H + +#include "compressor_comm.h" +#include "compressor_template_tiling_key.h" +#include "compressor_tiling_data.h" +#if (__CCE_AICORE__ == 220) +#include "arch32/compressor_block_cube.h" +#include "arch32/compressor_block_vec.h" +#else +#include "arch35/compressor_block_cube.h" +#include "arch35/compressor_block_vec.h" +#endif + +using namespace AscendC; + +namespace XllmKernelCompressor { + +template +class CompressorKernel { + public: + __aicore__ inline CompressorKernel( + TPipe* pipe, + const optiling::CompressorTilingData* __restrict tilingData) + : pipe_(pipe), tilingData_(tilingData) {} + + __aicore__ inline void Init(__gm__ uint8_t* x, + __gm__ uint8_t* wKv, + __gm__ uint8_t* wGate, + __gm__ uint8_t* kvState, + __gm__ uint8_t* scoreState, + __gm__ uint8_t* ape, + __gm__ uint8_t* normWeight, + __gm__ uint8_t* ropeSin, + __gm__ uint8_t* ropeCos, + __gm__ uint8_t* kvBlockTable, + __gm__ uint8_t* scoreBlockTable, + __gm__ uint8_t* cuSeqlens, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* startPos, + __gm__ uint8_t* cmpKvOut, + __gm__ uint8_t* workspace); + __aicore__ inline void Process(); + + private: + // ================================Init + // functions================================== + __aicore__ inline void InitWorkspace(__gm__ uint8_t* workspace); + __aicore__ inline uint32_t CalcTcSize(); + // ================================Process + // functions================================ + __aicore__ inline void GetSeqLength(uint32_t index); + __aicore__ inline void GetStartPos(uint32_t index); + __aicore__ inline void GetCurCoreStartIdx(); + __aicore__ inline uint32_t GetBasicNum(); + __aicore__ inline uint32_t GetRemainTcNum(uint32_t sStart, + uint32_t headSize, + uint32_t cmpRatio, + uint32_t seqLength); + __aicore__ inline uint32_t GetTcHeadSize(uint32_t curStartPos, + uint32_t cmpRatio, + uint32_t seqLength); + __aicore__ inline void CalcParams(RunInfo& info); + __aicore__ inline void InitTilingData(); + __aicore__ inline bool IsNeedExcute(uint32_t curBasicBlockIdx); + __aicore__ inline uint32_t GetStartIdx(); + __aicore__ inline uint32_t GetEndIdx(); + __aicore__ inline void ComputeMm1(const RunInfo& info); + __aicore__ inline void ComputeVec1(const RunInfo& info); + __aicore__ inline void ComputeVec2(const RunInfo& info); + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + // ==============================TilingData&TPipe============================== + TPipe* pipe_; + const optiling::CompressorTilingData* __restrict tilingData_; + // ================================Task + // Info==================================== + ConstInfo constInfo{}; + + uint32_t tcStart = 0; + + uint32_t accSeqLength = 0; + uint32_t curActSeqLength = 0; + uint32_t lastActSeqLength = 0; + uint32_t curStartPos = 0; + uint32_t preActSeqIdx = 0; + uint32_t preStartPosIdx = 0; + + uint32_t curBStart = 0; + uint32_t curBEnd = 0; + uint32_t curSStart = 0; + uint32_t curSEnd = 0; + uint32_t curScEnd = 0; + + uint32_t aiCoreIdx = 0; + + bool isExistSeqUsed = false; + bool isExistStartPos = false; + + // 常量 + static constexpr uint64_t SYNC_MODE2 = 2; + static constexpr uint32_t SYNC_C1_V1_FLAG = 6; + static constexpr uint32_t SYNC_V1_C1_FLAG = 7; + + // ==============================Service Define============================== + CompressorBlockCube blockCube_; + CompressorBlockVector blockVec_; + static constexpr uint32_t dbWorkspaceRatio = 1; + + using X_T = typename AscendC:: + Conditional::type; + using T = float; + using MM1_OUT_T = T; + using VEC1_OUT_T = T; + + // GM + GlobalTensor xGm_; + GlobalTensor wkvGm_; + GlobalTensor wgateGm_; + GlobalTensor kvStateGm_; + GlobalTensor scoreStateGm_; + GlobalTensor apeGm_; + GlobalTensor ropeSinGm_; + GlobalTensor ropeCosGm_; + GlobalTensor normWeightGm_; + GlobalTensor kvBlockTableGm_; + GlobalTensor scoreBlockTableGm_; + GlobalTensor cuSeqlensGm_; + GlobalTensor sequsedGm_; + GlobalTensor startPosGm_; + + // ===========================Workspace Global + // Tensor=========================== + GlobalTensor preMm1ResGm; + GlobalTensor curMm1ResGm; + GlobalTensor vec1ResGm; + GlobalTensor vec2InputGm; +}; + +template +__aicore__ inline void CompressorKernel::Init( + __gm__ uint8_t* x, + __gm__ uint8_t* wKv, + __gm__ uint8_t* wGate, + __gm__ uint8_t* kvState, + __gm__ uint8_t* scoreState, + __gm__ uint8_t* ape, + __gm__ uint8_t* normWeight, + __gm__ uint8_t* ropeSin, + __gm__ uint8_t* ropeCos, + __gm__ uint8_t* kvBlockTable, + __gm__ uint8_t* scoreBlockTable, + __gm__ uint8_t* cuSeqlens, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* startPos, + __gm__ uint8_t* cmpKvOut, + __gm__ uint8_t* workspace) { + if ASCEND_IS_AIV { + constInfo.aiCoreIdx = GetBlockIdx() / 2; + } else { + constInfo.aiCoreIdx = GetBlockIdx(); + } + + // GM Init + xGm_.SetGlobalBuffer((__gm__ X_T*)x); + wkvGm_.SetGlobalBuffer((__gm__ X_T*)wKv); + wgateGm_.SetGlobalBuffer((__gm__ X_T*)wGate); + kvStateGm_.SetGlobalBuffer((__gm__ int32_t*)kvState); + scoreStateGm_.SetGlobalBuffer((__gm__ int32_t*)scoreState); + apeGm_.SetGlobalBuffer((__gm__ int32_t*)ape); + ropeSinGm_.SetGlobalBuffer((__gm__ X_T*)ropeSin); + ropeCosGm_.SetGlobalBuffer((__gm__ X_T*)ropeCos); + normWeightGm_.SetGlobalBuffer((__gm__ X_T*)normWeight); + kvBlockTableGm_.SetGlobalBuffer((__gm__ int32_t*)kvBlockTable); + scoreBlockTableGm_.SetGlobalBuffer((__gm__ int32_t*)scoreBlockTable); + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + cuSeqlensGm_.SetGlobalBuffer((__gm__ int32_t*)cuSeqlens); + } + isExistSeqUsed = (seqUsed != nullptr); + isExistStartPos = (startPos != nullptr); + if (isExistSeqUsed) { + sequsedGm_.SetGlobalBuffer((__gm__ int32_t*)seqUsed); + } + if (isExistStartPos) { + startPosGm_.SetGlobalBuffer((__gm__ int32_t*)startPos); + } + + InitTilingData(); + + // 初始化 curActSeqLength、start_pos + if (isExistSeqUsed) { + curActSeqLength = sequsedGm_.GetValue(0); + lastActSeqLength = sequsedGm_.GetValue(constInfo.batchSize - 1); + } else if constexpr (COMP::xLayout == X_LAYOUT::TH) { + curActSeqLength = cuSeqlensGm_.GetValue(1); + accSeqLength = curActSeqLength; + lastActSeqLength = cuSeqlensGm_.GetValue(constInfo.batchSize) - + cuSeqlensGm_.GetValue(constInfo.batchSize - 1); + } else { + curActSeqLength = constInfo.sSize; + lastActSeqLength = constInfo.sSize; + } + + if (isExistStartPos) { + curStartPos = startPosGm_.GetValue(0); + } + + // 计算分核基本信息 + constInfo.tcSize = CalcTcSize(); + constInfo.tcBaseSize = constInfo.mBaseSize / constInfo.cmpRatio; + constInfo.tcBasicBlockNum = (constInfo.tcSize + constInfo.tcBaseSize - 1) / + constInfo.tcBaseSize; // TC方向的基本块 + constInfo.dBasicBlockNum = + constInfo.headDim / constInfo.dBaseSize; // D方向的基本块 + constInfo.coreGroupNum = + constInfo.usedCoreNum / constInfo.dBasicBlockNum; // 核分为多少组 + constInfo.singleCoreDealTcBasicNum = + (constInfo.tcBasicBlockNum + constInfo.coreGroupNum - 1) / + constInfo.coreGroupNum; // 处理的最大基本块数量 + constInfo.dIdx = (constInfo.aiCoreIdx % constInfo.dBasicBlockNum) * + constInfo.dBaseSize; // 每个核处理的d方向的索引 + + // 计算当前核需要处理多少基本块 + constInfo.curGroupIdx = + constInfo.aiCoreIdx / constInfo.dBasicBlockNum; // 当前组id + constInfo.tailGroupIdx = + (constInfo.tcBasicBlockNum + constInfo.singleCoreDealTcBasicNum - 1) / + constInfo.singleCoreDealTcBasicNum - + 1; // 尾组所在id + constInfo.tailBasicBlockNum = + constInfo.tcBasicBlockNum % constInfo.singleCoreDealTcBasicNum == 0 + ? constInfo.singleCoreDealTcBasicNum + : constInfo.tcBasicBlockNum % + constInfo.singleCoreDealTcBasicNum; // 尾组处理基本块数量 + constInfo.realDealBasicBlockNum = + constInfo.curGroupIdx < constInfo.tailGroupIdx + ? constInfo.singleCoreDealTcBasicNum + : constInfo.tailBasicBlockNum; // 当前组实际处理的基本块 + if (constInfo.curGroupIdx > constInfo.tailGroupIdx) { + constInfo.realDealBasicBlockNum = 0; + } + InitWorkspace(workspace); + if ASCEND_IS_AIC { + blockCube_.InitParams(constInfo); + blockCube_.Init(x, + wKv, + wGate, + kvState, + scoreState, + ape, + normWeight, + ropeSin, + ropeCos, + kvBlockTable, + scoreBlockTable, + cuSeqlens, + seqUsed, + startPos, + cmpKvOut); + blockCube_.InitBuffers(pipe_); +#if __CCE_AICORE__ == 310 +#else + blockCube_.InitGlobalBuffers(preMm1ResGm, curMm1ResGm); +#endif + } else { + blockVec_.InitParams(constInfo); + blockVec_.Init(x, + wKv, + wGate, + kvState, + scoreState, + ape, + normWeight, + ropeSin, + ropeCos, + kvBlockTable, + scoreBlockTable, + cuSeqlens, + seqUsed, + startPos, + cmpKvOut); + blockVec_.InitBuffers(pipe_); +#if __CCE_AICORE__ == 310 + blockVec_.InitVec1GlobalTensor( + preMm1ResGm, curMm1ResGm, vec1ResGm, vec2InputGm); +#else + blockVec_.InitVec1GlobalTensor( + preMm1ResGm, curMm1ResGm, vec1ResGm, vec2InputGm); +#endif + } +} + +template +__aicore__ inline void CompressorKernel::InitTilingData() { + constInfo.cmpRatio = tilingData_->baseParams.cmpRatio; + constInfo.batchSize = tilingData_->baseParams.batchSize; + constInfo.mBaseSize = tilingData_->innerSplitParams.mBaseSize; + constInfo.dBaseSize = tilingData_->innerSplitParams.dBaseSize; + constInfo.headDim = tilingData_->baseParams.headDim; + constInfo.hSize = tilingData_->baseParams.hiddenSize; + constInfo.sSize = tilingData_->baseParams.seqSize; + constInfo.ropeHeadDim = tilingData_->baseParams.ropeHeadDim; + constInfo.normEps = tilingData_->baseParams.normEps; + constInfo.reciprocalD = tilingData_->baseParams.reciprocalD; + constInfo.usedCoreNum = tilingData_->baseParams.usedCoreNum; + + constInfo.blockNum = tilingData_->pageAttentionParams.blockNum; + constInfo.blockSize = tilingData_->pageAttentionParams.blockSize; + constInfo.maxBlockNumPerBatch = + tilingData_->pageAttentionParams.maxBlockNumPerBatch; + + constInfo.preMm1ResSize = tilingData_->workspaceParams.preMm1ResSize; + constInfo.curMm1ResSize = tilingData_->workspaceParams.curMm1ResSize; + constInfo.nSize = tilingData_->baseParams.nSize; + constInfo.vec1ResSize = tilingData_->workspaceParams.vec1ResSize; +} + +template +__aicore__ inline void CompressorKernel::InitWorkspace( + __gm__ uint8_t* workspace) { + uint64_t offset = 0; + // preMm1ResGm + preMm1ResGm.SetGlobalBuffer( + (__gm__ MM1_OUT_T*)(workspace + offset + + constInfo.aiCoreIdx * dbWorkspaceRatio * + constInfo.preMm1ResSize * sizeof(MM1_OUT_T))); + offset += GetBlockNum() * dbWorkspaceRatio * constInfo.preMm1ResSize * + sizeof(MM1_OUT_T); + + // curMm1ResGm + curMm1ResGm.SetGlobalBuffer( + (__gm__ MM1_OUT_T*)(workspace + offset + + constInfo.aiCoreIdx * dbWorkspaceRatio * + constInfo.curMm1ResSize * sizeof(MM1_OUT_T))); + offset += GetBlockNum() * dbWorkspaceRatio * constInfo.curMm1ResSize * + sizeof(MM1_OUT_T); + + uint64_t beforeVecOffset = offset; + + // vec1Res + vec1ResGm.SetGlobalBuffer( + (__gm__ VEC1_OUT_T*)(workspace + offset + + (constInfo.dIdx + + (constInfo.aiCoreIdx / constInfo.dBasicBlockNum) * + dbWorkspaceRatio * constInfo.vec1ResSize * + constInfo.dBasicBlockNum) * + sizeof(VEC1_OUT_T))); + offset += GetBlockNum() * dbWorkspaceRatio * constInfo.vec1ResSize * + sizeof(VEC1_OUT_T); + // vec2Input + vec2InputGm.SetGlobalBuffer( + (__gm__ VEC1_OUT_T*)(workspace + beforeVecOffset + + (constInfo.aiCoreIdx / constInfo.dBasicBlockNum) * + dbWorkspaceRatio * constInfo.vec1ResSize * + constInfo.dBasicBlockNum * sizeof(VEC1_OUT_T))); + offset += GetBlockNum() * dbWorkspaceRatio * constInfo.vec1ResSize * + sizeof(VEC1_OUT_T); +} + +template +__aicore__ inline uint32_t CompressorKernel::CalcTcSize() { + uint32_t totalBasicNum = 0; + + for (uint32_t bIdx = 0; bIdx < constInfo.batchSize; ++bIdx) { + GetStartPos(bIdx); + GetSeqLength(bIdx); + totalBasicNum += GetBasicNum(); + } + + return totalBasicNum; +} + +template +__aicore__ inline void CompressorKernel::GetSeqLength(uint32_t bIdx) { + if (preActSeqIdx != bIdx) { + preActSeqIdx = bIdx; + if (isExistSeqUsed) { + curActSeqLength = sequsedGm_.GetValue(bIdx); + } else { + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + if (bIdx == 0) { + accSeqLength = cuSeqlensGm_.GetValue(bIdx + 1); + curActSeqLength = accSeqLength; + } else { + uint32_t tmpSeqLength = accSeqLength; + accSeqLength = cuSeqlensGm_.GetValue(bIdx + 1); + curActSeqLength = accSeqLength - tmpSeqLength; + } + } else { + curActSeqLength = constInfo.sSize; + } + } + } +} + +template +__aicore__ inline void CompressorKernel::GetStartPos(uint32_t bIdx) { + if (!isExistStartPos) { + curStartPos = 0; + } else if (preStartPosIdx != bIdx) { + curStartPos = startPosGm_.GetValue(bIdx); + preStartPosIdx = bIdx; + } +} + +template +__aicore__ inline void CompressorKernel::GetCurCoreStartIdx() { + // 获取当前核开始索引 + + uint32_t totalBasicNum = 0; + // 在当前batch的seq开始索引位置 + uint32_t startIdx = 0; + // Tc的开始位置 + tcStart = (constInfo.aiCoreIdx / constInfo.dBasicBlockNum) * + constInfo.tcBaseSize * constInfo.singleCoreDealTcBasicNum; + if (tcStart >= constInfo.tcSize) { + tcStart = constInfo.tcSize; + curBEnd = constInfo.batchSize; + return; + } + for (uint32_t bIdx = 0; bIdx < constInfo.batchSize; ++bIdx) { + if (totalBasicNum == tcStart) { + curBEnd = bIdx; + curSEnd = 0; + curScEnd = 0; + return; + } + GetStartPos(bIdx); + GetSeqLength(bIdx); + + // 加上头块,若有 + uint32_t curBasicNum = 0; + uint32_t headSize = + GetTcHeadSize(curStartPos, constInfo.cmpRatio, curActSeqLength); + curBasicNum = headSize > 0 ? curBasicNum + 1 : curBasicNum; + // 加上中间整块及尾块 + curBasicNum += (curActSeqLength - headSize + constInfo.cmpRatio - 1) / + constInfo.cmpRatio; + if (totalBasicNum + curBasicNum > tcStart) { + uint32_t curBasicNumStart = tcStart - totalBasicNum; + if (curBasicNumStart > 0 && headSize > 0) { + startIdx = headSize + (curBasicNumStart - 1) * constInfo.cmpRatio; + } else { + startIdx = curBasicNumStart * constInfo.cmpRatio; + } + curBEnd = bIdx; + curSEnd = startIdx; + curScEnd = curBasicNumStart; + return; + } + totalBasicNum += curBasicNum; + } +} + +template +__aicore__ inline uint32_t CompressorKernel::GetBasicNum() { + // 获取 m方向上对应基本单元Tc的个数 + uint32_t curBasicNum = 0; + uint32_t headSize = 0; + if (curStartPos % constInfo.cmpRatio != 0) { + headSize = constInfo.cmpRatio - curStartPos % constInfo.cmpRatio; + headSize = headSize > curActSeqLength ? 0 : headSize; + curBasicNum = headSize > 0 ? curBasicNum + 1 : curBasicNum; + } + // 加上中间整块及尾块 + curBasicNum += (curActSeqLength - headSize + constInfo.cmpRatio - 1) / + constInfo.cmpRatio; + return curBasicNum; +} + +template +__aicore__ inline uint32_t CompressorKernel::GetTcHeadSize( + uint32_t curStartPos, + uint32_t cmpRatio, + uint32_t seqLength) { + // 计算头块大小 + uint32_t headSize = 0; + if (curStartPos % cmpRatio != 0) { + headSize = (cmpRatio - curStartPos % cmpRatio); + headSize = + headSize > seqLength ? 0 : headSize; // 处理seq不足head大小的情况 + } + + return headSize; +} + +template +__aicore__ inline uint32_t CompressorKernel::GetRemainTcNum( + uint32_t sStart, + uint32_t headSize, + uint32_t cmpRatio, + uint32_t seqLength) { + // 计算当前batch剩余的Tc块数量 + uint32_t curRemainTcNum = 0; + if (sStart == 0) { + curRemainTcNum = (seqLength - headSize + cmpRatio - 1) / cmpRatio; + curRemainTcNum = headSize == 0 ? curRemainTcNum : curRemainTcNum + 1; + } else { + curRemainTcNum = (seqLength - sStart + cmpRatio - 1) / cmpRatio; + } + + return curRemainTcNum; +} + +template +__aicore__ inline void CompressorKernel::CalcParams(RunInfo& info) { + if (curBEnd == constInfo.batchSize - 1 && curSEnd == lastActSeqLength) { + return; + } + + curBStart = curBEnd; + curSStart = curSEnd; + info.scStart = curScEnd; + + // sEnd到了seq末尾,切换到下一个batch + GetSeqLength(curBStart); + // 跳batch处理,batch=0且seq=0时不跳 + if (curSStart == curActSeqLength && + (curBStart != 0 || curActSeqLength != 0)) { + curBStart++; + curSStart = 0; + info.scStart = 0; + } + + info.bStart = curBStart; + info.sStart = curSStart; + + // 1. 计算本次需要处理的Tc块数量 + uint32_t dealTcNum = constInfo.tcBaseSize + tcStart <= constInfo.tcSize + ? constInfo.tcBaseSize + : constInfo.tcSize - tcStart; + info.dealTcNum = dealTcNum; + tcStart += dealTcNum; // 更新全局tc块起始偏移,下次使用 + uint32_t accBasicNum = 0; + info.dealScSize = 0; + + uint32_t tcNumCount = dealTcNum; + + for (uint32_t bIdx = curBStart; bIdx < constInfo.batchSize; ++bIdx) { + curBEnd = bIdx; + info.bEnd = curBEnd; + + GetSeqLength(bIdx); + GetStartPos(bIdx); + uint32_t headSize = + GetTcHeadSize(curStartPos, constInfo.cmpRatio, curActSeqLength); + uint32_t curBatchTcNum = + GetRemainTcNum(curSStart, + headSize, + constInfo.cmpRatio, + curActSeqLength); // 当前batch需要处理的Tc块 + uint32_t curDealTcNum = (tcNumCount >= curBatchTcNum) + ? curBatchTcNum + : tcNumCount; // 本次能处理多少个Tc块 + + tcNumCount -= curDealTcNum; // 更新需要处理Tc块的计数 + bool isSeqFinish = + (curDealTcNum == curBatchTcNum); // 处理到当前batch的末尾 + bool hasTail = ((curActSeqLength - headSize) % constInfo.cmpRatio) != + 0; // 是否存在尾块 + + uint32_t curValidSc = curDealTcNum; // 更新sc + if (isSeqFinish && hasTail && curValidSc > 0) { + curValidSc--; + } + info.dealScSize += curValidSc; + // 2. 当前batch全部处理完 + if (isSeqFinish) { + curSEnd = curActSeqLength; + uint32_t curBatchTotalTcNum = GetRemainTcNum( + 0, headSize, constInfo.cmpRatio, curActSeqLength); // 当前batch总Tc块 + uint32_t tcNumBefore = curBatchTotalTcNum - curDealTcNum; + info.scEnd = tcNumBefore + curDealTcNum; + + if (hasTail && info.scEnd > 0) { + info.scEnd--; + } + curScEnd = info.scEnd; + } else { + // 3. 处理到当前batch刚好攒满需要处理的Tc块 + uint32_t remainSLen = 0; + if (curSStart == 0) { + // 加上头块如果有 + uint32_t midTc = (headSize > 0) ? (curDealTcNum - 1) : curDealTcNum; + remainSLen = headSize + midTc * constInfo.cmpRatio; + info.scEnd = curValidSc; + } else { + remainSLen = curDealTcNum * constInfo.cmpRatio; + info.scEnd = info.scStart + curValidSc; + } + + curSEnd = curSStart + remainSLen; + // 尾块处理 + if (curSEnd > curActSeqLength) { + curSEnd = curActSeqLength; + } + } + info.sEnd = curSEnd; + curScEnd = info.scEnd; + + if (tcNumCount > 0) { + curSStart = 0; + } else { + break; + } + } +} + +template +__aicore__ inline bool CompressorKernel::IsNeedExcute( + uint32_t curBasicBlockIdx) { + // 处理v2的非完整轮,修正后的需要循环的次数 + uint32_t fixBasicBlockNum = + (constInfo.realDealBasicBlockNum + constInfo.nSize - 1) / + constInfo.nSize * constInfo.nSize; + if (constInfo.curGroupIdx > constInfo.tailGroupIdx || + curBasicBlockIdx >= fixBasicBlockNum) { + return false; + } + return true; +} + +template +__aicore__ inline void CompressorKernel::ComputeMm1(const RunInfo& info) { + CrossCoreWaitFlag(SYNC_V1_C1_FLAG); + blockCube_.ComputeMm1(info); + CrossCoreSetFlag(SYNC_C1_V1_FLAG); +} + +template +__aicore__ inline void CompressorKernel::ComputeVec1( + const RunInfo& info) { +#if (__CCE_AICORE__ == 220) + CrossCoreWaitFlag(SYNC_C1_V1_FLAG); +#else + CrossCoreWaitFlag(SYNC_C1_V1_FLAG); +#endif + blockVec_.ComputeVec1(info); +#if (__CCE_AICORE__ == 220) + CrossCoreSetFlag(SYNC_V1_C1_FLAG); +#else + CrossCoreSetFlag(SYNC_V1_C1_FLAG); +#endif +} + +template +__aicore__ inline void CompressorKernel::ComputeVec2( + const RunInfo& info) { + blockVec_.ComputeVec2(info); +} + +template +__aicore__ inline void CompressorKernel::AllocEventID() { + if ASCEND_IS_AIC { + blockCube_.AllocEventID(pipe_); + } else { + blockVec_.AllocEventID(); +#if (__CCE_AICORE__ == 220) + CrossCoreSetFlag(SYNC_V1_C1_FLAG); +#else + CrossCoreSetFlag(SYNC_V1_C1_FLAG); +#endif + } +} + +template +__aicore__ inline void CompressorKernel::FreeEventID() { + if ASCEND_IS_AIC { + CrossCoreWaitFlag(SYNC_V1_C1_FLAG); + blockCube_.FreeEventID(pipe_); + } else { + blockVec_.FreeEventID(); + } +} + +template +__aicore__ inline void CompressorKernel::Process() { + AllocEventID(); + + RunInfo extraInfo[1]; + GetCurCoreStartIdx(); + + RunInfo vec2Info{}; + for (uint32_t i = 0; i < constInfo.singleCoreDealTcBasicNum; ++i) { + RunInfo& extraInfo0 = extraInfo[0]; + // 获取各切分轴的起始核结束索引 + CalcParams(extraInfo0); + if ((i % constInfo.nSize) == 0) { + vec2Info.bStart = extraInfo0.bStart; + vec2Info.sStart = extraInfo0.sStart; + vec2Info.scStart = extraInfo0.scStart; + vec2Info.dealTcNum = 0; + vec2Info.dealScSize = 0; + } + + extraInfo0.vec1ResOffset = vec2Info.dealScSize * constInfo.headDim; + bool isNeedExcute = IsNeedExcute(i); + if ASCEND_IS_AIC { + if (isNeedExcute && i < constInfo.realDealBasicBlockNum) { + ComputeMm1(extraInfo0); + } + } else { + if (isNeedExcute && i < constInfo.realDealBasicBlockNum) { + ComputeVec1(extraInfo0); + vec2Info.dealTcNum += extraInfo0.dealTcNum; + vec2Info.dealScSize += extraInfo0.dealScSize; + } + + // 累积N个基本块/最后一次循环 + if ((i + 1) % constInfo.nSize == 0 || + (i + 1) == constInfo.singleCoreDealTcBasicNum) { + SyncAll(); + if (isNeedExcute) { + vec2Info.bEnd = extraInfo0.bEnd; + vec2Info.sEnd = extraInfo0.sEnd; + vec2Info.scEnd = extraInfo0.scEnd; + // 累计已压缩的块为0时, 不需要执行后续计算 + if (vec2Info.dealScSize) { + ComputeVec2(vec2Info); + } + } + SyncAll(); + } + } + } + FreeEventID(); +} + +} // namespace XllmKernelCompressor + +#endif // COMPRESSOR_KERNEL_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_kernel_perf.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_kernel_perf.h new file mode 100644 index 0000000000..c92be2c73d --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_kernel_perf.h @@ -0,0 +1,762 @@ +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved. + * This file is a part of the CANN Open Software. + * Licensed under CANN Open Software License Agreement Version 1.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 compressor_kernel_perf.h + * \brief + */ + +#ifndef COMPRESSOR_KERNEL_PERF_H +#define COMPRESSOR_KERNEL_PERF_H + +#include "compressor_comm.h" +#include "compressor_template_tiling_key.h" +#include "compressor_tiling_data.h" +#include "compressor_tools.h" +#if (__CCE_AICORE__ == 220) +#include "arch32/compressor_block_cube_perf.h" +#include "arch32/compressor_block_vec_perf.h" +#else +#include "arch35/compressor_block_cube.h" +#include "arch35/compressor_block_vec.h" +#endif + +using namespace AscendC; + +namespace XllmKernelCompressor { + +struct CmpBlockInfo { + __aicore__ inline CmpBlockInfo(){}; + __aicore__ inline CmpBlockInfo(uint32_t bIdx, + uint32_t sIdx, + bool needReset = false) + : bIdx(bIdx), sIdx(sIdx), needReset(needReset){}; + + uint32_t bIdx = 0U; + uint32_t sIdx = 0U; + uint32_t bSeqUsed = 0U; + uint32_t bStartPos = 0U; + bool needReset = false; + bool isFirst = true; + + uint32_t headSeqCnt = 0U; + uint32_t validSeqCnt = 0U; + uint32_t tailSeqCnt = 0U; + bool isCompress = 0U; +}; + +struct BasicBlockInfo { + uint32_t dealTcNum = 0; + uint32_t compressedTcNum = 0; + uint32_t dealSeqCnt = 0; + uint32_t preDealSeqCnt = 0; +}; + +template +class CompressorKernelPerf { + public: + __aicore__ inline CompressorKernelPerf( + TPipe* pipe, + const optiling::CompressorTilingData* __restrict tilingData) + : pipe_(pipe), tilingData_(tilingData) {} + + __aicore__ inline void Init(__gm__ uint8_t* x, + __gm__ uint8_t* wKv, + __gm__ uint8_t* wGate, + __gm__ uint8_t* kvState, + __gm__ uint8_t* scoreState, + __gm__ uint8_t* ape, + __gm__ uint8_t* normWeight, + __gm__ uint8_t* ropeSin, + __gm__ uint8_t* ropeCos, + __gm__ uint8_t* kvBlockTable, + __gm__ uint8_t* scoreBlockTable, + __gm__ uint8_t* cuSeqlens, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* startPos, + __gm__ uint8_t* cmpKvOut, + __gm__ uint8_t* workspace); + __aicore__ inline void Process(); + + private: + // ================================Init + // functions================================== + __aicore__ inline void InitWorkspace(__gm__ uint8_t* workspace); + // ================================Process + // functions================================ + __aicore__ inline void InitTilingData(); + __aicore__ inline uint32_t CalcSIdxOfLastTc(); + // 获取基本块数量 + __aicore__ inline void CalcCmpBlockInfo(CmpBlockInfo& cmpBlockInfo); + __aicore__ inline void SkipInvalidBatch(CmpBlockInfo& cmpBlockInfo, + uint32_t maxBatchSize); + __aicore__ inline uint32_t GetNextCmpSeqCnt(CmpBlockInfo& cmpBlockInfo); + __aicore__ inline void AcceptUpdate(CmpBlockInfo& cmpBlockInfo); + __aicore__ inline void UpdateBasicBlockInfo(BasicBlockInfo& basicBlockInfo, + CmpBlockInfo& cmpBlockInfo, + bool isLeft); + __aicore__ inline BasicBlockInfo SkipOneBasicBlock( + CmpBlockInfo& rightCmpBlockInfo, + CmpBlockInfo& leftCmpBlockInfo); + __aicore__ inline uint32_t GetBasicBlockNum(); + // 计算当前核起始位置 + __aicore__ inline void CalcCurCoreStartIdx(CmpBlockInfo& rightCmpBlockInfo, + CmpBlockInfo& leftCmpBlockInfo); + // 计算分核基本信息 + __aicore__ inline void CalcSplitCoreInfo(); + + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + __aicore__ inline void ComputeMm1(const RunInfo& info); + __aicore__ inline void ComputeVec1(const RunInfo& info); + __aicore__ inline void ComputeVec2(const Vec2RunInfo& info); + + __aicore__ inline bool IsNeedExcuteC1V1(uint32_t curBasicBlockIdx); + __aicore__ inline bool IsNeedSyncAll(uint32_t curBasicBlockIdx); + __aicore__ inline void CalcC1V1Params(RunInfo& info, + uint32_t curBasicBlockIdx, + CmpBlockInfo& rightCmpBlockInfo, + CmpBlockInfo& leftCmpBlockInfo); + __aicore__ inline void UpdateVec2Info(Vec2RunInfo& vec2Info, + uint32_t curBasicBlockIdx, + const RunInfo& info); + __aicore__ inline bool IsNeedExcuteV2(Vec2RunInfo& vec2Info); + + using X_T = typename AscendC:: + Conditional::type; + using T = float; + using MM1_OUT_T = T; + using VEC1_OUT_T = T; + + // 常量 + static constexpr uint64_t SYNC_MODE2 = 2; + static constexpr uint32_t SYNC_C1_V1_FLAG = 6; + static constexpr uint32_t SYNC_V1_C1_FLAG = 7; + static constexpr uint32_t dbWorkspaceRatio = 1; + + // ==============================TilingData&TPipe============================== + TPipe* pipe_; + const optiling::CompressorTilingData* __restrict tilingData_; + // ===========================Workspace Global + // Tensor=========================== + GlobalTensor preMm1ResGm; + GlobalTensor curMm1ResGm; + GlobalTensor vec1ResGm; + GlobalTensor vec2InputGm; + // ================================Task + // Info==================================== + CompressorTools tools_; + ConstInfo constInfo{}; + uint32_t aiCoreIdx = 0; + + // ==============================Service Define============================== + CompressorBlockCubePerf blockCube_; + CompressorBlockVectorPerf blockVec_; + + uint32_t allCompressedTcNum_ = 0; + uint32_t curCompressedTcNum_ = 0; + uint32_t accDealSize = 0; +}; + +template +__aicore__ inline void CompressorKernelPerf::Init( + __gm__ uint8_t* x, + __gm__ uint8_t* wKv, + __gm__ uint8_t* wGate, + __gm__ uint8_t* kvState, + __gm__ uint8_t* scoreState, + __gm__ uint8_t* ape, + __gm__ uint8_t* normWeight, + __gm__ uint8_t* ropeSin, + __gm__ uint8_t* ropeCos, + __gm__ uint8_t* kvBlockTable, + __gm__ uint8_t* scoreBlockTable, + __gm__ uint8_t* cuSeqlens, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* startPos, + __gm__ uint8_t* cmpKvOut, + __gm__ uint8_t* workspace) { + if ASCEND_IS_AIV { + constInfo.aiCoreIdx = GetBlockIdx() / 2; + } else { + constInfo.aiCoreIdx = GetBlockIdx(); + } + + InitTilingData(); + + // init tools + tools_.toolParams_.seqSize = tilingData_->baseParams.seqSize; + tools_.toolParams_.cmpRatio = tilingData_->baseParams.cmpRatio; + tools_.Init(startPos, seqUsed, cuSeqlens); + + // 剔除尾部的无效batch + for (; constInfo.batchSize > 0; --constInfo.batchSize) { + uint32_t bSeqUsed = tools_.GetSeqUsed(constInfo.batchSize - 1); + if (bSeqUsed > 0) { + break; + } + } + + // 所有batch的有效序列都为0时, 直接退出 + if (constInfo.batchSize == 0) { + return; + } + + // 0. 计算最后一个Tc块的起始位置 + constInfo.bIdxOfLastTc = constInfo.batchSize - 1; + constInfo.sIdxOfLastTc = CalcSIdxOfLastTc(); + // 1. 计算基本块数量 + constInfo.tcBasicBlockNum = GetBasicBlockNum(); + // 2. 计算head_dim的切分大小, 构建ConstInfo的其他信息 + CalcSplitCoreInfo(); + // 3. 初始化workspace + InitWorkspace(workspace); + // 4. 初始化block层 + if ASCEND_IS_AIC { +#if __CCE_AICORE__ == 310 + blockCube_.InitParams(constInfo); +#else + blockCube_.InitParams(constInfo, tools_); +#endif + blockCube_.Init(x, + wKv, + wGate, + kvState, + scoreState, + ape, + normWeight, + ropeSin, + ropeCos, + kvBlockTable, + scoreBlockTable, + cuSeqlens, + seqUsed, + startPos, + cmpKvOut); + blockCube_.InitBuffers(pipe_); +#if __CCE_AICORE__ == 310 +#else + blockCube_.InitGlobalBuffers(preMm1ResGm, curMm1ResGm); +#endif + } else { + blockVec_.InitParams(constInfo, tools_); + blockVec_.Init(x, + wKv, + wGate, + kvState, + scoreState, + ape, + normWeight, + ropeSin, + ropeCos, + kvBlockTable, + scoreBlockTable, + cuSeqlens, + seqUsed, + startPos, + cmpKvOut); + blockVec_.InitBuffers(pipe_); +#if __CCE_AICORE__ == 310 + blockVec_.InitVec1GlobalTensor( + preMm1ResGm, curMm1ResGm, vec1ResGm, vec2InputGm); +#else + blockVec_.InitVec1GlobalTensor( + preMm1ResGm, curMm1ResGm, vec1ResGm, vec2InputGm); +#endif + } +} + +template +__aicore__ inline void CompressorKernelPerf::InitTilingData() { + constInfo.cmpRatio = tilingData_->baseParams.cmpRatio; + constInfo.batchSize = tilingData_->baseParams.batchSize; + constInfo.mBaseSize = tilingData_->innerSplitParams.mBaseSize; + constInfo.headDim = tilingData_->baseParams.headDim; + constInfo.hSize = tilingData_->baseParams.hiddenSize; + constInfo.sSize = tilingData_->baseParams.seqSize; + constInfo.ropeHeadDim = tilingData_->baseParams.ropeHeadDim; + constInfo.normEps = tilingData_->baseParams.normEps; + constInfo.reciprocalD = tilingData_->baseParams.reciprocalD; + constInfo.usedCoreNum = tilingData_->baseParams.usedCoreNum; + + constInfo.blockNum = tilingData_->pageAttentionParams.blockNum; + constInfo.blockSize = tilingData_->pageAttentionParams.blockSize; + constInfo.maxBlockNumPerBatch = + tilingData_->pageAttentionParams.maxBlockNumPerBatch; + + constInfo.preMm1ResSize = tilingData_->workspaceParams.preMm1ResSize; + constInfo.curMm1ResSize = tilingData_->workspaceParams.curMm1ResSize; + constInfo.nSize = tilingData_->baseParams.nSize; + constInfo.vec1ResSize = tilingData_->workspaceParams.vec1ResSize; +} + +template +__aicore__ inline uint32_t CompressorKernelPerf::CalcSIdxOfLastTc() { + // 在Init中已确保倒数第一个batch的bSeqUsed不会是0 + uint32_t cmpRatio = constInfo.cmpRatio; + uint32_t bSeqUsed = tools_.GetSeqUsed(constInfo.batchSize - 1); + uint32_t bStartPos = tools_.GetStartPos(constInfo.batchSize - 1); + + // 1.先假设start_pos不再尾块、并且尾块未填满 + uint32_t lastSeqCnt = (bStartPos + bSeqUsed) % cmpRatio; + // 2.处理结束点正好填满cmp block的情况 + if (lastSeqCnt == 0) { + lastSeqCnt = cmpRatio; + } + // 3.处理start_pos在最后一个压缩块的情况 + if (bSeqUsed < lastSeqCnt) { + lastSeqCnt = bSeqUsed; + } + + return (bSeqUsed - lastSeqCnt); +} + +template +__aicore__ inline void CompressorKernelPerf::CalcCmpBlockInfo( + CmpBlockInfo& cmpBlockInfo) { + uint32_t cmpRatio = constInfo.cmpRatio; + // 计算压缩块信息 + cmpBlockInfo.headSeqCnt = + (cmpBlockInfo.bStartPos + cmpBlockInfo.sIdx) % cmpRatio; + cmpBlockInfo.validSeqCnt = cmpBlockInfo.bSeqUsed - cmpBlockInfo.sIdx; + if (cmpBlockInfo.headSeqCnt + cmpBlockInfo.validSeqCnt > cmpRatio) { + cmpBlockInfo.validSeqCnt = cmpRatio - cmpBlockInfo.headSeqCnt; + cmpBlockInfo.tailSeqCnt = 0; + } else { + cmpBlockInfo.tailSeqCnt = + cmpRatio - (cmpBlockInfo.headSeqCnt + cmpBlockInfo.validSeqCnt); + } + cmpBlockInfo.isCompress = (cmpBlockInfo.tailSeqCnt == 0); +} + +template +__aicore__ inline void CompressorKernelPerf::SkipInvalidBatch( + CmpBlockInfo& cmpBlockInfo, + uint32_t maxBatchSize) { + for (; cmpBlockInfo.bIdx < maxBatchSize; ++cmpBlockInfo.bIdx) { + cmpBlockInfo.bSeqUsed = tools_.GetSeqUsed(cmpBlockInfo.bIdx); + if (cmpBlockInfo.bSeqUsed > 0) { + break; + } + } + if (cmpBlockInfo.bIdx < maxBatchSize) { + cmpBlockInfo.bStartPos = tools_.GetStartPos(cmpBlockInfo.bIdx); + } +} + +template +__aicore__ inline uint32_t CompressorKernelPerf::GetNextCmpSeqCnt( + CmpBlockInfo& cmpBlockInfo) { + if (cmpBlockInfo.isFirst) { + cmpBlockInfo.isFirst = false; + SkipInvalidBatch(cmpBlockInfo, constInfo.batchSize); + } + + if (cmpBlockInfo.bIdx >= constInfo.batchSize) { + return 0; + } + + CalcCmpBlockInfo(cmpBlockInfo); + return cmpBlockInfo.validSeqCnt; +} + +template +__aicore__ inline void CompressorKernelPerf::AcceptUpdate( + CmpBlockInfo& cmpBlockInfo) { + // 更新sIdx和bIdx、以及与bIdx相关的bStartPos和bSeqUsed + cmpBlockInfo.sIdx += cmpBlockInfo.validSeqCnt; + if (cmpBlockInfo.sIdx == cmpBlockInfo.bSeqUsed) { + cmpBlockInfo.sIdx = 0; + cmpBlockInfo.bIdx++; + if (cmpBlockInfo.needReset && cmpBlockInfo.bIdx == constInfo.batchSize) { + cmpBlockInfo.bIdx = 0; + cmpBlockInfo.needReset = false; + } + SkipInvalidBatch(cmpBlockInfo, constInfo.batchSize); + } +} + +template +__aicore__ inline void CompressorKernelPerf::UpdateBasicBlockInfo( + BasicBlockInfo& basicBlockInfo, + CmpBlockInfo& cmpBlockInfo, + bool isLeft) { + if (isLeft) { + basicBlockInfo.preDealSeqCnt += cmpBlockInfo.validSeqCnt; + } else { + basicBlockInfo.dealSeqCnt += cmpBlockInfo.validSeqCnt; + basicBlockInfo.dealTcNum++; + if (cmpBlockInfo.tailSeqCnt == 0) { + basicBlockInfo.compressedTcNum++; + } + } +} + +template +__aicore__ inline BasicBlockInfo CompressorKernelPerf::SkipOneBasicBlock( + CmpBlockInfo& rightCmpBlockInfo, + CmpBlockInfo& leftCmpBlockInfo) { + BasicBlockInfo basicBlockInfo{}; + if constexpr (COMP::coff == COFF::OVERLAP) { + uint32_t leftFinishSeqCnt = 0; + uint32_t rightFinishSeqCnt = 0; + for (;;) { + uint32_t rightSeqCnt = GetNextCmpSeqCnt(rightCmpBlockInfo); + if (rightSeqCnt == 0 || + (rightFinishSeqCnt + rightSeqCnt > constInfo.mBaseSize)) { + break; + } + uint32_t leftSeqCnt = GetNextCmpSeqCnt(leftCmpBlockInfo); + if ((leftSeqCnt == 0) || + (leftFinishSeqCnt + leftSeqCnt > constInfo.mBaseSize)) { + break; + } + // PRINTF("rightSeqCnt:%d leftSeqCnt:%d\n", rightSeqCnt, leftSeqCnt); + rightFinishSeqCnt += rightSeqCnt; + leftFinishSeqCnt += leftSeqCnt; + + // 收集基本块信息 + UpdateBasicBlockInfo(basicBlockInfo, leftCmpBlockInfo, true); + UpdateBasicBlockInfo(basicBlockInfo, rightCmpBlockInfo, false); + + AcceptUpdate(rightCmpBlockInfo); + // PRINTF("Right cmpBlockInfo.bIdx:%d cmpBlockInfo.sIdx:%d + // cmpBlockInfo.bSeqUsed:%d cmpBlockInfo.bStartPos:%d\n", + // rightCmpBlockInfo.bIdx, rightCmpBlockInfo.sIdx, + // rightCmpBlockInfo.bSeqUsed, rightCmpBlockInfo.bStartPos); + AcceptUpdate(leftCmpBlockInfo); + // PRINTF("Left cmpBlockInfo.bIdx:%d cmpBlockInfo.sIdx:%d + // cmpBlockInfo.bSeqUsed:%d cmpBlockInfo.bStartPos:%d\n", + // leftCmpBlockInfo.bIdx, leftCmpBlockInfo.sIdx, + // leftCmpBlockInfo.bSeqUsed, leftCmpBlockInfo.bStartPos); + } + } else { + uint32_t rightFinishSeqCnt = 0; + for (;;) { + uint32_t rightSeqCnt = GetNextCmpSeqCnt(rightCmpBlockInfo); + if (rightSeqCnt == 0 || + (rightFinishSeqCnt + rightSeqCnt > constInfo.mBaseSize)) { + break; + } + rightFinishSeqCnt += rightSeqCnt; + + // 收集基本块信息 + UpdateBasicBlockInfo(basicBlockInfo, rightCmpBlockInfo, false); + + AcceptUpdate(rightCmpBlockInfo); + } + } + + return basicBlockInfo; +} + +template +__aicore__ inline uint32_t CompressorKernelPerf::GetBasicBlockNum() { + // 计算基本块数量 + uint32_t basicBlockNum = 0; + CmpBlockInfo leftCmpBlockInfo( + constInfo.bIdxOfLastTc, constInfo.sIdxOfLastTc, true); + CmpBlockInfo rightCmpBlockInfo(0, 0, false); + + for (; rightCmpBlockInfo.bIdx < constInfo.batchSize; ++basicBlockNum) { + BasicBlockInfo basicBlockInfo = + SkipOneBasicBlock(rightCmpBlockInfo, leftCmpBlockInfo); + allCompressedTcNum_ += basicBlockInfo.compressedTcNum; + } + return basicBlockNum; +} + +template +__aicore__ inline void CompressorKernelPerf::CalcCurCoreStartIdx( + CmpBlockInfo& rightCmpBlockInfo, + CmpBlockInfo& leftCmpBlockInfo) { + uint32_t basicBlockNum = + constInfo.curGroupIdx * constInfo.singleCoreDealTcBasicNum; + for (; basicBlockNum > 0; --basicBlockNum) { + BasicBlockInfo basicBlockInfo = + SkipOneBasicBlock(rightCmpBlockInfo, leftCmpBlockInfo); + curCompressedTcNum_ += basicBlockInfo.compressedTcNum; + } +} + +template +__aicore__ inline void CompressorKernelPerf::CalcSplitCoreInfo() { + // 计算D的切分大小 + constInfo.dBaseSize = 64; // 默认按照64切分 + uint32_t maxEnableCoreNum = + constInfo.tcBasicBlockNum * (constInfo.headDim / constInfo.dBaseSize); + uint32_t minEnableCoreNum = 16; + if (maxEnableCoreNum < minEnableCoreNum) { + // headDim=128时, dBaseSize=8; headDim=512时, dBaseSize=32 + constInfo.dBaseSize = constInfo.headDim / minEnableCoreNum; + } + + // D方向的基本块数量 + constInfo.dBasicBlockNum = constInfo.headDim / constInfo.dBaseSize; + // 核的组数 + constInfo.coreGroupNum = constInfo.usedCoreNum / constInfo.dBasicBlockNum; + // 每个核处理的d方向的索引 + constInfo.dIdx = + (constInfo.aiCoreIdx % constInfo.dBasicBlockNum) * constInfo.dBaseSize; + // 当前组id + constInfo.curGroupIdx = constInfo.aiCoreIdx / constInfo.dBasicBlockNum; + + // 单组核在T方向处理的最大基本块数量 + constInfo.singleCoreDealTcBasicNum = + (constInfo.tcBasicBlockNum + constInfo.coreGroupNum - 1) / + constInfo.coreGroupNum; + // 尾组所在id + constInfo.tailGroupIdx = + (constInfo.tcBasicBlockNum - 1) / constInfo.singleCoreDealTcBasicNum; + // 尾组处理基本块数量 + constInfo.tailBasicBlockNum = + constInfo.tcBasicBlockNum - + constInfo.tailGroupIdx * constInfo.singleCoreDealTcBasicNum; + + // 计算当前核需要处理的基本块个数 + if (constInfo.curGroupIdx < constInfo.tailGroupIdx) { + constInfo.realDealBasicBlockNum = constInfo.singleCoreDealTcBasicNum; + } else if (constInfo.curGroupIdx > constInfo.tailGroupIdx) { + constInfo.realDealBasicBlockNum = 0; + } else { + constInfo.realDealBasicBlockNum = constInfo.tailBasicBlockNum; + } + // PRINTF("constInfo.dBaseSize:%d dBasicBlockNum:%d coreGroupNum:%d dIdx:%d + // curGroupIdx:%d singleCoreDealTcBasicNum:%d tailGroupIdx:%d + // tailBasicBlockNum:%d realDealBasicBlockNum:%d\n", + // constInfo.dBaseSize, constInfo.dBasicBlockNum, constInfo.coreGroupNum, + // constInfo.dIdx, constInfo.curGroupIdx, + // constInfo.singleCoreDealTcBasicNum, constInfo.tailGroupIdx, + // constInfo.tailBasicBlockNum, constInfo.realDealBasicBlockNum); +} + +template +__aicore__ inline void CompressorKernelPerf::InitWorkspace( + __gm__ uint8_t* workspace) { + uint64_t offset = 0; + // preMm1ResGm + preMm1ResGm.SetGlobalBuffer( + (__gm__ MM1_OUT_T*)(workspace + offset + + constInfo.aiCoreIdx * dbWorkspaceRatio * + constInfo.preMm1ResSize * sizeof(MM1_OUT_T))); + offset += GetBlockNum() * dbWorkspaceRatio * constInfo.preMm1ResSize * + sizeof(MM1_OUT_T); + + // curMm1ResGm + curMm1ResGm.SetGlobalBuffer( + (__gm__ MM1_OUT_T*)(workspace + offset + + constInfo.aiCoreIdx * dbWorkspaceRatio * + constInfo.curMm1ResSize * sizeof(MM1_OUT_T))); + offset += GetBlockNum() * dbWorkspaceRatio * constInfo.curMm1ResSize * + sizeof(MM1_OUT_T); + + uint64_t beforeVecOffset = offset; + + // vec1Res + vec1ResGm.SetGlobalBuffer( + (__gm__ VEC1_OUT_T*)(workspace + offset + + (constInfo.dIdx + + (constInfo.aiCoreIdx / constInfo.dBasicBlockNum) * + dbWorkspaceRatio * constInfo.vec1ResSize * + constInfo.dBasicBlockNum) * + sizeof(VEC1_OUT_T))); + offset += GetBlockNum() * dbWorkspaceRatio * constInfo.vec1ResSize * + sizeof(VEC1_OUT_T); + // vec2Input + vec2InputGm.SetGlobalBuffer( + (__gm__ VEC1_OUT_T*)(workspace + beforeVecOffset + + (constInfo.aiCoreIdx / constInfo.dBasicBlockNum) * + dbWorkspaceRatio * constInfo.vec1ResSize * + constInfo.dBasicBlockNum * sizeof(VEC1_OUT_T))); + offset += GetBlockNum() * dbWorkspaceRatio * constInfo.vec1ResSize * + sizeof(VEC1_OUT_T); +} + +template +__aicore__ inline void CompressorKernelPerf::ComputeMm1( + const RunInfo& info) { + CrossCoreWaitFlag(SYNC_V1_C1_FLAG); + blockCube_.ComputeMm1(info); + CrossCoreSetFlag(SYNC_C1_V1_FLAG); +} + +template +__aicore__ inline void CompressorKernelPerf::ComputeVec1( + const RunInfo& info) { +#if (__CCE_AICORE__ == 220) + CrossCoreWaitFlag(SYNC_C1_V1_FLAG); +#else + CrossCoreWaitFlag(SYNC_C1_V1_FLAG); +#endif + blockVec_.ComputeVec1(info); +#if (__CCE_AICORE__ == 220) + CrossCoreSetFlag(SYNC_V1_C1_FLAG); +#else + CrossCoreSetFlag(SYNC_V1_C1_FLAG); +#endif +} + +template +__aicore__ inline void CompressorKernelPerf::ComputeVec2( + const Vec2RunInfo& info) { + blockVec_.ComputeVec2(info); +} + +template +__aicore__ inline void CompressorKernelPerf::AllocEventID() { + if ASCEND_IS_AIC { + blockCube_.AllocEventID(pipe_); + } else { + blockVec_.AllocEventID(); +#if (__CCE_AICORE__ == 220) + CrossCoreSetFlag(SYNC_V1_C1_FLAG); +#else + CrossCoreSetFlag(SYNC_V1_C1_FLAG); +#endif + } +} + +template +__aicore__ inline void CompressorKernelPerf::FreeEventID() { + if ASCEND_IS_AIC { + CrossCoreWaitFlag(SYNC_V1_C1_FLAG); + blockCube_.FreeEventID(pipe_); + } else { + blockVec_.FreeEventID(); + } +} + +template +__aicore__ inline bool CompressorKernelPerf::IsNeedExcuteC1V1( + uint32_t curBasicBlockIdx) { + return (curBasicBlockIdx < constInfo.realDealBasicBlockNum); +} + +template +__aicore__ inline void CompressorKernelPerf::CalcC1V1Params( + RunInfo& info, + uint32_t curBasicBlockIdx, + CmpBlockInfo& rightCmpBlockInfo, + CmpBlockInfo& leftCmpBlockInfo) { + // 计算v1写出偏移 + if (curBasicBlockIdx % constInfo.nSize == 0) { + info.vec1ResOffset = 0; + accDealSize = 0; + } else { + info.vec1ResOffset = accDealSize * constInfo.headDim; + } + + info.preFirstSeqCnt = GetNextCmpSeqCnt(leftCmpBlockInfo); + info.preBStart = leftCmpBlockInfo.bIdx; + info.preSStart = leftCmpBlockInfo.sIdx; + info.bStart = rightCmpBlockInfo.bIdx; + info.sStart = rightCmpBlockInfo.sIdx; + BasicBlockInfo basicBlockInfo = + SkipOneBasicBlock(rightCmpBlockInfo, leftCmpBlockInfo); + info.dealTcNum = basicBlockInfo.dealTcNum; + info.dealScSize = basicBlockInfo.compressedTcNum; + info.dealSeqCnt = basicBlockInfo.dealSeqCnt; + info.preDealSeqCnt = basicBlockInfo.preDealSeqCnt; + accDealSize += info.dealScSize; +} + +template +__aicore__ inline bool CompressorKernelPerf::IsNeedExcuteV2( + Vec2RunInfo& vec2Info) { + return (vec2Info.dealScSize > 0); +} + +template +__aicore__ inline bool CompressorKernelPerf::IsNeedSyncAll( + uint32_t curBasicBlockIdx) { + if (allCompressedTcNum_ == 0) { + return false; + } + + uint32_t cnt = curBasicBlockIdx + 1; + if ((cnt == constInfo.singleCoreDealTcBasicNum) || + (cnt % constInfo.nSize == 0)) { + return true; + } + return false; +} + +template +__aicore__ inline void CompressorKernelPerf::UpdateVec2Info( + Vec2RunInfo& vec2Info, + uint32_t curBasicBlockIdx, + const RunInfo& info) { + // nSize轮起始先重置v2Info信息 + if (curBasicBlockIdx % constInfo.nSize == 0) { + vec2Info.bStart = info.bStart; + vec2Info.sStart = info.sStart; + // 将sStart转成bCompressedId + uint32_t startPos = tools_.GetStartPos(info.bStart); + vec2Info.bCompressedId = (startPos + info.sStart) / constInfo.cmpRatio - + startPos / constInfo.cmpRatio; + + vec2Info.dealScSize = 0; + } + vec2Info.dealScSize += info.dealScSize; + // TODO 应该是加上上一轮的 + vec2Info.compressedId += info.dealScSize; +} + +template +__aicore__ inline void CompressorKernelPerf::Process() { + // 所有batch的有效序列都为0时, 直接退出 + if (constInfo.batchSize == 0) { + return; + } + AllocEventID(); + + CmpBlockInfo leftCmpBlockInfo( + constInfo.bIdxOfLastTc, constInfo.sIdxOfLastTc, true); + CmpBlockInfo rightCmpBlockInfo(0, 0, false); + CalcCurCoreStartIdx(rightCmpBlockInfo, leftCmpBlockInfo); + // PRINTF("allCompressedTcNum_:%d curCompressedTcNum_:%d\n", + // allCompressedTcNum_, curCompressedTcNum_); + + RunInfo extraInfo[1]; + Vec2RunInfo vec2Info{}; + for (uint32_t i = 0; i < constInfo.singleCoreDealTcBasicNum; ++i) { + RunInfo& extraInfo0 = extraInfo[0]; + bool isNeedExcuteC1V1 = IsNeedExcuteC1V1(i); + if (isNeedExcuteC1V1) { + CalcC1V1Params(extraInfo0, i, rightCmpBlockInfo, leftCmpBlockInfo); + } + + if ASCEND_IS_AIC { + if (isNeedExcuteC1V1) { + ComputeMm1(extraInfo0); + } + } else { + if (isNeedExcuteC1V1) { + ComputeVec1(extraInfo0); + UpdateVec2Info(vec2Info, i, extraInfo0); + } + + if (IsNeedSyncAll(i)) { + SyncAll(); + if (IsNeedExcuteV2(vec2Info)) { + ComputeVec2(vec2Info); + } + SyncAll(); + } + } + } + FreeEventID(); +} + +} // namespace XllmKernelCompressor + +#endif // COMPRESSOR_KERNEL_PERF_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_template_tiling_key.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_template_tiling_key.h new file mode 100644 index 0000000000..71219b24e4 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_template_tiling_key.h @@ -0,0 +1,64 @@ +/** + * 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 COMPRESSOR_template_tiling_key.h + * \brief + */ + +#ifndef COMPRESSOR_TEMPLATE_TILING_KEY_H +#define COMPRESSOR_TEMPLATE_TILING_KEY_H + +#include "ascendc/host_api/tiling/template_argument.h" + +#define ASCENDC_TPL_1_BW 1 // 每个参数占用1个bit位 +#define ASCENDC_TPL_2_BW 2 // 每个参数占用2个bit位 +#define ASCENDC_TPL_4_BW 4 // 每个参数占用4个bit位 + +// 可表示的tilingkey范围为64bit,注意不可超过限制 +ASCENDC_TPL_ARGS_DECL( + XllmKernelCompressor, // 算子唯一标识,与opType保持一致 + // 可能需要切分之后的headdim + // bit:0 LAYOUT 0:BSH 1:TH + ASCENDC_TPL_UINT_DECL(X_LAYOUT, + ASCENDC_TPL_1_BW, + ASCENDC_TPL_UI_LIST, + 0, + 1), + // bit:1-4 x的dtype 0:BF16 1:FP16 + ASCENDC_TPL_UINT_DECL(X_DTYPE, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, 0, 1), + // bit:5-6 coff 1:无需overlap 2:需要overlap + ASCENDC_TPL_UINT_DECL(COFF, ASCENDC_TPL_2_BW, ASCENDC_TPL_UI_LIST, 1, 2), + // bit:7-8 rotary_mode 1:half 2:interleave + ASCENDC_TPL_UINT_DECL(ROTARY_MODE, + ASCENDC_TPL_2_BW, + ASCENDC_TPL_UI_LIST, + 1, + 2), + // bit:9-10 template_id 0:empty_tensor 1:normal 2:perf + ASCENDC_TPL_UINT_DECL(TEMPLATE_ID, + ASCENDC_TPL_2_BW, + ASCENDC_TPL_UI_LIST, + 0, + 1, + 2), ); + +ASCENDC_TPL_SEL( + + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_UINT_SEL(X_LAYOUT, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(X_DTYPE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(COFF, ASCENDC_TPL_UI_LIST, 1, 2), + ASCENDC_TPL_UINT_SEL(ROTARY_MODE, ASCENDC_TPL_UI_LIST, 1, 2), + ASCENDC_TPL_UINT_SEL(TEMPLATE_ID, ASCENDC_TPL_UI_LIST, 0, 1, 2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::CompressorTilingData)), ); + +#endif // COMPRESSOR_TEMPLATE_TILING_KEY_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_tiling_data.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_tiling_data.h new file mode 100644 index 0000000000..182b52ff75 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_tiling_data.h @@ -0,0 +1,69 @@ +/** + * 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 COMPRESSOR_tiling_datay.h + * \brief + */ + +#ifndef COMPRESSOR_TILING_DATA_H +#define COMPRESSOR_TILING_DATA_H +#include + +#include "kernel_tiling/kernel_tiling.h" + +const uint32_t CMP_MAX_AIC_CORE_NUM = 26; // 25 + 1 保证数组8字节对齐 + +namespace optiling { +// 1. 基础参数结构体 +struct CompressorBaseParams { + uint32_t batchSize = 0; // bastch size(批大小) + uint32_t seqSize = 0; // sequence size(kvs大小) + uint32_t hiddenSize = 0; // hidden size(隐藏层大小) + uint32_t tokenSize = + 0; // token size = batchSize * seqSize(token总数:批大小x序列1长度) + uint32_t headDim = 0; // head size of kv + uint32_t ropeHeadDim = 64; // dim size per rope head 64(单个带RoPE头的维度) + uint32_t csSize = 0; // Compress sequence len + uint32_t cmpRatio = 4; // Compress ratio + uint32_t cgSize = 0; // Compress group size + float normEps = 1e-6; // RMSNorm eps + float reciprocalD = 0; // 1分之D + uint32_t usedCoreNum = 0; // 使用核数 + uint32_t nSize = 0; // 控制v2积攒的轮数 +}; + +struct CompressorPageAttentionParams { + uint32_t blockNum; + uint32_t blockSize; + uint32_t maxBlockNumPerBatch; +}; + +struct CompressorInnerSplitParams { + uint32_t mBaseSize; + uint32_t dBaseSize; +}; + +struct CompressorWorkspaceParams { + uint32_t preMm1ResSize; + uint32_t curMm1ResSize; + uint32_t vec1ResSize; +}; + +struct CompressorTilingData { + CompressorBaseParams baseParams; + CompressorPageAttentionParams pageAttentionParams; + CompressorInnerSplitParams innerSplitParams; + CompressorWorkspaceParams workspaceParams; +}; +} // namespace optiling + +#endif // COMPRESSOR_TILING_DATA_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_tools.h b/xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_tools.h new file mode 100644 index 0000000000..8499197c19 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/compressor_tools.h @@ -0,0 +1,835 @@ +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved. + * This file is a part of the CANN Open Software. + * Licensed under CANN Open Software License Agreement Version 1.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 compressor_slice_iterator.h + * \brief 放算子都需要、与算子联系紧密、但是又不方便单独独立出来的公共工具 + */ + +#ifndef COMPRESSOR_TOOLS_H +#define COMPRESSOR_TOOLS_H + +#include "compressor_comm.h" + +using namespace AscendC; + +namespace XllmKernelCompressor { + +struct ToolsParams { + uint32_t seqSize = 0U; + uint32_t cmpRatio = 0U; +}; + +template +class CompressorTools { + public: + __aicore__ inline CompressorTools() {} + + __aicore__ inline void Init(__gm__ uint8_t* cuSeqlens, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* startPos); + + __aicore__ inline uint32_t GetSeqUsed(uint32_t bIdx); + __aicore__ inline uint32_t GetStartPos(uint32_t bIdx); + __aicore__ inline uint32_t GetSeqLength(uint32_t bIdx); + __aicore__ inline uint32_t GetTIdxByBatch(uint32_t bIdx); + + public: + ToolsParams toolParams_{}; + + private: + bool isExistStartPos_ = false; + bool isExistSeqUsed_ = false; + GlobalTensor cuSeqlensGm_; + GlobalTensor sequsedGm_; + GlobalTensor startPosGm_; +}; + +template +__aicore__ inline void CompressorTools::Init(__gm__ uint8_t* startPos, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* cuSeqlens) { + isExistStartPos_ = (startPos != nullptr); + if (isExistStartPos_) { + startPosGm_.SetGlobalBuffer((__gm__ int32_t*)startPos); + } + + isExistSeqUsed_ = (seqUsed != nullptr); + if (isExistSeqUsed_) { + sequsedGm_.SetGlobalBuffer((__gm__ int32_t*)seqUsed); + } + + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + cuSeqlensGm_.SetGlobalBuffer((__gm__ int32_t*)cuSeqlens); + } +} + +template +__aicore__ inline uint32_t CompressorTools::GetSeqUsed(uint32_t bIdx) { + if (isExistSeqUsed_) { + return (uint32_t)sequsedGm_.GetValue(bIdx); + } else { + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + return (uint32_t)(cuSeqlensGm_.GetValue(bIdx + 1) - + cuSeqlensGm_.GetValue(bIdx)); + } else { + return toolParams_.seqSize; + } + } +} + +template +__aicore__ inline uint32_t CompressorTools::GetStartPos(uint32_t bIdx) { + if (isExistStartPos_) { + return (uint32_t)startPosGm_.GetValue(bIdx); + } else { + return 0; + } +} + +template +__aicore__ inline uint32_t CompressorTools::GetSeqLength(uint32_t bIdx) { + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + return cuSeqlensGm_.GetValue(bIdx + 1) - cuSeqlensGm_.GetValue(bIdx); + } else { + return toolParams_.seqSize; + } +} + +template +__aicore__ inline uint32_t CompressorTools::GetTIdxByBatch( + uint32_t bIdx) { + if constexpr (COMP::xLayout == X_LAYOUT::TH) { + return (uint32_t)(cuSeqlensGm_.GetValue(bIdx)); + } else { + return toolParams_.seqSize * bIdx; + } +} + +// iterator +struct SliceInfo { + __aicore__ inline SliceInfo(){}; + __aicore__ inline SliceInfo(uint32_t bIdx, uint32_t sIdx) + : bIdx(bIdx), sIdx(sIdx){}; + + uint32_t bIdx = 0U; + uint32_t sIdx = 0U; + uint32_t bSeqUsed = 0U; + uint32_t bStartPos = 0U; + + uint32_t headHolderSeqCnt = 0U; + uint32_t validSeqCnt = 0U; + uint32_t tailHolderSeqCnt = 0U; + + uint32_t dealSeqCnt = 0; + uint32_t dealTcSize = 0U; + uint32_t compressTcSize = 0U; +}; + +template +class CompressorSliceIterator { + public: + __aicore__ inline CompressorSliceIterator(CompressorTools& tools) + : tools_(tools) {} + + __aicore__ inline void Reset(uint32_t bIdx, uint32_t sIdx); + __aicore__ inline void SetMaxBatchSize(uint32_t batch_size); + __aicore__ inline void SetMaxDealSeqCnt(uint32_t maxDealSeqCnt); + __aicore__ inline bool IsEnd(); + __aicore__ inline void IteratorSlice(); + __aicore__ inline SliceInfo& GetSlice(); + __aicore__ inline SliceInfo& GetSliceByCmp(); + + bool isFirst_ = true; + SliceInfo sliceInfo_{}; + + private: + CompressorTools& tools_; + + // iterator + uint32_t maxDealSeqCnt_ = 0; + uint32_t batch_size_ = 0; +}; + +template +__aicore__ inline void CompressorSliceIterator::Reset(uint32_t bIdx, + uint32_t sIdx) { + sliceInfo_.bIdx = bIdx; + sliceInfo_.sIdx = sIdx; + isFirst_ = true; +} + +template +__aicore__ inline void CompressorSliceIterator::SetMaxBatchSize( + uint32_t batch_size) { + this->batch_size_ = batch_size; +} + +template +__aicore__ inline void CompressorSliceIterator::SetMaxDealSeqCnt( + uint32_t maxDealSeqCnt) { + this->maxDealSeqCnt_ = maxDealSeqCnt; +} + +template +__aicore__ inline bool CompressorSliceIterator::IsEnd() { + return (sliceInfo_.bIdx >= batch_size_) || (maxDealSeqCnt_ == 0); +} + +template +__aicore__ inline void CompressorSliceIterator::IteratorSlice() { + bool isUpdateBatchInfo = false; + if (!isFirst_) { + // 更新剩余未处理的行数 + maxDealSeqCnt_ -= sliceInfo_.dealSeqCnt; + // 更新sIdx和bIdx、以及与bIdx相关的bStartPos和bSeqUsed + sliceInfo_.sIdx += sliceInfo_.validSeqCnt; + if (sliceInfo_.sIdx == sliceInfo_.bSeqUsed) { + sliceInfo_.sIdx = 0; + sliceInfo_.bIdx++; + isUpdateBatchInfo = true; + } + } else { + isUpdateBatchInfo = true; + isFirst_ = false; + } + + // 更新与bIdx相关的bStartPos和bSeqUsed + if (isUpdateBatchInfo) { + // SkipInvalidBatch + while (sliceInfo_.bIdx < batch_size_) { + sliceInfo_.bSeqUsed = tools_.GetSeqUsed(sliceInfo_.bIdx); + if (sliceInfo_.bSeqUsed > 0) { + break; + } + sliceInfo_.bIdx++; + } + if (sliceInfo_.bIdx < batch_size_) { + sliceInfo_.bStartPos = tools_.GetStartPos(sliceInfo_.bIdx); + } + } +} + +template +__aicore__ inline SliceInfo& CompressorSliceIterator::GetSliceByCmp() { + uint32_t cmpRatio = tools_.toolParams_.cmpRatio; + if (isFirst_) { + sliceInfo_.bSeqUsed = tools_.GetSeqUsed(sliceInfo_.bIdx); + sliceInfo_.bStartPos = tools_.GetStartPos(sliceInfo_.bIdx); + isFirst_ = false; + } + // 计算头部占位行数、有效数据行数、尾部占位行数 + sliceInfo_.headHolderSeqCnt = + (sliceInfo_.bStartPos + sliceInfo_.sIdx) % cmpRatio; + + sliceInfo_.validSeqCnt = sliceInfo_.bSeqUsed - sliceInfo_.sIdx; + if (sliceInfo_.headHolderSeqCnt + sliceInfo_.validSeqCnt > maxDealSeqCnt_) { + sliceInfo_.validSeqCnt = maxDealSeqCnt_ - sliceInfo_.headHolderSeqCnt; + } + sliceInfo_.tailHolderSeqCnt = + cmpRatio - + (sliceInfo_.bStartPos + sliceInfo_.sIdx + sliceInfo_.validSeqCnt) % + cmpRatio; + if (sliceInfo_.tailHolderSeqCnt == cmpRatio) { + sliceInfo_.tailHolderSeqCnt = 0; + } + + // 头和尾处理,否则需要处理的seq等于cmpRatio + if (sliceInfo_.validSeqCnt < cmpRatio) { + sliceInfo_.dealSeqCnt = sliceInfo_.validSeqCnt; + if (sliceInfo_.sIdx == 0) { + sliceInfo_.dealSeqCnt = cmpRatio - sliceInfo_.headHolderSeqCnt; + } + } else { + sliceInfo_.dealSeqCnt = cmpRatio; + } + sliceInfo_.validSeqCnt = sliceInfo_.dealSeqCnt; + + // 计算本次可以处理的Tc个数 + sliceInfo_.dealTcSize = (sliceInfo_.dealSeqCnt + cmpRatio - 1) / cmpRatio; + + // 因为是一个batch的数据, 只有最后一个压缩块才可能不需要压缩, + // 此时sliceInfo_.tailHolderSeqCnt > 0 + sliceInfo_.compressTcSize = sliceInfo_.dealTcSize; + if (sliceInfo_.tailHolderSeqCnt > 0) { + sliceInfo_.compressTcSize = + sliceInfo_.dealTcSize - 1; // 最后一个压缩块不满时,其不需要压缩 + } + + return sliceInfo_; +} + +template +__aicore__ inline SliceInfo& CompressorSliceIterator::GetSlice() { + uint32_t cmpRatio = tools_.toolParams_.cmpRatio; + if (isFirst_) { + sliceInfo_.bSeqUsed = tools_.GetSeqUsed(sliceInfo_.bIdx); + sliceInfo_.bStartPos = tools_.GetStartPos(sliceInfo_.bIdx); + isFirst_ = false; + } + // 计算头部占位行数、有效数据行数、尾部占位行数 + sliceInfo_.headHolderSeqCnt = + (sliceInfo_.bStartPos + sliceInfo_.sIdx) % cmpRatio; + sliceInfo_.validSeqCnt = sliceInfo_.bSeqUsed - sliceInfo_.sIdx; + if (sliceInfo_.headHolderSeqCnt + sliceInfo_.validSeqCnt > maxDealSeqCnt_) { + sliceInfo_.validSeqCnt = maxDealSeqCnt_ - sliceInfo_.headHolderSeqCnt; + } + sliceInfo_.tailHolderSeqCnt = + cmpRatio - + (sliceInfo_.bStartPos + sliceInfo_.sIdx + sliceInfo_.validSeqCnt) % + cmpRatio; + if (sliceInfo_.tailHolderSeqCnt == cmpRatio) { + sliceInfo_.tailHolderSeqCnt = 0; + } + + sliceInfo_.dealSeqCnt = sliceInfo_.headHolderSeqCnt + sliceInfo_.validSeqCnt + + sliceInfo_.tailHolderSeqCnt; + // 计算本次可以处理的Tc个数 + sliceInfo_.dealTcSize = sliceInfo_.dealSeqCnt / cmpRatio; + + // 因为是一个batch的数据, 只有最后一个压缩块才可能不需要压缩, + // 此时sliceInfo_.tailHolderSeqCnt > 0 + sliceInfo_.compressTcSize = sliceInfo_.dealTcSize; + if (sliceInfo_.tailHolderSeqCnt > 0) { + sliceInfo_.compressTcSize = + sliceInfo_.dealTcSize - 1; // 最后一个压缩块不满时,其不需要压缩 + } + + return sliceInfo_; +} + +struct SplitCoreSliceInfo : public SliceInfo { + __aicore__ inline SplitCoreSliceInfo(){}; + __aicore__ inline SplitCoreSliceInfo(uint32_t bIdx, uint32_t sIdx) + : SliceInfo(bIdx, sIdx){}; + + uint32_t preFirstSeqCnt = 0U; // 左边每次迭代基本块的第一个seqCnt大小 +}; + +template +class CompressorSplitCoreSliceIterator { + public: + __aicore__ inline CompressorSplitCoreSliceIterator( + CompressorTools& tools) + : tools_(tools) {} + + __aicore__ inline void Reset(uint32_t bIdx, uint32_t sIdx); + __aicore__ inline void SetMaxBatchSize(uint32_t batch_size); + __aicore__ inline void SetMaxDealSeqCnt(uint32_t maxDealSeqCnt); + __aicore__ inline bool IsEnd(); + __aicore__ inline void IteratorSlice(); + __aicore__ inline SplitCoreSliceInfo& GetSlice(); + __aicore__ inline SplitCoreSliceInfo& GetSliceByCmp(); + __aicore__ inline uint32_t GetBIdx(); + __aicore__ inline SplitCoreSliceInfo& GetLeftNextCmpSeqCnt(); + __aicore__ inline SplitCoreSliceInfo& GetRightNextCmpSeqCnt(); + + bool isFirst_ = true; + bool isLeftFirstBath = false; + bool isMaxDealSeqCntFirst = false; + + SplitCoreSliceInfo sliceInfo_{}; + + private: + CompressorTools& tools_; + + // iterator + uint32_t maxDealSeqCnt_ = 0; + uint32_t batch_size_ = 0; +}; + +template +__aicore__ inline void CompressorSplitCoreSliceIterator::Reset( + uint32_t bIdx, + uint32_t sIdx) { + sliceInfo_.bIdx = bIdx; + sliceInfo_.sIdx = sIdx; + isFirst_ = true; +} + +template +__aicore__ inline void CompressorSplitCoreSliceIterator::SetMaxBatchSize( + uint32_t batch_size) { + this->batch_size_ = batch_size; + isMaxDealSeqCntFirst = true; +} + +template +__aicore__ inline void CompressorSplitCoreSliceIterator::SetMaxDealSeqCnt( + uint32_t maxDealSeqCnt) { + this->maxDealSeqCnt_ = maxDealSeqCnt; +} + +template +__aicore__ inline bool CompressorSplitCoreSliceIterator::IsEnd() { + return (sliceInfo_.bIdx >= batch_size_) || (maxDealSeqCnt_ == 0); +} + +template +__aicore__ inline uint32_t CompressorSplitCoreSliceIterator::GetBIdx() { + return sliceInfo_.bIdx; +} + +template +__aicore__ inline void CompressorSplitCoreSliceIterator::IteratorSlice() { + bool isUpdateBatchInfo = false; + if (isMaxDealSeqCntFirst) { + isMaxDealSeqCntFirst = false; + } + if (!isFirst_) { + // 更新剩余未处理的行数 + maxDealSeqCnt_ -= sliceInfo_.dealSeqCnt; + // 更新sIdx和bIdx、以及与bIdx相关的bStartPos和bSeqUsed + sliceInfo_.sIdx += sliceInfo_.validSeqCnt; + if (sliceInfo_.sIdx == sliceInfo_.bSeqUsed) { + sliceInfo_.sIdx = 0; + // 左边最后一块跳到b=0 s=0处理 + if (isLeftFirstBath) { + isLeftFirstBath = false; + } else { + sliceInfo_.bIdx++; + } + isUpdateBatchInfo = true; + } + } else { + isUpdateBatchInfo = true; + isFirst_ = false; + } + + // 更新与bIdx相关的bStartPos和bSeqUsed + if (isUpdateBatchInfo) { + // SkipInvalidBatch + while (sliceInfo_.bIdx < batch_size_) { + sliceInfo_.bSeqUsed = tools_.GetSeqUsed(sliceInfo_.bIdx); + if (sliceInfo_.bSeqUsed > 0) { + break; + } + sliceInfo_.bIdx++; + } + if (sliceInfo_.bIdx < batch_size_) { + sliceInfo_.bStartPos = tools_.GetStartPos(sliceInfo_.bIdx); + } + } +} + +template +__aicore__ inline SplitCoreSliceInfo& +CompressorSplitCoreSliceIterator::GetLeftNextCmpSeqCnt() { + uint32_t cmpRatio = tools_.toolParams_.cmpRatio; + if (isFirst_) { + // 左边 T轴首次减去T轴最后一块 + sliceInfo_.bSeqUsed = tools_.GetSeqUsed(batch_size_ - 1); + sliceInfo_.bStartPos = tools_.GetStartPos(batch_size_ - 1); + // 处理最后一块是中间整块或者尾块的情况 + uint32_t lastSeqCnt = + (sliceInfo_.bStartPos + sliceInfo_.bSeqUsed) % cmpRatio == 0 + ? cmpRatio + : (sliceInfo_.bStartPos + sliceInfo_.bSeqUsed) % cmpRatio; + // 处理最后一块是头块的情况 + if (sliceInfo_.bSeqUsed < cmpRatio) { + lastSeqCnt = sliceInfo_.bSeqUsed; + } + + sliceInfo_.sIdx = sliceInfo_.bSeqUsed - lastSeqCnt; + isLeftFirstBath = true; + isFirst_ = false; + } + // 计算头部占位行数、有效数据行数、尾部占位行数 + sliceInfo_.headHolderSeqCnt = + (sliceInfo_.bStartPos + sliceInfo_.sIdx) % cmpRatio; + + sliceInfo_.validSeqCnt = sliceInfo_.bSeqUsed - sliceInfo_.sIdx; + if (sliceInfo_.headHolderSeqCnt + sliceInfo_.validSeqCnt > maxDealSeqCnt_) { + sliceInfo_.validSeqCnt = maxDealSeqCnt_ - sliceInfo_.headHolderSeqCnt; + } + sliceInfo_.tailHolderSeqCnt = + cmpRatio - + (sliceInfo_.bStartPos + sliceInfo_.sIdx + sliceInfo_.validSeqCnt) % + cmpRatio; + if (sliceInfo_.tailHolderSeqCnt == cmpRatio) { + sliceInfo_.tailHolderSeqCnt = 0; + } + + // 头和尾处理,否则需要处理的seq等于cmpRatio + if (sliceInfo_.validSeqCnt < cmpRatio) { + sliceInfo_.dealSeqCnt = sliceInfo_.validSeqCnt; + if (sliceInfo_.sIdx == 0) { + sliceInfo_.dealSeqCnt = cmpRatio - sliceInfo_.headHolderSeqCnt; + } + } else { + sliceInfo_.dealSeqCnt = cmpRatio; + } + sliceInfo_.validSeqCnt = sliceInfo_.dealSeqCnt; + + // 计算本次可以处理的Tc个数 + sliceInfo_.dealTcSize = (sliceInfo_.dealSeqCnt + cmpRatio - 1) / cmpRatio; + + // 因为是一个batch的数据, 只有最后一个压缩块才可能不需要压缩, + // 此时sliceInfo_.tailHolderSeqCnt > 0 + sliceInfo_.compressTcSize = sliceInfo_.dealTcSize; + if (sliceInfo_.tailHolderSeqCnt > 0) { + sliceInfo_.compressTcSize = + sliceInfo_.dealTcSize - 1; // 最后一个压缩块不满时,其不需要压缩 + } + + // 记录左边第一个块 + if (isMaxDealSeqCntFirst) { + sliceInfo_.preFirstSeqCnt = sliceInfo_.dealSeqCnt; + } + + return sliceInfo_; +} + +template +__aicore__ inline SplitCoreSliceInfo& +CompressorSplitCoreSliceIterator::GetRightNextCmpSeqCnt() { + uint32_t cmpRatio = tools_.toolParams_.cmpRatio; + if (isFirst_) { + sliceInfo_.bSeqUsed = tools_.GetSeqUsed(sliceInfo_.bIdx); + sliceInfo_.bStartPos = tools_.GetStartPos(sliceInfo_.bIdx); + isFirst_ = false; + } + // 计算头部占位行数、有效数据行数、尾部占位行数 + sliceInfo_.headHolderSeqCnt = + (sliceInfo_.bStartPos + sliceInfo_.sIdx) % cmpRatio; + + sliceInfo_.validSeqCnt = sliceInfo_.bSeqUsed - sliceInfo_.sIdx; + if (sliceInfo_.headHolderSeqCnt + sliceInfo_.validSeqCnt > maxDealSeqCnt_) { + sliceInfo_.validSeqCnt = maxDealSeqCnt_ - sliceInfo_.headHolderSeqCnt; + } + sliceInfo_.tailHolderSeqCnt = + cmpRatio - + (sliceInfo_.bStartPos + sliceInfo_.sIdx + sliceInfo_.validSeqCnt) % + cmpRatio; + if (sliceInfo_.tailHolderSeqCnt == cmpRatio) { + sliceInfo_.tailHolderSeqCnt = 0; + } + + // 头和尾处理,否则需要处理的seq等于cmpRatio + if (sliceInfo_.validSeqCnt < cmpRatio) { + sliceInfo_.dealSeqCnt = sliceInfo_.validSeqCnt; + if (sliceInfo_.sIdx == 0) { + sliceInfo_.dealSeqCnt = cmpRatio - sliceInfo_.headHolderSeqCnt; + } + } else { + sliceInfo_.dealSeqCnt = cmpRatio; + } + sliceInfo_.validSeqCnt = sliceInfo_.dealSeqCnt; + + // 计算本次可以处理的Tc个数 + sliceInfo_.dealTcSize = (sliceInfo_.dealSeqCnt + cmpRatio - 1) / cmpRatio; + + // 因为是一个batch的数据, 只有最后一个压缩块才可能不需要压缩, + // 此时sliceInfo_.tailHolderSeqCnt > 0 + sliceInfo_.compressTcSize = sliceInfo_.dealTcSize; + if (sliceInfo_.tailHolderSeqCnt > 0) { + sliceInfo_.compressTcSize = + sliceInfo_.dealTcSize - 1; // 最后一个压缩块不满时,其不需要压缩 + } + + return sliceInfo_; +} + +struct Vec1SliceInfo : public SliceInfo { + __aicore__ inline Vec1SliceInfo(){}; + __aicore__ inline Vec1SliceInfo(uint32_t bIdx, uint32_t sIdx) + : SliceInfo(bIdx, sIdx){}; + __aicore__ inline Vec1SliceInfo(uint32_t bIdx, + uint32_t sIdx, + uint32_t dealedSeqCnt) + : SliceInfo(bIdx, sIdx), dealedSeqCnt(dealedSeqCnt){}; + + uint32_t preBIdx = 0U; + uint32_t preSIdx = 0U; + uint32_t preBSeqUsed = 0U; + uint32_t preBStartPos = 0U; + uint32_t preHeadHolderSeqCnt = 0U; + uint32_t preValidSeqCnt = 0U; + uint32_t preTailHolderSeqCnt = 0U; + uint32_t lastTcSeqCnt = 0U; + uint32_t dealedSeqCnt = 0U; + uint32_t preDealedSeqCnt = 0U; + uint32_t dealedTcCnt = 0U; +}; + +struct SeqCntInfo { + __aicore__ inline SeqCntInfo(){}; + + uint32_t dealedSeqCnt = 0U; + uint32_t preDealedSeqCnt = 0U; +}; + +template +class CompressorVec1SliceIterator { + public: + __aicore__ inline CompressorVec1SliceIterator(CompressorTools& tools) + : tools_(tools) {} + + template + __aicore__ inline void Reset(uint32_t bIdx, uint32_t sIdx); + template + __aicore__ inline void Reset(uint32_t bIdx, + uint32_t sIdx, + uint32_t dealedSeqCnt, + uint32_t dealedTcCnt); + __aicore__ inline void SetMaxBatchSize(uint32_t batch_size); + __aicore__ inline void SetDealedSeqCnt(uint32_t dealedSeqCnt); + __aicore__ inline void SetDealedTcCnt(uint32_t dealedTcCnt); + __aicore__ inline void SetNeedDealTcSize(uint32_t needDealTcSize); + __aicore__ inline uint32_t GetNeedDealTcSize(); + __aicore__ inline bool IsEnd(); + __aicore__ inline void IteratorSlice(); + __aicore__ inline Vec1SliceInfo& GetSlice(); + __aicore__ inline void GetPreTc(); + __aicore__ inline SeqCntInfo FullIteratorSlice(); + __aicore__ inline void Clear(); + __aicore__ inline void Load(); + __aicore__ inline void Save(); + + private: + CompressorTools& tools_; + + // iterator + bool isFirst_ = true; + bool isSaved_ = false; + Vec1SliceInfo sliceInfo_{}; + Vec1SliceInfo tempSliceInfo_{}; + uint32_t tempNeedDealTcSize_ = 0; + uint32_t preFirstSeqCnt_ = 0U; + uint32_t needDealTcSize_ = 0U; + uint32_t batch_size_ = 0U; +}; + +template +template +__aicore__ inline void CompressorVec1SliceIterator::Reset(uint32_t bIdx, + uint32_t sIdx) { + sliceInfo_.bIdx = bIdx; + sliceInfo_.sIdx = sIdx; + sliceInfo_.bSeqUsed = tools_.GetSeqUsed(sliceInfo_.bIdx); + sliceInfo_.bStartPos = tools_.GetStartPos(sliceInfo_.bIdx); + if constexpr (COMP::coff == COFF::OVERLAP) { + GetPreTc(); + } + if constexpr (RESET_FIRST) { + isFirst_ = true; + } +} + +template +template +__aicore__ inline void CompressorVec1SliceIterator::Reset( + uint32_t bIdx, + uint32_t sIdx, + uint32_t dealedSeqCnt, + uint32_t dealedTcCnt) { + Reset(bIdx, sIdx); + SetDealedSeqCnt(dealedSeqCnt); + SetDealedTcCnt(dealedTcCnt); +} + +template +__aicore__ inline void CompressorVec1SliceIterator::SetMaxBatchSize( + uint32_t batch_size) { + this->batch_size_ = batch_size; +} + +template +__aicore__ inline void CompressorVec1SliceIterator::SetDealedSeqCnt( + uint32_t dealedSeqCnt) { + this->sliceInfo_.dealedSeqCnt = dealedSeqCnt; +} + +template +__aicore__ inline void CompressorVec1SliceIterator::SetDealedTcCnt( + uint32_t dealedTcCnt) { + this->sliceInfo_.dealedTcCnt = dealedTcCnt; +} + +template +__aicore__ inline void CompressorVec1SliceIterator::SetNeedDealTcSize( + uint32_t needDealTcSize) { + this->needDealTcSize_ = needDealTcSize; +} + +template +__aicore__ inline void CompressorVec1SliceIterator::GetPreTc() { + uint32_t cmpRatio = tools_.toolParams_.cmpRatio; + if (sliceInfo_.sIdx == 0) { + // seqlen == 0 ? + sliceInfo_.preBIdx = sliceInfo_.bIdx; + do { + if (sliceInfo_.preBIdx == 0) { + sliceInfo_.preBIdx = batch_size_ - 1; + } else { + sliceInfo_.preBIdx--; + } + } while (tools_.GetSeqUsed(sliceInfo_.preBIdx) == 0); + sliceInfo_.preBSeqUsed = tools_.GetSeqUsed(sliceInfo_.preBIdx); + sliceInfo_.preBStartPos = tools_.GetStartPos(sliceInfo_.preBIdx); + sliceInfo_.preSIdx = + max(Trunc(sliceInfo_.preBStartPos + sliceInfo_.preBSeqUsed - 1, + cmpRatio), + sliceInfo_.preBStartPos) - + sliceInfo_.preBStartPos; + } else { + sliceInfo_.preBIdx = sliceInfo_.bIdx; + if (sliceInfo_.sIdx < cmpRatio) { + sliceInfo_.preSIdx = 0; + } else { + sliceInfo_.preSIdx = sliceInfo_.sIdx - cmpRatio; + } + sliceInfo_.preBSeqUsed = sliceInfo_.bSeqUsed; + sliceInfo_.preBStartPos = sliceInfo_.bStartPos; + } +} + +template +__aicore__ inline void CompressorVec1SliceIterator::IteratorSlice() { + // printf("needDealTcSize_: %d -> ", needDealTcSize_); + needDealTcSize_ -= (sliceInfo_.headHolderSeqCnt + sliceInfo_.validSeqCnt + + sliceInfo_.tailHolderSeqCnt) / + tools_.toolParams_.cmpRatio; + // printf("%d\n", needDealTcSize_); + sliceInfo_.dealedSeqCnt += sliceInfo_.validSeqCnt; + sliceInfo_.dealedTcCnt += sliceInfo_.dealTcSize; + sliceInfo_.sIdx += sliceInfo_.validSeqCnt; + if (sliceInfo_.sIdx == sliceInfo_.bSeqUsed) { + do { + sliceInfo_.bIdx++; + if (sliceInfo_.bIdx == batch_size_) { + sliceInfo_.bIdx = 0; + } + } while (tools_.GetSeqUsed(sliceInfo_.bIdx) == 0); + sliceInfo_.sIdx = 0; + sliceInfo_.bSeqUsed = tools_.GetSeqUsed(sliceInfo_.bIdx); + sliceInfo_.bStartPos = tools_.GetStartPos(sliceInfo_.bIdx); + } + if constexpr (COMP::coff == COFF::OVERLAP) { + GetPreTc(); + } + if (isFirst_) { + isFirst_ = false; + } +} + +template +__aicore__ inline uint32_t +CompressorVec1SliceIterator::GetNeedDealTcSize() { + return needDealTcSize_; +} + +template +__aicore__ inline bool CompressorVec1SliceIterator::IsEnd() { + return (needDealTcSize_ == 0); +} + +template +__aicore__ inline Vec1SliceInfo& CompressorVec1SliceIterator::GetSlice() { + uint32_t cmpRatio = tools_.toolParams_.cmpRatio; + if constexpr (COMP::coff == COFF::OVERLAP) { + sliceInfo_.preHeadHolderSeqCnt = + (sliceInfo_.preBStartPos + sliceInfo_.preSIdx) % cmpRatio; + sliceInfo_.preValidSeqCnt = min(sliceInfo_.preBSeqUsed - sliceInfo_.preSIdx, + cmpRatio - sliceInfo_.preHeadHolderSeqCnt); + sliceInfo_.preTailHolderSeqCnt = + cmpRatio - (sliceInfo_.preBStartPos + sliceInfo_.preSIdx + + sliceInfo_.preValidSeqCnt) % + cmpRatio; + if (sliceInfo_.preTailHolderSeqCnt == cmpRatio) { + sliceInfo_.preTailHolderSeqCnt = 0; + } + if (isFirst_) { + preFirstSeqCnt_ = sliceInfo_.preValidSeqCnt; + } + sliceInfo_.preDealedSeqCnt = + preFirstSeqCnt_ + sliceInfo_.dealedSeqCnt - sliceInfo_.preValidSeqCnt; + } + // 计算头部占位行数、有效数据行数、尾部占位行数 + sliceInfo_.headHolderSeqCnt = + (sliceInfo_.bStartPos + sliceInfo_.sIdx) % cmpRatio; + sliceInfo_.validSeqCnt = sliceInfo_.bSeqUsed - sliceInfo_.sIdx; + if (CeilDivT(sliceInfo_.headHolderSeqCnt + sliceInfo_.validSeqCnt, cmpRatio) > + needDealTcSize_) { + sliceInfo_.validSeqCnt = + needDealTcSize_ * cmpRatio - sliceInfo_.headHolderSeqCnt; + } + uint32_t globalTotalSeqCnt = + sliceInfo_.bStartPos + sliceInfo_.sIdx + sliceInfo_.validSeqCnt; + sliceInfo_.tailHolderSeqCnt = + Align(globalTotalSeqCnt, cmpRatio) - globalTotalSeqCnt; + sliceInfo_.lastTcSeqCnt = + globalTotalSeqCnt - max(Trunc(globalTotalSeqCnt - 1, cmpRatio), + sliceInfo_.bStartPos + sliceInfo_.sIdx); + + // 计算本次可以处理的Tc个数 + sliceInfo_.dealTcSize = + (sliceInfo_.headHolderSeqCnt + sliceInfo_.validSeqCnt + + sliceInfo_.tailHolderSeqCnt) / + cmpRatio; + + // 因为是一个batch的数据, 只有最后一个压缩块才可能不需要压缩, + // 此时blockInfo.tailHolderSeqCnt > 0 + sliceInfo_.compressTcSize = sliceInfo_.dealTcSize; + if (sliceInfo_.tailHolderSeqCnt > 0) { + sliceInfo_.compressTcSize = + sliceInfo_.dealTcSize - 1; // 最后一个压缩块不满时,其不需要压缩 + } + + return sliceInfo_; +} + +template +__aicore__ inline void CompressorVec1SliceIterator::Save() { + tempSliceInfo_ = GetSlice(); + tempNeedDealTcSize_ = needDealTcSize_; + isSaved_ = true; +} + +template +__aicore__ inline void CompressorVec1SliceIterator::Load() { + if (isSaved_) { + sliceInfo_ = tempSliceInfo_; + needDealTcSize_ = tempNeedDealTcSize_; + } +} + +template +__aicore__ inline void CompressorVec1SliceIterator::Clear() { + isSaved_ = false; +} + +template +__aicore__ inline SeqCntInfo +CompressorVec1SliceIterator::FullIteratorSlice() { + tempSliceInfo_ = GetSlice(); + tempNeedDealTcSize_ = needDealTcSize_; + while (!IsEnd()) { + GetSlice(); + IteratorSlice(); + } + Vec1SliceInfo sliceInfo = GetSlice(); + SeqCntInfo seqCntInfo{}; + seqCntInfo.dealedSeqCnt = + sliceInfo.dealedSeqCnt - tempSliceInfo_.dealedSeqCnt; + if constexpr (COMP::coff == COFF::OVERLAP) { + seqCntInfo.preDealedSeqCnt = + sliceInfo.preDealedSeqCnt - tempSliceInfo_.preDealedSeqCnt; + } + sliceInfo_ = tempSliceInfo_; + needDealTcSize_ = tempNeedDealTcSize_; + return seqCntInfo; +} + +} // namespace XllmKernelCompressor + +#endif \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/compressor/op_kernel/xllm_kernel_compressor.cpp b/xllm-kernel/csrc/ascendc/compressor/op_kernel/xllm_kernel_compressor.cpp new file mode 100644 index 0000000000..39195a7dbc --- /dev/null +++ b/xllm-kernel/csrc/ascendc/compressor/op_kernel/xllm_kernel_compressor.cpp @@ -0,0 +1,100 @@ +/** + * 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 compressor.cpp + * \brief + */ + +#include "compressor_kernel.h" +#if (__CCE_AICORE__ == 220) +#include "compressor_kernel_perf.h" +#endif + +using namespace XllmKernelCompressor; + +#define INVOKE_COMPRESSOR_GENERAL_OP_IMPL(templateClass, ...) \ + do { \ + templateClass> op(&pipe, tilingData); \ + op.Init(x, \ + wKv, \ + wGate, \ + kvState, \ + scoreState, \ + ape, \ + normWeight, \ + ropeSin, \ + ropeCos, \ + kvBlockTable, \ + scoreBlockTable, \ + cuSeqlens, \ + seqUsed, \ + startPos, \ + cmpKvOut, \ + workspace); \ + op.Process(); \ + } while (0) + +template +__global__ __aicore__ void xllm_kernel_compressor( + __gm__ uint8_t* x, + __gm__ uint8_t* wKv, + __gm__ uint8_t* wGate, + __gm__ uint8_t* kvState, + __gm__ uint8_t* scoreState, + __gm__ uint8_t* ape, + __gm__ uint8_t* normWeight, + __gm__ uint8_t* ropeSin, + __gm__ uint8_t* ropeCos, + __gm__ uint8_t* kvBlockTable, + __gm__ uint8_t* scoreBlockTable, + __gm__ uint8_t* cuSeqlens, + __gm__ uint8_t* seqUsed, + __gm__ uint8_t* startPos, + __gm__ uint8_t* cmpKvOut, + __gm__ uint8_t* kvStateOut, + __gm__ uint8_t* scoreStateOut, + __gm__ uint8_t* wkvProjOut, + __gm__ uint8_t* softmaxResOut, + __gm__ uint8_t* normXOut, + __gm__ uint8_t* normRstdOut, + __gm__ uint8_t* workspace, + __gm__ uint8_t* tiling) { + REGISTER_TILING_DEFAULT(optiling::CompressorTilingData); + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); + GET_TILING_DATA_WITH_STRUCT( + optiling::CompressorTilingData, tilingDataIn, tiling); + if constexpr (static_cast(TemplateId) == TEMPLATE_ID::EMPTY_X) { + return; + } + const optiling::CompressorTilingData* __restrict tilingData = &tilingDataIn; + TPipe pipe; + constexpr auto xLayout = static_cast(XLayout); + constexpr auto xDtype = static_cast(XDType); + constexpr auto coff = static_cast(Coff); + constexpr auto rotaryMode = static_cast(RotaryMode); +#if (__CCE_AICORE__ == 220) + if constexpr (static_cast(TemplateId) == TEMPLATE_ID::PERF) { + INVOKE_COMPRESSOR_GENERAL_OP_IMPL( + CompressorKernelPerf, xLayout, xDtype, coff, rotaryMode); + } else { + INVOKE_COMPRESSOR_GENERAL_OP_IMPL( + CompressorKernel, xLayout, xDtype, coff, rotaryMode); + } +#else + INVOKE_COMPRESSOR_GENERAL_OP_IMPL( + CompressorKernel, xLayout, xDtype, coff, rotaryMode); +#endif +} \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/SOURCE.txt b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/SOURCE.txt new file mode 100644 index 0000000000..5fceed3540 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/SOURCE.txt @@ -0,0 +1,7 @@ +SparseAttnSharedkv CANN implementation + +Source: https://gitcode.com/xLLM-AI/xllm_ops +Revision: 8bd2b014c38fec33ecf14dd33e05e8ad792ec5c8 +Directory: xllm_ops/attention/sparse_attn_sharedkv + +Packaged under a private CANN operator type and ACLNN entry points. diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_host/sparse_attn_sharedkv_def.cpp b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_host/sparse_attn_sharedkv_def.cpp new file mode 100644 index 0000000000..2dc611693c --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_host/sparse_attn_sharedkv_def.cpp @@ -0,0 +1,137 @@ +/** + * 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_attn_sharedkv_def.cpp + * \brief + */ + +#include "register/op_def_registry.h" + +namespace ops { +class XllmKernelSparseAttnSharedkv : public OpDef { + public: + explicit XllmKernelSparseAttnSharedkv(const char* name) : OpDef(name) { + this->Input("q") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("ori_kv") + .ParamType(OPTIONAL) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .IgnoreContiguous(); + this->Input("cmp_kv") + .ParamType(OPTIONAL) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .IgnoreContiguous(); + this->Input("ori_sparse_indices") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cmp_sparse_indices") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("ori_block_table") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cmp_block_table") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cu_seqlens_q") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cu_seqlens_ori_kv") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cu_seqlens_cmp_kv") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("seqused_q") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("seqused_kv") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("sinks") + .ParamType(OPTIONAL) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("metadata") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Output("attn_out") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("softmax_lse") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Attr("softmax_scale").AttrType(REQUIRED).Float(1.0); + this->Attr("cmp_ratio").AttrType(REQUIRED).Int(1); + this->Attr("ori_mask_mode") + .AttrType(REQUIRED) + .Int(4); // ori_mask_mode默认值4 + this->Attr("cmp_mask_mode") + .AttrType(REQUIRED) + .Int(3); // cmp_mask_mode默认值3 + this->Attr("ori_kv_stride") + .AttrType(REQUIRED) + .Int(0); // ori_mask_mode默认值4 + this->Attr("cmp_kv_stride") + .AttrType(REQUIRED) + .Int(0); // cmp_mask_mode默认值3 + this->Attr("ori_win_left") + .AttrType(OPTIONAL) + .Int(127); // ori_win_left默认值127 + this->Attr("ori_win_right").AttrType(OPTIONAL).Int(0); + this->Attr("layout_q").AttrType(OPTIONAL).String("BSND"); + this->Attr("layout_kv").AttrType(OPTIONAL).String("PA_ND"); + 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("ascend910b", aicore_config); + this->AICore().AddConfig("ascend910_93", aicore_config); + this->AICore().AddConfig("ascend950", aicore_config); + } +}; +OP_ADD(XllmKernelSparseAttnSharedkv); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_host/sparse_attn_sharedkv_proto.cpp b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_host/sparse_attn_sharedkv_proto.cpp new file mode 100644 index 0000000000..24319437a1 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_host/sparse_attn_sharedkv_proto.cpp @@ -0,0 +1,72 @@ +/** + * 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_attn_sharedkv_proto.cpp + * \brief + */ + +#include +#include + +#include "common/error/ops_error.h" +#include "sparse_attn_sharedkv_tiling.h" + +using namespace ge; + +namespace ops { +constexpr uint32_t QUERY_INPUT_INDEX = 0; + +ge::graphStatus InferShapeSparseAttnSharedkv(gert::InferShapeContext* context) { + OPS_ERR_IF( + context == nullptr, + OPS_LOG_E("XllmKernelSparseAttnSharedkv", "InferShapeContext is nullptr"), + return ge::GRAPH_FAILED); + const gert::Shape* queryShape = context->GetInputShape(QUERY_INPUT_INDEX); + OPS_LOG_E_IF_NULL(context, queryShape, return ge::GRAPH_FAILED) + gert::Shape* attentionOutShape = context->GetOutputShape(0); + OPS_LOG_E_IF_NULL(context, attentionOutShape, return ge::GRAPH_FAILED) + *attentionOutShape = *queryShape; + + gert::Shape* softmaxLseShape = context->GetOutputShape(1); + OPS_LOG_E_IF_NULL(context, softmaxLseShape, return ge::GRAPH_FAILED) + auto attr = context->GetAttrs(); + const bool* returnSoftmaxLsePtr = + attr->GetAttrPointer(optiling::ATTR_RETURN_SOFTMAX_LSE); + bool returnSoftmaxLse = + (returnSoftmaxLsePtr != nullptr) ? *returnSoftmaxLsePtr : false; + if (returnSoftmaxLse) { + *softmaxLseShape = *queryShape; + auto lastDimIdx = softmaxLseShape->GetDimNum() - 1; + softmaxLseShape->SetDim(lastDimIdx, 1); + } else { + softmaxLseShape->SetDimNum(1); + softmaxLseShape->SetDim(0, 0); + } + return GRAPH_SUCCESS; +} + +ge::graphStatus InferDataTypeSparseAttnSharedkv( + gert::InferDataTypeContext* context) { + OPS_ERR_IF( + context == nullptr, + OPS_LOG_E("XllmKernelSparseAttnSharedkv", "InferShapeContext is nullptr"), + return ge::GRAPH_FAILED); + const auto inputDataType = context->GetInputDataType(QUERY_INPUT_INDEX); + context->SetOutputDataType(0, inputDataType); + context->SetOutputDataType(1, ge::DT_FLOAT); + return ge::GRAPH_SUCCESS; +} + +IMPL_OP(XllmKernelSparseAttnSharedkv) + .InferShape(InferShapeSparseAttnSharedkv) + .InferDataType(InferDataTypeSparseAttnSharedkv); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_host/sparse_attn_sharedkv_tiling.cpp b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_host/sparse_attn_sharedkv_tiling.cpp new file mode 100644 index 0000000000..8ed0235ae6 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_host/sparse_attn_sharedkv_tiling.cpp @@ -0,0 +1,1860 @@ +/** + * 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_attn_sharedkv_tiling.cpp + * \brief + */ + +#include "sparse_attn_sharedkv_tiling.h" + +#include "sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_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 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"; +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}}, + {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}}}; + +const std::map> LAYOUT_SUPPORT_MAP = { + {QUERY_NAME, {SASLayout::BSND, SASLayout::TND}}, + {ORI_KV_NAME, {SASLayout::PA_ND, SASLayout::BSND, SASLayout::TND}}, + {CMP_KV_NAME, {SASLayout::PA_ND, SASLayout::BSND, SASLayout::TND}}, + {ATTEN_OUT_NAME, {SASLayout::BSND, SASLayout::TND}}, + {ORI_SPARSE_INDICES, {SASLayout::BSND, SASLayout::TND}}, + {CMP_SPARSE_INDICES, {SASLayout::BSND, SASLayout::TND}}, +}; + +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 +}; + +std::string SASLayoutToSerialString(SASLayout layout) { + switch (layout) { + case SASLayout::BSND: + return "BSND"; + case SASLayout::TND: + return "TND"; + case SASLayout::PA_ND: + return "PA_ND"; + default: + return "UNKNOWN"; + } +} + +struct SASCompileInfo { + int64_t core_num; +}; + +static const std::map> SAS_LAYOUT_AXIS_MAP = { + {SASLayout::BSND, {SASAxis::B, SASAxis::S, SASAxis::N, SASAxis::D}}, + {SASLayout::TND, {SASAxis::T, SASAxis::N, SASAxis::D}}, + {SASLayout::PA_ND, {SASAxis::Bn, SASAxis::Bs, SASAxis::N, SASAxis::D}}, +}; + +static const std::map SAS_LAYOUT_DIM_MAP = { + {SASLayout::BSND, DIM_NUM_FOUR}, + {SASLayout::TND, DIM_NUM_THREE}, + {SASLayout::PA_ND, DIM_NUM_FOUR}, +}; + +static std::string SASDataTypeToSerialString(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("sparseAttnSharedkv", "datatype %d not support", type); + return "UNDEFINED"; + } +} + +// --------------------------SASInfoParser类成员函数定义------------------------------------- +ge::graphStatus SASInfoParser::CheckRequiredInOutExistence() const { + OP_CHECK_IF(opParamInfo_.q.shape == nullptr, + OP_LOGE(opName_, "Shape of tensor q is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.q.desc == nullptr, + OP_LOGE(opName_, "Desc of tensor q is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.oriKv.tensor == nullptr, + OP_LOGE(opName_, "tensor of ori_Kv is nullptr"), + return ge::GRAPH_FAILED); + if (kvLayout_ == SASLayout::PA_ND) { + OP_CHECK_IF(opParamInfo_.oriBlockTable.tensor == nullptr, + OP_LOGE(opName_, "tensor of ori_block_table is nullptr"), + return ge::GRAPH_FAILED); + } + if (perfMode_ == SASTemplateMode::CFA_TEMPLATE_MODE) { + OP_CHECK_IF(opParamInfo_.cmpKv.tensor == nullptr, + OP_LOGE(opName_, "tensor of cmp_kv is nullptr"), + return ge::GRAPH_FAILED); + } + if (perfMode_ == SASTemplateMode::SCFA_TEMPLATE_MODE) { + OP_CHECK_IF(opParamInfo_.cmpKv.tensor == nullptr, + OP_LOGE(opName_, "tensor of cmp_kv is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.cmpSparseIndices.tensor == nullptr, + OP_LOGE(opName_, "cmp_sparse_indices is nullptr"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::CheckRequiredAttrExistence() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::CheckRequiredParaExistence() const { + if (CheckRequiredInOutExistence() != ge::GRAPH_SUCCESS || + CheckRequiredAttrExistence() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::CheckUnrequiredParaExistence() const { + OP_CHECK_IF( + opParamInfo_.oriSparseIndices.tensor != nullptr || + opParamInfo_.oriSparseIndices.desc != nullptr, + OP_LOGE(opName_, "Currently, ori_sparse_indices must be a nullptr"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetOpName() { + if (context_->GetNodeName() == nullptr) { + OP_LOGE("XllmKernelSparseAttnSharedkv", + "opName got from TilingContext is nullptr"); + return ge::GRAPH_FAILED; + } + opName_ = context_->GetNodeName(); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::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_); + aivNum_ = ascendcPlatform.GetCoreNumAiv(); + aicNum_ = ascendcPlatform.GetCoreNumAic(); + OP_CHECK_IF(aicNum_ == 0 || aivNum_ == 0, + OP_LOGE(opName_, "num of core obtained is 0."), + return ge::GRAPH_FAILED); + + socVersion_ = ascendcPlatform.GetSocVersion(); + if ((socVersion_ != platform_ascendc::SocVersion::ASCEND910B) && + (socVersion_ != platform_ascendc::SocVersion::ASCEND910_93)) { + OP_LOGE(opName_, "SOC Version[%d] is not support.", (int32_t)socVersion_); + return GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +void SASInfoParser::GetOptionalInputParaInfo() { + opParamInfo_.oriKv.tensor = context_->GetOptionalInputTensor(ORI_KV_INDEX); + opParamInfo_.oriKv.desc = context_->GetOptionalInputDesc(ORI_KV_INDEX); + opParamInfo_.cmpKv.tensor = context_->GetOptionalInputTensor(CMP_KV_INDEX); + opParamInfo_.cmpKv.desc = context_->GetOptionalInputDesc(CMP_KV_INDEX); + opParamInfo_.oriSparseIndices.tensor = + context_->GetOptionalInputTensor(ORI_SPARSE_INDICES_INDEX); + opParamInfo_.oriSparseIndices.desc = + context_->GetOptionalInputDesc(ORI_SPARSE_INDICES_INDEX); + opParamInfo_.cmpSparseIndices.tensor = + context_->GetOptionalInputTensor(CMP_SPARSE_INDICES_INDEX); + opParamInfo_.cmpSparseIndices.desc = + context_->GetOptionalInputDesc(CMP_SPARSE_INDICES_INDEX); + opParamInfo_.oriBlockTable.tensor = + context_->GetOptionalInputTensor(ORI_BLOCK_TABLE_INDEX); + opParamInfo_.oriBlockTable.desc = + context_->GetOptionalInputDesc(ORI_BLOCK_TABLE_INDEX); + opParamInfo_.cmpBlockTable.tensor = + context_->GetOptionalInputTensor(CMP_BLOCK_TABLE_INDEX); + opParamInfo_.cmpBlockTable.desc = + context_->GetOptionalInputDesc(CMP_BLOCK_TABLE_INDEX); + opParamInfo_.sinks.tensor = context_->GetOptionalInputTensor(SINKS_INDEX); + opParamInfo_.sinks.desc = context_->GetOptionalInputDesc(SINKS_INDEX); + opParamInfo_.cuSeqLensQ.tensor = + context_->GetOptionalInputTensor(CU_SEQLENS_Q_INDEX); + opParamInfo_.cuSeqLensQ.desc = + context_->GetOptionalInputDesc(CU_SEQLENS_Q_INDEX); + opParamInfo_.seqUsedQ.tensor = + context_->GetOptionalInputTensor(SEQUSED_Q_INDEX); + opParamInfo_.seqUsedQ.desc = context_->GetOptionalInputDesc(SEQUSED_Q_INDEX); + opParamInfo_.cuSeqLensKv.tensor = + context_->GetOptionalInputTensor(CU_SEQLENS_KV_INDEX); + opParamInfo_.cuSeqLensKv.desc = + context_->GetOptionalInputDesc(CU_SEQLENS_KV_INDEX); + opParamInfo_.cuSeqLensCmpKv.tensor = + context_->GetOptionalInputTensor(CU_SEQLENS_CMP_KV_INDEX); + opParamInfo_.cuSeqLensCmpKv.desc = + context_->GetOptionalInputDesc(CU_SEQLENS_CMP_KV_INDEX); + opParamInfo_.sequsedKv.tensor = + context_->GetOptionalInputTensor(SEQUSED_KV_INDEX); + opParamInfo_.sequsedKv.desc = + context_->GetOptionalInputDesc(SEQUSED_KV_INDEX); + opParamInfo_.metadata.desc = context_->GetOptionalInputDesc(METADATA_INDEX); + opParamInfo_.metadata.tensor = + context_->GetOptionalInputTensor(METADATA_INDEX); +} + +void SASInfoParser::GetInputParaInfo() { + opParamInfo_.q.desc = context_->GetInputDesc(Q_INDEX); + opParamInfo_.q.shape = context_->GetInputShape(Q_INDEX); + GetOptionalInputParaInfo(); +} + +void SASInfoParser::GetOutputParaInfo() { + opParamInfo_.attnOut.desc = context_->GetOutputDesc(ATTN_OUT_INDEX); + opParamInfo_.attnOut.shape = context_->GetOutputShape(ATTN_OUT_INDEX); +} + +ge::graphStatus SASInfoParser::GetAttrParaInfo() { + auto attrs = context_->GetAttrs(); + OP_CHECK_IF(attrs == nullptr, + OPS_REPORT_VECTOR_INNER_ERR(context_->GetNodeName(), + "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_.oriKvStride = + attrs->GetAttrPointer(ATTR_ORI_KV_STRIDE_INDEX); + opParamInfo_.cmpKvStride = + attrs->GetAttrPointer(ATTR_CMP_KV_STRIDE_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_.returnSoftmaxLse = + attrs->GetAttrPointer(ATTR_RETURN_SOFTMAX_LSE); + + OP_LOGI(context_->GetNodeName(), "GetAttrParaInfo end"); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetOpParaInfo() { + GetInputParaInfo(); + GetOutputParaInfo(); + if (ge::GRAPH_SUCCESS != GetAttrParaInfo()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::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 SASInfoParser::GetSASTemplateMode(SASTilingInfo& sasInfo) { + if (opParamInfo_.oriKv.desc != nullptr) { + if (opParamInfo_.cmpKv.desc != nullptr && + opParamInfo_.cmpSparseIndices.tensor != nullptr) { + perfMode_ = SASTemplateMode::SCFA_TEMPLATE_MODE; + } else if (opParamInfo_.cmpKv.desc != nullptr && + opParamInfo_.cmpSparseIndices.tensor == nullptr) { + perfMode_ = SASTemplateMode::CFA_TEMPLATE_MODE; + } else if (opParamInfo_.cmpKv.desc == nullptr && + opParamInfo_.cmpSparseIndices.tensor == nullptr) { + perfMode_ = SASTemplateMode::SWA_TEMPLATE_MODE; + } else { + OP_LOGE( + opName_, + "When cmp_sparse_indices is not nullptr, cmp_kv cannot be nullptr."); + return ge::GRAPH_FAILED; + } + if (sasInfo.perfMode == SASTemplateMode::CFA_TEMPLATE_MODE || + sasInfo.perfMode == SASTemplateMode::SCFA_TEMPLATE_MODE) { + if (kvLayout_ == SASLayout::TND && + opParamInfo_.cuSeqLensCmpKv.tensor == nullptr) { + OP_LOGE(opName_, + "the layout_kv is %s, seqlens_cmp_kv must be provided.", + SASLayoutToSerialString(kvLayout_).c_str()); + return ge::GRAPH_FAILED; + } + } + return ge::GRAPH_SUCCESS; + } else { + OP_LOGE(opName_, "ori_kv is nullptr"); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetQueryAndOutLayout() { + // 获取q和attnOut的Layout基准值 + // layoutQuery: {qLayout, outLayout} + const map> layoutMap = { + {"BSND", {SASLayout::BSND, SASLayout::BSND}}, + {"TND", {SASLayout::TND, SASLayout::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(opName_, "layout of q is %s, it is unsupported.", layout.c_str()); + return ge::GRAPH_FAILED; + } + if (qLayout_ == SASLayout::BSND) { + OP_CHECK_IF( + opParamInfo_.cuSeqLensQ.tensor != nullptr, + OP_LOGE(opName_, "when q's layout is BSND, cu_seqlens_q is null."), + return ge::GRAPH_FAILED); + } + if (qLayout_ == SASLayout::TND) { + OP_CHECK_IF(opParamInfo_.seqUsedQ.tensor != nullptr, + OP_LOGE(opName_, "when q's layout is TND, seqused_q is null."), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetKvLayout() { + const map layoutKVMap = { + {"PA_ND", SASLayout::PA_ND}, + {"BSND", SASLayout::BSND}, + {"TND", SASLayout::TND}, + }; + std::string layout(opParamInfo_.layoutKv); + auto it = layoutKVMap.find(layout); + if (it != layoutKVMap.end()) { + kvLayout_ = it->second; + } else { + OP_LOGE(opName_, "layout_kv is %s, it is unsupported.", layout.c_str()); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +// =============Parser function==================== +bool SASInfoParser::HasAxis(const SASAxis& axis, + const SASLayout& layout, + const gert::Shape& shape) const { + const auto& layoutIt = SAS_LAYOUT_AXIS_MAP.find(layout); + if (layoutIt == SAS_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 = SAS_LAYOUT_DIM_MAP.find(layout); + if (dimIt == SAS_LAYOUT_DIM_MAP.end() || dimIt->second != shape.GetDimNum()) { + return false; + } + return true; +} + +size_t SASInfoParser::GetAxisIdx(const SASAxis& axis, + const SASLayout& layout) const { + const std::vector& axes = SAS_LAYOUT_AXIS_MAP.find(layout)->second; + const auto& axisIt = std::find(axes.begin(), axes.end(), axis); + return std::distance(axes.begin(), axisIt); +} + +uint32_t SASInfoParser::GetAxisNum(const gert::Shape& shape, + const SASAxis& axis, + const SASLayout& layout) const { + return HasAxis(axis, layout, shape) ? shape.GetDim(GetAxisIdx(axis, layout)) + : invalidDimValue_; +} + +void SASInfoParser::SetSASShape() { + qShape_ = opParamInfo_.q.shape->GetStorageShape(); + if (opParamInfo_.oriKv.tensor != nullptr) { + oriKvShape_ = opParamInfo_.oriKv.tensor->GetStorageShape(); + } else { + OP_LOGE(opName_, "q tensor is nullptr, please check input parameters."); + } + if (opParamInfo_.cmpKv.tensor != nullptr) { + cmpKvShape_ = opParamInfo_.cmpKv.tensor->GetStorageShape(); + } + if (perfMode_ == SASTemplateMode::SCFA_TEMPLATE_MODE) { + if (opParamInfo_.cmpSparseIndices.tensor != nullptr) { + cmpSparseIndicesShape_ = + opParamInfo_.cmpSparseIndices.tensor->GetStorageShape(); + uint32_t cmpSparseIndicesT = GetAxisNum( + cmpSparseIndicesShape_, SASAxis::T, cmpSparseIndicesLayout_); + } else { + OP_LOGE(opName_, + "cmp_sparse_indices tensor is nullptr, please check input " + "parameters."); + } + } +} + +ge::graphStatus SASInfoParser::GetN1Size() { + n1Size_ = GetAxisNum(qShape_, SASAxis::N, qLayout_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetN2Size() { + if (opParamInfo_.oriKv.tensor != nullptr) { + n2Size_ = GetAxisNum(oriKvShape_, SASAxis::N, kvLayout_); + } + if (opParamInfo_.cmpKv.tensor != nullptr) { + uint32_t cmpKvN2Size_ = GetAxisNum(cmpKvShape_, SASAxis::N, kvLayout_); + if (perfMode_ == SASTemplateMode::SCFA_TEMPLATE_MODE) { + uint32_t cmpSparseIndicesN2Size_ = GetAxisNum( + cmpSparseIndicesShape_, SASAxis::N, cmpSparseIndicesLayout_); + OP_CHECK_IF(cmpKvN2Size_ != n2Size_ || n2Size_ != cmpSparseIndicesN2Size_, + OP_LOGE(opName_, + "N2 size check failed! Expected ori_kv's N2(%u) == " + "cmp_sparse_indices's N2(%u).", + n2Size_, + cmpSparseIndicesN2Size_), + return ge::GRAPH_FAILED); + } + OP_CHECK_IF( + cmpKvN2Size_ != n2Size_, + OP_LOGE( + opName_, + "N2 size check failed! Expected cmp_kv's N2(%u) ==ori_kv's N2(%u).", + cmpKvN2Size_, + n2Size_), + return ge::GRAPH_FAILED); + n2Size_ = cmpKvN2Size_; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetGSize() { + if (n2Size_ != 0) { + gSize_ = n1Size_ / n2Size_; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetActualSeqLenSize( + uint32_t& size, + const gert::Tensor* tensor, + SASLayout& layout, + const std::string& name) const { + if ((tensor == nullptr)) { + OP_LOGE(opName_, + "when layout of q is %s, %s must be provided.", + SASLayoutToSerialString(layout).c_str(), + name.c_str()); + return ge::GRAPH_FAILED; + } + int64_t shapeSize = tensor->GetShapeSize(); + if (shapeSize <= 0) { + OP_LOGE(opName_, + "the shape size of %s is %ld, it should be greater than 0.", + name.c_str(), + shapeSize); + return ge::GRAPH_FAILED; + } + size = static_cast(shapeSize); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetActualSeqLenQSize(uint32_t& size) { + return GetActualSeqLenSize( + size, opParamInfo_.cuSeqLensQ.tensor, qLayout_, "cuSeqLensQ"); +} + +ge::graphStatus SASInfoParser::GetBatchSize() { + // 获取B基准值 + // 1、非TND时, 以query的batch_size维度为基准; + // 2、TND时, actual_seq_lens_q必须传入, 以actual_seq_lens_q数组的长度为B轴大小 + if (qLayout_ == SASLayout::TND) { + return GetActualSeqLenQSize(bSize_); + } else { // BSND + bSize_ = GetAxisNum(qShape_, SASAxis::B, qLayout_); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetQTSize() { + // 获取query的T基准值 + // 1、非TND时, 以query的batch_size维度为基准; + // 2、TND时, actual_seq_lens_q必须传入, 以actual_seq_lens_q数组的长度为B轴大小 + qTSize_ = (qLayout_ == SASLayout::TND) + ? GetAxisNum(qShape_, SASAxis::T, qLayout_) + : 0; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetKVTSize() { + // 获取KV的T基准值 + // 1、非TND时, 以KV的batch_size维度为基准; + // 2、TND时, actual_seq_lens_ori_kv和actual_seq_lens_cmp_kv必须传入, + // 以actual_seq_lens_ori_kv数组的长度为B轴大小(当前接口只传入oriseq,先以oriseq算出cmpseq) + orikvTSize_ = (kvLayout_ == SASLayout::TND) + ? GetAxisNum(oriKvShape_, SASAxis::T, kvLayout_) + : 0; + // 入参接口信息可以从GetOptionalInputParaInfo()函数中获取 + // cmpkvTSize_ = (kvLayout_ == SASLayout::TND) ? GetAxisNum(cmpKvShape_, + // SASAxis::T, kvLayout_) : 0; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetS1Size() { + // 获取S1基准值 + // 1、非TND时, 以query的S维度为基准; + // 2、TND时, actual_seq_lens_q必须传入, + // 以actual_seq_lens_q数组中的最大值为基准 + if (qLayout_ == SASLayout::TND) { + s1Size_ = GetAxisNum(qShape_, SASAxis::T, qLayout_); + } else { // BSND + s1Size_ = GetAxisNum(qShape_, SASAxis::S, qLayout_); + } + if (perfMode_ == SASTemplateMode::SCFA_TEMPLATE_MODE) { + if (cmpSparseIndicesLayout_ == SASLayout::TND) { + uint32_t cmpSparseIndicesT = GetAxisNum( + cmpSparseIndicesShape_, SASAxis::T, cmpSparseIndicesLayout_); + OP_CHECK_IF(cmpSparseIndicesT != s1Size_, + OP_LOGE(opName_, "T size check failed !"), + return ge::GRAPH_FAILED); + } else { + uint32_t cmpSparseIndicesS1 = GetAxisNum( + cmpSparseIndicesShape_, SASAxis::S, cmpSparseIndicesLayout_); + OP_CHECK_IF(cmpSparseIndicesS1 != s1Size_, + OP_LOGE(opName_, "s1 size check failed !"), + return ge::GRAPH_FAILED); + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetMaxBlockNumPerBatch() { + if (opParamInfo_.oriBlockTable.tensor == nullptr) { + OP_LOGE(opName_, + "the layout_kv is %s, block_table must be provided.", + SASLayoutToSerialString(kvLayout_).c_str()); + return ge::GRAPH_FAILED; + } + uint32_t oriDimNum = + opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDimNum(); + if (oriDimNum != DIM_NUM_TWO) { + OP_LOGE(opName_, + "the dim num of ori_block_table is %u, it should be %u.", + oriDimNum, + DIM_NUM_TWO); + return ge::GRAPH_FAILED; + } + if (opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDim(1) < 0) { + OP_LOGE(opName_, + "%s's second dimension(%lld) should be non-negative number.", + ORI_BLOCK_TABLE_NAME.c_str(), + opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetDim(1)); + 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(opName_, + "the dim num of cmp_block_table is %u, it should be %u.", + cmpDimNum, + DIM_NUM_TWO); + return ge::GRAPH_FAILED; + } + if (qLayout_ == SASLayout::TND) { + if (opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim(0) != + bSize_ - 1) { + OP_LOGE(opName_, + "cmp_block_table's first dimension(%u) should be equal to " + "query's B(%u).", + opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim(1), + bSize_ - 1); + return ge::GRAPH_FAILED; + } + } else if (qLayout_ == SASLayout::BSND) { + if (opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim(0) != + bSize_) { + OP_LOGE(opName_, + "cmp_block_table's first dimension(%u) should be equal to " + "query's B(%u).", + opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim(1), + bSize_); + return ge::GRAPH_FAILED; + } + } + if (opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim(1) <= 0) { + OP_LOGE(opName_, + "%s's second dimension(%lld) should be greater than 0", + CMP_BLOCK_TABLE_NAME.c_str(), + opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim(1)); + return ge::GRAPH_FAILED; + } + cmpMaxBlockNumPerBatch_ = + opParamInfo_.cmpBlockTable.tensor->GetStorageShape().GetDim(1); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetBlockSize() { + oriBlockSize_ = GetAxisNum(oriKvShape_, SASAxis::Bs, kvLayout_); + cmpBlockSize_ = GetAxisNum(cmpKvShape_, SASAxis::Bs, kvLayout_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetS2SizeForPageAttention() { + if (GetMaxBlockNumPerBatch() != ge::GRAPH_SUCCESS || + GetBlockSize() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + s2Size_ = oriMaxBlockNumPerBatch_ * oriBlockSize_; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetS2SizeForTND() { + if (opParamInfo_.cuSeqLensKv.tensor == nullptr) { + OP_LOGE(opName_, + "the layout_kv is %s, seqlens_ori_kv must be provided.", + SASLayoutToSerialString(kvLayout_).c_str()); + return ge::GRAPH_FAILED; + } + // if (opParamInfo_.sequsedKv.tensor == nullptr) { + // OP_LOGE(opName_, "the layout_kv is %s, sequsedKv must be provided.", + // SASLayoutToSerialString(kvLayout_).c_str()); return ge::GRAPH_FAILED; + // } + // 这里返回累加和的最大值 + s2Size_ = GetAxisNum(oriKvShape_, SASAxis::T, qLayout_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetS2Size() { + // 获取S2基准值:PAGE_ATTENTION时, S2 = block_table.dim1 * block_size + // 1、PAGE_ATTENTION时, S2 = block_table.dim1 * block_size + // 2、BSND时, S2直接获取 + if (kvLayout_ == SASLayout::BSND) { + if (opParamInfo_.oriKv.tensor != nullptr) { + s2Size_ = GetAxisNum(oriKvShape_, SASAxis::S, kvLayout_); + return ge::GRAPH_SUCCESS; + } + if (opParamInfo_.cmpKv.tensor != nullptr) { + s2Size_ = GetAxisNum(cmpKvShape_, SASAxis::S, kvLayout_); + return ge::GRAPH_SUCCESS; + } + return ge::GRAPH_FAILED; + } + return (kvLayout_ == SASLayout::PA_ND) ? GetS2SizeForPageAttention() + : GetS2SizeForTND(); +} + +ge::graphStatus SASInfoParser::GetQHeadDim() { + qHeadDim_ = GetAxisNum(qShape_, SASAxis::D, qLayout_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetValueHeadDim() { + if (opParamInfo_.oriKv.tensor != nullptr) { + oriKvHeadDim_ = GetAxisNum(oriKvShape_, SASAxis::D, kvLayout_); + } + if (opParamInfo_.cmpKv.tensor != nullptr) { + cmpKvHeadDim_ = GetAxisNum(cmpKvShape_, SASAxis::D, kvLayout_); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetSparseBlockCount() { + if (opParamInfo_.cmpSparseIndices.tensor != nullptr) { + sparseBlockCount_ = + GetAxisNum(cmpSparseIndicesShape_, SASAxis::K, cmpSparseIndicesLayout_); + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetSinks() { + if (opParamInfo_.sinks.tensor == nullptr) { + OP_LOGE(opName_, "%s must be provided!", SINKS_NAME.c_str()); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASInfoParser::GetActualseqInfo() { + maxActualseq_ = static_cast(s2Size_); + if (qLayout_ == SASLayout::TND) { + if (opParamInfo_.cuSeqLensQ.tensor != nullptr) { + if (opParamInfo_.cuSeqLensQ.tensor->GetShapeSize() != bSize_) { + OP_LOGE( + opName_, "cu_seqlens_q's dimension should be equal to %u.", bSize_); + return ge::GRAPH_FAILED; + } + actualLenDimsQ_ = opParamInfo_.cuSeqLensQ.tensor->GetShapeSize() - + 1; // cuSeqLensQ shape is B+1 + OP_CHECK_IF(actualLenDimsQ_ == 0, + OP_LOGE(opName_, "cu_seqlens_q cannot be empty tensor."), + return ge::GRAPH_FAILED); + } else { + OP_LOGE(opName_, + "When layout_q is TND, input cu_seqlens_q must be provided"); + return ge::GRAPH_FAILED; + } + } else { + if (opParamInfo_.seqUsedQ.tensor != nullptr) { + actualLenDimsQ_ = opParamInfo_.seqUsedQ.tensor->GetShapeSize(); + } + } + if (kvLayout_ != SASLayout::PA_ND && kvLayout_ != SASLayout::BSND && + kvLayout_ != SASLayout::TND) { + OP_LOGE(opName_, + "ori_kv and cmp_kv only support PA_ND, BSND and TND layout."); + return ge::GRAPH_FAILED; + } + if (kvLayout_ == SASLayout::PA_ND) { + if (opParamInfo_.sequsedKv.tensor != nullptr) { + if (qLayout_ == SASLayout::BSND) { + if (opParamInfo_.sequsedKv.tensor->GetShapeSize() != bSize_) { + OP_LOGE(opName_, + "seqused_kv's dimension should be equal to %u, but got %ld.", + bSize_, + opParamInfo_.sequsedKv.tensor->GetShapeSize()); + return ge::GRAPH_FAILED; + } + } else { + if (opParamInfo_.sequsedKv.tensor->GetShapeSize() != (bSize_ - 1)) { + OP_LOGE(opName_, + "seqused_kv's dimension should be equal to %u (bSize - 1), " + "but got %ld.", + (bSize_ - 1), + opParamInfo_.sequsedKv.tensor->GetShapeSize()); + return ge::GRAPH_FAILED; + } + } + OP_CHECK_IF(opParamInfo_.sequsedKv.desc->GetDataType() != ge::DT_INT32, + OP_LOGE(opName_, "seqused_kv's dtype must be DT_INT32."), + return ge::GRAPH_FAILED); + actualLenDimsKV_ = opParamInfo_.sequsedKv.tensor->GetShapeSize(); + OP_CHECK_IF(actualLenDimsKV_ == 0, + OP_LOGE(opName_, "seqused_kv cannot be empty tensor."), + return ge::GRAPH_FAILED); + } else { + OP_LOGE(opName_, + "When kv layout is PA_ND, input sequsedKv must be provided"); + return ge::GRAPH_FAILED; + } + } else if (kvLayout_ == SASLayout::TND) { + if (opParamInfo_.cuSeqLensKv.tensor != nullptr) { + if (qLayout_ == SASLayout::BSND) { + if (opParamInfo_.cuSeqLensKv.tensor->GetShapeSize() != bSize_ + 1) { + OP_LOGE(opName_, + "cuSeqLensKv's dimension should be equal to %u (bSize + 1), " + "but got %ld.", + (bSize_ + 1), + opParamInfo_.sequsedKv.tensor->GetShapeSize()); + return ge::GRAPH_FAILED; + } + } else { + if (opParamInfo_.cuSeqLensKv.tensor->GetShapeSize() != (bSize_)) { + OP_LOGE(opName_, + "cuSeqLensKv's dimension should be equal to %u, but got %ld.", + bSize_, + opParamInfo_.sequsedKv.tensor->GetShapeSize()); + return ge::GRAPH_FAILED; + } + } + actualLenDimsKV_ = opParamInfo_.cuSeqLensKv.tensor->GetShapeSize(); + } else { + OP_LOGE(opName_, + "When kv layout is TND, input cuSeqLensKv must be provided"); + return ge::GRAPH_FAILED; + } + } + if (opParamInfo_.seqUsedQ.tensor != nullptr) { + actualLenDimsQ_ = opParamInfo_.seqUsedQ.tensor->GetShapeSize(); + } else if (opParamInfo_.cuSeqLensQ.tensor != nullptr) { + actualLenDimsQ_ = opParamInfo_.cuSeqLensQ.tensor->GetShapeSize() - + 1; // cuSeqLensQ shape is B+1 + } + return ge::GRAPH_SUCCESS; +} + +void SASInfoParser::GenerateInfo(SASTilingInfo& sasInfo) { + sasInfo.opName = opName_; + sasInfo.platformInfo = platformInfo_; + sasInfo.opParamInfo = opParamInfo_; + sasInfo.socVersion = socVersion_; + + sasInfo.bSize = bSize_; + sasInfo.n1Size = n1Size_; + sasInfo.n2Size = n2Size_; + sasInfo.s1Size = s1Size_; + sasInfo.s2Size = s2Size_; + sasInfo.gSize = gSize_; + sasInfo.qHeadDim = qHeadDim_; + sasInfo.oriKvHeadDim = oriKvHeadDim_; + sasInfo.cmpKvHeadDim = cmpKvHeadDim_; + sasInfo.qTSize = qTSize_; + sasInfo.sparseBlockCount = sparseBlockCount_; + sasInfo.oriWinLeft = oriWinLeft_; + sasInfo.oriWinRight = oriWinRight_; + sasInfo.qType = qType_; + sasInfo.oriKvType = oriKvType_; + sasInfo.cmpKvType = cmpKvType_; + sasInfo.outputType = outputType_; + sasInfo.perfMode = perfMode_; + + if (kvLayout_ == SASLayout::PA_ND) { + sasInfo.totalBlockNum = + (opParamInfo_.oriKv.tensor != nullptr) + ? opParamInfo_.oriKv.tensor->GetStorageShape().GetDim(0) + : 0; + } + sasInfo.sparseBlockSize = 1; + sasInfo.oriBlockSize = oriBlockSize_; + sasInfo.cmpBlockSize = cmpBlockSize_; + sasInfo.blockTypeSize = sizeof(float); + sasInfo.oriMaxBlockNumPerBatch = oriMaxBlockNumPerBatch_; + sasInfo.cmpMaxBlockNumPerBatch = cmpMaxBlockNumPerBatch_; + + sasInfo.actualLenDimsQ = actualLenDimsQ_; + sasInfo.actualLenDimsKV = actualLenDimsKV_; + sasInfo.maxActualseq = maxActualseq_; + sasInfo.actualSeqLenFlag = (opParamInfo_.sequsedKv.tensor != nullptr); + sasInfo.isSameSeqAllKVTensor = isSameSeqAllKVTensor_; + + sasInfo.softmaxScale = *opParamInfo_.softmaxScale; + sasInfo.cmpRatio = *opParamInfo_.cmpRatio; + sasInfo.oriMaskMode = *opParamInfo_.oriMaskMode; + sasInfo.cmpMaskMode = *opParamInfo_.cmpMaskMode; + sasInfo.oriKvStride = *opParamInfo_.oriKvStride; + sasInfo.cmpKvStride = *opParamInfo_.cmpKvStride; + sasInfo.oriWinLeft = *opParamInfo_.oriWinLeft; + sasInfo.oriWinRight = *opParamInfo_.oriWinRight; + + sasInfo.qLayout = qLayout_; + sasInfo.oriSparseIndicesLayout = oriSparseIndicesLayout_; + sasInfo.cmpSparseIndicesLayout = cmpSparseIndicesLayout_; + sasInfo.kvLayout = kvLayout_; + sasInfo.outLayout = outLayout_; + sasInfo.returnSoftmaxLse = *opParamInfo_.returnSoftmaxLse; +} + +ge::graphStatus SASInfoParser::Parse(SASTilingInfo& sasInfo) { + if (context_ == nullptr) { + OP_LOGE("SparseFlashAttention", "tiling context is nullptr!"); + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != GetOpName() || ge::GRAPH_SUCCESS != GetNpuInfo() || + ge::GRAPH_SUCCESS != GetOpParaInfo() || + ge::GRAPH_SUCCESS != GetKvLayout() || + ge::GRAPH_SUCCESS != CheckRequiredParaExistence() || + ge::GRAPH_SUCCESS != CheckUnrequiredParaExistence()) { + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != GetInOutDataType() || + ge::GRAPH_SUCCESS != GetQueryAndOutLayout() || + ge::GRAPH_SUCCESS != GetSASTemplateMode(sasInfo)) { + return ge::GRAPH_FAILED; + } + + SetSASShape(); + if (ge::GRAPH_SUCCESS != GetN1Size() || ge::GRAPH_SUCCESS != GetN2Size() || + ge::GRAPH_SUCCESS != GetGSize() || ge::GRAPH_SUCCESS != GetBatchSize() || + ge::GRAPH_SUCCESS != GetQTSize() || ge::GRAPH_SUCCESS != GetKVTSize() || + ge::GRAPH_SUCCESS != GetS1Size() || ge::GRAPH_SUCCESS != GetS2Size() || + 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; + } + GenerateInfo(sasInfo); + return ge::GRAPH_SUCCESS; +} + +void SASTilingCheck::Init() { + opName_ = sasInfo_.opName; + platformInfo_ = sasInfo_.platformInfo; + opParamInfo_ = sasInfo_.opParamInfo; + socVersion_ = sasInfo_.socVersion; + bSize_ = sasInfo_.bSize; + n1Size_ = sasInfo_.n1Size; + n2Size_ = sasInfo_.n2Size; + s1Size_ = sasInfo_.s1Size; + s2Size_ = sasInfo_.s2Size; + gSize_ = sasInfo_.gSize; + qHeadDim_ = sasInfo_.qHeadDim; + oriKvHeadDim_ = sasInfo_.oriKvHeadDim; + cmpKvHeadDim_ = sasInfo_.cmpKvHeadDim; + oriBlockSize_ = sasInfo_.oriBlockSize; + cmpBlockSize_ = sasInfo_.cmpBlockSize; + qTSize_ = sasInfo_.qTSize; + qType_ = sasInfo_.qType; + oriKvType_ = sasInfo_.oriKvType; + cmpKvType_ = sasInfo_.cmpKvType; + outputType_ = sasInfo_.outputType; + cmpRatio_ = sasInfo_.cmpRatio; + qLayout_ = sasInfo_.qLayout; + oriSparseIndicesLayout_ = sasInfo_.oriSparseIndicesLayout; + cmpSparseIndicesLayout_ = sasInfo_.cmpSparseIndicesLayout; + oriWinLeft_ = sasInfo_.oriWinLeft; + oriWinRight_ = sasInfo_.oriWinRight; + kvLayout_ = sasInfo_.kvLayout; + outLayout_ = sasInfo_.outLayout; +} + +void SASTilingCheck::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 << SASDataTypeToSerialString(expectDtypeList[i]); + if (i < expectDtypeList.size() - 1) { + oss << ", "; + } + } + OP_LOGE(opName_, + "Tensor %s only supports dtype %s, but got %s", + name.c_str(), + oss.str().c_str(), + SASDataTypeToSerialString(actualDtype).c_str()); +} + +ge::graphStatus SASTilingCheck::CheckDtypeSupport( + const gert::CompileTimeTensorDesc* desc, + const std::string& name) const { + if (desc != nullptr) { + const auto& it = DTYPE_SUPPORT_MAP.find(name); + OP_CHECK_IF( + it == DTYPE_SUPPORT_MAP.end(), + OP_LOGE( + opName_, + "%s datatype support list should be specify in DTYPE_SUPPORT_MAP", + name.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 SASTilingCheck::LogErrorLayoutSupport( + const std::vector& expectLayoutList, + const SASLayout& actualLayout, + const std::string& name) const { + std::ostringstream oss; + for (size_t i = 0; i < expectLayoutList.size(); ++i) { + oss << SASLayoutToSerialString(expectLayoutList[i]); + if (i < expectLayoutList.size() - 1) { + oss << ", "; + } + } + OP_LOGE(opName_, + "Tensor %s only supports layout %s, but got %s", + name.c_str(), + oss.str().c_str(), + SASLayoutToSerialString(actualLayout).c_str()); +} + +ge::graphStatus SASTilingCheck::CheckLayoutSupport( + const SASLayout& actualLayout, + const std::string& name) const { + const auto& it = LAYOUT_SUPPORT_MAP.find(name); + OP_CHECK_IF( + it == LAYOUT_SUPPORT_MAP.end(), + OP_LOGE(opName_, + "%s layout support list should be specify in LAYOUT_SUPPORT_MAP", + name.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 SASTilingCheck::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(opName_, + "%s %s only supports %s, but got %s", + name.c_str(), + subName.c_str(), + oss.str().c_str(), + std::to_string(actualValue).c_str()); +} + +template +void SASTilingCheck::LogErrorDimNumSupport( + const std::vector& expectNumberList, + const T& actualValue, + const std::string& name) const { + LogErrorNumberSupport(expectNumberList, actualValue, name, "dimension"); +} + +ge::graphStatus SASTilingCheck::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 SASTilingCheck::CheckDimNumInLayoutSupport( + const SASLayout& layout, + const gert::StorageShape* shape, + const std::string& name) const { + const auto& dimIt = SAS_LAYOUT_DIM_MAP.find(layout); + OP_CHECK_IF( + shape->GetStorageShape().GetDimNum() != dimIt->second, + OP_LOGE(opName_, + "When layout is %s, %s dimension should be %zu, but it's %zu", + SASLayoutToSerialString(layout).c_str(), + name.c_str(), + dimIt->second, + shape->GetStorageShape().GetDimNum()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckSingleParaQuery() const { + OP_CHECK_IF(opParamInfo_.q.shape->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(opName_, "q cannot be empty tensor."), + return ge::GRAPH_FAILED); + if (opParamInfo_.q.desc == nullptr) { + OP_LOGE(opName_, "%s must be provided!", QUERY_NAME.c_str()); + 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 SASTilingCheck::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; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckSingleParaCmpKv() const { + if (sasInfo_.perfMode == SASTemplateMode::SCFA_TEMPLATE_MODE || + sasInfo_.perfMode == SASTemplateMode::CFA_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; + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckSingleParaNumHeads() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckSingleParaKvHeadNums() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckSingleParaCmpSparseIndices() const { + if (sasInfo_.perfMode == optiling::SASTemplateMode::SCFA_TEMPLATE_MODE) { + OP_CHECK_IF(opParamInfo_.cmpSparseIndices.tensor->GetStorageShape() + .GetShapeSize() == 0, + OP_LOGE(opName_, + "when cmp_sparse_indices is not nullptr(SCFA), " + "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; + } + if (cmpSparseIndicesLayout_ == SASLayout::TND) { + OP_CHECK_IF( + !(opParamInfo_.cmpSparseIndices.tensor->GetStorageShape().GetDim( + DIM_NUM_THREE - 1) != 512 || + opParamInfo_.cmpSparseIndices.tensor->GetStorageShape().GetDim( + DIM_NUM_THREE - 1) != 1024), + OP_LOGE( + opName_, + "K should be 512 or 1024, but got: %lld ", + opParamInfo_.cmpSparseIndices.tensor->GetStorageShape().GetDim( + DIM_NUM_THREE - 1)), + return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF( + !(opParamInfo_.cmpSparseIndices.tensor->GetStorageShape().GetDim( + DIM_NUM_THREE - 1) != 512 || + opParamInfo_.cmpSparseIndices.tensor->GetStorageShape().GetDim( + DIM_NUM_THREE - 1) != 1024), + OP_LOGE( + opName_, + "K should be 512 or 1024, but got: %lld ", + opParamInfo_.cmpSparseIndices.tensor->GetStorageShape().GetDim( + DIM_NUM_FOUR - 1)), + return ge::GRAPH_FAILED); + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckSingleParaOriBlockTable() const { + if (kvLayout_ == SASLayout::BSND) { + return ge::GRAPH_SUCCESS; // BSND 场景不需要使用oriBlockTable + } + if (kvLayout_ == SASLayout::TND) { + return ge::GRAPH_SUCCESS; + } + OP_CHECK_IF( + opParamInfo_.oriBlockTable.tensor->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(opName_, "ori_block_table cannot be empty tensor."), + return ge::GRAPH_FAILED); + 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((oriBlockSize_ <= 0 || oriBlockSize_ > BLOCK_SIZE_LIMIT || + (static_cast(oriBlockSize_) % 16 != 0UL)), + OP_LOGE(opName_, + "ori_block_size should be in range [1, 1024], and be " + "aligned to 16, but got: %d.", + oriBlockSize_), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckSingleParaCmpBlockTable() const { + if (kvLayout_ == SASLayout::BSND) { + return ge::GRAPH_SUCCESS; // BSND 场景不需要使用oriBlockTable + } + if (kvLayout_ == SASLayout::TND) { + return ge::GRAPH_SUCCESS; + } + if (sasInfo_.perfMode == optiling::SASTemplateMode::SCFA_TEMPLATE_MODE || + sasInfo_.perfMode == optiling::SASTemplateMode::CFA_TEMPLATE_MODE) { + 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((cmpBlockSize_ <= 0 || cmpBlockSize_ > BLOCK_SIZE_LIMIT || + (static_cast(cmpBlockSize_) % 16 != 0UL)), + OP_LOGE(opName_, + "cmp_block_size should be in [1, 1024], and be aligned " + "to 16, but got: %d.", + cmpBlockSize_), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckSingleParaSinks() const { + OP_CHECK_IF(opParamInfo_.sinks.tensor->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(opName_, "sinks cannot be empty tensor."), + return ge::GRAPH_FAILED); + if (opParamInfo_.sinks.tensor->GetStorageShape().GetDimNum() != DIM_NUM_ONE) { + OP_LOGE(opName_, + "the dim num of %s is %u, it should be %u.", + SINKS_NAME.c_str(), + opParamInfo_.sinks.tensor->GetStorageShape().GetDimNum(), + DIM_NUM_ONE); + return ge::GRAPH_FAILED; + } + if (opParamInfo_.sinks.tensor->GetStorageShape().GetDim(0) != n1Size_) { + OP_LOGE(opName_, + "%s's dimension(%ld) should be equal to query head num(%u).", + SINKS_NAME.c_str(), + opParamInfo_.sinks.tensor->GetStorageShape().GetDim(0), + n1Size_); + return ge::GRAPH_FAILED; + } + OP_CHECK_IF(opParamInfo_.sinks.desc->GetDataType() != ge::DT_FLOAT, + OP_LOGE(opName_, "sinks's dtype must be DT_FLOAT."), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckSingleParaMetadata() const { + if (opParamInfo_.metadata.tensor == nullptr) { + OP_LOGE(opName_, "%s must be provided!", METADATA_NAME.c_str()); + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + (opParamInfo_.metadata.tensor->GetShapeSize() != METADATA_LIMIT), + OP_LOGE(opName_, "input metadata dim 0 must be %u.", METADATA_LIMIT), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.metadata.desc->GetDataType() != ge::DT_INT32, + OP_LOGE(opName_, "metadata's dtype must be DT_INT32."), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckSingleParaCmpRatio() const { + if (sasInfo_.perfMode == optiling::SASTemplateMode::CFA_TEMPLATE_MODE || + sasInfo_.perfMode == optiling::SASTemplateMode::SCFA_TEMPLATE_MODE) { + OP_CHECK_IF( + cmpRatio_ != 128 && cmpRatio_ != 4, + OP_LOGE(opName_, "cmp_ratio should be 128 or 4, but got %u", cmpRatio_), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckSingleParaOriMaskMode() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckSingleParaCmpMaskMode() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckSingleParaOriKvStride() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckSingleParaCmpKvStride() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckSingleParaOriWinLeft() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckSingleParaOriWinRight() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckSinglePara() const { + if (ge::GRAPH_SUCCESS != CheckSingleParaQuery() || + ge::GRAPH_SUCCESS != CheckSingleParaOriKv() || + ge::GRAPH_SUCCESS != CheckSingleParaCmpKv() || + ge::GRAPH_SUCCESS != CheckSingleParaNumHeads() || + ge::GRAPH_SUCCESS != CheckSingleParaKvHeadNums() || + ge::GRAPH_SUCCESS != CheckSingleParaCmpSparseIndices() || + ge::GRAPH_SUCCESS != CheckSingleParaOriBlockTable() || + ge::GRAPH_SUCCESS != CheckSingleParaCmpBlockTable() || + ge::GRAPH_SUCCESS != CheckSingleParaSinks() || + ge::GRAPH_SUCCESS != CheckSingleParaMetadata() || + ge::GRAPH_SUCCESS != CheckSingleParaCmpRatio() || + ge::GRAPH_SUCCESS != CheckSingleParaOriMaskMode() || + ge::GRAPH_SUCCESS != CheckSingleParaCmpMaskMode() || + ge::GRAPH_SUCCESS != CheckSingleParaOriKvStride() || + ge::GRAPH_SUCCESS != CheckSingleParaCmpKvStride() || + ge::GRAPH_SUCCESS != CheckSingleParaOriWinLeft() || + ge::GRAPH_SUCCESS != CheckSingleParaOriWinRight()) { + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckExists(const void* pointer, + const std::string& name) const { + OP_CHECK_IF(pointer == nullptr, + OP_LOGE(opName_, "%s should not be null", name.c_str()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckNotExists(const void* pointer, + const std::string& name) const { + OP_CHECK_IF(pointer != nullptr, + OP_LOGE(opName_, "%s should be null", name.c_str()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::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 SASTilingCheck::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 SASTilingCheck::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 SASTilingCheck::CheckParaExistence() const { + if (kvLayout_ != SASLayout::PA_ND) { + return ge::GRAPH_SUCCESS; + } + std::map ParamExistMap = { + {"actualSeqLengths", opParamInfo_.sequsedKv.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 SASTilingCheck::CheckFeatureShape() const { + OP_CHECK_IF( + bSize_ <= 0, + OP_LOGE( + opName_, "batch_size should be greater than 0, but got %u", bSize_), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(qTSize_ <= 0 && (qLayout_ == SASLayout::TND), + OP_LOGE(opName_, + "T_size of query should be greater than 0, but got %u", + qTSize_), + return ge::GRAPH_FAILED); + + OP_CHECK_IF( + n1Size_ % 4 != 0, + OP_LOGE( + opName_, "q_head_num should be multiple of 4, but got %u", n1Size_), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(n2Size_ != 1, + OP_LOGE(opName_, "kv_head_num should be 1, but got %u", n2Size_), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(n1Size_ % n2Size_ != 0, + OP_LOGE(opName_, + "q_head_num(%u) must be divisible by kv_head_num(%u)", + n1Size_, + n2Size_), + return ge::GRAPH_FAILED); + + OP_CHECK_IF( + gSize_ % 4 != 0, + OP_LOGE(opName_, "group num should be multiple of 4, but got %u", gSize_), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(qHeadDim_ != DIM_LIMIT, + OP_LOGE(opName_, + "q_head_dim only support %u, but got %u", + DIM_LIMIT, + qHeadDim_), + return ge::GRAPH_FAILED); + OP_CHECK_IF(oriKvHeadDim_ != DIM_LIMIT, + OP_LOGE(opName_, + "ori_kv_head_dim only support %u, but got %u", + DIM_LIMIT, + oriKvHeadDim_), + return ge::GRAPH_FAILED); + if (!(sasInfo_.perfMode == SASTemplateMode::SWA_TEMPLATE_MODE)) { + OP_CHECK_IF(cmpKvHeadDim_ != DIM_LIMIT, + OP_LOGE(opName_, + "cmp_kv_head_dim only support %u, but got %u", + DIM_LIMIT, + cmpKvHeadDim_), + return ge::GRAPH_FAILED); + } + + OP_CHECK_IF(!(qType_ == oriKvType_), + OP_LOGE(opName_, + "Head dimension data type check failed! qType[%s] must " + "be the same with oriKvType[%s].", + SASDataTypeToSerialString(qType_).c_str(), + SASDataTypeToSerialString(oriKvType_).c_str()), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(*opParamInfo_.oriMaskMode != 4, + OP_LOGE(opName_, + "ori_mask_mode should be 4, but got %d", + *opParamInfo_.oriMaskMode), + return ge::GRAPH_FAILED); + OP_CHECK_IF(*opParamInfo_.cmpMaskMode != 3, + OP_LOGE(opName_, + "cmp_mask_mode should be 3, but got %d", + *opParamInfo_.cmpMaskMode), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + oriWinLeft_ != 127, + OP_LOGE(opName_, "ori_win_left should be 127, but got %d", oriWinLeft_), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + oriWinRight_ != 0, + OP_LOGE(opName_, "ori_win_right should be 0, but got %d", oriWinRight_), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::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(opName_, + "layout_q only supports BSND/TND, but got %s", + layoutQuery.c_str()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckFeatureDtype() const { + OP_CHECK_IF(qType_ != ge::DT_BF16 && qType_ != ge::DT_FLOAT16, + OP_LOGE(opName_, + "q dtype only support %s and %s, but got %s", + SASDataTypeToSerialString(ge::DT_BF16).c_str(), + SASDataTypeToSerialString(ge::DT_FLOAT16).c_str(), + SASDataTypeToSerialString(qType_).c_str()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckFeaturePa() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::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; +} + +void SASTilingCheck::SetSASShapeCompare() { + queryShapeCmp_ = opParamInfo_.q.shape->GetStorageShape(); + oriKvShapeCmp_ = opParamInfo_.oriKv.tensor->GetShape().GetStorageShape(); + attenOutShapeCmp_ = opParamInfo_.attnOut.shape->GetStorageShape(); + if (sasInfo_.perfMode == SASTemplateMode::CFA_TEMPLATE_MODE || + sasInfo_.perfMode == SASTemplateMode::SCFA_TEMPLATE_MODE) { + cmpKvShapeCmp_ = opParamInfo_.cmpKv.tensor->GetShape().GetStorageShape(); + } + if (sasInfo_.perfMode == SASTemplateMode::SCFA_TEMPLATE_MODE) { + cmpKvSparseIndicesCmp_ = + opParamInfo_.cmpSparseIndices.tensor->GetShape().GetStorageShape(); + } +} + +ge::graphStatus SASTilingCheck::CheckDTypeConsistency( + const ge::DataType& actualDtype, + const ge::DataType& expectDtype, + const std::string& name) const { + if (actualDtype != expectDtype) { + OP_LOGE(opName_, + "%s dtype should be the same to %s, but it's %s.", + name.c_str(), + SASDataTypeToSerialString(expectDtype).c_str(), + SASDataTypeToSerialString(actualDtype).c_str()); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckOriAndCmpKv() const { + OP_CHECK_IF(opParamInfo_.oriKv.tensor->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(opName_, "ori_kv cannot be empty tensor."), + return ge::GRAPH_FAILED); + if (sasInfo_.perfMode == SASTemplateMode::CFA_TEMPLATE_MODE || + sasInfo_.perfMode == SASTemplateMode::SCFA_TEMPLATE_MODE) { + if (opParamInfo_.cmpKv.tensor->GetStorageShape().GetDim(0) != 0) { + OP_CHECK_IF( + opParamInfo_.cmpKv.tensor->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(opName_, "cmp_kv cannot be empty tensor."), + return ge::GRAPH_FAILED); + } + if (ge::GRAPH_SUCCESS != + CheckDTypeConsistency(cmpKvType_, oriKvType_, CMP_KV_NAME)) { + return ge::GRAPH_FAILED; + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckAttenOut() const { + if (opParamInfo_.attnOut.desc != nullptr && + opParamInfo_.attnOut.shape != nullptr) { + OP_CHECK_IF( + opParamInfo_.attnOut.shape->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(opName_, "attn_out cannot be empty tensor."), + return ge::GRAPH_FAILED); + } else { + OP_LOGE(opName_, "attn_out cannot be nullptr."); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckActualSeqLensQ() const { + if (qLayout_ == SASLayout::TND) { + OP_CHECK_IF( + opParamInfo_.cuSeqLensQ.tensor->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(opName_, + "when q's is TND, cu_seqlens_q cannot be empty tensor."), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.cuSeqLensQ.desc->GetDataType() != ge::DT_INT32, + OP_LOGE(opName_, + "when q's is TND, cu_seqlens_q's dtype msut be DT_INT32."), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckActualSeqLens() const { + return ge::GRAPH_SUCCESS; +} +ge::graphStatus SASTilingCheck::CheckBlockTable() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::CheckMultiParaConsistency() { + SetSASShapeCompare(); + if (ge::GRAPH_SUCCESS != CheckOriAndCmpKv() || + ge::GRAPH_SUCCESS != CheckAttenOut() || + ge::GRAPH_SUCCESS != CheckActualSeqLensQ() || + ge::GRAPH_SUCCESS != CheckActualSeqLens() || + ge::GRAPH_SUCCESS != CheckBlockTable()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SASTilingCheck::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; +} + +// --------------------------TilingPrepare函数定义------------------------------------- +static ge::graphStatus TilingPrepareForSparseAttnSharedkv( + gert::TilingParseContext* /* context */) { + return ge::GRAPH_SUCCESS; +} + +void SparseAttnSharedkvTiling::CalcUbBmm(SASTilingInfo* 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 SparseAttnSharedkvTiling::SplitBalanced(SASTilingInfo* tilingInfo) { + uint32_t s2Size = tilingInfo->s2Size; + sInnerSizeAlign_ = + Align(sInnerSize_, BYTE_BLOCK); // 元素个数按照基本块大小对齐 + 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_); +} + +// --------------------------SparseAttnSharedkvTiling类成员函数定义----------------------- +ge::graphStatus SparseAttnSharedkvTiling::DoOpTiling( + SASTilingInfo* 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); + OP_LOGI(tilingInfo->opName, + "SAS block dim: %u aiv Num: %u aic Num: %u.", + blockDim, + aivNum, + aicNum); + + SplitBalanced(tilingInfo); + // -------------set workspacesize----------------- + constexpr uint32_t MM1_RES_ELEM_SIZE = 4; // 4: fp32 + constexpr uint32_t VEC1_RES_ELEM_SIZE = 2; // 2: fp16/bf16 + constexpr uint32_t MM2_RES_ELEM_SIZE = 4; // 4: fp32 + constexpr uint32_t VEC2_RES_ELEM_SIZE = 4; // 4: fp32 + constexpr uint32_t PRELOAD_NUM = 2; // preload数量 + + uint32_t workspaceSize = ascendcPlatform.GetLibApiWorkSpaceSize(); + // 主流程需Workspace大小 + 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 == SASTemplateMode::SCFA_TEMPLATE_MODE) { + workspaceSize += 4 * 512 * 512 * 2 * + aicNum; // 4:bufNum 512:s2Size 512:D 2:sizeof(half) + workspaceSize += + 4 * 128 * 4 * + (2 * + aicNum); // 4:缓存有效mte2 size长度 128:份数 4:512B对齐长度 2:aiv数量 + } + size_t* workSpaces = context_->GetWorkspaceSizes(1); + workSpaces[0] = workspaceSize; + + // -------------set tilingdata----------------- + 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_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_oriKvStride(tilingInfo->oriKvStride); + 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_sparseBlockCount(tilingInfo->sparseBlockCount); + tilingData_.cmpParams.set_cmpRatio(tilingInfo->cmpRatio); + tilingData_.cmpParams.set_cmpMaskMode(tilingInfo->cmpMaskMode); + tilingData_.cmpParams.set_cmpKvStride(tilingInfo->cmpKvStride); + + usedCoreNum_ = aicNum; + tilingData_.baseParams.set_usedCoreNum(usedCoreNum_); + tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), + context_->GetRawTilingData()->GetCapacity()); + context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize()); + + // -------------set tilingkey----------------- + // FLASH_DECODE, LAYOUT_T, KV_LAYOUT_T, TEMPLATE_MODE + uint32_t qLayout = static_cast(tilingInfo->qLayout); + uint32_t inputKvLayout = static_cast(tilingInfo->kvLayout); + + uint32_t tilingKey = GET_TPL_TILING_KEY( + 0U, qLayout, inputKvLayout, static_cast(tilingInfo->perfMode)); + context_->SetScheduleMode(1); + context_->SetTilingKey(tilingKey); + + return ge::GRAPH_SUCCESS; +} + +// --------------------------Tiling函数定义--------------------------- +ge::graphStatus TilingSparseAttnSharedkv(gert::TilingContext* context) { + OP_CHECK_IF(context == nullptr, + OPS_REPORT_VECTOR_INNER_ERR("XllmKernelSparseAttnSharedkv", + "Tiling context is null."), + return ge::GRAPH_FAILED); + SASTilingInfo sasInfo; + SASInfoParser sasInfoParser(context); + if (sasInfoParser.Parse(sasInfo) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + SASTilingCheck sasTilingChecker(sasInfo); + if (sasTilingChecker.Process() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + SparseAttnSharedkvTiling tiling(context); + return tiling.DoOpTiling(&sasInfo); +} +// --------------------------Tiling函数及TilingPrepare函数注册-------- +IMPL_OP_OPTILING(XllmKernelSparseAttnSharedkv) + .Tiling(TilingSparseAttnSharedkv) + .TilingParse(TilingPrepareForSparseAttnSharedkv); +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_host/sparse_attn_sharedkv_tiling.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_host/sparse_attn_sharedkv_tiling.h new file mode 100644 index 0000000000..6f80e1e283 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_host/sparse_attn_sharedkv_tiling.h @@ -0,0 +1,590 @@ +/** + * 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_attn_sharedkv_tiling.h + * \brief + */ +#ifndef SPARSE_ATTN_SHAREDKV_TILING_H +#define SPARSE_ATTN_SHAREDKV_TILING_H + +#include +#include +#include + +#include "err/ops_err.h" +#include "log/error_code.h" +#include "log/log.h" +#include "platform/platform_info.h" +#include "register/op_def_registry.h" +#include "register/tilingdata_base.h" +#include "tiling/tiling_api.h" + +namespace optiling { +// ------------------公共定义-------------------------- +struct SASTilingRequiredParaInfo { + const gert::CompileTimeTensorDesc* desc; + const gert::StorageShape* shape; +}; + +struct SASTilingOptionalParaInfo { + const gert::CompileTimeTensorDesc* desc; + const gert::Tensor* tensor; +}; + +enum class SASLayout : uint32_t { BSND = 0, TND = 1, PA_ND = 2 }; + +enum class SASAxis : 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 SASTemplateMode : uint32_t { + SWA_TEMPLATE_MODE = 0, + CFA_TEMPLATE_MODE = 1, + SCFA_TEMPLATE_MODE = 2 +}; + +enum class KvStorageMode : uint32_t { + BATCH_CONTINUOUS = 0, + TENSOR_LIST = 1, + PAGE_ATTENTION = 2 +}; + +// ------------------算子原型索引常量定义---------------- +// Inputs Index +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_KV_INDEX = 8; +constexpr uint32_t CU_SEQLENS_CMP_KV_INDEX = 9; +constexpr uint32_t SEQUSED_Q_INDEX = 10; +constexpr uint32_t SEQUSED_KV_INDEX = 11; +constexpr uint32_t SINKS_INDEX = 12; +constexpr uint32_t METADATA_INDEX = 13; +// Outputs Index +constexpr uint32_t ATTN_OUT_INDEX = 0; + +// 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_KV_STRIDE_INDEX = 4; +constexpr uint32_t ATTR_CMP_KV_STRIDE_INDEX = 5; +constexpr uint32_t ATTR_ORI_WIN_LEFT_INDEX = 6; +constexpr uint32_t ATTR_ORI_WIN_RIGHT_INDEX = 7; +constexpr uint32_t ATTR_LAYOUT_Q_INDEX = 8; +constexpr uint32_t ATTR_LAYOUT_KV_INDEX = 9; +constexpr uint32_t ATTR_RETURN_SOFTMAX_LSE = 10; + +// Dim Index +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; + +// 常量 +constexpr uint32_t MAX_BLOCK_SIZE = 1024; +constexpr uint32_t COPYND2NZ_SRC_STRIDE_LIMITATION = 65535; +constexpr uint32_t NUM_BYTES_FLOAT = 4; +constexpr uint32_t NUM_BYTES_FLOAT16 = 2; +constexpr uint32_t NUM_BYTES_BF16 = 2; +constexpr uint32_t BYTE_BLOCK = 32; + +// 入参限制常量 +constexpr uint32_t HEAD_DIM_LIMIT = 128; +constexpr uint32_t SPARSE_LIMIT = 2048; +constexpr uint32_t SPARSE_MODE_LOWER = 3; +constexpr uint32_t METADATA_LIMIT = 1024; +constexpr uint32_t DIM_LIMIT = 512; +constexpr uint32_t TOPK_LIMIT = 1024; +constexpr uint32_t BLOCK_SIZE_LIMIT = 1024; + +// -----------算子TilingData定义--------------- +BEGIN_TILING_DATA_DEF(SparseAttnSharedkvSwaParams) +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, oriKvStride) +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, usedCoreNum); + +TILING_DATA_FIELD_DEF(uint32_t, mmResUbSize); +TILING_DATA_FIELD_DEF(uint32_t, bmm2ResUbSize); + +TILING_DATA_FIELD_DEF(uint32_t, mBaseSize) +TILING_DATA_FIELD_DEF(uint32_t, s2BaseSize) +TILING_DATA_FIELD_DEF(bool, returnSoftmaxLse) +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(SparseAttnSharedkvSwaParamsOp, + SparseAttnSharedkvSwaParams) + +BEGIN_TILING_DATA_DEF(SparseAttnSharedkvCmpParams) + +TILING_DATA_FIELD_DEF(uint32_t, cmpMaxBlockNumPerBatch) +TILING_DATA_FIELD_DEF(uint32_t, sparseBlockCount) +TILING_DATA_FIELD_DEF(int64_t, cmpRatio) +TILING_DATA_FIELD_DEF(uint64_t, cmpMaskMode) +TILING_DATA_FIELD_DEF(int64_t, cmpKvStride) +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(SparseAttnSharedkvCmpParamsOp, + SparseAttnSharedkvCmpParams) + +BEGIN_TILING_DATA_DEF(SparseAttnSharedkvTilingData) +TILING_DATA_FIELD_DEF_STRUCT(SparseAttnSharedkvSwaParams, baseParams); +TILING_DATA_FIELD_DEF_STRUCT(SparseAttnSharedkvCmpParams, cmpParams); +END_TILING_DATA_DEF + +REGISTER_TILING_DATA_CLASS(XllmKernelSparseAttnSharedkv, + SparseAttnSharedkvTilingData) + +struct SASParaInfo { + SASTilingRequiredParaInfo q = {nullptr, nullptr}; + SASTilingOptionalParaInfo oriKv = {nullptr, nullptr}; + SASTilingOptionalParaInfo cmpKv = {nullptr, nullptr}; + SASTilingOptionalParaInfo oriSparseIndices = {nullptr, nullptr}; + SASTilingOptionalParaInfo cmpSparseIndices = {nullptr, nullptr}; + SASTilingOptionalParaInfo oriBlockTable = {nullptr, nullptr}; + SASTilingOptionalParaInfo cmpBlockTable = {nullptr, nullptr}; + SASTilingOptionalParaInfo cuSeqLensQ = {nullptr, nullptr}; + SASTilingOptionalParaInfo seqUsedQ = {nullptr, nullptr}; + SASTilingOptionalParaInfo cuSeqLensKv = {nullptr, nullptr}; + SASTilingOptionalParaInfo cuSeqLensCmpKv = {nullptr, nullptr}; + SASTilingOptionalParaInfo sequsedKv = {nullptr, nullptr}; + SASTilingOptionalParaInfo sinks = {nullptr, nullptr}; + SASTilingOptionalParaInfo metadata = {nullptr, nullptr}; + SASTilingRequiredParaInfo attnOut = {nullptr, nullptr}; + + const float* softmaxScale = nullptr; + const uint32_t* cmpRatio = nullptr; + const uint32_t* oriMaskMode = nullptr; + const uint32_t* cmpMaskMode = nullptr; + const uint32_t* oriKvStride = nullptr; + const uint32_t* cmpKvStride = nullptr; + const uint32_t* oriWinLeft = nullptr; + const uint32_t* oriWinRight = nullptr; + const char* layoutQ = nullptr; + const char* layoutKv = nullptr; + const bool* returnSoftmaxLse = nullptr; +}; + +static std::string SASDataTypeToSerialString(ge::DataType type); +std::string SASLayoutToSerialString(SASLayout layout); + +// -----------算子Tiling入参信息类--------------- +class SASTilingInfo { + public: + const char* opName = nullptr; + fe::PlatFormInfos* platformInfo = nullptr; + SASParaInfo opParamInfo; + + // Base Param + platform_ascendc::SocVersion socVersion = + platform_ascendc::SocVersion::ASCEND910B; + uint32_t bSize = 0; + uint32_t n1Size = 0; + uint32_t n2Size = 0; + uint32_t s1Size = 0; + int64_t s2Size = 0; + 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 maxActualseq = 0; + bool actualSeqLenFlag = false; + bool isSameSeqAllKVTensor = true; + bool isSameActualseq = true; + uint32_t actualLenDimsKV = 0; + + float softmaxScale = 0; + int64_t cmpRatio = 1; + uint64_t oriMaskMode = 0; + uint64_t cmpMaskMode = 0; + uint64_t oriKvStride = 0; + uint64_t cmpKvStride = 0; + int64_t oriWinLeft = 0; + int64_t oriWinRight = 0; + int64_t sparseBlockSize = 0; + int64_t sparseBlockCount = 0; + // Mask + int32_t sparseMode = 0; + // Others Flag + uint32_t sparseCount = 0; + + bool returnSoftmaxLse = false; + // PageAttention + uint32_t blockTypeSize = 0; + uint32_t oriMaxBlockNumPerBatch = 0; + int32_t blockSize = 0; + int32_t oriBlockSize = 0; + int32_t cmpBlockSize = 0; + uint32_t cmpMaxBlockNumPerBatch = 0; + uint32_t totalBlockNum = 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 + SASLayout qLayout = SASLayout::TND; + SASLayout cmpSparseIndicesLayout = SASLayout::TND; + SASLayout oriSparseIndicesLayout = SASLayout::TND; + SASLayout kvLayout = SASLayout::PA_ND; + SASLayout outLayout = SASLayout::BSND; + + // template mode + SASTemplateMode perfMode = SASTemplateMode::SWA_TEMPLATE_MODE; +}; + +// -----------算子Tiling入参信息解析及Check类--------------- +class SASTilingCheck { + public: + explicit SASTilingCheck(const SASTilingInfo& sasInfo) : sasInfo_(sasInfo) {}; + ~SASTilingCheck() = 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 SASLayout& 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 SASLayout& actualLayout, + const std::string& name) const; + ge::graphStatus CheckDimNumInLayoutSupport(const SASLayout& 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 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 CheckSingleParaOriKvStride() const; + ge::graphStatus CheckSingleParaCmpKvStride() const; + 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(); + void SetSASShapeCompare(); + 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; + ge::graphStatus CheckBlockTable() const; + + gert::Shape queryShapeCmp_{}; + gert::Shape oriKvShapeCmp_{}; + gert::Shape cmpKvShapeCmp_{}; + gert::Shape oriKvSparseIndicesCmp_{}; + gert::Shape cmpKvSparseIndicesCmp_{}; + gert::Shape attenOutShapeCmp_{}; + + private: + const char* opName_; + fe::PlatFormInfos* platformInfo_; + SASParaInfo opParamInfo_; + const SASTilingInfo& sasInfo_; + + 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 qHeadDim_ = 0; + uint32_t oriKvHeadDim_ = 0; + uint32_t cmpKvHeadDim_ = 0; + + uint32_t qTSize_ = 0; // 仅TND时生效 + uint32_t kvTSize_ = 0; // 仅TND时生效 + int64_t cmpRatio_ = 1; + KvStorageMode kvStorageMode_ = KvStorageMode::BATCH_CONTINUOUS; + uint32_t sparseBlockCount_ = 0; + int64_t oriWinLeft_ = 0; + int64_t oriWinRight_ = 0; + SASLayout qLayout_ = SASLayout::TND; + SASLayout cmpSparseIndicesLayout_ = SASLayout::TND; + SASLayout oriSparseIndicesLayout_ = SASLayout::TND; + SASLayout outLayout_ = SASLayout::TND; + SASLayout kvLayout_ = SASLayout::PA_ND; + + uint32_t oriMaxBlockNumPerBatch_ = 0; + uint32_t cmpMaxBlockNumPerBatch_ = 0; + int64_t blockSize_ = 0; + int32_t oriBlockSize_ = 0; + int32_t cmpBlockSize_ = 0; + + uint32_t aicNum_ = 0; + uint32_t aivNum_ = 0; + platform_ascendc::SocVersion socVersion_ = + platform_ascendc::SocVersion::ASCEND910B; + uint64_t l2CacheSize_ = 0; + + bool isSameSeqAllKVTensor_ = true; + bool isSameActualseq_ = true; + uint32_t maxActualseq_ = 0; + + 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 SASInfoParser { + public: + explicit SASInfoParser(gert::TilingContext* context) : context_(context) {} + ~SASInfoParser() = default; + + ge::graphStatus CheckRequiredInOutExistence() const; + ge::graphStatus CheckRequiredAttrExistence() const; + ge::graphStatus CheckRequiredParaExistence() const; + ge::graphStatus CheckUnrequiredParaExistence() const; + + ge::graphStatus GetActualSeqLenSize(uint32_t& size, + const gert::Tensor* tensor, + SASLayout& layout, + const std::string& name) const; + ge::graphStatus GetActualSeqLenQSize(uint32_t& size); + ge::graphStatus GetOpName(); + ge::graphStatus GetNpuInfo(); + void GetOptionalInputParaInfo(); + void GetInputParaInfo(); + void GetOutputParaInfo(); + ge::graphStatus GetAttrParaInfo(); + ge::graphStatus GetKvCache(); + ge::graphStatus GetOpParaInfo(); + + ge::graphStatus GetInOutDataType(); + ge::graphStatus GetQueryAndOutLayout(); + ge::graphStatus GetKvLayout(); + ge::graphStatus GetSASTemplateMode(SASTilingInfo& sasInfo); + void SetSASShape(); + ge::graphStatus GetN1Size(); + ge::graphStatus GetN2Size(); + ge::graphStatus GetGSize(); + ge::graphStatus GetBatchSize(); + ge::graphStatus GetQTSize(); + ge::graphStatus GetKVTSize(); + ge::graphStatus GetS1Size(); + ge::graphStatus GetS2SizeForPageAttention(); + ge::graphStatus GetS2SizeForTND(); + ge::graphStatus GetS2Size(); + ge::graphStatus GetMaxBlockNumPerBatch(); + ge::graphStatus GetBlockSize(); + ge::graphStatus GetQHeadDim(); + ge::graphStatus GetValueHeadDim(); + ge::graphStatus GetSparseBlockCount(); + ge::graphStatus GetActualseqInfo(); + ge::graphStatus GetSinks(); + void GenerateInfo(SASTilingInfo& sasInfo); + ge::graphStatus Parse(SASTilingInfo& sasInfo); + + public: + gert::TilingContext* context_ = nullptr; + const char* opName_; + fe::PlatFormInfos* platformInfo_; + SASParaInfo opParamInfo_; + + bool HasAxis(const SASAxis& axis, + const SASLayout& layout, + const gert::Shape& shape) const; + size_t GetAxisIdx(const SASAxis& axis, const SASLayout& layout) const; + uint32_t GetAxisNum(const gert::Shape& shape, + const SASAxis& axis, + const SASLayout& layout) const; + static constexpr int64_t invalidDimValue_ = + std::numeric_limits::min(); + + // 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; + uint32_t qTSize_ = 0; + uint32_t orikvTSize_ = 0; + uint32_t cmpkvTSize_ = 0; + uint32_t qHeadDim_ = 0; + uint32_t oriKvHeadDim_ = 0; + uint32_t cmpKvHeadDim_ = 0; + int64_t sparseBlockSize_ = 0; + int64_t sparseBlockCount_ = 0; + int64_t oriWinLeft_ = 0; + int64_t oriWinRight_ = 0; + uint32_t maxActualseq_ = 0; + bool isSameSeqAllKVTensor_ = true; + uint32_t actualLenDimsKV_ = 0; + uint32_t actualLenDimsQ_ = 0; + + uint32_t aicNum_ = 0; + uint32_t aivNum_ = 0; + // Layout + SASLayout qLayout_ = SASLayout::TND; + SASLayout cmpSparseIndicesLayout_ = SASLayout::TND; + SASLayout oriSparseIndicesLayout_ = SASLayout::TND; + SASLayout outLayout_ = SASLayout::BSND; + SASLayout kvLayout_ = SASLayout::PA_ND; + // PageAttention + uint32_t oriMaxBlockNumPerBatch_ = 0; + uint32_t cmpMaxBlockNumPerBatch_ = 0; + int32_t oriBlockSize_ = 0; + int32_t cmpBlockSize_ = 0; + + // template mode + SASTemplateMode perfMode_ = SASTemplateMode::SWA_TEMPLATE_MODE; + + platform_ascendc::SocVersion socVersion_ = + platform_ascendc::SocVersion::ASCEND910B; + 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 SparseAttnSharedkvTiling { + public: + explicit SparseAttnSharedkvTiling(gert::TilingContext* context) + : context_(context) {}; + ge::graphStatus DoOpTiling(SASTilingInfo* tilingInfo); + + private: + void SplitBalanced(SASTilingInfo* tilingInfo); + void CalcUbBmm(SASTilingInfo* tilingInfo); + gert::TilingContext* context_ = nullptr; + SASTemplateMode perfMode_ = SASTemplateMode::SWA_TEMPLATE_MODE; + SparseAttnSharedkvTilingData tilingData_; + uint32_t blockDim_{0}; + uint64_t workspaceSize_{0}; + uint64_t tilingKey_{0}; + + SASTilingInfo* sasInfo_ = 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 \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_scfa_block_cube.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_scfa_block_cube.h new file mode 100644 index 0000000000..3d920aadd4 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_scfa_block_cube.h @@ -0,0 +1,1000 @@ +/** + * 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_attn_sharedkv_scfa_block_cube.h + * \brief use 7 buffer for matmul l1, better pipeline + */ +#ifndef SPARSE_ATTN_SHAREDKV_SCFA_BLOCK_CUBE_H +#define SPARSE_ATTN_SHAREDKV_SCFA_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_attn_sharedkv/op_kernel/sparse_attn_sharedkv_common.h" + +namespace SASKernel { +template +class SASCubeBlock { + public: + // 中间计算数据类型为float, 高精度模式 + using T = float; + using Q_T = typename SAST::queryType; + using KV_T = typename SAST::kvType; + using OUT_T = typename SAST::outputType; + using MM_OUT_T = T; + + __aicore__ inline SASCubeBlock(){}; + __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 = SAST::pageAttention; + static constexpr int TEMPLATE_MODE = SAST::templateMode; + static constexpr bool FLASH_DECODE = SAST::flashDecode; + static constexpr SAS_LAYOUT LAYOUT_T = SAST::layout; + static constexpr SAS_LAYOUT KV_LAYOUT_T = SAST::kvLayout; + + 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 SASCubeBlock::InitParams( + const ConstInfo& constInfo) { + this->constInfo = constInfo; +} + +template +__aicore__ inline void SASCubeBlock::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 SASCubeBlock::InitMm2GlobalTensor( + GlobalTensor vec1ResGm, + GlobalTensor mm2ResGm, + GlobalTensor attentionOutGm) { + // mm2 + this->vec1ResGm = vec1ResGm; + this->mm2ResGm = mm2ResGm; + this->attentionOutGm = attentionOutGm; +} + +template +__aicore__ inline void SASCubeBlock::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 SASCubeBlock::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 SASCubeBlock::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 SASCubeBlock::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 SASCubeBlock::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 SASCubeBlock::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 SASCubeBlock::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 SASCubeBlock::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 SASCubeBlock::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 SASCubeBlock::ComputeMm1( + const RunInfo& info, + const MSplitInfo mSplitInfo) { + uint32_t mSize = mSplitInfo.nBufferDealM; + uint32_t mL1Size = M_SPLIT_SIZE; + uint32_t mL1SizeAlign = SASAlign(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 = SASAlign(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 = SASAlign(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.isOri) { + if constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + 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.oriKvStride; + 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 == SAS_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; + uint32_t batchStride = constInfo.kvSeqSize * seqStride; + + 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 == SAS_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 % 4 * 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 % 4 * 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 = SASAlign(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 = SASAlign(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 SASCubeBlock::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 = SASAlign(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 = SASAlign(nL1Size, 16U); + } + // k l1写成一个循环, 和mm1保持一致 + kL1Size = 256; + kL1SizeAlign = SASAlign(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 = SASAlign(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 = SASAlign(kL0Size, 16U); + } + + uint32_t curSeqIdx = + info.s2BatchOffset + (kL1 - kOffset) * 128 + k1 * 256; + if (info.isOri) { + if constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + 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.oriKvStride; + 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 == SAS_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; + uint32_t batchStride = constInfo.kvSeqSize * seqStride; + + 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 == SAS_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 % 4 * 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 = SASAlign(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 = SASAlign(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; // Select FMATRIX_LEFT. + 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 SASKernel +#endif // SPARSE_ATTN_SHAREDKV_SCFA_BLOCK_CUBE_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_scfa_block_vector.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_scfa_block_vector.h new file mode 100644 index 0000000000..406f4554b6 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_scfa_block_vector.h @@ -0,0 +1,1441 @@ +/** + * 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_attn_sharedkv_scfa_block_vector.h + * \brief + */ +#ifndef SPARSE_ATTN_SHAREDKV_SCFA_BLOCK_VECTOR_H +#define SPARSE_ATTN_SHAREDKV_SCFA_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_attn_sharedkv/op_kernel/sparse_attn_sharedkv_common.h" + +namespace SASKernel { +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +template +class SASVectorBlock { + public: + // 中间计算数据类型为float,高精度模式 + using T = float; + using KV_T = typename SAST::kvType; + using OUT_T = typename SAST::outputType; + using UPDATE_T = T; + using SINKS_T = T; + using MM1_OUT_T = float; + using MM2_OUT_T = float; + + __aicore__ inline SASVectorBlock(){}; + __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 SparseAttnSharedkvTilingData* __restrict tilingData); + __aicore__ inline void InitVec0GlobalTensor( + const GlobalTensor& kvValidSizeGm, + 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 = SAST::pageAttention; + static constexpr int TEMPLATE_MODE = SAST::templateMode; + static constexpr bool FLASH_DECODE = SAST::flashDecode; + static constexpr SAS_LAYOUT LAYOUT_T = SAST::layout; + static constexpr SAS_LAYOUT KV_LAYOUT_T = SAST::kvLayout; + + static constexpr uint64_t MERGE_CACHE_GM_BUF_NUM = 4; + 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); // 32768/4=8096 + static constexpr uint32_t BLOCK_ELEMENT_NUM = + BYTE_BLOCK / sizeof(T); // 32/4=8 + static constexpr uint32_t MAX_N1_SIZE = 128U; + static constexpr T SOFTMAX_MIN_NUM = -2e38; + static constexpr SINKS_T R0 = 1.0f; + + const SparseAttnSharedkvTilingData* __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 kvValidSizeGm_; + 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 SASVectorBlock::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 SASVectorBlock::InitParams( + const struct ConstInfo& constInfo, + const SparseAttnSharedkvTilingData* __restrict tilingData) { + this->constInfo = constInfo; + this->tilingData = tilingData; +} + +template +__aicore__ inline void SASVectorBlock::InitVec0GlobalTensor( + const GlobalTensor& kvValidSizeGm, + const GlobalTensor& kvMergeGm, + const GlobalTensor& oriKvGm, + const GlobalTensor& cmpKvGm, + const GlobalTensor& oriBlockTableGm, + const GlobalTensor& cmpBlockTableGm) { + this->kvValidSizeGm_ = kvValidSizeGm; + this->kvMergeGm_ = kvMergeGm; + this->oriKvGm_ = oriKvGm; + this->cmpKvGm_ = cmpKvGm; + this->oriBlockTableGm_ = oriBlockTableGm; + this->cmpBlockTableGm_ = cmpBlockTableGm; +} + +template +__aicore__ inline void SASVectorBlock::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 SASVectorBlock::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 SASVectorBlock::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 SASVectorBlock::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 SASVectorBlock::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; // 每次处理 8 datablocks + 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 SASVectorBlock::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 SASVectorBlock::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 SASVectorBlock::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 SASVectorBlock::ProcessLse( + const RunInfo& info, + const MSplitInfo& mSplitInfo) { + if (mSplitInfo.vecDealM == 0) { + return; + } + uint64_t lseOffset = 0; + if (constInfo.outputLayout == SAS_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 == SAS_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 SASVectorBlock::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 = SASAlign(dealRowCount, FP32_BLOCK_ELEMENT_NUM); + DataCopy(softmaxSumUb[softmaxOutOffset], inSumTensor, dealRowCountAlign); + PipeBarrier(); + DataCopy(softmaxMaxUb[softmaxOutOffset], inMaxTensor, dealRowCountAlign); + } +} + +template +__aicore__ inline void SASVectorBlock::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 SASVectorBlock::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; + + SliceAndContactSinksValue( + (mSplitInfo.nBufferStartM + mSplitInfo.vecStartM) % constInfo.qHeadNum, + 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 SASVectorBlock::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 SASVectorBlock::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 == SAS_LAYOUT::PA_ND) { + int64_t blkTableIdx = realS2Idx / constInfo.paCmpBlockSize; + int64_t blkTableOffset = realS2Idx % constInfo.paCmpBlockSize; + realKeyGmOffset = + cmpBlockTableGm_.GetValue( + runInfo.bIdx * constInfo.cmpMaxBlockNumPerBatch + blkTableIdx) * + static_cast(constInfo.cmpKvStride) + + blkTableOffset * static_cast(constInfo.kvHeadNum) * + static_cast(constInfo.headDim); + + } else if constexpr (KV_LAYOUT_T == SAS_LAYOUT::BSND) { + realKeyGmOffset = runInfo.bIdx * constInfo.kvSeqSize / constInfo.cmpRatio * + constInfo.kvHeadNum + + realS2Idx * constInfo.kvHeadNum; + } else if constexpr (KV_LAYOUT_T == SAS_LAYOUT::TND) { + realKeyGmOffset = (runInfo.tensorCmpBOffset + + realS2Idx * constInfo.kvHeadNum * constInfo.headDim) / + constInfo.headDim; + } + return realKeyGmOffset; +} + +template +__aicore__ inline void SASVectorBlock::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; + if constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + DataCopyPad( + kvMergUb_[mergeMte3Idx % 2 * INPUT2_BUFFER_OFFSET / sizeof(KV_T) + + (mte2Size - mte3Size) * constInfo.headDim], + cmpKvGm_[keyBNBOffset], + intriParams, + padParams); + } else { + DataCopyPad( + kvMergUb_[mergeMte3Idx % 2 * INPUT2_BUFFER_OFFSET / sizeof(KV_T) + + (mte2Size - mte3Size) * constInfo.headDim], + cmpKvGm_[keyBNBOffset * constInfo.headDim], + intriParams, + padParams); + } + mte2Size += validS2Count; +} + +template +__aicore__ inline void SASVectorBlock::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; + if constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + int64_t blkTableSrcStride = + ((keyOffset1 > keyOffset2 ? (keyOffset1 - keyOffset2) + : (keyOffset2 - keyOffset1)) - + constInfo.sparseBlockSize * constInfo.headDim); + keySrcStride = blkTableSrcStride * sizeof(KV_T); + } else if constexpr (KV_LAYOUT_T == SAS_LAYOUT::BSND) { + keySrcStride = ((keyOffset1 > keyOffset2 ? (keyOffset1 - keyOffset2) + : (keyOffset2 - keyOffset1)) - + constInfo.sparseBlockSize) * + constInfo.headDim * sizeof(KV_T); + } else if constexpr (KV_LAYOUT_T == SAS_LAYOUT::TND) { + 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; + + int64_t startGmOffset = keyOffset1 > -1 ? keyOffset1 : keyOffset2; + if (keyOffset2 > -1 && keyOffset2 < keyOffset1) { + startGmOffset = keyOffset2; + } + if constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + DataCopyPad( + kvMergUb_[mergeMte3Idx % 2 * INPUT2_BUFFER_OFFSET / sizeof(KV_T) + + (mte2Size - mte3Size) * constInfo.headDim], + cmpKvGm_[startGmOffset], + intriParams, + padParams); + } else { + DataCopyPad( + kvMergUb_[mergeMte3Idx % 2 * INPUT2_BUFFER_OFFSET / sizeof(KV_T) + + (mte2Size - mte3Size) * constInfo.headDim], + cmpKvGm_[startGmOffset * constInfo.headDim], + intriParams, + padParams); + } + mte2Size += + ((keyOffset1 > -1) + (keyOffset2 > -1)) * constInfo.sparseBlockSize; + } +} + +template +__aicore__ inline void SASVectorBlock::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 % 4 * 512 * 512 + + (s2GmStartOffset + mte3Size) * constInfo.headDim], + kvMergUb_[mergeMte3Idx % 2 * INPUT2_BUFFER_OFFSET / sizeof(KV_T)], + dataCopyParams); +} + +// b s1 k +template +__aicore__ inline void SASVectorBlock::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 = SASAlign(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 SASVectorBlock::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); + } + } +} + +template +__aicore__ inline uint64_t SASVectorBlock::CalcAccumOffset( + uint32_t bN2Idx, + uint32_t gS1Idx) { + return 0; +} + +template +__aicore__ inline void SASVectorBlock::ProcessVec2SingleBuf( + const RunInfo& info, + const MSplitInfo& mSplitInfo) { + if (mSplitInfo.vecDealM == 0) { + return; + } + + ProcessVec2Inner(info, mSplitInfo, 0, mSplitInfo.vecDealM); +} + +template +__aicore__ inline void SASVectorBlock::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 SASVectorBlock::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 SASVectorBlock::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 SASVectorBlock::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 SASVectorBlock::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 SASVectorBlock::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 SASVectorBlock::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 (!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]; // 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 { + 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); + } +} + +template +__aicore__ inline void SASVectorBlock::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 SASVectorBlock::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 SASKernel +#endif // SPARSE_ATTN_SHAREDKV_SCFA_BLOCK_VECTOR_H diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_scfa_kernel.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_scfa_kernel.h new file mode 100644 index 0000000000..d3dd12d7d3 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_scfa_kernel.h @@ -0,0 +1,990 @@ +/** + * 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_attn_sharedkv_scfa_kernel.h + * \brief + */ + +#ifndef SPARSE_ATTN_SHAREDKV_SCFA_KERNEL_H +#define SPARSE_ATTN_SHAREDKV_SCFA_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_attn_sharedkv/op_kernel/sparse_attn_sharedkv_common.h" +#include "sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_metadata.h" +#include "sparse_attn_sharedkv_scfa_block_cube.h" +#include "sparse_attn_sharedkv_scfa_block_vector.h" + +namespace SASKernel { +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 SparseAttnSharedkvScfa { + public: + // 中间计算数据类型为float,高精度模式 + using T = float; + using Q_T = typename SAST::queryType; + using KV_T = typename SAST::kvType; + using OUT_T = typename SAST::outputType; + using SINKS_T = float; + using UPDATE_T = T; + using MM1_OUT_T = T; + using MM2_OUT_T = T; + + __aicore__ inline SparseAttnSharedkvScfa(){}; + __aicore__ inline void Init( + __gm__ uint8_t* query, + __gm__ uint8_t* oriKV, + __gm__ uint8_t* cmpKV, + __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* sinks, + __gm__ uint8_t* metadata, + __gm__ uint8_t* attentionOut, + __gm__ uint8_t* softmaxLse, + __gm__ uint8_t* workspace, + const SparseAttnSharedkvTilingData* __restrict tiling, + __gm__ uint8_t* gmTiling, + TPipe* tPipe); + + __aicore__ inline void Process(); + + private: + static constexpr bool PAGE_ATTENTION = SAST::pageAttention; + static constexpr bool FLASH_DECODE = SAST::flashDecode; + static constexpr SAS_LAYOUT LAYOUT_T = SAST::layout; + static constexpr SAS_LAYOUT KV_LAYOUT_T = SAST::kvLayout; + + static constexpr uint32_t PRELOAD_NUM = 2; + static constexpr uint32_t N_BUFFER_M_BASIC_SIZE = 256; + static constexpr uint32_t SAS_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 uint64_t kvHeadNum = 1ULL; + static constexpr uint64_t headDim = 512ULL; + + static constexpr uint32_t dbWorkspaceRatio = PRELOAD_NUM; + + const SparseAttnSharedkvTilingData* __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{}; + + SASCubeBlock cubeBlock; + SASVectorBlock 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; + + // workspace + GlobalTensor mm1ResGm; + GlobalTensor vec1ResGm; + GlobalTensor mm2ResGm; + GlobalTensor kvMergeGm_; + GlobalTensor kvValidSizeGm_; + + 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[SAS_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 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 SparseAttnSharedkvScfa::InitTilingData() { + // singleCoreParams + // singleCoreTensorSize + constInfo.mmResUbSize = tilingData->baseParams.mmResUbSize; + constInfo.bmm2ResUbSize = tilingData->baseParams.bmm2ResUbSize; + + // baseParams + constInfo.batchSize = tilingData->baseParams.batchSize; + constInfo.qHeadNum = constInfo.gSize = + tilingData->baseParams.nNumOfQInOneGroup; + 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.kvHeadNum = kvHeadNum; + constInfo.headDim = headDim; + constInfo.oriMaskMode = tilingData->baseParams.oriMaskMode; + constInfo.oriKvStride = tilingData->baseParams.oriKvStride; + constInfo.oriWinLeft = tilingData->baseParams.oriWinLeft; + constInfo.oriWinRight = tilingData->baseParams.oriWinRight; + + constInfo.actualLenDimsQ = tilingData->baseParams.actualLenDimsQ; + constInfo.actualLenDimsKV = tilingData->baseParams.actualLenDimsKV; + 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.cmpKvStride = tilingData->cmpParams.cmpKvStride; +} + +template +__aicore__ inline void SparseAttnSharedkvScfa::InitBuffers() { + if ASCEND_IS_AIV { + vectorBlock.InitBuffers(pipe); + } else { + cubeBlock.InitBuffers(pipe); + } +} + +template +__aicore__ inline void SparseAttnSharedkvScfa::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 SparseAttnSharedkvScfa::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); + actualSeqLengthsCmpKVGm.SetGlobalBuffer( + (__gm__ int32_t*)actualSeqLengthsCmpKV, constInfo.actualLenDimsKV); + } + if (constInfo.actualLenDimsQ != 0) { + actualSeqLengthsQGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsQ, + constInfo.actualLenDimsQ); + } +} + +template +__aicore__ inline void SparseAttnSharedkvScfa::InitAllZeroOutput( + uint32_t bIdx, + uint32_t s1Idx, + uint32_t n2Idx) { + if (constInfo.outputLayout == SAS_LAYOUT::TND) { + if (tempLoopInfo.actS1Size == 0) { + return; + } + uint32_t tBase = actualSeqLengthsQGm.GetValue(bIdx); + uint32_t s1Count = tempLoopInfo.actS1Size; + + uint64_t attenOutOffset = (tBase + s1Idx) * kvHeadNum * constInfo.gSize * + headDim + // T轴、s1轴偏移 + n2Idx * constInfo.gSize * headDim; // N2轴偏移 + uint64_t lseOffset = + (tBase + s1Idx) * constInfo.gSize + // T轴、s1轴偏移 + n2Idx * constInfo.qSeqSize * constInfo.gSize; // N2轴偏移 + matmul::InitOutput( + attentionOutGm[attenOutOffset], constInfo.gSize * headDim, 0); + if (constInfo.returnSoftmaxLse) { + matmul::InitOutput(softmaxLseGm[lseOffset], constInfo.gSize, 0); + } + } else if (constInfo.outputLayout == SAS_LAYOUT::BSND) { + uint64_t attenOutOffset = + bIdx * constInfo.qSeqSize * kvHeadNum * constInfo.gSize * headDim + + s1Idx * kvHeadNum * constInfo.gSize * headDim + // B轴、S1轴偏移 + n2Idx * constInfo.gSize * headDim; // N2轴偏移 + 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 * headDim, 0); + if (constInfo.returnSoftmaxLse) { + matmul::InitOutput(softmaxLseGm[lseOffset], constInfo.gSize, 0); + } + } +} + +template +__aicore__ inline void SparseAttnSharedkvScfa::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 SparseAttnSharedkvScfa::GetActualSeqLenQ( + uint32_t bIdx) { + if constexpr (LAYOUT_T == SAS_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 SparseAttnSharedkvScfa::GetActualSeqLenKV( + uint32_t bIdx) { + if constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + 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 == SAS_LAYOUT::BSND) { + return static_cast(constInfo.kvSeqSize); + } else if constexpr (KV_LAYOUT_T == SAS_LAYOUT::TND) { + int32_t actualSeqKVPrefixSum = actualSeqLengthsKVGm.GetValue(bIdx); + int32_t actualSeqKVNextSum = actualSeqLengthsKVGm.GetValue(bIdx + 1); + tempLoopInfo.actualSeqCmpKVPrefixSum = + actualSeqLengthsCmpKVGm.GetValue(bIdx); + tempLoopInfo.actualSeqKVPrefixSum = actualSeqKVPrefixSum; + return actualSeqKVNextSum - actualSeqKVPrefixSum; + } +} + +template +__aicore__ inline void SparseAttnSharedkvScfa::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(constInfo.sparseBlockCount * constInfo.sparseBlockSize, thresHold); +} + +template +__aicore__ inline void SparseAttnSharedkvScfa::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 SparseAttnSharedkvScfa::Init( + __gm__ uint8_t* query, + __gm__ uint8_t* oriKV, + __gm__ uint8_t* cmpKV, + __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* sinks, + __gm__ uint8_t* metadata, + __gm__ uint8_t* attentionOut, + __gm__ uint8_t* softmaxLse, + __gm__ uint8_t* workspace, + const SparseAttnSharedkvTilingData* __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 == SAS_LAYOUT::TND && LAYOUT_T == SAS_LAYOUT::TND) { + InitActualSeqLen(cuSeqlensQ, cuSeqlensKV, cuSeqlensCmpKV); + } else if (KV_LAYOUT_T == SAS_LAYOUT::TND) { + InitActualSeqLen(seqUsedQ, cuSeqlensKV, cuSeqlensCmpKV); + } else if ((KV_LAYOUT_T == SAS_LAYOUT::PA_ND || + KV_LAYOUT_T == SAS_LAYOUT::BSND) && + LAYOUT_T == SAS_LAYOUT::TND) { + InitActualSeqLen(cuSeqlensQ, seqUsedKV); + } else if ((KV_LAYOUT_T == SAS_LAYOUT::PA_ND || + KV_LAYOUT_T == SAS_LAYOUT::BSND)) { + InitActualSeqLen(seqUsedQ, seqUsedKV); + } + + 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 (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 != SAS_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 * 4 * sizeof(KV_T))); + offset += GetBlockNum() * 512 * 512 * 4 * sizeof(KV_T); + + kvValidSizeGm_.SetGlobalBuffer( + (__gm__ int32_t*)(workspace + offset + + (aiCoreIdx * 2) * 128 * 4 * sizeof(int32_t))); + + if ASCEND_IS_AIV { + vectorBlock.InitParams(constInfo, tilingData); + vectorBlock.InitVec0GlobalTensor(kvValidSizeGm_, + 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 SparseAttnSharedkvScfa::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 SparseAttnSharedkvScfa::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) { + tensorACoreOffset = tndBIdxOffsetForQ + info.gS1Idx * constInfo.headDim; + tensorBCoreOffset = + tndBIdxOffsetForKV + + info.n2Idx * constInfo.headDim; // 当前为PA场景,该变量失效 + tensorCmpBCoreOffset = + tndBIdxOffsetForCmpKV + info.n2Idx * constInfo.headDim; + if constexpr (LAYOUT_T == SAS_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 == SAS_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.isOri = 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.isOri = 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; + } + + info.actualSingleProcessSInnerSizeAlign = SASAlign( + info.actualSingleProcessSInnerSize, SASVectorBlock::BYTE_BLOCK); + if (info.isOri) { + info.v0S2Start = 0; + info.v0S2DealSize = 0; + } else { + info.v0S2Start = 0; + if (s2LoopIdx + 1 == tempLoopInfo.s2LoopTimes && s2LoopIdx == 2) { // tail + info.v0S2Start = 512; + } + info.v0S2DealSize = 512; + } +} + +template +__aicore__ inline void SparseAttnSharedkvScfa::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 SparseAttnSharedkvScfa::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 SparseAttnSharedkvScfa::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 SparseAttnSharedkvScfa::GetBN2Idx( + uint32_t bN2Idx, + uint32_t& bIdx, + uint32_t& n2Idx) { + bIdx = bN2Idx / kvHeadNum; + n2Idx = bN2Idx % kvHeadNum; +} + +template +__aicore__ inline void SparseAttnSharedkvScfa::ProcessBalance() { + RunInfo extraInfo[SAS_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 == SAS_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.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); + tempLoopInfo.cmpMaskRight = + tempLoopInfo.actOriS2Size - 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 = SASAlign(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 SparseAttnSharedkvScfa::PreloadPipeline( + uint32_t loop, + uint32_t cmpLoop, + uint64_t s2Start, + uint64_t s2LoopIdx, + RunInfo extraInfo[SAS_PRELOAD_TASK_CACHE_SIZE]) { + RunInfo& extraInfo0 = + extraInfo[loop % SAS_PRELOAD_TASK_CACHE_SIZE]; // 本轮任务 + RunInfo& extraInfo2 = + extraInfo[(loop + 2) % SAS_PRELOAD_TASK_CACHE_SIZE]; // 上一轮任务 + RunInfo& extraInfo1 = + extraInfo[(loop + 1) % SAS_PRELOAD_TASK_CACHE_SIZE]; // 上两轮任务 + + CalcParams(loop, cmpLoop, s2Start, s2LoopIdx, extraInfo0); + if (extraInfo0.isValid) { + if ASCEND_IS_AIC { + if (!extraInfo0.isOri) { + CrossCoreWaitFlag(constInfo.syncV0C1); + } + ComputeMm1(extraInfo0); + } else { + if (extraInfo0.isFirstSInnerLoop) { + CrossCoreWaitFlag(3); + } + vectorBlock.ProcessVec0L(extraInfo0); + if (!extraInfo0.isOri) { + 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; + } +} + +} // namespace SASKernel +#endif // SPARSE_ATTN_SHAREDKV_SCFA_KERNEL_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_swa_block_cube.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_swa_block_cube.h new file mode 100644 index 0000000000..46243cf559 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_swa_block_cube.h @@ -0,0 +1,1125 @@ +/** + * 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_attn_sharedkv_swa_block_cube.h + * \brief use 7 buffer for matmul l1, better pipeline + */ +#ifndef SPARSE_ATTN_SHAREDKV_SWA_BLOCK_CUBE_H +#define SPARSE_ATTN_SHAREDKV_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_attn_sharedkv/op_kernel/sparse_attn_sharedkv_common.h" + +namespace SASKernel { +template +class SWACubeBlock { + public: + // 中间计算数据类型为float, 高精度模式 + using T = float; + using Q_T = typename SAST::queryType; + using KV_T = typename SAST::kvType; + using OUT_T = typename SAST::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, // 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 = SAST::pageAttention; + // static constexpr int TEMPLATE_MODE = SAST::templateMode; + static constexpr bool FLASH_DECODE = SAST::flashDecode; + static constexpr SAS_LAYOUT LAYOUT_T = SAST::layout; + static constexpr SAS_LAYOUT KV_LAYOUT_T = SAST::kvLayout; + + 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 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 (constInfo.templateMode == CFA_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, // const GlobalTensor& kvMergeGm, + GlobalTensor oriBlockTableGm, + GlobalTensor cmpBlockTableGm) { + this->oriKvGm = oriKvGm; + this->oriBlockTableGm = oriBlockTableGm; + if (constInfo.templateMode == CFA_TEMPLATE) { + this->cmpBlockTableGm = cmpBlockTableGm; + } +} + +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 = SASAlign(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 = SASAlign(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 = SASAlign(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; + uint32_t copyFinishRowCnt = 0; + + if (info.isOri) { + if constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + uint32_t curS2Offset = info.s2Idx * constInfo.s2BaseSize + + info.s2StartPoint + nL1 * N_SPLIT_SIZE; + 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; + } + 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.oriKvStride; + 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 == SAS_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; + uint32_t batchStride = constInfo.kvSeqSize * seqStride; + + 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 == SAS_LAYOUT::TND) { + uint32_t curS2Offset = info.s2Idx * constInfo.s2BaseSize + + info.s2StartPoint + nL1 * N_SPLIT_SIZE; + 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 constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + uint32_t curS2Offset = + info.relativeS2Idx * constInfo.s2BaseSize + 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.cmpKvStride; + 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 == SAS_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; + uint32_t batchStride = + constInfo.kvSeqSize / constInfo.cmpRatio * seqStride; + + uint32_t curS2 = + info.relativeS2Idx * constInfo.s2BaseSize + 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 == SAS_LAYOUT::TND) { + uint32_t curS2Offset = + info.relativeS2Idx * constInfo.s2BaseSize + nL1 * N_SPLIT_SIZE; + 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, + cmpKvGm[info.tensorCmpBOffset + + curS2Offset * 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, + cmpKvGm[info.tensorCmpBOffset + + curS2Offset * constInfo.headDim + + (constInfo.headDim >> 1)], + nd2nzPara); + } + } + } + + SetFlag(mte21KVIds[kb]); + WaitFlag(mte21KVIds[kb]); + mL1Size = M_SPLIT_SIZE; + mL1SizeAlign = SASAlign(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 = SASAlign(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 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 = 256; + uint32_t kL1SizeAlign = SASAlign(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 + if (nL1 == (nL1Loops - 1)) { + // 尾块 + nL1Size = nSize - (nL1Loops - 1) * N_SPLIT_SIZE; + nL1SizeAlign = SASAlign(nL1Size, 16U); + } + // k l1写成一个循环, 和mm1保持一致 + kL1Size = 256; + kL1SizeAlign = SASAlign(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 = SASAlign(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 + if (kL1 == kOffset + kL0Loops - 1) { + // 尾块 + kL0Size = kL1Size - (kL0Loops - 1) * kL0Size; + kL0SizeAlign = SASAlign(kL0Size, 16U); + } + + uint32_t copyFinishRowCnt = 0; + + if (info.isOri) { + if constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + uint32_t curS2Offset = info.s2Idx * constInfo.s2BaseSize + + info.s2StartPoint + kL1 * K_L0_SPLIT_SIZE; + 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.oriKvStride; + 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 == SAS_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; + uint32_t batchStride = constInfo.kvSeqSize * seqStride; + + uint32_t curS2 = info.s2Idx * constInfo.s2BaseSize + + 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 == SAS_LAYOUT::TND) { + uint32_t curS2Offset = 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 constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + uint32_t curS2Offset = info.relativeS2Idx * constInfo.s2BaseSize + + 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.cmpKvStride; + 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 == SAS_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; + uint32_t batchStride = + constInfo.kvSeqSize / constInfo.cmpRatio * seqStride; + + uint32_t curS2 = info.relativeS2Idx * constInfo.s2BaseSize + + 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 == SAS_LAYOUT::TND) { + uint32_t curS2Offset = info.relativeS2Idx * constInfo.s2BaseSize + + 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 = SASAlign(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 = SASAlign(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; // Select FMATRIX_LEFT. + 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 SASKernel +#endif \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_swa_block_vector.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_swa_block_vector.h new file mode 100644 index 0000000000..ae39e2bb65 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_swa_block_vector.h @@ -0,0 +1,1115 @@ +/** + * 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_attn_sharedkv_swa_block_vector.h + * \brief + */ +#ifndef SPARSE_ATTN_SHAREDKV_SWA_BLOCK_VECTOR_H +#define SPARSE_ATTN_SHAREDKV_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_attn_sharedkv/op_kernel/sparse_attn_sharedkv_common.h" + +namespace SASKernel { +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +template +class SWAVectorBlock { + public: + // 中间计算数据类型为float,高精度模式 + using T = float; + using KV_T = typename SAST::kvType; + using OUT_T = typename SAST::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 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 SparseAttnSharedkvTilingData* __restrict tilingData); + __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 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 = SAST::pageAttention; + static constexpr bool FLASH_DECODE = SAST::flashDecode; + static constexpr SAS_LAYOUT LAYOUT_T = SAST::layout; + static constexpr SAS_LAYOUT KV_LAYOUT_T = SAST::kvLayout; + + 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); // 32768/4=8096 + static constexpr uint32_t BLOCK_ELEMENT_NUM = + BYTE_BLOCK / sizeof(T); // 32/4=8 + static constexpr uint32_t MAX_N1_SIZE = 128U; + static constexpr T SOFTMAX_MIN_NUM = -2e38; + static constexpr SINKS_T R0 = 1.0f; + + const SparseAttnSharedkvTilingData* __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 blkTableGm_; + GlobalTensor keyGm_; + GlobalTensor kvValidSizeGm_; + GlobalTensor oriKvGm_; + GlobalTensor cmpKvGm_; + GlobalTensor oriBlockTableGm_; + GlobalTensor cmpBlockTableGm_; + GlobalTensor softmaxLseGm; + + // ================================Local + // Buffer区==================================== + TBuf<> inputBuff1; // 32K + TBuf<> inputBuff2; // 16K + 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; +}; + +// ============================== 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(); +} + +template +__aicore__ inline void SWAVectorBlock::InitParams( + const struct ConstInfo& constInfo, + const SparseAttnSharedkvTilingData* __restrict tilingData) { + this->constInfo = constInfo; + this->tilingData = tilingData; +} + +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); + 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); + 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; // 每次处理 8 datablocks + 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 LocalTensor& mmResUb, + uint32_t dealRowCount, + uint32_t columnCount) { + Muls(mmResUb, + mmResUb, + static_cast(tilingData->baseParams.softmaxScale), + dealRowCount * columnCount); +} + +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 = SASAlign(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 = 0; + if (constInfo.outputLayout == SAS_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 == SAS_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 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, 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); + + 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; + + SliceAndContactSinksValue( + (mSplitInfo.nBufferStartM + mSplitInfo.vecStartM) % constInfo.qHeadNum, + 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); + 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 SASKernel +#endif \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_swa_kernel.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_swa_kernel.h new file mode 100644 index 0000000000..8c49495338 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch32/sparse_attn_sharedkv_swa_kernel.h @@ -0,0 +1,918 @@ +/** + * 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_attn_sharedkv_swa_kernel.h + * \brief + */ + +#ifndef SPARSE_ATTN_SHAREDKV_SWA_KERNEL_H +#define SPARSE_ATTN_SHAREDKV_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_attn_sharedkv/op_kernel/sparse_attn_sharedkv_common.h" +#include "sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_metadata.h" +#include "sparse_attn_sharedkv_swa_block_cube.h" +#include "sparse_attn_sharedkv_swa_block_vector.h" + +namespace SASKernel { +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; + 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; + + 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 SparseAttnSharedkvSwa { + public: + // 中间计算数据类型为float,高精度模式 + using T = float; + using Q_T = typename SAST::queryType; + using KV_T = typename SAST::kvType; + using OUT_T = typename SAST::outputType; + using SINKS_T = float; + using UPDATE_T = T; + using MM1_OUT_T = T; + using MM2_OUT_T = T; + + __aicore__ inline SparseAttnSharedkvSwa(){}; + __aicore__ inline void Init( + __gm__ uint8_t* query, + __gm__ uint8_t* oriKV, + __gm__ uint8_t* cmpKV, + __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* sinks, + __gm__ uint8_t* metadata, + __gm__ uint8_t* attentionOut, + __gm__ uint8_t* softmaxLse, + __gm__ uint8_t* workspace, + const SparseAttnSharedkvTilingData* __restrict tiling, + __gm__ uint8_t* gmTiling, + TPipe* tPipe); + + __aicore__ inline void Process(); + + private: + static constexpr bool PAGE_ATTENTION = SAST::pageAttention; + static constexpr int TEMPLATE_MODE = SAST::templateMode; + static constexpr bool FLASH_DECODE = SAST::flashDecode; + static constexpr SAS_LAYOUT LAYOUT_T = SAST::layout; + static constexpr SAS_LAYOUT KV_LAYOUT_T = SAST::kvLayout; + + static constexpr uint32_t PRELOAD_NUM = 2; + static constexpr uint32_t N_BUFFER_M_BASIC_SIZE = 256; + static constexpr uint32_t SAS_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 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 kvHeadNum = 1ULL; + 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 SparseAttnSharedkvTilingData* __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 actualSeqLengthsQGm; + GlobalTensor actualSeqLengthsKVGm; + GlobalTensor actualSeqLengthsCmpKVGm; + + // workspace + GlobalTensor mm1ResGm; + GlobalTensor vec1ResGm; + GlobalTensor mm2ResGm; + + 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[SAS_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 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 SparseAttnSharedkvSwa::InitTilingData() { + // singleCoreParams + // singleCoreTensorSize + constInfo.mmResUbSize = tilingData->baseParams.mmResUbSize; + constInfo.bmm2ResUbSize = tilingData->baseParams.bmm2ResUbSize; + // baseParams + constInfo.batchSize = tilingData->baseParams.batchSize; + constInfo.qHeadNum = constInfo.gSize = + tilingData->baseParams.nNumOfQInOneGroup; + 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.kvHeadNum = kvHeadNum; + constInfo.headDim = headDim; + constInfo.oriMaskMode = tilingData->baseParams.oriMaskMode; + constInfo.oriKvStride = tilingData->baseParams.oriKvStride; + constInfo.oriWinLeft = tilingData->baseParams.oriWinLeft; + constInfo.oriWinRight = tilingData->baseParams.oriWinRight; + constInfo.returnSoftmaxLse = tilingData->baseParams.returnSoftmaxLse; + + constInfo.actualLenDimsQ = tilingData->baseParams.actualLenDimsQ; + constInfo.actualLenDimsKV = tilingData->baseParams.actualLenDimsKV; + + // innerSplitParams + constInfo.mBaseSize = constInfo.gSize; + ; + constInfo.s2BaseSize = tilingData->baseParams.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; + constInfo.templateMode = TEMPLATE_MODE; + + // cmp + if (constInfo.templateMode == CFA_TEMPLATE) { + constInfo.cmpRatio = tilingData->cmpParams.cmpRatio; + constInfo.cmpMaskMode = tilingData->cmpParams.cmpMaskMode; + constInfo.cmpKvStride = tilingData->cmpParams.cmpKvStride; + constInfo.cmpMaxBlockNumPerBatch = + tilingData->cmpParams.cmpMaxBlockNumPerBatch; + } +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::InitBuffers() { + if ASCEND_IS_AIV { + vectorBlock.InitBuffers(pipe); + } else { + cubeBlock.InitBuffers(pipe); + } +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::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 SparseAttnSharedkvSwa::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.templateMode == CFA_TEMPLATE) { + actualSeqLengthsCmpKVGm.SetGlobalBuffer( + (__gm__ int32_t*)actualSeqLengthsCmpKV, constInfo.actualLenDimsKV); + } + } + if (constInfo.actualLenDimsQ != 0) { + actualSeqLengthsQGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsQ, + constInfo.actualLenDimsQ); + } +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::InitAllZeroOutput( + uint32_t bIdx, + uint32_t s1Idx, + uint32_t n2Idx) { + if (constInfo.outputLayout == SAS_LAYOUT::TND) { + if (tempLoopInfo.actS1Size == 0) { + return; + } + uint32_t tBase = actualSeqLengthsQGm.GetValue(bIdx); + uint64_t attenOutOffset = (tBase + s1Idx) * kvHeadNum * constInfo.gSize * + headDim + // T轴、s1轴偏移 + n2Idx * constInfo.gSize * headDim; // N2轴偏移 + uint64_t lseOffset = + (tBase + s1Idx) * constInfo.gSize + // T轴、s1轴偏移 + n2Idx * constInfo.qSeqSize * constInfo.gSize; // N2轴偏移 + matmul::InitOutput( + attentionOutGm[attenOutOffset], constInfo.gSize * headDim, 0); + if (constInfo.returnSoftmaxLse) { + matmul::InitOutput(softmaxLseGm[lseOffset], constInfo.gSize, 0); + } + } else if (constInfo.outputLayout == SAS_LAYOUT::BSND) { + uint64_t attenOutOffset = + bIdx * constInfo.qSeqSize * kvHeadNum * constInfo.gSize * headDim + + s1Idx * kvHeadNum * constInfo.gSize * headDim + // B轴、S1轴偏移 + n2Idx * constInfo.gSize * headDim; // N2轴偏移 + 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 * headDim, 0); + if (constInfo.returnSoftmaxLse) { + matmul::InitOutput(softmaxLseGm[lseOffset], constInfo.gSize, 0); + } + } +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::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 SparseAttnSharedkvSwa::GetActualSeqLenQ( + uint32_t bIdx) { + if constexpr (LAYOUT_T == SAS_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 SparseAttnSharedkvSwa::GetActualSeqLenKV( + uint32_t bIdx) { + if constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + 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 == SAS_LAYOUT::BSND) { + return static_cast(constInfo.kvSeqSize); + } else if constexpr (KV_LAYOUT_T == SAS_LAYOUT::TND) { + int32_t actualSeqKVPrefixSum = actualSeqLengthsKVGm.GetValue(bIdx); + int32_t actualSeqKVNextSum = actualSeqLengthsKVGm.GetValue(bIdx + 1); + if (constInfo.templateMode == CFA_TEMPLATE) { + tempLoopInfo.actualSeqCmpKVPrefixSum = + actualSeqLengthsCmpKVGm.GetValue(bIdx); + } + tempLoopInfo.actualSeqKVPrefixSum = actualSeqKVPrefixSum; + return actualSeqKVNextSum - actualSeqKVPrefixSum; + } +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::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 (constInfo.templateMode == CFA_TEMPLATE) { + int32_t thresHold = + (tempLoopInfo.cmpMaskRight + tempLoopInfo.s1EndIdx + 1) / + constInfo.cmpRatio; + tempLoopInfo.actCmpS2Size = thresHold; + } +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::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 SparseAttnSharedkvSwa::Init( + __gm__ uint8_t* query, + __gm__ uint8_t* oriKV, + __gm__ uint8_t* cmpKV, + __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* sinks, + __gm__ uint8_t* metadata, + __gm__ uint8_t* attentionOut, + __gm__ uint8_t* softmaxLse, + __gm__ uint8_t* workspace, + const SparseAttnSharedkvTilingData* __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 == SAS_LAYOUT::TND && LAYOUT_T == SAS_LAYOUT::TND) { + InitActualSeqLen(cuSeqlensQ, cuSeqlensKV, cuSeqlensCmpKV); + } else if (KV_LAYOUT_T == SAS_LAYOUT::TND) { + InitActualSeqLen(seqUsedQ, cuSeqlensKV, cuSeqlensCmpKV); + } else if ((KV_LAYOUT_T == SAS_LAYOUT::PA_ND || + KV_LAYOUT_T == SAS_LAYOUT::BSND) && + LAYOUT_T == SAS_LAYOUT::TND) { + InitActualSeqLen(cuSeqlensQ, seqUsedKV); + } else if ((KV_LAYOUT_T == SAS_LAYOUT::PA_ND || + KV_LAYOUT_T == SAS_LAYOUT::BSND)) { + InitActualSeqLen(seqUsedQ, seqUsedKV); + } + 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 (constInfo.templateMode == CFA_TEMPLATE) { + cmpKvGm.SetGlobalBuffer((__gm__ KV_T*)cmpKV); + } + + 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 != SAS_LAYOUT::TND) { + if (constInfo.needInit) { + InitOutputSingleCore(); + } + } + } + + if constexpr (PAGE_ATTENTION) { + oriBlockTableGm.SetGlobalBuffer((__gm__ int32_t*)oriBlockTable); + if (constInfo.templateMode == CFA_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 ASCEND_IS_AIV { + vectorBlock.InitParams(constInfo, tilingData); + 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); + } + // 要在InitParams之后执行 + if (pipe != nullptr) { + InitBuffers(); + } +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::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 SparseAttnSharedkvSwa::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; + + // 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) { + tensorACoreOffset = tndBIdxOffsetForQ + info.gS1Idx * 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 (s2LoopIdx < tempLoopInfo.oriLoopTimes) { + // S2首次循环只能在ori_kv + info.isOri = 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 = 0; + } else { + if (constInfo.templateMode == CFA_TEMPLATE) { + info.isOri = 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; + } + } + + info.actualSingleProcessSInnerSizeAlign = SASAlign( + info.actualSingleProcessSInnerSize, SASVectorBlock::BYTE_BLOCK); +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::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 SparseAttnSharedkvSwa::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 SparseAttnSharedkvSwa::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 SparseAttnSharedkvSwa::GetBN2Idx(uint32_t bN2Idx, + uint32_t& bIdx, + uint32_t& n2Idx) { + bIdx = bN2Idx / kvHeadNum; + n2Idx = bN2Idx % kvHeadNum; +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::ProcessBalance() { + RunInfo extraInfo[SAS_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 + bool isS1ZeroAndLastBatch = (tempLoopInfo.actS1Size == 0) && + ((constInfo.outputLayout == SAS_LAYOUT::BSND) || + (bN2LoopIdx + 1 == constInfo.bN2End)); + uint32_t gS1SplitNum = + CeilDiv(tempLoopInfo.actS1Size * constInfo.gSize, constInfo.mBaseSize); + + // 当处于最后一个BN2时, 且gS1End为0时, 说明当前BN2里的所有数据都在当前核处理 + gS1LoopEnd = (bN2LoopIdx == constInfo.bN2End - 1 && 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); + // 对于各轴上的真实的idx, 采用左闭右闭的方案 + 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); + if (constInfo.templateMode == CFA_TEMPLATE) { + tempLoopInfo.cmpMaskRight = + tempLoopInfo.actOriS2Size - tempLoopInfo.actS1Size; + } + GetSparseActualSeqLen(); + UpdateInnerLoopCond(); + uint32_t oriSplitNum = 0; + uint32_t s2SplitNum = 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(tempLoopInfo.oriMaskRight - tempLoopInfo.oriMaskLeft + 1, + constInfo.s2BaseSize); + s2SplitNum = oriSplitNum; + if (constInfo.templateMode == CFA_TEMPLATE) { + uint32_t cmpSplitNum = + CeilDiv(tempLoopInfo.actCmpS2Size, constInfo.s2BaseSize); + s2SplitNum = oriSplitNum + cmpSplitNum; + tempLoopInfo.cmpLoopTimes = cmpSplitNum; + } + } + tempLoopInfo.s2LoopTimes = s2SplitNum; + tempLoopInfo.oriLoopTimes = oriSplitNum; + 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 ? PRELOAD_NUM : 0; + + for (uint32_t s2LoopIdx = constInfo.s2Start; + s2LoopIdx < (s2LoopEnd + extraLoop); + s2LoopIdx++) { + // PreloadPipeline loop初始值要求为 PRELOAD_NUM + PreloadPipeline( + gloop, cmpLoop, constInfo.s2Start, s2LoopIdx, extraInfo); + ++gloop; + } + globalLoopStart = false; + constInfo.s2Start = 0; + } + constInfo.gS1Start = 0; + } +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::PreloadPipeline( + uint32_t loop, + uint32_t cmpLoop, + uint64_t s2Start, + uint64_t s2LoopIdx, + RunInfo extraInfo[SAS_PRELOAD_TASK_CACHE_SIZE]) { + RunInfo& extraInfo0 = + extraInfo[loop % SAS_PRELOAD_TASK_CACHE_SIZE]; // 本轮任务 + RunInfo& extraInfo2 = + extraInfo[(loop + 2) % SAS_PRELOAD_TASK_CACHE_SIZE]; // 上一轮任务 + RunInfo& extraInfo1 = + extraInfo[(loop + 1) % SAS_PRELOAD_TASK_CACHE_SIZE]; // 上两轮任务 + + CalcParams(loop, cmpLoop, s2Start, s2LoopIdx, extraInfo0); + if (extraInfo0.isValid) { + 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; + } +} +} // namespace SASKernel +#endif // SPARSE_ATTN_SHAREDKV_SWA_KERNEL_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_scfa_block_cube.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_scfa_block_cube.h new file mode 100644 index 0000000000..783ce28d7b --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_scfa_block_cube.h @@ -0,0 +1,1047 @@ +/** + * 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_attn_sharedkv_scfa_block_cube.h + * \brief use 7 buffer for matmul l1, better pipeline + */ +#ifndef SPARSE_ATTN_SHAREDKV_SCFA_BLOCK_CUBE_H +#define SPARSE_ATTN_SHAREDKV_SCFA_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_attn_sharedkv/op_kernel/sparse_attn_sharedkv_common.h" + +namespace SASKernel { +template +class SASCubeBlock { + public: + // Intermediate computation data type is float, high-precision mode + using T = float; + using Q_T = typename SAST::queryType; + using KV_T = typename SAST::kvType; + using OUT_T = typename SAST::outputType; + using MM_OUT_T = T; + + __aicore__ inline SASCubeBlock(){}; + __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 = SAST::pageAttention; + static constexpr int TEMPLATE_MODE = SAST::templateMode; + static constexpr bool FLASH_DECODE = SAST::flashDecode; + static constexpr SAS_LAYOUT LAYOUT_T = SAST::layout; + static constexpr SAS_LAYOUT KV_LAYOUT_T = SAST::kvLayout; + + static constexpr uint32_t M_SPLIT_SIZE = 128; // m-direction split + static constexpr uint32_t N_SPLIT_SIZE = 128; // n-direction split + static constexpr uint32_t K_L0_SPLIT_SIZE = 128; // k-direction L0 split + static constexpr uint32_t K_L1_SPLIT_SIZE = 256; // k-direction L1 split + static constexpr uint32_t N_WORKSPACE_SIZE = 512; // n-direction split + static constexpr uint32_t D_SPLIT_SIZE = 256; // d-axis split + + 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, uses 3 eventIds + 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 reuse + static constexpr uint32_t mte21KVIds[3] = {L1_EVENT4, L1_EVENT5, L1_EVENT6}; + + ConstInfo constInfo{}; + + // L1 is divided into 3 buf blocks, used for recording + 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}; // Ensure block 0 and block 1 are adjacent, block 2 and block 3 are + // adjacent, to keep addresses of the same m block contiguous + 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 SASCubeBlock::InitParams( + const ConstInfo& constInfo) { + this->constInfo = constInfo; +} + +template +__aicore__ inline void SASCubeBlock::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 SASCubeBlock::InitMm2GlobalTensor( + GlobalTensor vec1ResGm, + GlobalTensor mm2ResGm, + GlobalTensor attentionOutGm) { + // mm2 + this->vec1ResGm = vec1ResGm; + this->mm2ResGm = mm2ResGm; + this->attentionOutGm = attentionOutGm; +} + +template +__aicore__ inline void SASCubeBlock::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 SASCubeBlock::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 SASCubeBlock::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 SASCubeBlock::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 SASCubeBlock::CopyGmToL1( + LocalTensor& l1Tensor, + GlobalTensor& gmSrcTensor, + uint32_t srcN, + uint32_t srcD, + uint32_t srcDstride) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = srcN; // number of rows + nd2nzPara.dValue = srcD; + nd2nzPara.srcDValue = srcDstride; + nd2nzPara.dstNzC0Stride = (srcN + 15) / 16 * 16; // align to 16-unit block + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(l1Tensor, gmSrcTensor, nd2nzPara); +} + +template +__aicore__ inline void SASCubeBlock::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 SASCubeBlock::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; // tail data does not affect the sliding-window result + + // 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 SASCubeBlock::LoadDataMm1B( + LocalTensor& l0Tensor, + LocalTensor& l1Tensor, + uint32_t idx, + uint32_t kSplitSize, + uint32_t kSize, + uint32_t nSize) { + // N direction fully loaded + 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 SASCubeBlock::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 SASCubeBlock::ComputeMm1( + const RunInfo& info, + const MSplitInfo mSplitInfo) { + uint32_t mSize = mSplitInfo.nBufferDealM; + uint32_t mL1Size = M_SPLIT_SIZE; + uint32_t mL1SizeAlign = SASAlign(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 = SASAlign(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 split n and k + for (uint32_t nL1 = 0; nL1 < nL1Loops; nL1++) { + if (nL1 == (nL1Loops - 1)) { + // recompute size for the tail block + nL1Size = nSize - (nL1Loops - 1) * N_SPLIT_SIZE; + nL1SizeAlign = SASAlign(nL1Size, 16); + } + + for (uint32_t kL1 = 0; kL1 < kL1Loops; kL1++) { + kvL1BufIter++; + uint32_t kb = kvL1BufIter % 3; + WaitFlag(mte21KVIds[kb]); + // take the current block from k + bL1Tensor = l1KVTensor[kb * L1_BLOCK_OFFSET]; + uint32_t curSeqIdx = info.s2BatchOffset + nL1 * N_SPLIT_SIZE; + if (info.isOri) { + if constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + uint32_t curS2Offset = + info.s2Idx * constInfo.s2BaseSize + info.s2StartPoint; + uint32_t copyFinishRowCnt = 0; + LocalTensor kTensor; + uint32_t copyRowCnt = 0; + + while (copyFinishRowCnt < nL1Size) { + // Due to the existence of ori_left, even the first moved block may + // not be the zero position of 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.oriKvStride; + 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 right matrix bn2s2d, d is the k axis + // and is not split; mm2 right matrix, s2 + // is the k axis, d axis is split + DataCopyPA( + kTensor, oriKvGm, oriBlockTableGm, shape, startPos); + + // update loop variable + copyFinishRowCnt += copyRowCnt; + curS2Offset += copyRowCnt; + } + } else if constexpr (KV_LAYOUT_T == SAS_LAYOUT::BSND) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nL1Size; // number of rows + 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; + uint32_t batchStride = constInfo.kvSeqSize * seqStride; + + 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 == SAS_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 % 4 * 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 % 4 * 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 = SASAlign(M_SPLIT_SIZE, 16U); + for (uint32_t mL1 = 0; mL1 < mL1Loops; mL1++) { + uint32_t aL1PaddingSize = + 0; // used to align the left matrix to the tail so that the two 32K + // memory blocks are contiguous + if (mL1 == (mL1Loops - 1)) { + mL1Size = mSize - (mL1Loops - 1) * M_SPLIT_SIZE; + mL1SizeAlign = SASAlign(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]); + } + // synchronize using unitflag + LocalTensor cL0Tensor = cL0TensorPingPong + [(cL0BufIter % 2) * + (L0C_PP_SIZE / sizeof(MM_OUT_T))]; // must keep cL0BufIter + // consistent with the m pace + 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; // flip the flag on the last accumulation, indicating + // it can be moved out + 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]); // reverse synchronization, indicating A in L1 + // has been fully consumed by mte1 + } + + if (kL1 == 1) { // last round of the kL1 loop + FixpipeParamsV220 fixParams; + fixParams.nSize = nL1SizeAlign; + fixParams.mSize = mL1SizeAlign; + fixParams.srcStride = mL1SizeAlign; + // change to nSizeAlign + fixParams.dstStride = + info.actualSingleProcessSInnerSizeAlign; // interval between two + // rows of mm1ResGm + fixParams.unitFlag = 0b11; + fixParams.ndNum = 1; // output 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]); // reverse synchronization, indicating L1 has been + // fully consumed by mte1 + } + if (mL1Loops == 1) { + cL0BufIter++; + } + } + qpL1BufIter += mL1Loops; +} + +template +__aicore__ inline void SASCubeBlock::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-aligned + uint32_t mL1Size = M_SPLIT_SIZE; // actual size of 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-aligned + uint32_t nL1Size = N_SPLIT_SIZE; // actual size of n + + uint32_t kSize = info.actualSingleProcessSInnerSize; + uint32_t kL1Size = 256; + uint32_t kL1SizeAlign = SASAlign(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 indicates which buf of the left matrix's 4 bufs is selected, kb + // indicates which buf of the right matrix's 3 bufs is selected + uint32_t ka = 0, kb = 0; + uint32_t mBaseIdx = qpL1BufIter; + for (uint32_t nL1 = 0; nL1 < nL1Loops; nL1++) { // n split L1 -> D + if (nL1 == (nL1Loops - 1)) { + // tail block + nL1Size = nSize - (nL1Loops - 1) * N_SPLIT_SIZE; + nL1SizeAlign = SASAlign(nL1Size, 16U); + } + // write k l1 as a single loop, consistent with mm1 + kL1Size = 256; + kL1SizeAlign = SASAlign(kL1Size, 16U); + uint32_t copyRowCnt = 0; + + for (uint32_t k1 = 0; k1 < kL1Loops; + k1++) { // k split L1, an l0 layer is nested here to operate -> S2, + // 256 each time + if (k1 == (kL1Loops - 1)) { + // tail block + kL1Size = kSize - (kL1Loops - 1) * 256; + kL1SizeAlign = SASAlign(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 must be initialized first, then kL0Loops computed, otherwise + // the loop would change kL0Size and cause an incorrect kL0Loops + kL0Loops = (kL1Size + kL0Size - 1) / kL0Size; + kL0SizeAlign = kL0Size; + for (uint32_t kL1 = kOffset; kL1 < kL0Loops + kOffset; + kL1++) { // 128 loop moving pa, 128 each time + if (kL1 == kOffset + kL0Loops - 1) { + // tail block + kL0Size = kL1Size - (kL0Loops - 1) * kL0Size; + kL0SizeAlign = SASAlign(kL0Size, 16U); + } + + uint32_t curSeqIdx = + info.s2BatchOffset + (kL1 - kOffset) * 128 + k1 * 256; + if (info.isOri) { + if constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + 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 right matrix bn2s2d, d is the k axis and + // is not split; mm2 right matrix, s2 is the k + // axis, d axis is split + PAShape shape; + shape.blockSize = constInfo.paOriBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.kvStride = constInfo.oriKvStride; + 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); + + // update loop variable + copyFinishRowCnt += copyRowCnt; + curS2Offset += copyRowCnt; + } + } else if constexpr (KV_LAYOUT_T == SAS_LAYOUT::BSND) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = kL0Size; // number of rows + 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; + uint32_t batchStride = constInfo.kvSeqSize * seqStride; + + 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 == SAS_LAYOUT::TND) { + uint32_t curS2Offset = + info.s2Idx * constInfo.s2BaseSize + info.s2StartPoint; + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = kL0Size; // number of rows + 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; // number of rows + 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 % 4 * 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; // actual size of m + for (uint32_t mL1 = 0; mL1 < mL1Loops; mL1++) { + if (mL1 == (mL1Loops - 1)) { + // tail block + mL1Size = mSize - (mL1Loops - 1) * M_SPLIT_SIZE; + mL1SizeAlign = SASAlign(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))]; // must keep cL0BufIter + // consistent with the m pace + 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 = SASAlign(kL0Size, 16U); + } + WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); + LocalTensor bL0Tensor = + bL0TensorPingPong[(abL0BufIter % 2) * + (L0B_PP_SIZE / sizeof(KV_T))]; + LoadData3DParamsV2 loadData3DParamsForB; + loadData3DParamsForB.l1H = + kL0SizeAlign / 16; // source operand height + loadData3DParamsForB.l1W = + 16; // source operand weight=16, destination height=l1H*L1W + loadData3DParamsForB.padList[0] = 0; + loadData3DParamsForB.padList[1] = 0; + loadData3DParamsForB.padList[2] = 0; + loadData3DParamsForB.padList[3] = + 255; // tail data does not affect the sliding-window result + + loadData3DParamsForB.mExtension = + kL0SizeAlign; // transfer length in the destination operand's + // height dimension + loadData3DParamsForB.kExtension = + nL1SizeAlign; // transfer length in the destination operand's + // width dimension + loadData3DParamsForB.mStartPt = + 0; // start point of the convolution kernel in the destination + // operand's width dimension + loadData3DParamsForB.kStartPt = + 0; // start point of the convolution kernel in the destination + // operand's height dimension + loadData3DParamsForB.strideW = 1; + loadData3DParamsForB.strideH = 1; + loadData3DParamsForB.filterW = 1; + loadData3DParamsForB.filterSizeW = + false; // whether to increase the convolution kernel width by 256 + // elements on top of filterW + loadData3DParamsForB.filterH = 1; + loadData3DParamsForB.filterSizeH = + false; // whether to increase the convolution kernel height by + // 256 elements on top of filterH + loadData3DParamsForB.dilationFilterW = + 1; // convolution kernel width dilation factor + loadData3DParamsForB.dilationFilterH = + 1; // convolution kernel height dilation factor + loadData3DParamsForB.enTranspose = + 1; // whether to enable the transpose function + loadData3DParamsForB.fMatrixCtrl = + 0; // use FMATRIX_LEFT or FMATRIX_RIGHT, =0 uses FMATRIX_LEFT, =1 + // uses FMATRIX_RIGHT 1 + loadData3DParamsForB.channelSize = + nL1SizeAlign; // number of channels of the source operand. When + // the dilation factor is 1, the destination weight + // is 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; // source operand height + loadData3DParamsForA.l1W = 16; // source operand weight + loadData3DParamsForA.padList[0] = 0; + loadData3DParamsForA.padList[1] = 0; + loadData3DParamsForA.padList[2] = 0; + loadData3DParamsForA.padList[3] = + 255; // tail data does not affect the sliding-window result + + loadData3DParamsForA.mExtension = + mL1SizeAlign; // transfer length in the destination operand's + // height dimension + loadData3DParamsForA.kExtension = + kL0SizeAlign; // transfer length in the destination operand's + // width dimension + loadData3DParamsForA.mStartPt = + 0; // start point of the convolution kernel in the destination + // operand's width dimension + loadData3DParamsForA.kStartPt = + 0; // start point of the convolution kernel in the destination + // operand's height dimension + loadData3DParamsForA.strideW = + 1; // stride of the convolution kernel sliding in the source + // operand's width dimension + loadData3DParamsForA.strideH = + 1; // stride of the convolution kernel sliding in the source + // operand's height dimension + loadData3DParamsForA.filterW = 1; // convolution kernel width + loadData3DParamsForA.filterSizeW = + false; // whether to increase the convolution kernel width by 256 + // elements on top of filterW + loadData3DParamsForA.filterH = 1; // convolution kernel height + loadData3DParamsForA.filterSizeH = + false; // whether to increase the convolution kernel height by + // 256 elements on top of filterH + loadData3DParamsForA.dilationFilterW = + 1; // convolution kernel width dilation factor + loadData3DParamsForA.dilationFilterH = + 1; // convolution kernel height dilation factor + loadData3DParamsForA.enTranspose = + 0; // whether to enable transpose, transposing the entire target + // matrix + loadData3DParamsForA.fMatrixCtrl = 0; + loadData3DParamsForA.channelSize = + kL0SizeAlign; // number of channels of the source operand. When + // the dilation factor is 1, the destination weight + // is 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)) { // last round of nL1, B needs to stay resident in + // L1 for the next round of computation? + SetFlag( + mte21QPIds[ka]); // reverse synchronization, indicating A in L1 + // has been fully consumed by mte1 + } + + if (k1 == (kL1Loops - 1)) { + // ND + FixpipeParamsV220 fixParams; + fixParams.nSize = nL1SizeAlign; + fixParams.mSize = mL1SizeAlign; + fixParams.srcStride = mL1SizeAlign; + fixParams.dstStride = nSize; // interval between two rows of mm2ResGm + fixParams.ndNum = 1; // output 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]); // reverse synchronization, indicating L1 has been + // fully consumed by mte1 + } + // cL0BufIter is no longer used + if (mL1Loops == 1) { + cL0BufIter++; + } + } + qpL1BufIter += mL1Loops; +} +} // namespace SASKernel +#endif // SPARSE_ATTN_SHAREDKV_SCFA_BLOCK_CUBE_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_scfa_block_vector.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_scfa_block_vector.h new file mode 100644 index 0000000000..7b84b575e1 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_scfa_block_vector.h @@ -0,0 +1,1458 @@ +/** + * 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_attn_sharedkv_scfa_block_vector.h + * \brief + */ +#ifndef SPARSE_ATTN_SHAREDKV_SCFA_BLOCK_VECTOR_H +#define SPARSE_ATTN_SHAREDKV_SCFA_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_attn_sharedkv/op_kernel/sparse_attn_sharedkv_common.h" + +namespace SASKernel { +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +template +class SASVectorBlock { + public: + // Intermediate computation data type is float, high-precision mode + using T = float; + using KV_T = typename SAST::kvType; + using OUT_T = typename SAST::outputType; + using UPDATE_T = T; + using SINKS_T = T; + using MM1_OUT_T = float; + using MM2_OUT_T = float; + + __aicore__ inline SASVectorBlock(){}; + __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 SparseAttnSharedkvTilingData* __restrict tilingData); + __aicore__ inline void InitVec0GlobalTensor( + const GlobalTensor& kvValidSizeGm, + 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); + + // byte count of BLOCK and REPEAT + static constexpr uint64_t BYTE_BLOCK = 32UL; + static constexpr uint32_t REPEAT_BLOCK_BYTE = 256U; + // number of FP32 elements of BLOCK and REPEAT + 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 cannot exceed 256 + static constexpr uint32_t REPEATE_STRIDE_UP_BOUND = 256; + + private: + static constexpr bool PAGE_ATTENTION = SAST::pageAttention; + static constexpr int TEMPLATE_MODE = SAST::templateMode; + static constexpr bool FLASH_DECODE = SAST::flashDecode; + static constexpr SAS_LAYOUT LAYOUT_T = SAST::layout; + static constexpr SAS_LAYOUT KV_LAYOUT_T = SAST::kvLayout; + + static constexpr uint64_t MERGE_CACHE_GM_BUF_NUM = 4; + 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); // 32768/4=8096 + static constexpr uint32_t BLOCK_ELEMENT_NUM = + BYTE_BLOCK / sizeof(T); // 32/4=8 + static constexpr uint32_t MAX_N1_SIZE = 128U; + static constexpr T SOFTMAX_MIN_NUM = -2e38; + static constexpr SINKS_T R0 = 1.0f; + + const SparseAttnSharedkvTilingData* __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 kvValidSizeGm_; + GlobalTensor oriKvGm_; + GlobalTensor cmpKvGm_; + GlobalTensor oriBlockTableGm_; + GlobalTensor cmpBlockTableGm_; + + // ================================Local Buffer + // area==================================== + 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 SASVectorBlock::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)); + // allocate memory of size 256+N1, where 256 is the maximum VEC block size on + // the m axis + 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 SASVectorBlock::InitParams( + const struct ConstInfo& constInfo, + const SparseAttnSharedkvTilingData* __restrict tilingData) { + this->constInfo = constInfo; + this->tilingData = tilingData; +} + +template +__aicore__ inline void SASVectorBlock::InitVec0GlobalTensor( + const GlobalTensor& kvValidSizeGm, + const GlobalTensor& kvMergeGm, + const GlobalTensor& oriKvGm, + const GlobalTensor& cmpKvGm, + const GlobalTensor& oriBlockTableGm, + const GlobalTensor& cmpBlockTableGm) { + this->kvValidSizeGm_ = kvValidSizeGm; + this->kvMergeGm_ = kvMergeGm; + this->oriKvGm_ = oriKvGm; + this->cmpKvGm_ = cmpKvGm; + this->oriBlockTableGm_ = oriBlockTableGm; + this->cmpBlockTableGm_ = cmpBlockTableGm; +} + +template +__aicore__ inline void SASVectorBlock::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 SASVectorBlock::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 SASVectorBlock::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 SASVectorBlock::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 SASVectorBlock::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; // process 8 datablocks each time + Brcb(sinksBrcbUb, sinksUb, repeatTimes, {1, BLOCK_ELEMENT_NUM}); + PipeBarrier(); + + DataCopyParams repeatParams; + repeatParams.blockCount = 1; // move until one block exceeds the per-vec-core + // M-axis size; inter-core split is 256 per vec + 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 SASVectorBlock::SliceAndContactSinksValue( + uint32_t nIdx, + uint32_t dealRowCount) { + // The repeatTimes of WholeReduceMax supports the range (0,255), so + // WholeReduceMax must be called multiple times, with repeatTime=128 each time + 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 SASVectorBlock::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 SASVectorBlock::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 SASVectorBlock::ProcessLse( + const RunInfo& info, + const MSplitInfo& mSplitInfo) { + if (mSplitInfo.vecDealM == 0) { + return; + } + uint64_t lseOffset = 0; + if (constInfo.outputLayout == SAS_LAYOUT::TND) { + uint32_t tBase = actualSeqLengthsQGm.GetValue(info.bIdx); + lseOffset = + (tBase + info.s1Idx) * constInfo.gSize + // T-axis and s1-axis offset + info.n2IdxReal * constInfo.qSeqSize * + constInfo.gSize; // N2-axis offset + } else if (constInfo.outputLayout == SAS_LAYOUT::BSND) { + lseOffset = info.bIdx * constInfo.qSeqSize * constInfo.kvHeadNum * + constInfo.gSize + // B-axis offset + info.n2IdxReal * constInfo.qSeqSize * + constInfo.gSize + // N2-axis offset + info.s1Idx * constInfo.gSize; // S1-axis offset + } + 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 SASVectorBlock::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 = SASAlign(dealRowCount, FP32_BLOCK_ELEMENT_NUM); + DataCopy(softmaxSumUb[softmaxOutOffset], inSumTensor, dealRowCountAlign); + PipeBarrier(); + DataCopy(softmaxMaxUb[softmaxOutOffset], inMaxTensor, dealRowCountAlign); + } +} + +template +__aicore__ inline void SASVectorBlock::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 switch + + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + DataCopy(vec1ResGm[inOutGmOffset], tmpMMResCastTensor, computeSize); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); +} + +template +__aicore__ inline void SASVectorBlock::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. rounding down to 8 alignment because UB operations are at least 32B + // 2. info.actualSingleProcessSInnerSizeAlign is at most 512, mSplitSize can + // ensure a minimum of 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; + + SliceAndContactSinksValue( + (mSplitInfo.nBufferStartM + mSplitInfo.vecStartM) % constInfo.qHeadNum, + 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 SASVectorBlock::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 SASVectorBlock::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 == SAS_LAYOUT::PA_ND) { + int64_t blkTableIdx = realS2Idx / constInfo.paCmpBlockSize; + int64_t blkTableOffset = realS2Idx % constInfo.paCmpBlockSize; + realKeyGmOffset = + cmpBlockTableGm_.GetValue( + runInfo.bIdx * constInfo.cmpMaxBlockNumPerBatch + blkTableIdx) * + static_cast(constInfo.cmpKvStride) + + blkTableOffset * static_cast(constInfo.kvHeadNum) * + static_cast(constInfo.headDim); + + } else if constexpr (KV_LAYOUT_T == SAS_LAYOUT::BSND) { + realKeyGmOffset = runInfo.bIdx * constInfo.kvSeqSize / constInfo.cmpRatio * + constInfo.kvHeadNum + + realS2Idx * constInfo.kvHeadNum; + } else if constexpr (KV_LAYOUT_T == SAS_LAYOUT::TND) { + realKeyGmOffset = (runInfo.tensorCmpBOffset + + realS2Idx * constInfo.kvHeadNum * constInfo.headDim) / + constInfo.headDim; + } + return realKeyGmOffset; +} + +template +__aicore__ inline void SASVectorBlock::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; + if constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + DataCopyPad( + kvMergUb_[mergeMte3Idx % 2 * INPUT2_BUFFER_OFFSET / sizeof(KV_T) + + (mte2Size - mte3Size) * constInfo.headDim], + cmpKvGm_[keyBNBOffset], + intriParams, + padParams); + } else { + DataCopyPad( + kvMergUb_[mergeMte3Idx % 2 * INPUT2_BUFFER_OFFSET / sizeof(KV_T) + + (mte2Size - mte3Size) * constInfo.headDim], + cmpKvGm_[keyBNBOffset * constInfo.headDim], + intriParams, + padParams); + } + mte2Size += validS2Count; +} + +template +__aicore__ inline void SASVectorBlock::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; + if constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + int64_t blkTableSrcStride = + ((keyOffset1 > keyOffset2 ? (keyOffset1 - keyOffset2) + : (keyOffset2 - keyOffset1)) - + constInfo.sparseBlockSize * constInfo.headDim); + keySrcStride = blkTableSrcStride * sizeof(KV_T); + } else if constexpr (KV_LAYOUT_T == SAS_LAYOUT::BSND) { + keySrcStride = ((keyOffset1 > keyOffset2 ? (keyOffset1 - keyOffset2) + : (keyOffset2 - keyOffset1)) - + constInfo.sparseBlockSize) * + constInfo.headDim * sizeof(KV_T); + } else if constexpr (KV_LAYOUT_T == SAS_LAYOUT::TND) { + 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)) { + // for abnormal cases such as stride overflow, negative stride, or over-long + // s2, fall back to 2 move instructions because two blocks need to be copied + 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; + + int64_t startGmOffset = keyOffset1 > -1 ? keyOffset1 : keyOffset2; + if (keyOffset2 > -1 && keyOffset2 < keyOffset1) { + startGmOffset = keyOffset2; + } + if constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + DataCopyPad( + kvMergUb_[mergeMte3Idx % 2 * INPUT2_BUFFER_OFFSET / sizeof(KV_T) + + (mte2Size - mte3Size) * constInfo.headDim], + cmpKvGm_[startGmOffset], + intriParams, + padParams); + } else { + DataCopyPad( + kvMergUb_[mergeMte3Idx % 2 * INPUT2_BUFFER_OFFSET / sizeof(KV_T) + + (mte2Size - mte3Size) * constInfo.headDim], + cmpKvGm_[startGmOffset * constInfo.headDim], + intriParams, + padParams); + } + mte2Size += + ((keyOffset1 > -1) + (keyOffset2 > -1)) * constInfo.sparseBlockSize; + } +} + +template +__aicore__ inline void SASVectorBlock::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 % 4 * 512 * 512 + + (s2GmStartOffset + mte3Size) * constInfo.headDim], + kvMergUb_[mergeMte3Idx % 2 * INPUT2_BUFFER_OFFSET / sizeof(KV_T)], + dataCopyParams); +} + +// b s1 k +template +__aicore__ inline void SASVectorBlock::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 = SASAlign(s2Pair, 2) * constInfo.sparseBlockSize; + int64_t s2GmStartOffset = GetSubBlockIdx() == 0 ? 0 : s2SplitPoint; + int64_t s2GmLimit = GetSubBlockIdx() == 0 ? s2SplitPoint : s2ProcessSize; + if (s2GmLimit > s2ProcessSize) { + s2GmLimit = s2ProcessSize; + } + // process two basic blocks + 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 SASVectorBlock::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); + } + } +} + +template +__aicore__ inline uint64_t SASVectorBlock::CalcAccumOffset( + uint32_t bN2Idx, + uint32_t gS1Idx) { + return 0; +} + +template +__aicore__ inline void SASVectorBlock::ProcessVec2SingleBuf( + const RunInfo& info, + const MSplitInfo& mSplitInfo) { + if (mSplitInfo.vecDealM == 0) { + return; + } + + ProcessVec2Inner(info, mSplitInfo, 0, mSplitInfo.vecDealM); +} + +template +__aicore__ inline void SASVectorBlock::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 SASVectorBlock::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 SASVectorBlock::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 + // count offset + wsMStart * actualColumnCount; // m-axis 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 SASVectorBlock::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 SASVectorBlock::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 uses round-half-to-even mode + 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 SASVectorBlock::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 SASVectorBlock::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 switch + + uint32_t inOutBaseOffset = mStart * columnCount; + uint32_t baseOffset = mSplitInfo.nBufferStartM / 2 + startRow; + + // except for the first loop, the intermediate computation result must be + // updated + 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]; // sumUb uses temporary memory 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 switch + } + + // output the result on the last iteration; otherwise store the intermediate + // result in workspace + if (info.isLastS2Loop) { + uint32_t idx = info.loop % (constInfo.preLoadNum); + LocalTensor tmpSumUb = + v0ValidSizeBuff + .Get()[384]; // sumUb uses temporary memory 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); + 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 SASVectorBlock::RowDivs( + LocalTensor dstUb, + LocalTensor src0Ub, + LocalTensor src1Ub, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + // divs by row, elements of each row are divided by the same element + // 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; // in the column direction, the start-address interval between two + // repeats is dtypeMask=64 elements, i.e. 8 blocks + columnRepeatParams.src1RepStride = 0; + columnRepeatParams.dstRepStride = + 8; // in the column direction, the start-address interval between two + // repeats is dtypeMask=64 elements, i.e. 8 blocks + 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 SASVectorBlock::RowMuls( + LocalTensor dstUb, + LocalTensor src0Ub, + LocalTensor src1Ub, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + // muls by row, elements of each row are multiplied by the same element + // 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) { + // this limit is because each repeat can read at most 256B of contiguous + // data + repeatElementNum = FP32_REPEAT_ELEMENT_NUM * 2; // 256/4 * 2=128 + blockElementNum = FP32_BLOCK_ELEMENT_NUM * 2; // 32/4 * 2 = 16 + } + + // each time only 256B of contiguous data can be read for computation, so only + // 256B/sizeof(dType)= can be processed each time the column direction is + // split into dLoop iterations, processing 8 columns of data each time + uint32_t dLoop = actualColumnCount / repeatElementNum; + uint32_t dRemain = actualColumnCount % repeatElementNum; + // REPEATE_STRIDE_UP_BOUND=256; this limit is because src0RepStride is of type + // uint8, allowing at most a 256-datablock interval + 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; + + // if the number of repeats processed by column is fewer than by row, + // process by column; otherwise process by row + 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; // in the column direction, the start-address interval between two + // repeats is dtypeMask=64 elements, i.e. 8 blocks + columnRepeatParams.src1RepStride = 0; + columnRepeatParams.dstRepStride = + 8; // in the column direction, the start-address interval between two + // repeats is dtypeMask=64 elements, i.e. 8 blocks + for (uint32_t i = 0; i < dealRowCount; i++) { + Mul(dstUb[i * columnCount], + src0Ub[i * columnCount], + src1Ub[i * blockElementNum], + repeatElementNum, + dLoop, + columnRepeatParams); + } + } + + // the last iteration completes [dealRowCount, dRemain] * [dealRowCount, + // blockElementNum], computing only the valid part + if (dRemain > 0) { + Mul(dstUb[dLoop * repeatElementNum], + src0Ub[dLoop * repeatElementNum], + src1Ub, + dRemain, + dealRowCount, + repeatParams); + } + } else { + BinaryRepeatParams repeatParams; + repeatParams.src0RepStride = + 8; // each repeat is 256B of data, exactly 8 datablocks + repeatParams.src0BlkStride = 1; + repeatParams.src1RepStride = 0; + repeatParams.src1BlkStride = 0; + repeatParams.dstRepStride = 8; + repeatParams.dstBlkStride = 1; + // compute one row each time, computing dealRowCount rows in total + for (uint32_t i = 0; i < dealRowCount; i++) { + // compute dLoop repeats within one row, each repeat computes + // 256/block_size data_blocks + Mul(dstUb[i * columnCount], + src0Ub[i * columnCount], + src1Ub[i * blockElementNum], + repeatElementNum, + dLoop, + repeatParams); + // compute the tail block within one row + if (dRemain > 0) { + Mul(dstUb[i * columnCount + dLoop * repeatElementNum], + src0Ub[i * columnCount + dLoop * repeatElementNum], + src1Ub[i * blockElementNum], + dRemain, + 1, + repeatParams); + } + } + } +} +} // namespace SASKernel +#endif // SPARSE_ATTN_SHAREDKV_SCFA_BLOCK_VECTOR_H diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_scfa_kernel.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_scfa_kernel.h new file mode 100644 index 0000000000..40bc8adc90 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_scfa_kernel.h @@ -0,0 +1,1006 @@ +/** + * 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_attn_sharedkv_scfa_kernel.h + * \brief + */ + +#ifndef SPARSE_ATTN_SHAREDKV_SCFA_KERNEL_H +#define SPARSE_ATTN_SHAREDKV_SCFA_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_attn_sharedkv/op_kernel/sparse_attn_sharedkv_common.h" +#include "sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_metadata.h" +#include "sparse_attn_sharedkv_scfa_block_cube.h" +#include "sparse_attn_sharedkv_scfa_block_vector.h" + +namespace SASKernel { +using namespace matmul; +using namespace optiling; +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +// Before the S2 loop, RunInfo is not yet assigned, so Bngs1Param temporarily +// holds info about the B, N and S1 axes; this also reduces redundant +// computation +struct TempLoopInfo { + uint32_t bn2IdxInCurCore = 0; + uint32_t bIdx = 0U; + uint32_t n2Idx = 0U; + uint64_t s2BasicSizeTail = + 0U; // Tail basic block size of the S2-direction loop + uint32_t s2LoopTimes = + 0U; // Total number of S2-direction loops; equals the actual count for + // both TND and BXXD, no need to subtract 1 + + int32_t actS1Size = 0; // In the TND scenario, the S1-axis size processed by + // the current batch loop + 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; // Tail basic block size of the gS1-direction loop + 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 SparseAttnSharedkvScfa { + public: + // Intermediate computation data type is float, high-precision mode + using T = float; + using Q_T = typename SAST::queryType; + using KV_T = typename SAST::kvType; + using OUT_T = typename SAST::outputType; + using SINKS_T = float; + using UPDATE_T = T; + using MM1_OUT_T = T; + using MM2_OUT_T = T; + + __aicore__ inline SparseAttnSharedkvScfa(){}; + __aicore__ inline void Init( + __gm__ uint8_t* query, + __gm__ uint8_t* oriKV, + __gm__ uint8_t* cmpKV, + __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* sinks, + __gm__ uint8_t* metadata, + __gm__ uint8_t* attentionOut, + __gm__ uint8_t* softmaxLse, + __gm__ uint8_t* workspace, + const SparseAttnSharedkvTilingData* __restrict tiling, + __gm__ uint8_t* gmTiling, + TPipe* tPipe); + + __aicore__ inline void Process(); + + private: + static constexpr bool PAGE_ATTENTION = SAST::pageAttention; + static constexpr bool FLASH_DECODE = SAST::flashDecode; + static constexpr SAS_LAYOUT LAYOUT_T = SAST::layout; + static constexpr SAS_LAYOUT KV_LAYOUT_T = SAST::kvLayout; + + static constexpr uint32_t PRELOAD_NUM = 2; + static constexpr uint32_t N_BUFFER_M_BASIC_SIZE = 256; + static constexpr uint32_t SAS_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 uint64_t kvHeadNum = 1ULL; + static constexpr uint64_t headDim = 512ULL; + + static constexpr uint32_t dbWorkspaceRatio = PRELOAD_NUM; + + const SparseAttnSharedkvTilingData* __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{}; + + SASCubeBlock cubeBlock; + SASVectorBlock 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; + + // workspace + GlobalTensor mm1ResGm; + GlobalTensor vec1ResGm; + GlobalTensor mm2ResGm; + GlobalTensor kvMergeGm_; + GlobalTensor kvValidSizeGm_; + + 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[SAS_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 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 SparseAttnSharedkvScfa::InitTilingData() { + // singleCoreParams + // singleCoreTensorSize + constInfo.mmResUbSize = tilingData->baseParams.mmResUbSize; + constInfo.bmm2ResUbSize = tilingData->baseParams.bmm2ResUbSize; + + // baseParams + constInfo.batchSize = tilingData->baseParams.batchSize; + constInfo.qHeadNum = constInfo.gSize = + tilingData->baseParams.nNumOfQInOneGroup; + 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.kvHeadNum = kvHeadNum; + constInfo.headDim = headDim; + constInfo.oriMaskMode = tilingData->baseParams.oriMaskMode; + constInfo.oriKvStride = tilingData->baseParams.oriKvStride; + constInfo.oriWinLeft = tilingData->baseParams.oriWinLeft; + constInfo.oriWinRight = tilingData->baseParams.oriWinRight; + + constInfo.actualLenDimsQ = tilingData->baseParams.actualLenDimsQ; + constInfo.actualLenDimsKV = tilingData->baseParams.actualLenDimsKV; + 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 is fixed to 1 + constInfo.cmpMaskMode = tilingData->cmpParams.cmpMaskMode; + constInfo.cmpKvStride = tilingData->cmpParams.cmpKvStride; +} + +template +__aicore__ inline void SparseAttnSharedkvScfa::InitBuffers() { + if ASCEND_IS_AIV { + vectorBlock.InitBuffers(pipe); + } else { + cubeBlock.InitBuffers(pipe); + } +} + +template +__aicore__ inline void SparseAttnSharedkvScfa::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 SparseAttnSharedkvScfa::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); + actualSeqLengthsCmpKVGm.SetGlobalBuffer( + (__gm__ int32_t*)actualSeqLengthsCmpKV, constInfo.actualLenDimsKV); + } + if (constInfo.actualLenDimsQ != 0) { + actualSeqLengthsQGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsQ, + constInfo.actualLenDimsQ); + } +} + +template +__aicore__ inline void SparseAttnSharedkvScfa::InitAllZeroOutput( + uint32_t bIdx, + uint32_t s1Idx, + uint32_t n2Idx) { + if (constInfo.outputLayout == SAS_LAYOUT::TND) { + if (tempLoopInfo.actS1Size == 0) { + return; + } + uint32_t tBase = actualSeqLengthsQGm.GetValue(bIdx); + uint32_t s1Count = tempLoopInfo.actS1Size; + + uint64_t attenOutOffset = + (tBase + s1Idx) * kvHeadNum * constInfo.gSize * + headDim + // T-axis and s1-axis offset + n2Idx * constInfo.gSize * headDim; // N2-axis offset + uint64_t lseOffset = + (tBase + s1Idx) * constInfo.gSize + // T-axis and s1-axis offset + n2Idx * constInfo.qSeqSize * constInfo.gSize; // N2-axis offset + matmul::InitOutput( + attentionOutGm[attenOutOffset], constInfo.gSize * headDim, 0); + if (constInfo.returnSoftmaxLse) { + matmul::InitOutput(softmaxLseGm[lseOffset], constInfo.gSize, 0); + } + } else if (constInfo.outputLayout == SAS_LAYOUT::BSND) { + uint64_t attenOutOffset = + bIdx * constInfo.qSeqSize * kvHeadNum * constInfo.gSize * headDim + + s1Idx * kvHeadNum * constInfo.gSize * + headDim + // B-axis and S1-axis offset + n2Idx * constInfo.gSize * headDim; // N2-axis offset + uint64_t lseOffset = + bIdx * constInfo.qSeqSize * constInfo.kvHeadNum * + constInfo.gSize + // B-axis offset + n2Idx * constInfo.qSeqSize * constInfo.gSize + // N2-axis offset + s1Idx * constInfo.gSize; // S1-axis offset + matmul::InitOutput( + attentionOutGm[attenOutOffset], constInfo.gSize * headDim, 0); + if (constInfo.returnSoftmaxLse) { + matmul::InitOutput(softmaxLseGm[lseOffset], constInfo.gSize, 0); + } + } +} + +template +__aicore__ inline void SparseAttnSharedkvScfa::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 SparseAttnSharedkvScfa::GetActualSeqLenQ( + uint32_t bIdx) { + if constexpr (LAYOUT_T == SAS_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 SparseAttnSharedkvScfa::GetActualSeqLenKV( + uint32_t bIdx) { + if constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + 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 == SAS_LAYOUT::BSND) { + return static_cast(constInfo.kvSeqSize); + } else if constexpr (KV_LAYOUT_T == SAS_LAYOUT::TND) { + int32_t actualSeqKVPrefixSum = actualSeqLengthsKVGm.GetValue(bIdx); + int32_t actualSeqKVNextSum = actualSeqLengthsKVGm.GetValue(bIdx + 1); + tempLoopInfo.actualSeqCmpKVPrefixSum = + actualSeqLengthsCmpKVGm.GetValue(bIdx); + tempLoopInfo.actualSeqKVPrefixSum = actualSeqKVPrefixSum; + return actualSeqKVNextSum - actualSeqKVPrefixSum; + } +} + +template +__aicore__ inline void SparseAttnSharedkvScfa::GetSparseActualSeqLen() { + // Row invalidity is judged by the ori part; if the ori part has invalid rows, + // both ori and cmp have them + if (static_cast(tempLoopInfo.s1EndIdx) < + -(tempLoopInfo.actOriS2Size - tempLoopInfo.actS1Size)) { + tempLoopInfo.actOriS2Size = 0; + tempLoopInfo.actCmpS2Size = 0; + return; + } + + // The cmp part also has top-k; tempLoopInfo.actS2Size applies only to cmp + int32_t thresHold = (tempLoopInfo.cmpMaskRight + tempLoopInfo.s1EndIdx + 1) / + constInfo.cmpRatio; + tempLoopInfo.actCmpS2Size = + Min(constInfo.sparseBlockCount * constInfo.sparseBlockSize, thresHold); +} + +template +__aicore__ inline void SparseAttnSharedkvScfa::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 SparseAttnSharedkvScfa::Init( + __gm__ uint8_t* query, + __gm__ uint8_t* oriKV, + __gm__ uint8_t* cmpKV, + __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* sinks, + __gm__ uint8_t* metadata, + __gm__ uint8_t* attentionOut, + __gm__ uint8_t* softmaxLse, + __gm__ uint8_t* workspace, + const SparseAttnSharedkvTilingData* __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 == SAS_LAYOUT::TND && LAYOUT_T == SAS_LAYOUT::TND) { + InitActualSeqLen(cuSeqlensQ, cuSeqlensKV, cuSeqlensCmpKV); + } else if (KV_LAYOUT_T == SAS_LAYOUT::TND) { + InitActualSeqLen(seqUsedQ, cuSeqlensKV, cuSeqlensCmpKV); + } else if ((KV_LAYOUT_T == SAS_LAYOUT::PA_ND || + KV_LAYOUT_T == SAS_LAYOUT::BSND) && + LAYOUT_T == SAS_LAYOUT::TND) { + InitActualSeqLen(cuSeqlensQ, seqUsedKV); + } else if ((KV_LAYOUT_T == SAS_LAYOUT::PA_ND || + KV_LAYOUT_T == SAS_LAYOUT::BSND)) { + InitActualSeqLen(seqUsedQ, seqUsedKV); + } + + 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 (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 != SAS_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 memory layout + // |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 * 4 * sizeof(KV_T))); + offset += GetBlockNum() * 512 * 512 * 4 * sizeof(KV_T); + + kvValidSizeGm_.SetGlobalBuffer( + (__gm__ int32_t*)(workspace + offset + + (aiCoreIdx * 2) * 128 * 4 * sizeof(int32_t))); + + if ASCEND_IS_AIV { + vectorBlock.InitParams(constInfo, tilingData); + vectorBlock.InitVec0GlobalTensor(kvValidSizeGm_, + 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); + } + // Must be executed after InitParams + if (pipe != nullptr) { + InitBuffers(); + } +} + +template +__aicore__ inline void SparseAttnSharedkvScfa::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 SparseAttnSharedkvScfa::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; + + // Tail block in the M direction + 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) { + tensorACoreOffset = tndBIdxOffsetForQ + info.gS1Idx * constInfo.headDim; + tensorBCoreOffset = + tndBIdxOffsetForKV + + info.n2Idx * constInfo.headDim; // Currently in the PA scenario, this + // variable is invalid + tensorCmpBCoreOffset = + tndBIdxOffsetForCmpKV + info.n2Idx * constInfo.headDim; + if constexpr (LAYOUT_T == SAS_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 == SAS_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) { + // The first S2 loop can only be in ori_kv + info.isOri = 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.isOri = 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; + } + + info.actualSingleProcessSInnerSizeAlign = SASAlign( + info.actualSingleProcessSInnerSize, SASVectorBlock::BYTE_BLOCK); + if (info.isOri) { + info.v0S2Start = 0; + info.v0S2DealSize = 0; + } else { + info.v0S2Start = 0; + if (s2LoopIdx + 1 == tempLoopInfo.s2LoopTimes && s2LoopIdx == 2) { // tail + info.v0S2Start = 512; + } + info.v0S2DealSize = 512; + } +} + +template +__aicore__ inline void SparseAttnSharedkvScfa::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 SparseAttnSharedkvScfa::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 SparseAttnSharedkvScfa::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 SparseAttnSharedkvScfa::GetBN2Idx( + uint32_t bN2Idx, + uint32_t& bIdx, + uint32_t& n2Idx) { + bIdx = bN2Idx / kvHeadNum; + n2Idx = bN2Idx % kvHeadNum; +} + +template +__aicore__ inline void SparseAttnSharedkvScfa::ProcessBalance() { + RunInfo extraInfo[SAS_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); + } + + // Adapt to left-closed right-open interval + 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); // Get actualSeqLength + bool isS1ZeroAndLastBatch = (tempLoopInfo.actS1Size == 0) && + ((constInfo.outputLayout == SAS_LAYOUT::BSND) || + (bN2LoopIdx + 1 == constInfo.bN2End)); + uint32_t gS1SplitNum = + CeilDiv(tempLoopInfo.actS1Size * constInfo.gSize, constInfo.mBaseSize); + + // When at the last BN2 and gS1End is 0, all data in the current BN2 is + // processed by the current core + gS1LoopEnd = (bN2LoopIdx + 1 == constInfo.bN2End && constInfo.gS1End != 0) + ? constInfo.gS1End + : gS1SplitNum; + // When at the last BN2 and current S1 is 0, enter the loop to compute the + // unfinished part caused by preload + gS1LoopEnd = isS1ZeroAndLastBatch ? gS1LoopEnd + 1 : gS1LoopEnd; + for (uint32_t gS1LoopIdx = constInfo.gS1Start; gS1LoopIdx < gS1LoopEnd; + gS1LoopIdx++) { + tempLoopInfo.actOriS2Size = GetActualSeqLenKV(tempLoopInfo.bIdx); + // Compute required data to avoid redundant computation + tempLoopInfo.gS1Idx = gS1LoopIdx * constInfo.mBaseSize; + tempLoopInfo.s1StartIdx = tempLoopInfo.gS1Idx / constInfo.gSize; + tempLoopInfo.s1EndIdx = Min( + (tempLoopInfo.s1StartIdx + constInfo.mBaseSize / constInfo.gSize - 1), + tempLoopInfo.actS1Size - 1); + + // These are all closed intervals + 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); + tempLoopInfo.cmpMaskRight = + tempLoopInfo.actOriS2Size - 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 = SASAlign(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; + // Needs to be enabled after core partitioning modification + // Whether the current s2 is split determines whether the output must be + // written to 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) { // Used to determine the id of the loop GM + // used by v0 + ++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 SparseAttnSharedkvScfa::PreloadPipeline( + uint32_t loop, + uint32_t cmpLoop, + uint64_t s2Start, + uint64_t s2LoopIdx, + RunInfo extraInfo[SAS_PRELOAD_TASK_CACHE_SIZE]) { + RunInfo& extraInfo0 = + extraInfo[loop % SAS_PRELOAD_TASK_CACHE_SIZE]; // Current-round task + RunInfo& extraInfo2 = + extraInfo[(loop + 2) % + SAS_PRELOAD_TASK_CACHE_SIZE]; // Previous-round task + RunInfo& extraInfo1 = + extraInfo[(loop + 1) % + SAS_PRELOAD_TASK_CACHE_SIZE]; // Task from two rounds ago + + CalcParams(loop, cmpLoop, s2Start, s2LoopIdx, extraInfo0); + if (extraInfo0.isValid) { + if ASCEND_IS_AIC { + if (!extraInfo0.isOri) { + CrossCoreWaitFlag(constInfo.syncV0C1); + } + ComputeMm1(extraInfo0); + } else { + if (extraInfo0.isFirstSInnerLoop) { + CrossCoreWaitFlag(3); + } + vectorBlock.ProcessVec0L(extraInfo0); + if (!extraInfo0.isOri) { + 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; + } +} + +} // namespace SASKernel +#endif // SPARSE_ATTN_SHAREDKV_SCFA_KERNEL_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_swa_block_cube.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_swa_block_cube.h new file mode 100644 index 0000000000..1b7deb55b8 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_swa_block_cube.h @@ -0,0 +1,1092 @@ +/** + * 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_attn_sharedkv_swa_block_cube.h + * \brief use 7 buffer for matmul l1, better pipeline + */ +#ifndef SPARSE_ATTN_SHAREDKV_SWA_BLOCK_CUBE_H +#define SPARSE_ATTN_SHAREDKV_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_attn_sharedkv/op_kernel/sparse_attn_sharedkv_common.h" + +namespace SASKernel { +template +class SWACubeBlock { + public: + // Intermediate computation data type is float, high-precision mode + using T = float; + using Q_T = typename SAST::queryType; + using KV_T = typename SAST::kvType; + using OUT_T = typename SAST::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, // 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 = SAST::pageAttention; + // static constexpr int TEMPLATE_MODE = SAST::templateMode; + static constexpr bool FLASH_DECODE = SAST::flashDecode; + static constexpr SAS_LAYOUT LAYOUT_T = SAST::layout; + static constexpr SAS_LAYOUT KV_LAYOUT_T = SAST::kvLayout; + + static constexpr uint32_t M_SPLIT_SIZE = 128; // m-direction split + static constexpr uint32_t N_SPLIT_SIZE = 128; // n-direction split + static constexpr uint32_t K_L0_SPLIT_SIZE = 128; // k-direction L0 split + static constexpr uint32_t K_L1_SPLIT_SIZE = 256; // k-direction L1 split + static constexpr uint32_t N_WORKSPACE_SIZE = 512; // n-direction split + static constexpr uint32_t D_SPLIT_SIZE = 256; // d-axis split + + 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, uses 3 eventIds + 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 reuse + static constexpr uint32_t mte21KVIds[3] = {L1_EVENT4, L1_EVENT5, L1_EVENT6}; + + ConstInfo constInfo{}; + + // L1 is divided into 3 buf blocks, used for recording + 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}; // Ensure block 0 and block 1 are adjacent, block 2 and block 3 are + // adjacent, to keep addresses of the same m block contiguous + 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 (constInfo.templateMode == CFA_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, // const GlobalTensor& kvMergeGm, + GlobalTensor oriBlockTableGm, + GlobalTensor cmpBlockTableGm) { + this->oriKvGm = oriKvGm; + this->oriBlockTableGm = oriBlockTableGm; + if (constInfo.templateMode == CFA_TEMPLATE) { + this->cmpBlockTableGm = cmpBlockTableGm; + } +} + +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; // number of rows + nd2nzPara.dValue = srcD; + nd2nzPara.srcDValue = srcDstride; + nd2nzPara.dstNzC0Stride = (srcN + 15) / 16 * 16; // align to 16-unit 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]; + // arch35: 3D convolution loading degenerates to 2D matrix loading (refer to + // compressor LoadAToL0) + LoadData2DParamsV2 loadData2DParamsV2; + loadData2DParamsV2.mStartPosition = 0; + loadData2DParamsV2.kStartPosition = 0; + loadData2DParamsV2.mStep = (mSize + 15) / 16; + loadData2DParamsV2.kStep = (kSize + 15) / 16; + loadData2DParamsV2.srcStride = (mSize + 15) / 16; + loadData2DParamsV2.dstStride = loadData2DParamsV2.mStep; + loadData2DParamsV2.ifTranspose = false; + LoadData(aL0Tensor, srcTensor, loadData2DParamsV2); +} + +template +__aicore__ inline void SWACubeBlock::LoadDataMm1B( + LocalTensor& l0Tensor, + LocalTensor& l1Tensor, + uint32_t idx, + uint32_t kSplitSize, + uint32_t kSize, + uint32_t nSize) { + // N direction fully loaded + 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 = SASAlign(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 = SASAlign(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 split n and k + for (uint32_t nL1 = 0; nL1 < nL1Loops; nL1++) { // L1 split n, 512/128=4 + if (nL1 == (nL1Loops - 1)) { + // recompute size for the tail block + nL1Size = nSize - (nL1Loops - 1) * N_SPLIT_SIZE; + nL1SizeAlign = SASAlign(nL1Size, 16); + } + + for (uint32_t kL1 = 0; kL1 < kL1Loops; kL1++) { + kvL1BufIter++; + uint32_t kb = kvL1BufIter % 3; + WaitFlag(mte21KVIds[kb]); + // take the current block from k + bL1Tensor = l1KVTensor[kb * L1_BLOCK_OFFSET]; + // FIX: clear L1 KV padding rows [nL1Size, nL1SizeAlign) to avoid dirty + // buffer reuse polluting QK^T tail columns + if (nL1SizeAlign > nL1Size) { + AscendC::InitConstValue( + bL1Tensor, + AscendC::InitConstValueParams( + 1, (uint16_t)(nL1SizeAlign * 256 / 32), 0, (KV_T)0)); + PipeBarrier(); + } + uint32_t curSeqIdx = info.s2BatchOffset + nL1 * N_SPLIT_SIZE; + uint32_t copyFinishRowCnt = 0; + + if (info.isOri) { + if constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + uint32_t curS2Offset = info.s2Idx * constInfo.s2BaseSize + + info.s2StartPoint + nL1 * N_SPLIT_SIZE; + uint32_t copyFinishRowCnt = 0; + LocalTensor kTensor; + uint32_t copyRowCnt = 0; + + while (copyFinishRowCnt < nL1Size) { + // Due to the existence of ori_left, even the first moved block may + // not be the zero position of 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 pending 7buf naming change + startPos.dIdx = + kL1 * 256; // mm1 right matrix bn2s2d, d is the k axis and is + // not split; mm2 right matrix, s2 is the k axis, d + // axis is split + PAShape shape; + shape.blockSize = constInfo.paOriBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.kvStride = constInfo.oriKvStride; + shape.actHeadDim = 256; + shape.maxblockNumPerBatch = constInfo.oriMaxBlockNumPerBatch; + shape.copyRowNum = copyRowCnt; + shape.copyRowNumAlign = nL1SizeAlign; + kTensor = bL1Tensor[copyFinishRowCnt * 16]; + DataCopyPA( + kTensor, oriKvGm, oriBlockTableGm, shape, startPos); + // update loop variable + copyFinishRowCnt += copyRowCnt; + curS2Offset += copyRowCnt; + } + } else if constexpr (KV_LAYOUT_T == SAS_LAYOUT::BSND) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nL1Size; // number of rows + 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; + uint32_t batchStride = constInfo.kvSeqSize * seqStride; + + 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 == SAS_LAYOUT::TND) { + uint32_t curS2Offset = info.s2Idx * constInfo.s2BaseSize + + info.s2StartPoint + nL1 * N_SPLIT_SIZE; + 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 constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + uint32_t curS2Offset = + info.relativeS2Idx * constInfo.s2BaseSize + nL1 * N_SPLIT_SIZE; + while (copyFinishRowCnt < nL1Size) { + // Due to the existence of ori_left, even the first moved block may + // not be the zero position of 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 pending 7buf naming change + startPos.dIdx = + kL1 * 256; // mm1 right matrix bn2s2d, d is the k axis and is + // not split; mm2 right matrix, s2 is the k axis, d + // axis is split + + PAShape shape; + shape.blockSize = constInfo.paCmpBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.kvStride = constInfo.cmpKvStride; + shape.actHeadDim = 256; + shape.maxblockNumPerBatch = constInfo.cmpMaxBlockNumPerBatch; + shape.copyRowNum = copyRowCnt; + shape.copyRowNumAlign = nL1SizeAlign; + kTensor = bL1Tensor[copyFinishRowCnt * 16]; + DataCopyPA( + kTensor, cmpKvGm, cmpBlockTableGm, shape, startPos); + // update loop variable + copyFinishRowCnt += copyRowCnt; + curS2Offset += copyRowCnt; + } + } else if constexpr (KV_LAYOUT_T == SAS_LAYOUT::BSND) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nL1Size; // number of rows + 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; + uint32_t batchStride = + constInfo.kvSeqSize / constInfo.cmpRatio * seqStride; + + uint32_t curS2 = + info.relativeS2Idx * constInfo.s2BaseSize + 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 == SAS_LAYOUT::TND) { + uint32_t curS2Offset = + info.relativeS2Idx * constInfo.s2BaseSize + nL1 * N_SPLIT_SIZE; + 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, + cmpKvGm[info.tensorCmpBOffset + + curS2Offset * 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, + cmpKvGm[info.tensorCmpBOffset + + curS2Offset * constInfo.headDim + + (constInfo.headDim >> 1)], + nd2nzPara); + } + } + } + + SetFlag(mte21KVIds[kb]); + WaitFlag(mte21KVIds[kb]); + mL1Size = M_SPLIT_SIZE; + mL1SizeAlign = SASAlign(M_SPLIT_SIZE, 16U); + for (uint32_t mL1 = 0; mL1 < mL1Loops; mL1++) { + uint32_t aL1PaddingSize = + 0; // used to align the left matrix to the tail so that the two 32K + // memory blocks are contiguous + if (mL1 == (mL1Loops - 1)) { + mL1Size = mSize - (mL1Loops - 1) * M_SPLIT_SIZE; + mL1SizeAlign = SASAlign(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]); + } + // synchronize using unitflag + LocalTensor cL0Tensor = cL0TensorPingPong + [(cL0BufIter % 2) * + (L0C_PP_SIZE / sizeof(MM_OUT_T))]; // must keep cL0BufIter + // consistent with the m pace + 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; + 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]); // reverse synchronization, indicating A in L1 + // has been fully consumed by mte1 + } + + if (kL1 == 1) { // last round of the kL1 loop + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + FixpipeParamsV220 fixParams; + fixParams.nSize = nL1SizeAlign; + fixParams.mSize = mL1SizeAlign; + fixParams.srcStride = mL1SizeAlign; + // change to nSizeAlign + fixParams.dstStride = + info.actualSingleProcessSInnerSizeAlign; // interval between two + // rows of mm1ResGm + fixParams.ndNum = 1; // output 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]); // reverse synchronization, indicating L1 has been + // fully consumed by 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-aligned + uint32_t mL1Size = M_SPLIT_SIZE; // actual size of 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-aligned + uint32_t nL1Size = N_SPLIT_SIZE; // actual size of n + + uint32_t kSize = info.actualSingleProcessSInnerSize; + uint32_t kL1Size = 256; + uint32_t kL1SizeAlign = SASAlign(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 indicates which buf of the left matrix's 4 bufs is selected, kb + // indicates which buf of the right matrix's 3 bufs is selected + uint32_t ka = 0, kb = 0; + uint32_t mBaseIdx = qpL1BufIter; + for (uint32_t nL1 = 0; nL1 < nL1Loops; nL1++) { // n split L1 + if (nL1 == (nL1Loops - 1)) { + // tail block + nL1Size = nSize - (nL1Loops - 1) * N_SPLIT_SIZE; + nL1SizeAlign = SASAlign(nL1Size, 16U); + } + // write k l1 as a single loop, consistent with mm1 + kL1Size = 256; + kL1SizeAlign = SASAlign(kL1Size, 16U); + uint32_t copyRowCnt = 0; + for (uint32_t k1 = 0; k1 < kL1Loops; + k1++) { // k split L1, an l0 layer is nested here to operate + if (k1 == (kL1Loops - 1)) { + // tail block + kL1Size = kSize - (kL1Loops - 1) * K_L1_SPLIT_SIZE; + kL1SizeAlign = SASAlign(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 must be initialized first, then kL0Loops computed, otherwise + // the loop would change kL0Size and cause an incorrect kL0Loops + kL0Loops = (kL1Size + kL0Size - 1) / kL0Size; + kL0SizeAlign = kL0Size; + for (uint32_t kL1 = kOffset; kL1 < kL0Loops + kOffset; + kL1++) { // 128 loop moving pa + if (kL1 == kOffset + kL0Loops - 1) { + // tail block + kL0Size = kL1Size - (kL0Loops - 1) * kL0Size; + kL0SizeAlign = SASAlign(kL0Size, 16U); + } + + uint32_t copyFinishRowCnt = 0; + + if (info.isOri) { + if constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + uint32_t curS2Offset = info.s2Idx * constInfo.s2BaseSize + + info.s2StartPoint + kL1 * K_L0_SPLIT_SIZE; + 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 right matrix bn2s2d, d is the k axis and + // is not split; mm2 right matrix, s2 is the k + // axis, d axis is split + PAShape shape; + shape.blockSize = constInfo.paOriBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.kvStride = constInfo.oriKvStride; + 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); + + // update loop variable + copyFinishRowCnt += copyRowCnt; + curS2Offset += copyRowCnt; + } + } else if constexpr (KV_LAYOUT_T == SAS_LAYOUT::BSND) { + subvTensor = + bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE]; + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = kL0Size; // number of rows + 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; + uint32_t batchStride = constInfo.kvSeqSize * seqStride; + + uint32_t curS2 = info.s2Idx * constInfo.s2BaseSize + + 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 == SAS_LAYOUT::TND) { + uint32_t curS2Offset = info.s2Idx * constInfo.s2BaseSize + + info.s2StartPoint + kL1 * K_L0_SPLIT_SIZE; + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = kL0Size; // number of rows + 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 constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + uint32_t curS2Offset = info.relativeS2Idx * constInfo.s2BaseSize + + 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 pending 7buf naming change + startPos.dIdx = + nL1 * + N_SPLIT_SIZE; // mm1 right matrix bn2s2d, d is the k axis and + // is not split; mm2 right matrix, s2 is the k + // axis, d axis is split + + PAShape shape; + shape.blockSize = constInfo.paCmpBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.kvStride = constInfo.cmpKvStride; + 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); + // update loop variable + copyFinishRowCnt += copyRowCnt; + curS2Offset += copyRowCnt; + } + } else if constexpr (KV_LAYOUT_T == SAS_LAYOUT::BSND) { + subvTensor = + bL1Tensor[(kL1 - kOffset) * K_L0_SPLIT_SIZE * N_SPLIT_SIZE]; + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = kL0Size; // number of rows + 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; + uint32_t batchStride = + constInfo.kvSeqSize / constInfo.cmpRatio * seqStride; + + uint32_t curS2 = info.relativeS2Idx * constInfo.s2BaseSize + + 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 == SAS_LAYOUT::TND) { + uint32_t curS2Offset = info.relativeS2Idx * constInfo.s2BaseSize + + K_L0_SPLIT_SIZE * kL1; + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = kL0Size; // number of rows + 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; // actual size of m + for (uint32_t mL1 = 0; mL1 < mL1Loops; mL1++) { + if (mL1 == (mL1Loops - 1)) { + // tail block + mL1Size = mSize - (mL1Loops - 1) * M_SPLIT_SIZE; + mL1SizeAlign = SASAlign(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))]; // must keep cL0BufIter + // consistent with the m pace + 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 = SASAlign(kL0Size, 16U); + } + WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); + LocalTensor bL0Tensor = + bL0TensorPingPong[(abL0BufIter % 2) * + (L0B_PP_SIZE / sizeof(KV_T))]; + // arch35: 3D loading degenerates to 2D matrix loading (transpose B, + // enTranspose=1 -> ifTranspose=true) + LoadData2DParamsV2 loadData2DParamsForB; + loadData2DParamsForB.mStartPosition = 0; + loadData2DParamsForB.kStartPosition = 0; + loadData2DParamsForB.mStep = (kL0SizeAlign + 15) / 16; + loadData2DParamsForB.kStep = (nL1SizeAlign + 15) / 16; + loadData2DParamsForB.srcStride = (kL0SizeAlign + 15) / 16; + loadData2DParamsForB.dstStride = loadData2DParamsForB.mStep; + loadData2DParamsForB.ifTranspose = true; + LoadData( + bL0Tensor, bL1Tensor[kL0 * baseK * baseN], loadData2DParamsForB); + + LocalTensor aL0Tensor = + aL0TensorPingPong[(abL0BufIter % 2) * + (L0A_PP_SIZE / sizeof(KV_T))]; + // arch35: 3D loading degenerates to 2D matrix loading (no transpose, + // refer to compressor LoadAToL0) + LoadData2DParamsV2 loadData2DParamsForA; + loadData2DParamsForA.mStartPosition = 0; + loadData2DParamsForA.kStartPosition = 0; + loadData2DParamsForA.mStep = (mL1SizeAlign + 15) / 16; + loadData2DParamsForA.kStep = (kL0SizeAlign + 15) / 16; + loadData2DParamsForA.srcStride = (mL1SizeAlign + 15) / 16; + loadData2DParamsForA.dstStride = loadData2DParamsForA.mStep; + loadData2DParamsForA.ifTranspose = false; + LoadData(aL0Tensor, + aL1Tensor[kL0 * baseK * mL1SizeAlign], + loadData2DParamsForA); + 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; + + Mmad(cL0Tensor, aL0Tensor, bL0Tensor, mmadParams); + if ((mmadParams.m / 16) * (mmadParams.n / 16) < 10) { + PipeBarrier(); + } + SetFlag(Mte1MmABEventId(abL0BufIter % 2)); + abL0BufIter++; + } + + if (nL1 == + (nL1Loops - 1)) { // last round of nL1, B needs to stay resident in + // L1 for the next round of computation? + SetFlag( + mte21QPIds[ka]); // reverse synchronization, indicating A in L1 + // has been fully consumed by mte1 + } + + if (k1 == (kL1Loops - 1)) { + // ND + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + FixpipeParamsV220 fixParams; + fixParams.nSize = nL1SizeAlign; + fixParams.mSize = mL1SizeAlign; + fixParams.srcStride = mL1SizeAlign; + fixParams.dstStride = nSize; // interval between two rows of mm2ResGm + fixParams.ndNum = 1; // output ND + + 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]); // reverse synchronization, indicating L1 has been + // fully consumed by mte1 + } + // cL0BufIter is no longer used + if (mL1Loops == 1) { + cL0BufIter++; + } + } + qpL1BufIter += mL1Loops; +} +} // namespace SASKernel +#endif \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_swa_block_vector.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_swa_block_vector.h new file mode 100644 index 0000000000..3c801baf8a --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_swa_block_vector.h @@ -0,0 +1,1134 @@ +/** + * 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_attn_sharedkv_swa_block_vector.h + * \brief + */ +#ifndef SPARSE_ATTN_SHAREDKV_SWA_BLOCK_VECTOR_H +#define SPARSE_ATTN_SHAREDKV_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_attn_sharedkv/op_kernel/sparse_attn_sharedkv_common.h" + +namespace SASKernel { +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +template +class SWAVectorBlock { + public: + // Intermediate computation data type is float, high-precision mode + using T = float; + using KV_T = typename SAST::kvType; + using OUT_T = typename SAST::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 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 SparseAttnSharedkvTilingData* __restrict tilingData); + __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 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); + + // Byte count of BLOCK and REPEAT + static constexpr uint64_t BYTE_BLOCK = 32UL; + static constexpr uint32_t REPEAT_BLOCK_BYTE = 256U; + // FP32 element count of BLOCK and REPEAT + 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 cannot exceed 256 + static constexpr uint32_t REPEATE_STRIDE_UP_BOUND = 256; + + private: + static constexpr bool PAGE_ATTENTION = SAST::pageAttention; + static constexpr bool FLASH_DECODE = SAST::flashDecode; + static constexpr SAS_LAYOUT LAYOUT_T = SAST::layout; + static constexpr SAS_LAYOUT KV_LAYOUT_T = SAST::kvLayout; + + 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); // 32768/4=8096 + static constexpr uint32_t BLOCK_ELEMENT_NUM = + BYTE_BLOCK / sizeof(T); // 32/4=8 + static constexpr uint32_t MAX_N1_SIZE = 128U; + static constexpr T SOFTMAX_MIN_NUM = -2e38; + static constexpr SINKS_T R0 = 1.0f; + + const SparseAttnSharedkvTilingData* __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 blkTableGm_; + GlobalTensor keyGm_; + GlobalTensor kvValidSizeGm_; + GlobalTensor oriKvGm_; + GlobalTensor cmpKvGm_; + GlobalTensor oriBlockTableGm_; + GlobalTensor cmpBlockTableGm_; + GlobalTensor softmaxLseGm; + + // ================================Local Buffer + // region==================================== + TBuf<> inputBuff1; // 32K + TBuf<> inputBuff2; // 16K + 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; +}; + +// ============================== 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)); + // Allocate 256+N1 size memory, where 256 is the maximum VEC tile of the m + // axis + 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(); +} + +template +__aicore__ inline void SWAVectorBlock::InitParams( + const struct ConstInfo& constInfo, + const SparseAttnSharedkvTilingData* __restrict tilingData) { + this->constInfo = constInfo; + this->tilingData = tilingData; +} + +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); + 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); + 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; // Process 8 datablocks each time + Brcb(sinksBrcbUb, sinksUb, repeatTimes, {1, BLOCK_ELEMENT_NUM}); + PipeBarrier(); + + DataCopyParams repeatParams; + repeatParams.blockCount = + 1; // Move until a block exceeds the M-axis size of a single vec core + // after subdivision; inter-core split gives each vec 256 + 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) { + // Since the repeatTimes of the WholeReduceMax interface supports range + // (0,255), WholeReduceMax must be called multiple times; here repeatTime=128 + // is used each time + 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 LocalTensor& mmResUb, + uint32_t dealRowCount, + uint32_t columnCount) { + Muls(mmResUb, + mmResUb, + static_cast(tilingData->baseParams.softmaxScale), + dealRowCount * columnCount); +} + +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 = SASAlign(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 = 0; + if (constInfo.outputLayout == SAS_LAYOUT::TND) { + uint32_t tBase = actualSeqLengthsQGm.GetValue(info.bIdx); + lseOffset = + (tBase + info.s1Idx) * constInfo.gSize + // T-axis and s1-axis offset + info.n2IdxReal * constInfo.qSeqSize * + constInfo.gSize; // N2-axis offset + } else if (constInfo.outputLayout == SAS_LAYOUT::BSND) { + lseOffset = info.bIdx * constInfo.qSeqSize * constInfo.kvHeadNum * + constInfo.gSize + // B-axis offset + info.n2IdxReal * constInfo.qSeqSize * + constInfo.gSize + // N2-axis offset + info.s1Idx * constInfo.gSize; // S1-axis offset + } + 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, 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); + + 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. Align down to 8 because UB operation is at least 32B + // 2. info.actualSingleProcessSInnerSizeAlign is at most 512, mSplitSize can + // ensure a minimum of 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; + + SliceAndContactSinksValue( + (mSplitInfo.nBufferStartM + mSplitInfo.vecStartM) % constInfo.qHeadNum, + 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 switch + } +} + +// =======================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 switch + } +} + +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 + // share count offset + wsMStart * actualColumnCount; // m-axis 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 uses round-half-to-even mode + 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; + + // Except for the first loop, the intermediate computation result must be + // updated + 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 uses temporary memory 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); + } + + // Output the computation result on the last iteration, otherwise store the + // intermediate result to workspace + if (info.isLastS2Loop) { + uint32_t idx = info.loop % (constInfo.preLoadNum); + LocalTensor tmpSumUb = + v0ValidSizeBuff + .Get()[384]; // sumUb uses temporary memory 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); + 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, elements of each row are divided by the same element + // 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; // In the column direction, the start-address interval between two + // repeats is dtypeMask=64 elements, i.e. 8 blocks + columnRepeatParams.src1RepStride = 0; + columnRepeatParams.dstRepStride = + 8; // In the column direction, the start-address interval between two + // repeats is dtypeMask=64 elements, i.e. 8 blocks + 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, elements of each row are multiplied by the same element + // 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) { + // This limitation is because each repeat reads at most 256B of contiguous + // data + repeatElementNum = FP32_REPEAT_ELEMENT_NUM * 2; // 256/4 * 2=128 + blockElementNum = FP32_BLOCK_ELEMENT_NUM * 2; // 32/4 * 2 = 16 + } + + // Only 256B of contiguous data can be read for computation each time, so only + // 256B/sizeof(dType)= can be processed each time Split the column direction + // into dLoop iterations, processing 8 columns of data each time + uint32_t dLoop = actualColumnCount / repeatElementNum; + uint32_t dRemain = actualColumnCount % repeatElementNum; + // REPEATE_STRIDE_UP_BOUND=256, this limitation is because the src0RepStride + // data type is uint8 with at most 256 datablock intervals + 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; + + // If the repeat count processed by column is less than that by row, process + // by column; otherwise process the repeat by row + 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; // In the column direction, the start-address interval between two + // repeats is dtypeMask=64 elements, i.e. 8 blocks + columnRepeatParams.src1RepStride = 0; + columnRepeatParams.dstRepStride = + 8; // In the column direction, the start-address interval between two + // repeats is dtypeMask=64 elements, i.e. 8 blocks + for (uint32_t i = 0; i < dealRowCount; i++) { + Mul(dstUb[i * columnCount], + src0Ub[i * columnCount], + src1Ub[i * blockElementNum], + repeatElementNum, + dLoop, + columnRepeatParams); + } + } + + // The last time completes [dealRowCount, dRemain] * [dealRowCount, + // blockElementNum], computing only the valid part + if (dRemain > 0) { + Mul(dstUb[dLoop * repeatElementNum], + src0Ub[dLoop * repeatElementNum], + src1Ub, + dRemain, + dealRowCount, + repeatParams); + } + } else { + BinaryRepeatParams repeatParams; + repeatParams.src0RepStride = + 8; // Each repeat is 256B of data, exactly 8 datablocks + repeatParams.src0BlkStride = 1; + repeatParams.src1RepStride = 0; + repeatParams.src1BlkStride = 0; + repeatParams.dstRepStride = 8; + repeatParams.dstBlkStride = 1; + // Compute one row each time, computing dealRowCount rows in total + for (uint32_t i = 0; i < dealRowCount; i++) { + // Compute dLoop repeats in one row, each repeat computes 256/block_size + // data_blocks + Mul(dstUb[i * columnCount], + src0Ub[i * columnCount], + src1Ub[i * blockElementNum], + repeatElementNum, + dLoop, + repeatParams); + // Compute the tail block in one row + if (dRemain > 0) { + Mul(dstUb[i * columnCount + dLoop * repeatElementNum], + src0Ub[i * columnCount + dLoop * repeatElementNum], + src1Ub[i * blockElementNum], + dRemain, + 1, + repeatParams); + } + } + } +} +} // namespace SASKernel +#endif \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_swa_kernel.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_swa_kernel.h new file mode 100644 index 0000000000..3297b5c7ca --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/arch35/sparse_attn_sharedkv_swa_kernel.h @@ -0,0 +1,933 @@ +/** + * 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_attn_sharedkv_swa_kernel.h + * \brief + */ + +#ifndef SPARSE_ATTN_SHAREDKV_SWA_KERNEL_H +#define SPARSE_ATTN_SHAREDKV_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_attn_sharedkv/op_kernel/sparse_attn_sharedkv_common.h" +#include "sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_metadata.h" +#include "sparse_attn_sharedkv_swa_block_cube.h" +#include "sparse_attn_sharedkv_swa_block_vector.h" + +namespace SASKernel { +using namespace matmul; +using namespace optiling; +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +// Before the S2 loop, RunInfo is not yet assigned, so use Bngs1Param to +// temporarily store info related to the B, N, S1 axes; this also reduces +// redundant computation +struct SwaTempLoopInfo { + uint32_t bn2IdxInCurCore = 0; + uint32_t bIdx = 0U; + uint32_t n2Idx = 0U; + uint64_t s2BasicSizeTail = + 0U; // Tail basic block size of the S2 direction loop + uint32_t s2LoopTimes = + 0U; // Total number of S2 direction loop iterations; equals the actual + // count for both TND and BXXD, no need to subtract 1 + + int32_t actS1Size = 0; // Size of the S1 axis processed in the current Batch + // loop under the TND scenario + 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; // Tail basic block size of the gS1 direction loop + uint32_t cmpLoopTimes = 0; + uint32_t oriLoopTimes = 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 SparseAttnSharedkvSwa { + public: + // Intermediate computation data type is float, high-precision mode + using T = float; + using Q_T = typename SAST::queryType; + using KV_T = typename SAST::kvType; + using OUT_T = typename SAST::outputType; + using SINKS_T = float; + using UPDATE_T = T; + using MM1_OUT_T = T; + using MM2_OUT_T = T; + + __aicore__ inline SparseAttnSharedkvSwa(){}; + __aicore__ inline void Init( + __gm__ uint8_t* query, + __gm__ uint8_t* oriKV, + __gm__ uint8_t* cmpKV, + __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* sinks, + __gm__ uint8_t* metadata, + __gm__ uint8_t* attentionOut, + __gm__ uint8_t* softmaxLse, + __gm__ uint8_t* workspace, + const SparseAttnSharedkvTilingData* __restrict tiling, + __gm__ uint8_t* gmTiling, + TPipe* tPipe); + + __aicore__ inline void Process(); + + private: + static constexpr bool PAGE_ATTENTION = SAST::pageAttention; + static constexpr int TEMPLATE_MODE = SAST::templateMode; + static constexpr bool FLASH_DECODE = SAST::flashDecode; + static constexpr SAS_LAYOUT LAYOUT_T = SAST::layout; + static constexpr SAS_LAYOUT KV_LAYOUT_T = SAST::kvLayout; + + static constexpr uint32_t PRELOAD_NUM = 2; + static constexpr uint32_t N_BUFFER_M_BASIC_SIZE = 256; + static constexpr uint32_t SAS_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 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 kvHeadNum = 1ULL; + 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 SparseAttnSharedkvTilingData* __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 actualSeqLengthsQGm; + GlobalTensor actualSeqLengthsKVGm; + GlobalTensor actualSeqLengthsCmpKVGm; + + // workspace + GlobalTensor mm1ResGm; + GlobalTensor vec1ResGm; + GlobalTensor mm2ResGm; + + 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[SAS_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 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 SparseAttnSharedkvSwa::InitTilingData() { + // singleCoreParams + // singleCoreTensorSize + constInfo.mmResUbSize = tilingData->baseParams.mmResUbSize; + constInfo.bmm2ResUbSize = tilingData->baseParams.bmm2ResUbSize; + // baseParams + constInfo.batchSize = tilingData->baseParams.batchSize; + constInfo.qHeadNum = constInfo.gSize = + tilingData->baseParams.nNumOfQInOneGroup; + 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.kvHeadNum = kvHeadNum; + constInfo.headDim = headDim; + constInfo.oriMaskMode = tilingData->baseParams.oriMaskMode; + constInfo.oriKvStride = tilingData->baseParams.oriKvStride; + constInfo.oriWinLeft = tilingData->baseParams.oriWinLeft; + constInfo.oriWinRight = tilingData->baseParams.oriWinRight; + constInfo.returnSoftmaxLse = tilingData->baseParams.returnSoftmaxLse; + + constInfo.actualLenDimsQ = tilingData->baseParams.actualLenDimsQ; + constInfo.actualLenDimsKV = tilingData->baseParams.actualLenDimsKV; + + // innerSplitParams + constInfo.mBaseSize = constInfo.gSize; + ; + constInfo.s2BaseSize = tilingData->baseParams.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; + constInfo.templateMode = TEMPLATE_MODE; + + // cmp + if (constInfo.templateMode == CFA_TEMPLATE) { + constInfo.cmpRatio = tilingData->cmpParams.cmpRatio; + constInfo.cmpMaskMode = tilingData->cmpParams.cmpMaskMode; + constInfo.cmpKvStride = tilingData->cmpParams.cmpKvStride; + constInfo.cmpMaxBlockNumPerBatch = + tilingData->cmpParams.cmpMaxBlockNumPerBatch; + } +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::InitBuffers() { + if ASCEND_IS_AIV { + vectorBlock.InitBuffers(pipe); + } else { + cubeBlock.InitBuffers(pipe); + } +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::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 SparseAttnSharedkvSwa::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.templateMode == CFA_TEMPLATE) { + actualSeqLengthsCmpKVGm.SetGlobalBuffer( + (__gm__ int32_t*)actualSeqLengthsCmpKV, constInfo.actualLenDimsKV); + } + } + if (constInfo.actualLenDimsQ != 0) { + actualSeqLengthsQGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsQ, + constInfo.actualLenDimsQ); + } +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::InitAllZeroOutput( + uint32_t bIdx, + uint32_t s1Idx, + uint32_t n2Idx) { + if (constInfo.outputLayout == SAS_LAYOUT::TND) { + if (tempLoopInfo.actS1Size == 0) { + return; + } + uint32_t tBase = actualSeqLengthsQGm.GetValue(bIdx); + uint64_t attenOutOffset = + (tBase + s1Idx) * kvHeadNum * constInfo.gSize * + headDim + // T axis and s1 axis offset + n2Idx * constInfo.gSize * headDim; // N2 axis offset + uint64_t lseOffset = + (tBase + s1Idx) * constInfo.gSize + // T axis and s1 axis offset + n2Idx * constInfo.qSeqSize * constInfo.gSize; // N2 axis offset + matmul::InitOutput( + attentionOutGm[attenOutOffset], constInfo.gSize * headDim, 0); + if (constInfo.returnSoftmaxLse) { + matmul::InitOutput(softmaxLseGm[lseOffset], constInfo.gSize, 0); + } + } else if (constInfo.outputLayout == SAS_LAYOUT::BSND) { + uint64_t attenOutOffset = + bIdx * constInfo.qSeqSize * kvHeadNum * constInfo.gSize * headDim + + s1Idx * kvHeadNum * constInfo.gSize * + headDim + // B axis and S1 axis offset + n2Idx * constInfo.gSize * headDim; // N2 axis offset + uint64_t lseOffset = + bIdx * constInfo.qSeqSize * constInfo.kvHeadNum * + constInfo.gSize + // B axis offset + n2Idx * constInfo.qSeqSize * constInfo.gSize + // N2 axis offset + s1Idx * constInfo.gSize; // S1 axis offset + matmul::InitOutput( + attentionOutGm[attenOutOffset], constInfo.gSize * headDim, 0); + if (constInfo.returnSoftmaxLse) { + matmul::InitOutput(softmaxLseGm[lseOffset], constInfo.gSize, 0); + } + } +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::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 SparseAttnSharedkvSwa::GetActualSeqLenQ( + uint32_t bIdx) { + if constexpr (LAYOUT_T == SAS_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 SparseAttnSharedkvSwa::GetActualSeqLenKV( + uint32_t bIdx) { + if constexpr (KV_LAYOUT_T == SAS_LAYOUT::PA_ND) { + 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 == SAS_LAYOUT::BSND) { + return static_cast(constInfo.kvSeqSize); + } else if constexpr (KV_LAYOUT_T == SAS_LAYOUT::TND) { + int32_t actualSeqKVPrefixSum = actualSeqLengthsKVGm.GetValue(bIdx); + int32_t actualSeqKVNextSum = actualSeqLengthsKVGm.GetValue(bIdx + 1); + if (constInfo.templateMode == CFA_TEMPLATE) { + tempLoopInfo.actualSeqCmpKVPrefixSum = + actualSeqLengthsCmpKVGm.GetValue(bIdx); + } + tempLoopInfo.actualSeqKVPrefixSum = actualSeqKVPrefixSum; + return actualSeqKVNextSum - actualSeqKVPrefixSum; + } +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::GetSparseActualSeqLen() { + // Row invalidity is determined by the ori part; if the ori part has invalid + // rows, then both ori and cmp have them + if (static_cast(tempLoopInfo.s1EndIdx) < + -(tempLoopInfo.actOriS2Size - tempLoopInfo.actS1Size)) { + tempLoopInfo.actOriS2Size = 0; + tempLoopInfo.actCmpS2Size = 0; + return; + } + + // For the cmp part there is also top k; tempLoopInfo.actS2Size applies only + // to cmp + if (constInfo.templateMode == CFA_TEMPLATE) { + int32_t thresHold = + (tempLoopInfo.cmpMaskRight + tempLoopInfo.s1EndIdx + 1) / + constInfo.cmpRatio; + tempLoopInfo.actCmpS2Size = thresHold; + } +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::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 SparseAttnSharedkvSwa::Init( + __gm__ uint8_t* query, + __gm__ uint8_t* oriKV, + __gm__ uint8_t* cmpKV, + __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* sinks, + __gm__ uint8_t* metadata, + __gm__ uint8_t* attentionOut, + __gm__ uint8_t* softmaxLse, + __gm__ uint8_t* workspace, + const SparseAttnSharedkvTilingData* __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 == SAS_LAYOUT::TND && LAYOUT_T == SAS_LAYOUT::TND) { + InitActualSeqLen(cuSeqlensQ, cuSeqlensKV, cuSeqlensCmpKV); + } else if (KV_LAYOUT_T == SAS_LAYOUT::TND) { + InitActualSeqLen(seqUsedQ, cuSeqlensKV, cuSeqlensCmpKV); + } else if ((KV_LAYOUT_T == SAS_LAYOUT::PA_ND || + KV_LAYOUT_T == SAS_LAYOUT::BSND) && + LAYOUT_T == SAS_LAYOUT::TND) { + InitActualSeqLen(cuSeqlensQ, seqUsedKV); + } else if ((KV_LAYOUT_T == SAS_LAYOUT::PA_ND || + KV_LAYOUT_T == SAS_LAYOUT::BSND)) { + InitActualSeqLen(seqUsedQ, seqUsedKV); + } + 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 (constInfo.templateMode == CFA_TEMPLATE) { + cmpKvGm.SetGlobalBuffer((__gm__ KV_T*)cmpKV); + } + + 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 != SAS_LAYOUT::TND) { + if (constInfo.needInit) { + InitOutputSingleCore(); + } + } + } + + if constexpr (PAGE_ATTENTION) { + oriBlockTableGm.SetGlobalBuffer((__gm__ int32_t*)oriBlockTable); + if (constInfo.templateMode == CFA_TEMPLATE) { + cmpBlockTableGm.SetGlobalBuffer((__gm__ int32_t*)cmpBlockTable); + } + } + + // workspace memory layout + // |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 ASCEND_IS_AIV { + vectorBlock.InitParams(constInfo, tilingData); + 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); + } + // Must be executed after InitParams + if (pipe != nullptr) { + InitBuffers(); + } +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::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 SparseAttnSharedkvSwa::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; + + // M direction tail block + 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) { + tensorACoreOffset = tndBIdxOffsetForQ + info.gS1Idx * 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 (s2LoopIdx < tempLoopInfo.oriLoopTimes) { + // The first S2 loop can only be in ori_kv + info.isOri = 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 = 0; + } else { + if (constInfo.templateMode == CFA_TEMPLATE) { + info.isOri = 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; + } + } + + info.actualSingleProcessSInnerSizeAlign = SASAlign( + info.actualSingleProcessSInnerSize, SASVectorBlock::BYTE_BLOCK); +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::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 SparseAttnSharedkvSwa::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 SparseAttnSharedkvSwa::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 SparseAttnSharedkvSwa::GetBN2Idx(uint32_t bN2Idx, + uint32_t& bIdx, + uint32_t& n2Idx) { + bIdx = bN2Idx / kvHeadNum; + n2Idx = bN2Idx % kvHeadNum; +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::ProcessBalance() { + RunInfo extraInfo[SAS_PRELOAD_TASK_CACHE_SIZE]; + uint32_t gloop = 0; + uint32_t cmpLoop = 0; + uint32_t gS1LoopEnd = 0; + bool globalLoopStart = true; + // Adapt to left-closed right-open interval + 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); // Get actualSeqLength + bool isS1ZeroAndLastBatch = (tempLoopInfo.actS1Size == 0) && + ((constInfo.outputLayout == SAS_LAYOUT::BSND) || + (bN2LoopIdx + 1 == constInfo.bN2End)); + uint32_t gS1SplitNum = + CeilDiv(tempLoopInfo.actS1Size * constInfo.gSize, constInfo.mBaseSize); + + // When at the last BN2 and gS1End is 0, it means all data in the current + // BN2 is processed by the current core + gS1LoopEnd = (bN2LoopIdx == constInfo.bN2End - 1 && constInfo.gS1End != 0) + ? constInfo.gS1End + : gS1SplitNum; + // When at the last BN2 and the current S1 is 0, we need to enter the loop + // to compute the unfinished part caused by preload + gS1LoopEnd = isS1ZeroAndLastBatch ? gS1LoopEnd + 1 : gS1LoopEnd; + for (uint32_t gS1LoopIdx = constInfo.gS1Start; gS1LoopIdx < gS1LoopEnd; + gS1LoopIdx++) { + tempLoopInfo.actOriS2Size = GetActualSeqLenKV(tempLoopInfo.bIdx); + // For the real idx on each axis, use a left-closed right-closed scheme + tempLoopInfo.gS1Idx = gS1LoopIdx * constInfo.mBaseSize; + tempLoopInfo.s1StartIdx = tempLoopInfo.gS1Idx / constInfo.gSize; + tempLoopInfo.s1EndIdx = Min( + (tempLoopInfo.s1StartIdx + constInfo.mBaseSize / constInfo.gSize - 1), + tempLoopInfo.actS1Size - 1); + // Both are closed intervals here + 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); + if (constInfo.templateMode == CFA_TEMPLATE) { + tempLoopInfo.cmpMaskRight = + tempLoopInfo.actOriS2Size - tempLoopInfo.actS1Size; + } + GetSparseActualSeqLen(); + UpdateInnerLoopCond(); + uint32_t oriSplitNum = 0; + uint32_t s2SplitNum = 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(tempLoopInfo.oriMaskRight - tempLoopInfo.oriMaskLeft + 1, + constInfo.s2BaseSize); + s2SplitNum = oriSplitNum; + if (constInfo.templateMode == CFA_TEMPLATE) { + uint32_t cmpSplitNum = + CeilDiv(tempLoopInfo.actCmpS2Size, constInfo.s2BaseSize); + s2SplitNum = oriSplitNum + cmpSplitNum; + tempLoopInfo.cmpLoopTimes = cmpSplitNum; + } + } + tempLoopInfo.s2LoopTimes = s2SplitNum; + tempLoopInfo.oriLoopTimes = oriSplitNum; + uint32_t s2LoopEnd = (isEnd && constInfo.s2End != 0) + ? constInfo.s2End + : tempLoopInfo.s2LoopTimes; + tempLoopInfo.s2LoopTimes = s2LoopEnd; + // Needs to be enabled after core splitting modification + // Whether the current s2 is split determines whether the output should be + // written to attenOut + tempLoopInfo.tndIsS2SplitCore = + ((constInfo.s2Start == 0) && (s2LoopEnd == s2SplitNum)) ? false + : true; + tempLoopInfo.tndCoreStartKVSplitPos = + globalLoopStart ? constInfo.coreStartKVSplitPos : 0; + uint32_t extraLoop = isEnd ? PRELOAD_NUM : 0; + + for (uint32_t s2LoopIdx = constInfo.s2Start; + s2LoopIdx < (s2LoopEnd + extraLoop); + s2LoopIdx++) { + // PreloadPipeline loop requires an initial value of PRELOAD_NUM + PreloadPipeline( + gloop, cmpLoop, constInfo.s2Start, s2LoopIdx, extraInfo); + ++gloop; + } + globalLoopStart = false; + constInfo.s2Start = 0; + } + constInfo.gS1Start = 0; + } +} + +template +__aicore__ inline void SparseAttnSharedkvSwa::PreloadPipeline( + uint32_t loop, + uint32_t cmpLoop, + uint64_t s2Start, + uint64_t s2LoopIdx, + RunInfo extraInfo[SAS_PRELOAD_TASK_CACHE_SIZE]) { + RunInfo& extraInfo0 = + extraInfo[loop % SAS_PRELOAD_TASK_CACHE_SIZE]; // Current round task + RunInfo& extraInfo2 = + extraInfo[(loop + 2) % + SAS_PRELOAD_TASK_CACHE_SIZE]; // Previous round task + RunInfo& extraInfo1 = + extraInfo[(loop + 1) % + SAS_PRELOAD_TASK_CACHE_SIZE]; // Two rounds ago task + + CalcParams(loop, cmpLoop, s2Start, s2LoopIdx, extraInfo0); + if (extraInfo0.isValid) { + 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; + } +} +} // namespace SASKernel +#endif // SPARSE_ATTN_SHAREDKV_SWA_KERNEL_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_common.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_common.h new file mode 100644 index 0000000000..7b1c04aec2 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_common.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 sparse_attn_sharedkv_common.h + * \brief + */ + +#ifndef SPARSE_ATTN_SHAREDKV_COMMON_H +#define SPARSE_ATTN_SHAREDKV_COMMON_H + +#include "kernel_operator.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" + +namespace SASKernel { +using namespace AscendC; +// 将isCheckTiling设置为false, 输入输出的max&sum&exp的shape为(m, 1) +constexpr SoftmaxConfig SAS_SOFTMAX_FLASHV2_CFG_WITHOUT_BRC = { + false, + 0, + 0, + SoftmaxMode::SOFTMAX_OUTPUT_WITHOUT_BRC}; + +enum class SAS_RUN_MODE { + SWA_MODE = 0, + SCFA_MODE = 1, + CFA_MODE = 2, +}; + +enum class SAS_LAYOUT { BSND = 0, TND = 1, PA_ND = 2 }; + +template +struct SASType { + using queryType = Q_T; + using kvType = KV_T; + using outputType = OUT_T; + static constexpr bool flashDecode = FLASH_DECODE; + static constexpr SAS_LAYOUT layout = LAYOUT_T; + static constexpr SAS_LAYOUT kvLayout = KV_LAYOUT_T; + static constexpr bool pageAttention = (KV_LAYOUT_T == SAS_LAYOUT::PA_ND); + static constexpr int templateMode = TEMPLATE_MODE; +}; + +// ================================Util +// functions================================== +template +__aicore__ inline T1 SASAlign(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; + uint32_t s1Idx; +}; + +// 场景: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分 BNBD(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.blockSize * shape.headNum * + // shape.headDim; // PA的偏移 + uint64_t offset = idInBlockTable * shape.kvStride; // PA的偏移 + uint64_t dStride = shape.headDim; + 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; + } +} + +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 attenMaskOffset = 0; + uint64_t topKBaseOffset = 0; + uint32_t actualSingleProcessSInnerSize = 0; + uint32_t actualSingleProcessSInnerSizeAlign = 0; + bool isFirstSInnerLoop = false; + 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 isBmm2Output = false; + bool isValid = false; + + static constexpr uint32_t n2Idx = 0; + uint64_t actS1Size = 1; + uint64_t actS2SizeOri = 0ULL; + uint32_t gS1Idx = 0; + uint64_t actS2Size = 1; + uint64_t actOriS2Size = 1; + uint32_t actMBaseSize = 0; + bool isLastS2Loop = 0; + int32_t nextTokensPerBatch = 0; + int64_t threshold = 0; + uint32_t curTopKIdx = 0; + uint64_t curOffsetInSparseBlock = 0; + bool isOri = true; // 判断当前块是在Ori部分还是Cmp部分 + uint64_t s2StartPoint = 0; + int64_t cmpS2IdLimit = 0; + int32_t v0S2DealSize = 0; + int32_t v0S2Start = 0; +}; + +struct ConstInfo { + // CUBE与VEC核间同步的模式 + static constexpr uint32_t SAS_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上的大小 + 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核间切分的切分份数 + SAS_LAYOUT outputLayout; // 输出的Transpose格式 + uint32_t oriMaskMode = 0; + uint32_t cmpMaskMode = 0; + uint32_t oriKvStride = 0; + uint32_t cmpKvStride = 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 的维度 + + // 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; + + // cmp attr + int64_t cmpRatio = 0; + + // win + int32_t oriWinRight = 0; + int32_t oriWinLeft = 128; + + // 是否返回SoftmaxLse + 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 SASKernel +#endif // SPARSE_ATTN_SHAREDKV_COMMON_H \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_metadata.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_metadata.h new file mode 100644 index 0000000000..2a84388dcf --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_metadata.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 sparse_attn_sharedkv_metadata.h + * \brief + */ + +#ifndef SPARSE_ATTN_SHAREDKV_METADATA_H +#define SPARSE_ATTN_SHAREDKV_METADATA_H + +#include + +namespace optiling { + +// Constants +constexpr uint32_t AIC_CORE_NUM = 36; +constexpr uint32_t AIV_CORE_NUM = 72; +constexpr uint32_t SAS_META_SIZE = 1024; +using SAS_METADATA_T = int32_t; + +constexpr uint32_t FA_METADATA_SIZE = 8; +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; + +// 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(SAS_META_SIZE * sizeof(SAS_METADATA_T) >= + sizeof(detail::SasMetaData)); +} // namespace optiling + +#endif \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_template_tiling_key.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_template_tiling_key.h new file mode 100644 index 0000000000..2cb43c53c9 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_template_tiling_key.h @@ -0,0 +1,96 @@ +/** + * 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_attn_sharedkv_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 SAS_LAYOUT_BSND 0 +#define SAS_LAYOUT_TND 1 +#define SAS_LAYOUT_PA_ND 2 + +#define ASCENDC_TPL_4_BW 4 + +#define SWA_TEMPLATE 0 +#define CFA_TEMPLATE 1 +#define SCFA_TEMPLATE 2 +// 模板参数支持的范围定义 +ASCENDC_TPL_ARGS_DECL(XllmKernelSparseAttnSharedkv, // 算子OpType + ASCENDC_TPL_BOOL_DECL(FLASH_DECODE, 0, 1), + ASCENDC_TPL_UINT_DECL(LAYOUT_T, + ASCENDC_TPL_4_BW, + ASCENDC_TPL_UI_LIST, + SAS_LAYOUT_BSND, + SAS_LAYOUT_TND), + ASCENDC_TPL_UINT_DECL(KV_LAYOUT_T, + ASCENDC_TPL_4_BW, + ASCENDC_TPL_UI_LIST, + SAS_LAYOUT_PA_ND, + SAS_LAYOUT_BSND, + SAS_LAYOUT_TND), + ASCENDC_TPL_UINT_DECL(TEMPLATE_MODE, + ASCENDC_TPL_4_BW, + ASCENDC_TPL_UI_LIST, + SWA_TEMPLATE, + CFA_TEMPLATE, + SCFA_TEMPLATE), ); + +// 支持的模板参数组合 +// 用于调用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, + SAS_LAYOUT_BSND, + SAS_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SAS_LAYOUT_PA_ND, + SAS_LAYOUT_BSND, + SAS_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, + ASCENDC_TPL_UI_LIST, + SWA_TEMPLATE), ), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SAS_LAYOUT_BSND, + SAS_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SAS_LAYOUT_PA_ND, + SAS_LAYOUT_BSND, + SAS_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, + ASCENDC_TPL_UI_LIST, + CFA_TEMPLATE), ), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SAS_LAYOUT_BSND, + SAS_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SAS_LAYOUT_PA_ND, + SAS_LAYOUT_BSND, + SAS_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, + ASCENDC_TPL_UI_LIST, + SCFA_TEMPLATE), ), ); + +#endif // TEMPLATE_TILING_KEY \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/xllm_kernel_sparse_attn_sharedkv.cpp b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/xllm_kernel_sparse_attn_sharedkv.cpp new file mode 100644 index 0000000000..c2b392dad9 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv/op_kernel/xllm_kernel_sparse_attn_sharedkv.cpp @@ -0,0 +1,132 @@ +/** + * 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_attn_sharedkv.cpp + * \brief + */ + +#include "kernel_operator.h" +#include "lib/matmul_intf.h" +#include "sparse_attn_sharedkv_template_tiling_key.h" +#if (__CCE_AICORE__ == 220) +#include "arch32/sparse_attn_sharedkv_scfa_kernel.h" +#include "arch32/sparse_attn_sharedkv_swa_kernel.h" +#else +#include "arch35/sparse_attn_sharedkv_scfa_kernel.h" +#include "arch35/sparse_attn_sharedkv_swa_kernel.h" +#endif +#include "sparse_attn_sharedkv_metadata.h" + +using namespace AscendC; +using namespace optiling::detail; +using namespace SASKernel; + +#define SAS_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, \ + cmpSparseIndices, \ + oriBlockTable, \ + cmpBlockTable, \ + cuSeqlensQ, \ + cuSeqlensOriKv, \ + cuSeqlensCmpKv, \ + seqUsedQ, \ + seqUsedKV, \ + sinks, \ + metadata, \ + attentionOut, \ + softmaxLse, \ + user, \ + tiling_data, \ + tiling, \ + &tPipe); \ + op.Process(); \ + } while (0) + +template +__global__ __aicore__ void xllm_kernel_sparse_attn_sharedkv( + __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* seqUsedKV, + __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); + + TPipe tPipe; + __gm__ uint8_t* user = GetUserWorkspace(workspace); + if constexpr (ORIG_DTYPE_Q == DT_FLOAT16 && ORIG_DTYPE_ORI_KV == DT_FLOAT16 && + ORIG_DTYPE_ATTN_OUT == DT_FLOAT16) { + if constexpr (TEMPLATE_MODE == SCFA_TEMPLATE) { + SAS_OP_IMPL(SparseAttnSharedkvScfa, + SparseAttnSharedkvTilingData, + half, + half, + half, + FLASH_DECODE, + static_cast(LAYOUT_T), + static_cast(KV_LAYOUT_T), + TEMPLATE_MODE); + } else { + SAS_OP_IMPL(SparseAttnSharedkvSwa, + SparseAttnSharedkvTilingData, + half, + half, + half, + FLASH_DECODE, + static_cast(LAYOUT_T), + static_cast(KV_LAYOUT_T), + TEMPLATE_MODE); + } + } + if constexpr (ORIG_DTYPE_Q == DT_BF16 && ORIG_DTYPE_ORI_KV == DT_BF16 && + ORIG_DTYPE_ATTN_OUT == DT_BF16) { + if constexpr (TEMPLATE_MODE == SCFA_TEMPLATE) { + SAS_OP_IMPL(SparseAttnSharedkvScfa, + SparseAttnSharedkvTilingData, + bfloat16_t, + bfloat16_t, + bfloat16_t, + FLASH_DECODE, + static_cast(LAYOUT_T), + static_cast(KV_LAYOUT_T), + TEMPLATE_MODE); + } else { + SAS_OP_IMPL(SparseAttnSharedkvSwa, + SparseAttnSharedkvTilingData, + bfloat16_t, + bfloat16_t, + bfloat16_t, + FLASH_DECODE, + static_cast(LAYOUT_T), + static_cast(KV_LAYOUT_T), + TEMPLATE_MODE); + } + } +} \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/SOURCE.txt b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/SOURCE.txt new file mode 100644 index 0000000000..7d73151b35 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/SOURCE.txt @@ -0,0 +1,7 @@ +SparseAttnSharedkvMetadata CANN implementation + +Source: https://gitcode.com/xLLM-AI/xllm_ops +Revision: 8bd2b014c38fec33ecf14dd33e05e8ad792ec5c8 +Directory: xllm_ops/attention/sparse_attn_sharedkv_metadata + +Packaged under a private CANN operator type and ACLNN entry points. diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_api/aclnn_sparse_attn_sharedkv_metadata.cpp b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_api/aclnn_sparse_attn_sharedkv_metadata.cpp new file mode 100644 index 0000000000..421c96a5ad --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_api/aclnn_sparse_attn_sharedkv_metadata.cpp @@ -0,0 +1,211 @@ +/** + * 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_attn_sharedkv_metadata.cpp + * \brief + */ + +#include "aclnn_sparse_attn_sharedkv_metadata.h" + +#include "aclnn/aclnn_base.h" +#include "aclnn_kernels/common/op_error_check.h" +#include "aclnn_kernels/contiguous.h" +#include "l0_sparse_attn_sharedkv_metadata.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" + +#ifdef __cplusplus +extern "C" { +#endif + +static aclnnStatus ParamsCheck(const aclTensor* cuSeqLensQOptional, + const aclTensor* cuSeqLensOriKvOptional, + const aclTensor* cuSeqLensCmpKvOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKvOptional, + int64_t numHeadsQ, + int64_t numHeadsKv, + int64_t headDim, + int64_t batchSizeOptional, + int64_t maxSeqlenQOptional, + int64_t maxSeqlenKvOptional, + int64_t oriTopKOptional, + int64_t cmpTopKOptional, + int64_t cmpRatioOptional, + int64_t oriMaskModeOptional, + int64_t cmpMaskModeOptional, + int64_t oriWinLeftOptional, + int64_t oriWinRightOptional, + char* layoutQOptional, + char* layoutKvOptional, + bool hasOriKvOptional, + bool hasCmpKvOptional, + const aclTensor* metaData) { + return ACLNN_SUCCESS; +} + +aclnnStatus aclnnXllmKernelSparseAttnSharedkvMetadataGetWorkspaceSize( + const aclTensor* cuSeqLensQOptional, + const aclTensor* cuSeqLensOriKvOptional, + const aclTensor* cuSeqLensCmpKvOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKvOptional, + int64_t numHeadsQ, + int64_t numHeadsKv, + int64_t headDim, + int64_t batchSizeOptional, + int64_t maxSeqlenQOptional, + int64_t maxSeqlenKvOptional, + int64_t oriTopKOptional, + int64_t cmpTopKOptional, + int64_t cmpRatioOptional, + int64_t oriMaskModeOptional, + int64_t cmpMaskModeOptional, + int64_t oriWinLeftOptional, + int64_t oriWinRightOptional, + char* layoutQOptional, + char* layoutKvOptional, + bool hasOriKvOptional, + bool hasCmpKvOptional, + const aclTensor* metaData, + uint64_t* workspaceSize, + aclOpExecutor** executor) { + L2_DFX_PHASE_1(aclnnXllmKernelSparseAttnSharedkvMetadata, + DFX_IN(cuSeqLensQOptional, + cuSeqLensOriKvOptional, + cuSeqLensCmpKvOptional, + sequsedQOptional, + sequsedKvOptional, + numHeadsQ, + numHeadsKv, + headDim, + batchSizeOptional, + maxSeqlenQOptional, + maxSeqlenKvOptional, + oriTopKOptional, + cmpTopKOptional, + cmpRatioOptional, + oriMaskModeOptional, + cmpMaskModeOptional, + oriWinLeftOptional, + oriWinRightOptional, + layoutQOptional, + layoutKvOptional, + hasOriKvOptional, + hasCmpKvOptional), + DFX_OUT(metaData)); + + auto uniqueExecutor = CREATE_EXECUTOR(); + CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + + auto ret = ParamsCheck(cuSeqLensQOptional, + cuSeqLensOriKvOptional, + cuSeqLensCmpKvOptional, + sequsedQOptional, + sequsedKvOptional, + numHeadsQ, + numHeadsKv, + headDim, + batchSizeOptional, + maxSeqlenQOptional, + maxSeqlenKvOptional, + oriTopKOptional, + cmpTopKOptional, + cmpRatioOptional, + oriMaskModeOptional, + cmpMaskModeOptional, + oriWinLeftOptional, + oriWinRightOptional, + layoutQOptional, + layoutKvOptional, + hasOriKvOptional, + hasCmpKvOptional, + metaData); + CHECK_RET(ret == ACLNN_SUCCESS, ret); + + const op::PlatformInfo& npuInfo = op::GetCurrentPlatformInfo(); + uint32_t aicCoreNum = npuInfo.GetCubeCoreNum(); + uint32_t aivCoreNum = npuInfo.GetVectorCoreNum(); + const char* socVersion = npuInfo.GetSocLongVersion().c_str(); + + auto cuSeqLensQOptionalContiguous = + l0op::Contiguous(cuSeqLensQOptional, uniqueExecutor.get()); + CHECK_RET(cuSeqLensQOptionalContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); + auto cuSeqLensOriKvOptionalContiguous = + l0op::Contiguous(cuSeqLensOriKvOptional, uniqueExecutor.get()); + CHECK_RET(cuSeqLensOriKvOptionalContiguous != nullptr, + ACLNN_ERR_INNER_NULLPTR); + auto cuSeqLensCmpKvOptionalContiguous = + l0op::Contiguous(cuSeqLensCmpKvOptional, uniqueExecutor.get()); + CHECK_RET(cuSeqLensCmpKvOptionalContiguous != nullptr, + ACLNN_ERR_INNER_NULLPTR); + auto sequsedQOptionalContiguous = + l0op::Contiguous(sequsedQOptional, uniqueExecutor.get()); + CHECK_RET(sequsedQOptionalContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); + auto sequsedKvOptionalContiguous = + l0op::Contiguous(sequsedKvOptional, uniqueExecutor.get()); + CHECK_RET(sequsedKvOptionalContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); + + auto output = l0op::XllmKernelSparseAttnSharedkvMetadata( + cuSeqLensQOptionalContiguous, + cuSeqLensOriKvOptionalContiguous, + cuSeqLensCmpKvOptionalContiguous, + sequsedQOptionalContiguous, + sequsedKvOptionalContiguous, + numHeadsQ, + numHeadsKv, + headDim, + batchSizeOptional, + maxSeqlenQOptional, + maxSeqlenKvOptional, + oriTopKOptional, + cmpTopKOptional, + cmpRatioOptional, + oriMaskModeOptional, + cmpMaskModeOptional, + oriWinLeftOptional, + oriWinRightOptional, + layoutQOptional, + layoutKvOptional, + hasOriKvOptional, + hasCmpKvOptional, + socVersion, + aicCoreNum, + aivCoreNum, + metaData, + uniqueExecutor.get()); + CHECK_RET(output != nullptr, ACLNN_ERR_INNER_NULLPTR); + + *workspaceSize = 0; + uniqueExecutor.ReleaseTo(executor); + return ACLNN_SUCCESS; +} + +__attribute__((visibility("default"))) aclnnStatus +aclnnXllmKernelSparseAttnSharedkvMetadata(void* workspace, + uint64_t workspaceSize, + aclOpExecutor* executor, + aclrtStream stream) { + L2_DFX_PHASE_2(aclnnXllmKernelSparseAttnSharedkvMetadata); + return CommonOpExecutorRun(workspace, workspaceSize, executor, stream); +} + +#ifdef __cplusplus +} +#endif diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_api/aclnn_sparse_attn_sharedkv_metadata.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_api/aclnn_sparse_attn_sharedkv_metadata.h new file mode 100644 index 0000000000..d03b68cefb --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_api/aclnn_sparse_attn_sharedkv_metadata.h @@ -0,0 +1,60 @@ +/** + * 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_ATTN_SHAREDKV_METADATA_AICPU_H +#define ACLNN_SPARSE_ATTN_SHAREDKV_METADATA_AICPU_H + +#include "aclnn/aclnn_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +__attribute__((visibility("default"))) aclnnStatus +aclnnXllmKernelSparseAttnSharedkvMetadataGetWorkspaceSize( + const aclTensor* cuSeqLensQOptional, + const aclTensor* cuSeqLensOriKvOptional, + const aclTensor* cuSeqLensCmpKvOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKvOptional, + int64_t numHeadsQ, + int64_t numHeadsKv, + int64_t headDim, + int64_t batchSizeOptional, + int64_t maxSeqlenQOptional, + int64_t maxSeqlenKvOptional, + int64_t oriTopKOptional, + int64_t cmpTopKOptional, + int64_t cmpRatioOptional, + int64_t oriMaskModeOptional, + int64_t cmpMaskModeOptional, + int64_t oriWinLeftOptional, + int64_t oriWinRightOptional, + char* layoutQOptional, + char* layoutKvOptional, + bool hasOriKvOptional, + bool hasCmpKvOptional, + const aclTensor* metaData, + uint64_t* workspaceSize, + aclOpExecutor** executor); + +__attribute__((visibility("default"))) aclnnStatus +aclnnXllmKernelSparseAttnSharedkvMetadata(void* workspace, + uint64_t workspaceSize, + aclOpExecutor* executor, + aclrtStream stream); + +#ifdef __cplusplus +} +#endif + +#endif // ACLNN_SPARSE_ATTN_SHAREDKV_METADATA_AICPU_H diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_api/l0_sparse_attn_sharedkv_metadata.cpp b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_api/l0_sparse_attn_sharedkv_metadata.cpp new file mode 100644 index 0000000000..5c998a128e --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_api/l0_sparse_attn_sharedkv_metadata.cpp @@ -0,0 +1,132 @@ +/** + * 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 l0_sparse_attn_sharedkv_metadata.cpp + * \brief + */ + +#include "l0_sparse_attn_sharedkv_metadata.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(XllmKernelSparseAttnSharedkvMetadata); + +const aclTensor* XllmKernelSparseAttnSharedkvMetadata( + const aclTensor* cuSeqLensQOptional, + const aclTensor* cuSeqLensOriKvOptional, + const aclTensor* cuSeqLensCmpKvOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKvOptional, + int64_t numHeadsQ, + int64_t numHeadsKv, + int64_t headDim, + int64_t batchSizeOptional, + int64_t maxSeqlenQOptional, + int64_t maxSeqlenKvOptional, + int64_t oriTopKOptional, + int64_t cmpTopKOptional, + int64_t cmpRatioOptional, + int64_t oriMaskModeOptional, + int64_t cmpMaskModeOptional, + int64_t oriWinLeftOptional, + int64_t oriWinRightOptional, + char* layoutQOptional, + char* layoutKvOptional, + bool hasOriKvOptional, + bool hasCmpKvOptional, + const char* socVersion, + int64_t aicCoreNum, + int64_t aivCoreNum, + const aclTensor* metaData, + aclOpExecutor* executor) { + L0_DFX(XllmKernelSparseAttnSharedkvMetadata, + cuSeqLensQOptional, + cuSeqLensOriKvOptional, + cuSeqLensCmpKvOptional, + sequsedQOptional, + sequsedKvOptional, + numHeadsQ, + numHeadsKv, + headDim, + batchSizeOptional, + maxSeqlenQOptional, + maxSeqlenKvOptional, + oriTopKOptional, + cmpTopKOptional, + cmpRatioOptional, + oriMaskModeOptional, + cmpMaskModeOptional, + oriWinLeftOptional, + oriWinRightOptional, + layoutQOptional, + layoutKvOptional, + hasOriKvOptional, + hasCmpKvOptional, + socVersion, + aicCoreNum, + aivCoreNum, + metaData); + + static internal::AicpuTaskSpace space("XllmKernelSparseAttnSharedkvMetadata"); + + auto ret = ADD_TO_LAUNCHER_LIST_AICPU( + XllmKernelSparseAttnSharedkvMetadata, + OP_ATTR_NAMES( + {"num_heads_q", "num_heads_kv", "head_dim", "batch_size", + "max_seqlen_q", "max_seqlen_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"}), + OP_INPUT(cuSeqLensQOptional, + cuSeqLensOriKvOptional, + cuSeqLensCmpKvOptional, + sequsedQOptional, + sequsedKvOptional), + OP_OUTPUT(metaData), + OP_ATTR(numHeadsQ, + numHeadsKv, + headDim, + batchSizeOptional, + maxSeqlenQOptional, + maxSeqlenKvOptional, + oriTopKOptional, + cmpTopKOptional, + cmpRatioOptional, + oriMaskModeOptional, + cmpMaskModeOptional, + oriWinLeftOptional, + oriWinRightOptional, + layoutQOptional, + layoutKvOptional, + hasOriKvOptional, + hasCmpKvOptional, + socVersion, + aicCoreNum, + aivCoreNum)); + OP_CHECK(ret == ACL_SUCCESS, + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, + "XllmKernelSparseAttnSharedkvMetadata" + " ADD_TO_LAUNCHER_LIST_AICPU failed."), + return nullptr); + return metaData; +} + +} // namespace l0op diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_api/l0_sparse_attn_sharedkv_metadata.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_api/l0_sparse_attn_sharedkv_metadata.h new file mode 100644 index 0000000000..24ee911cae --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_api/l0_sparse_attn_sharedkv_metadata.h @@ -0,0 +1,49 @@ +/** + * 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_ATTN_SHAREDKV_METADATA_AICPU_H +#define L0_SPARSE_ATTN_SHAREDKV_METADATA_AICPU_H + +#include "opdev/op_executor.h" + +namespace l0op { +const aclTensor* XllmKernelSparseAttnSharedkvMetadata( + const aclTensor* cuSeqLensQOptional, + const aclTensor* cuSeqLensOriKvOptional, + const aclTensor* cuSeqLensCmpKvOptional, + const aclTensor* sequsedQOptional, + const aclTensor* sequsedKvOptional, + int64_t numHeadsQ, + int64_t numHeadsKv, + int64_t headDim, + int64_t batchSizeOptional, + int64_t maxSeqlenQOptional, + int64_t maxSeqlenKvOptional, + int64_t oriTopKOptional, + int64_t cmpTopKOptional, + int64_t cmpRatioOptional, + int64_t oriMaskModeOptional, + int64_t cmpMaskModeOptional, + int64_t oriWinLeftOptional, + int64_t oriWinRightOptional, + char* layoutQOptional, + char* layoutKvOptional, + bool hasOriKvOptional, + bool hasCmpKvOptional, + const char* socVersion, + int64_t aicCoreNum, + int64_t aivCoreNum, + const aclTensor* metaData, + aclOpExecutor* executor); +} // namespace l0op + +#endif diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_graph/sparse_attn_sharedkv_metadata_proto.cpp b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_graph/sparse_attn_sharedkv_metadata_proto.cpp new file mode 100644 index 0000000000..36ef82ae97 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_graph/sparse_attn_sharedkv_metadata_proto.cpp @@ -0,0 +1,51 @@ +/** + * 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_attn_sharedkv_metadata_proto.h + * \brief + */ +#include "graph/operator_reg.h" +#include "graph/types.h" + +namespace ge { + +REG_OP(XllmKernelSparseAttnSharedkvMetadata) + .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_kv, 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_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_ND") + .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) + .OP_END_FACTORY_REG(XllmKernelSparseAttnSharedkvMetadata) + +} // namespace ge diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_host/sparse_attn_sharedkv_metadata_infershape.cpp b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_host/sparse_attn_sharedkv_metadata_infershape.cpp new file mode 100644 index 0000000000..f5e247e567 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_host/sparse_attn_sharedkv_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_attn_sharedkv_metadata_infershape.cpp + * \brief + */ +#include "register/op_impl_registry.h" +#include "sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_metadata.h" + +using namespace ge; + +namespace ops { +static ge::graphStatus InferShapeSparseAttnSharedkvMetadata( + gert::InferShapeContext* context) { + gert::Shape* oShape = context->GetOutputShape(0); + // output shape (SAS_METADATA_T, ) + oShape->SetDimNum(1); + oShape->SetDim(0, optiling::SAS_META_SIZE); + return GRAPH_SUCCESS; +} + +static ge::graphStatus InferDtypeSparseAttnSharedkvMetadata( + gert::InferDataTypeContext* context) { + context->SetOutputDataType(0, DT_INT32); + return GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(XllmKernelSparseAttnSharedkvMetadata) + .InferShape(InferShapeSparseAttnSharedkvMetadata) + .InferDataType(InferDtypeSparseAttnSharedkvMetadata); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_kernel_aicpu/sparse_attn_sharedkv_metadata_aicpu.cpp b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_kernel_aicpu/sparse_attn_sharedkv_metadata_aicpu.cpp new file mode 100644 index 0000000000..0c9c26becd --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_kernel_aicpu/sparse_attn_sharedkv_metadata_aicpu.cpp @@ -0,0 +1,1179 @@ +/** + * 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_attn_sharedkv_metadata_aicpu.cpp + * \brief + */ + +#include "sparse_attn_sharedkv_metadata_aicpu.h" + +#include +#include + +#include "quant_lightning_indexer_metadata/op_kernel_aicpu/cpu_context_util.h" +#include "sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_metadata.h" + +using namespace optiling; + +namespace aicpu { +uint32_t SparseAttnSharedkvMetadataCpuKernel::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 SparseAttnSharedkvMetadataCpuKernel::Prepare(CpuKernelContext& ctx) { + // input + actSeqLenQ_ = ctx.Input(static_cast(ParamId::actSeqLenQ)); + actSeqLenOriKv_ = ctx.Input(static_cast(ParamId::actSeqLenOriKv)); + actSeqLenCmpKv_ = ctx.Input(static_cast(ParamId::actSeqLenCmpKv)); + seqUsedQ_ = ctx.Input(static_cast(ParamId::seqUsedQ)); + seqUsedKv_ = ctx.Input(static_cast(ParamId::seqUsedKv)); + // output + metaData_ = ctx.Output(static_cast(ParamId::metaData)); + + bool requiredAttrs = GetAttrValue(ctx, "num_heads_q", queryHeadNum_) && + GetAttrValue(ctx, "num_heads_kv", kvHeadNum_) && + GetAttrValue(ctx, "head_dim", headDim_); + GetAttrValueOpt(ctx, "soc_version", socVersion_); + GetAttrValueOpt(ctx, "aic_core_num", aicCoreNum_); + GetAttrValueOpt(ctx, "aiv_core_num", aivCoreNum_); + if (!requiredAttrs) { + return false; + } + + // attributes optional + GetAttrValueOpt(ctx, "batch_size", batchSize_); + GetAttrValueOpt(ctx, "max_seqlen_q", querySeqSize_); + GetAttrValueOpt(ctx, "max_seqlen_kv", kvSeqSize_); + 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", winLeft_); + GetAttrValueOpt(ctx, "ori_win_right", winRight_); + GetAttrValueOpt(ctx, "layout_q", layoutQuery_); + GetAttrValueOpt(ctx, "layout_kv", layoutKv_); + GetAttrValueOpt(ctx, "has_ori_kv", hasOriKv_); + GetAttrValueOpt(ctx, "has_cmp_kv", hasCmpKv_); + + return (ParamsCheck() && ParamsInit()); +} + +bool SparseAttnSharedkvMetadataCpuKernel::CheckSingleParam() { + // metadata 输出占位校验 + KERNEL_CHECK_NULLPTR(metaData_, false, "metadata is null"); + auto metaShape = metaData_->GetTensorShape(); + KERNEL_CHECK_NULLPTR(metaShape, false, "shape of metadata is null"); + KERNEL_CHECK_NULLPTR(metaData_->GetData(), false, "data of metadata is null"); + // 核心数校验 + if (aicCoreNum_ == 0 || aivCoreNum_ == 0) { + KERNEL_LOG_ERROR("AIC num or AIV num should not be 0, but got %u and %u", + aicCoreNum_, + aivCoreNum_); + return false; + } + // batch_size 非负校验 + if (batchSize_ < 0) { + KERNEL_LOG_ERROR("batch_size should not be negative, but got %d", + batchSize_); + return false; + } + // max_seqlen_q 非负校验 + if (querySeqSize_ < 0) { + KERNEL_LOG_ERROR("max_seqlen_q should not be negative, but got %d", + querySeqSize_); + return false; + } + // // num_heads_q 校验 + // if (layoutKv_ == "PA_ND" && queryHeadNum_ != 64) { + // KERNEL_LOG_ERROR("num_heads_q should only be 64 when layout_kv is + // PA_ND, but got %d", queryHeadNum_); return false; + // } + if (layoutKv_ == "BSND" && queryHeadNum_ != 64 && queryHeadNum_ != 32) { + KERNEL_LOG_ERROR( + "num_heads_q should only be 64 or 32 when layout_kv is BSND, but got " + "%d", + queryHeadNum_); + return false; + } + // num_heads_kv 校验 + if (kvHeadNum_ != 1) { + KERNEL_LOG_ERROR("num_heads_kv should only be 1, but got %d", kvHeadNum_); + return false; + } + // ori_mask_mode 校验 + if (oriMaskMode_ != static_cast(SparseMode::DEFAULT_MASK) && + oriMaskMode_ != static_cast(SparseMode::RIGHT_DOWN_CAUSAL) && + oriMaskMode_ != static_cast(SparseMode::BAND)) { + KERNEL_LOG_ERROR("ori_mask_mode should be 4, but got %d", oriMaskMode_); + return false; + } + // ori_win_left 校验 + if (winLeft_ != 127) { + KERNEL_LOG_ERROR("ori_win_left should only be 127, but got %ld", winLeft_); + return false; + } + // layout_q 校验 + if (layoutQuery_ != "TND" && layoutQuery_ != "BSND") { + KERNEL_LOG_ERROR("layout_q must be TND or BSND!"); + return false; + } + // layout_kv 校验 + if (layoutKv_ != "PA_ND" && layoutKv_ != "TND" && layoutKv_ != "BSND") { + KERNEL_LOG_ERROR("layout_kv must be TND, BSND or PA_ND!"); + return false; + } + // layout交叉校验 + if (layoutQuery_ == "TND" && layoutKv_ == "BSND") { + KERNEL_LOG_ERROR("For layout_query TND, layout_key should be PA_BSND/TND"); + return false; + } + // if (layoutQuery_ == "BSND" && layoutKv_ == "TND") { + // KERNEL_LOG_ERROR("For layout_query BSND, layout_key should be + // PA_BSND/BSND"); return false; + // } + return true; +} + +bool SparseAttnSharedkvMetadataCpuKernel::CheckExistence() { + auto isInvalid = [](Tensor* t) { + return t == nullptr || t->GetData() == nullptr; + }; + // cu_seqlens_q 存在性校验 + if (layoutQuery_ == "TND") { + if (isInvalid(actSeqLenQ_)) { + KERNEL_LOG_ERROR("For layout_q TND, cu_seqlens_q must be provided!"); + return false; + } + } + // 2. seqused_kv 存在性校验 + if (layoutKv_ == "PA_ND" && isInvalid(seqUsedKv_)) { + KERNEL_LOG_ERROR("seqused_kv must be provided when layout_kv is PA_ND!"); + return false; + } + return true; +} + +int32_t SparseAttnSharedkvMetadataCpuKernel::GetQueryBatchSize() { + // 1. 如果seqUsedQ_ 传了,使用seqUsedQ_获取BatchSize + if (seqUsedQ_ != nullptr && seqUsedQ_->GetData() != nullptr) { + if (seqUsedQ_->GetTensorShape() != nullptr) { + return seqUsedQ_->GetTensorShape()->GetDimSize(0); + } + } + // 2. seqUsedQ_ 没传,判断 Layout + if (layoutQuery_ == "TND") { + // 如果是 TND,尝试使用 actSeqLenQ_获取BatchSize + if (actSeqLenQ_ != nullptr && actSeqLenQ_->GetData() != nullptr) { + if (actSeqLenQ_->GetTensorShape() != nullptr) { + return actSeqLenQ_->GetTensorShape()->GetDimSize(0) - 1; + } + } + } + // 3. 如果不是 TND,或者 actSeqLenQ_ 为空,使用batchSize_ + return batchSize_; +} + +int32_t SparseAttnSharedkvMetadataCpuKernel::GetKvBatchSize() { + // 1. 如果 seqUsedKv_ 传了,直接使用 + if (seqUsedKv_ != nullptr && seqUsedKv_->GetData() != nullptr) { + if (seqUsedKv_->GetTensorShape() != nullptr) { + return seqUsedKv_->GetTensorShape()->GetDimSize(0); + } + } + // 2. seqUsedKv_ 没传,判断 Layout + if (layoutKv_ == "TND") { + // 如果是 TND,尝试使用 actSeqLenOriKv_ + if (actSeqLenOriKv_ != nullptr && actSeqLenOriKv_->GetData() != nullptr) { + if (actSeqLenOriKv_->GetTensorShape() != nullptr) { + return actSeqLenOriKv_->GetTensorShape()->GetDimSize(0) - 1; + } + } + } + // 3. 如果不是 TND,或者 actSeqLenOriKv_ 为空,使用 kvSeqSize_ + return batchSize_; +} + +bool SparseAttnSharedkvMetadataCpuKernel::CheckConsistency() { + // int32_t queryBatchSize = GetQueryBatchSize(); + // int32_t kvBatchSize = GetKvBatchSize(); + // if (queryBatchSize != kvBatchSize) { + // KERNEL_LOG_ERROR("The batch_size obtained from q Tensor should be the + // same as " + // "that obtained from kv tensor, but got %d and %d", + // queryBatchSize, kvBatchSize); + // return false; + // } + return true; +} + +bool SparseAttnSharedkvMetadataCpuKernel::CheckFeature() { + // 压缩率校验 + if (hasCmpKv_) { + // cmp_topk 校验 + if (cmpTopK_ != 0 && cmpTopK_ != 512 && cmpTopK_ != 1024) { + KERNEL_LOG_ERROR("cmp_topk should be 0 or 512, but got %d", cmpTopK_); + return false; + } + if (cmpRatio_ != 4 && cmpRatio_ != 128) { + KERNEL_LOG_ERROR( + "In CFA or SCFA, cmpRatio_ should only be 4 or 128, but got %d", + cmpRatio_); + return false; + } + } + return true; +} + +bool SparseAttnSharedkvMetadataCpuKernel::ParamsCheck() { + return (CheckSingleParam() && CheckExistence() && CheckConsistency() && + CheckFeature()); +} + +ValidSocVersion SparseAttnSharedkvMetadataCpuKernel::ProcessSocVersion() { + const std::string ascend950 = "Ascend910_95"; + if (socVersion_.find(ascend950) != std::string::npos) { + return ValidSocVersion::ASCEND950; + } else { + return ValidSocVersion::ASCEND910; + } + return ValidSocVersion::RESERVED_VERSION; +} + +bool SparseAttnSharedkvMetadataCpuKernel::ParamsInit() { + batchSize_ = GetQueryBatchSize(); + auto mode = static_cast(oriMaskMode_); + if (mode == SparseMode::DEFAULT_MASK) { + preToken_ = INT64_MAX; + nextToken_ = INT64_MAX; + attentionMode_ = 0; + } else if (mode == SparseMode::RIGHT_DOWN_CAUSAL) { + preToken_ = INT64_MAX; + nextToken_ = 0; + attentionMode_ = 1; + } else { // SparseMode = 4 + preToken_ = (winLeft_ > -1) ? winLeft_ : INT64_MAX; + nextToken_ = 0; + attentionMode_ = 1; + } + isS1G_ = (layoutQuery_ == "BSND" || layoutQuery_ == "BSH" || + layoutQuery_ == "TND"); + groupSize_ = queryHeadNum_ / kvHeadNum_; + if (hasCmpKv_) { + if (cmpTopK_ > 0) { + isSCFA = true; + } else { + isCFA = true; + } + } + ValidSocVersion validSocVersion = ProcessSocVersion(); + if (validSocVersion == ValidSocVersion::ASCEND910) { + mBaseSize_ = groupSize_; + s2BaseSize_ = 512U; + } else if (validSocVersion == ValidSocVersion::ASCEND950) { + mBaseSize_ = 64U; + s2BaseSize_ = 128U; + } + return true; +} + +uint32_t SparseAttnSharedkvMetadataCpuKernel::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 (layoutQuery_ == "TND") { + // 如果是 TND,尝试使用 actSeqLenQ_ + if (actSeqLenQ_ != nullptr && actSeqLenQ_->GetData() != nullptr) { + const int32_t* s1Ptr = + static_cast(actSeqLenQ_->GetData()); + return static_cast(s1Ptr[bIdx + 1U] - s1Ptr[bIdx]); + } + } + // 3. 如果不是 TND,或者 actSeqLenQ_ 为空,使用 querySeqSize_ + return static_cast(querySeqSize_); +} + +uint32_t SparseAttnSharedkvMetadataCpuKernel::GetS2SeqSize(uint32_t bIdx) { + // 1. 如果 seqUsedKv_ 传了,直接使用 + if (seqUsedKv_ != nullptr && seqUsedKv_->GetData() != nullptr) { + const int32_t* seqUsedPtr = + static_cast(seqUsedKv_->GetData()); + return static_cast(seqUsedPtr[bIdx]); + } + // 2. seqUsedKv_ 没传,判断 Layout + if (layoutKv_ == "TND") { + // 如果是 TND,尝试使用 actSeqLenOriKv_ + if (actSeqLenOriKv_ != nullptr && actSeqLenOriKv_->GetData() != nullptr) { + const int32_t* s2Ptr = + static_cast(actSeqLenOriKv_->GetData()); + return static_cast(s2Ptr[bIdx + 1U] - s2Ptr[bIdx]); + } + } + // 3. 如果不是 TND,或者 actSeqLenOriKv_ 为空,使用 kvSeqSize_ + return static_cast(kvSeqSize_); +} + +void SparseAttnSharedkvMetadataCpuKernel::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); + uint32_t s2Size = GetS2SeqSize(bIdx); + splitInfo.s1GBaseNum[bIdx] = + (s1Size * groupSize_ + (mBaseSize_ - 1U)) / mBaseSize_; + splitInfo.s1GTailSize[bIdx] = (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; + } + } + return; +} + +int64_t SparseAttnSharedkvMetadataCpuKernel::CalcPreTokenLeftUp( + uint32_t s1Size, + uint32_t s2Size) { + auto mode = static_cast(oriMaskMode_); + if (mode == SparseMode::BAND) { + return static_cast(s1Size) - static_cast(s2Size) + + preToken_; + } + return preToken_; +} + +int64_t SparseAttnSharedkvMetadataCpuKernel::CalcNextTokenLeftUp( + 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 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 SparseAttnSharedkvMetadataCpuKernel::WinCalcCost(uint32_t basicM, + uint32_t basicS2) { + uint32_t winAlignCoefM = 16U; + uint32_t winAlignCoefS2 = 64U; + uint32_t winAlignBasicM = + (basicM + winAlignCoefM - 1U) >> + 4U; // 按alignCoefM对齐,向上取整,4:移位操作实现除16 + uint32_t winAlignBasicS2 = + (basicS2 + winAlignCoefS2 - 1U) >> + 6U; // 按alignCoefS2对齐,向上取整,6:移位操作实现除64 + return static_cast( + 6U * winAlignBasicM + 10U * winAlignBasicS2); // 6:M轴系数,10:S2轴系数 +} + +int64_t SparseAttnSharedkvMetadataCpuKernel::CmpCalcCost(uint32_t basicM, + uint32_t basicS2) { + uint32_t cmpAlignCoefM = 16U; + uint32_t cmpAlignCoefS2 = 64U; + uint32_t cmpAlignBasicM = + (basicM + cmpAlignCoefM - 1U) >> + 4U; // 按alignCoefM对齐,向上取整,4:移位操作实现除16 + uint32_t cmpAlignBasicS2 = + (basicS2 + cmpAlignCoefS2 - 1U) >> + 6U; // 按alignCoefS2对齐,向上取整,6:移位操作实现除64 + return static_cast( + 6U * cmpAlignBasicM + 10U * cmpAlignBasicS2); // 6:M轴系数,10:S2轴系数 +} + +void SparseAttnSharedkvMetadataCpuKernel::CalcCostTable( + uint32_t s1NormalSize, + uint32_t s2NormalSize, + uint32_t s1GTailSize, + uint32_t winS2TailSize, + uint32_t cmpS2TailSize) { + // win部分cost + typeCost_[WIN_NORMAL_BLOCK][WIN_NORMAL_BLOCK] = + WinCalcCost(s1NormalSize, s2NormalSize); + typeCost_[WIN_TAIL_BLOCK][WIN_NORMAL_BLOCK] = + (s1GTailSize == 0U) ? 0U : WinCalcCost(s1GTailSize, s2NormalSize); + typeCost_[WIN_NORMAL_BLOCK][WIN_TAIL_BLOCK] = + (winS2TailSize == 0U) ? 0U : WinCalcCost(s1NormalSize, winS2TailSize); + typeCost_[WIN_TAIL_BLOCK][WIN_TAIL_BLOCK] = + (s1GTailSize == 0U || winS2TailSize == 0U) + ? 0U + : WinCalcCost(s1GTailSize, winS2TailSize); + // cmp部分cost + if (hasCmpKv_) { + typeCost_[CMP_NORMAL_BLOCK][CMP_NORMAL_BLOCK] = + CmpCalcCost(s1NormalSize, s2NormalSize); + typeCost_[CMP_TAIL_BLOCK][CMP_NORMAL_BLOCK] = + (s1GTailSize == 0U) ? 0U : CmpCalcCost(s1GTailSize, s2NormalSize); + typeCost_[CMP_NORMAL_BLOCK][CMP_TAIL_BLOCK] = + (cmpS2TailSize == 0U) ? 0U : CmpCalcCost(s1NormalSize, cmpS2TailSize); + typeCost_[CMP_TAIL_BLOCK][CMP_TAIL_BLOCK] = + (s1GTailSize == 0U || cmpS2TailSize == 0U) + ? 0U + : CmpCalcCost(s1GTailSize, cmpS2TailSize); + } +} + +Range SparseAttnSharedkvMetadataCpuKernel::CalcS2TokenRange( + uint32_t s1GIdx, + const BatchCache& batchCache) { + // actual seq == 0 + if (batchCache.s1Size == 0U || batchCache.s2Size == 0U) { + return std::make_pair(0, 0); + } + + // no mask + if (!attentionMode_) { // attentionMaskFlag ? + return std::make_pair(0, static_cast(batchCache.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 = s1FirstToken - batchCache.preTokenLeftUp; + int64_t s2LastToken = s1LastToken + batchCache.nextTokenLeftUp; + return std::make_pair(s2FirstToken, s2LastToken); +} + +void SparseAttnSharedkvMetadataCpuKernel::CalcBatchCache( + uint32_t bIdx, + const SplitContext& splitContext, + BatchCache& batchCache) { + const SplitInfo& splitInfo = splitContext.splitInfo; + + batchCache.bIdx = bIdx; + batchCache.s1Size = GetS1SeqSize(bIdx); + batchCache.s2Size = GetS2SeqSize(bIdx); + batchCache.preTokenLeftUp = + CalcPreTokenLeftUp(batchCache.s1Size, batchCache.s2Size); + batchCache.nextTokenLeftUp = + CalcNextTokenLeftUp(batchCache.s1Size, batchCache.s2Size); +} + +void SparseAttnSharedkvMetadataCpuKernel::CalcWinS1GCache( + S1GCache& s1GCache, + const SplitInfo& splitInfo) { + // 处理win部分block信息 + if (s1GCache.winS2Start >= s1GCache.winS2End) { + // win范围无效, 则整个s1g行等效为空行 + s1GCache.winS1GBlock = 0; + s1GCache.winS1GCost = 0; + s1GCache.winS1GLastBlockCost = 0; + s1GCache.winS1GNormalBlockCost = 0; + } else { + // 计算 Win 方向 Block 数量及 Cost + s1GCache.winS1GBlock = s1GCache.winS2End - s1GCache.winS2Start; + // 判断 Win S2 方向是否包含尾块 + uint32_t curWinTailS2Num = (s1GCache.winS2TailSize != 0U) + ? 1U + : 0U; // Updated check using local var + uint32_t curWinNormalS2Num = s1GCache.winS1GBlock - curWinTailS2Num; + if (s1GCache.s1GIdx == (splitInfo.s1GBaseNum[s1GCache.bIdx] - 1U) && + splitInfo.s1GTailSize[s1GCache.bIdx] != 0U) { + s1GCache.winS1GCost = + typeCost_[WIN_TAIL_BLOCK][WIN_NORMAL_BLOCK] * curWinNormalS2Num + + typeCost_[WIN_TAIL_BLOCK][WIN_TAIL_BLOCK] * curWinTailS2Num; + s1GCache.winS1GLastBlockCost = + curWinTailS2Num > 0U ? typeCost_[WIN_TAIL_BLOCK][WIN_TAIL_BLOCK] + : typeCost_[WIN_TAIL_BLOCK][WIN_NORMAL_BLOCK]; + s1GCache.winS1GNormalBlockCost = + typeCost_[WIN_TAIL_BLOCK][WIN_NORMAL_BLOCK]; + } else { + s1GCache.winS1GCost = + typeCost_[WIN_NORMAL_BLOCK][WIN_NORMAL_BLOCK] * curWinNormalS2Num + + typeCost_[WIN_NORMAL_BLOCK][WIN_TAIL_BLOCK] * curWinTailS2Num; + s1GCache.winS1GLastBlockCost = + curWinTailS2Num > 0U ? typeCost_[WIN_NORMAL_BLOCK][WIN_TAIL_BLOCK] + : typeCost_[WIN_NORMAL_BLOCK][WIN_NORMAL_BLOCK]; + s1GCache.winS1GNormalBlockCost = + typeCost_[WIN_NORMAL_BLOCK][WIN_NORMAL_BLOCK]; + } + } +} + +void SparseAttnSharedkvMetadataCpuKernel::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 SparseAttnSharedkvMetadataCpuKernel::CalcBlockRangeAndTailSize( + Range& oriS2TokenRange, + const BatchCache& batchCache, + S1GCache& s1GCache) { + int64_t oriS2FirstToken = oriS2TokenRange.first; + int64_t oriS2LastToken = oriS2TokenRange.second; + // win部分s2起止和tailSize + if (oriS2FirstToken >= static_cast(batchCache.s2Size) || + oriS2LastToken < 0 || oriS2LastToken < oriS2FirstToken) { + oriS2FirstToken = 0; + oriS2LastToken = 0; + s1GCache.winS2Start = 0; + s1GCache.winS2End = 0; + s1GCache.winS2TailSize = 0; + } else { + oriS2FirstToken = Clip(oriS2FirstToken, + static_cast(0), + static_cast(batchCache.s2Size - 1U)); + oriS2LastToken = Clip(oriS2LastToken, + static_cast(0), + static_cast(batchCache.s2Size - 1U)); + s1GCache.winS2Start = 0; + s1GCache.winS2End = (oriS2LastToken - oriS2FirstToken) / s2BaseSize_ + 1U; + s1GCache.winS2TailSize = + (oriS2LastToken - oriS2FirstToken + 1) % s2BaseSize_; + } + // cmp部分s2起止和tailSize + s1GCache.cmpS2Start = s1GCache.winS2End; + // 计算CmpS2LastToken的长度 + uint32_t cmpS2LastTokenSize = + hasCmpKv_ ? (oriS2LastToken + 1) / cmpRatio_ : 0; + uint32_t actCmpS2LastTokenSize = 0; + if (isCFA) { + actCmpS2LastTokenSize = cmpS2LastTokenSize; + } else if (isSCFA) { + // CmpS2LastToken与topk取最小 + actCmpS2LastTokenSize = + std::min(cmpS2LastTokenSize, static_cast(cmpTopK_)); + } + // 将token长度转化为token索引,然后由token索引计算s2索引 + s1GCache.cmpS2End = (actCmpS2LastTokenSize == 0) + ? s1GCache.cmpS2Start + : s1GCache.cmpS2Start + + (actCmpS2LastTokenSize - 1) / s2BaseSize_ + 1U; + // 由token长度计算cmpS2TailSize + s1GCache.cmpS2TailSize = actCmpS2LastTokenSize % s2BaseSize_; +} + +void SparseAttnSharedkvMetadataCpuKernel::GatherWinAndCmpCache( + S1GCache& s1GCache) { + s1GCache.s2Start = + (s1GCache.winS1GBlock > 0) ? s1GCache.winS2Start : s1GCache.cmpS2Start; + if (s1GCache.cmpS1GBlock > 0) { + s1GCache.s1GLastBlockCost = s1GCache.cmpS1GLastBlockCost; + s1GCache.s2End = s1GCache.cmpS2End; + } else { + s1GCache.s1GLastBlockCost = s1GCache.winS1GLastBlockCost; + s1GCache.s2End = s1GCache.winS2End; + } + s1GCache.s1GBlock = s1GCache.winS1GBlock + s1GCache.cmpS1GBlock; + s1GCache.s1GCost = s1GCache.winS1GCost + s1GCache.cmpS1GCost; +} + +void SparseAttnSharedkvMetadataCpuKernel::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.winS1GNormalBlockCost = 0; + s1GCache.winS1GLastBlockCost = 0; + s1GCache.cmpS1GNormalBlockCost = 0; + s1GCache.cmpS1GLastBlockCost = 0; + s1GCache.s1GBlock = 0; + s1GCache.s2Start = 0; + s1GCache.cmpS2Start = 0; + s1GCache.s2End = 0; + return; + } + s1GCache.bIdx = batchCache.bIdx; + s1GCache.s1GIdx = s1GIdx; + // 计算ori_kv的token起止 + auto oriS2TokenRange = CalcS2TokenRange(s1GIdx, batchCache); + // 计算win和cmp部分s2起止和tailSize + CalcBlockRangeAndTailSize(oriS2TokenRange, batchCache, s1GCache); + // Calculate CostTable locally + CalcCostTable(mBaseSize_, + s2BaseSize_, + splitInfo.s1GTailSize[s1GCache.bIdx], + s1GCache.winS2TailSize, + s1GCache.cmpS2TailSize); + // 计算win和cmp部分的cost, block信息 + CalcWinS1GCache(s1GCache, splitInfo); + CalcCmpS1GCache(s1GCache, splitInfo); + // 汇总win和cmp部分的cost, block信息 + GatherWinAndCmpCache(s1GCache); +} + +void SparseAttnSharedkvMetadataCpuKernel::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 SparseAttnSharedkvMetadataCpuKernel::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] * kvHeadNum_; + costInfo.totalBlockNum += costInfo.bN2BlockOfEachBatch[bIdx] * kvHeadNum_; + } +} + +void SparseAttnSharedkvMetadataCpuKernel::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 == batchSize_ * kvHeadNum_) { + assignContext.curS1GIdx = 0U; + assignContext.curS2Idx = 0U; + assignContext.isFinished = true; + return; + } + + // next batch + if (assignContext.curBN2Idx / kvHeadNum_ != assignContext.curBIdx) { + assignContext.curBIdx = assignContext.curBN2Idx / kvHeadNum_; + 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 SparseAttnSharedkvMetadataCpuKernel::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; + } +} + +int64_t SparseAttnSharedkvMetadataCpuKernel::CalcCurBlockCost( + AssignContext& assignContext) { + int64_t curCost = 0; + if (assignContext.curS2Idx < assignContext.s1GCache.cmpS2Start) { + curCost = assignContext.s1GCache.winS1GNormalBlockCost; + if (assignContext.curS2Idx == (assignContext.s1GCache.cmpS2Start - 1U)) { + curCost = assignContext.s1GCache.winS1GLastBlockCost; + } + } else { + curCost = assignContext.s1GCache.cmpS1GNormalBlockCost; + if (assignContext.curS2Idx == (assignContext.s1GCache.s2End - 1U)) { + curCost = assignContext.s1GCache.cmpS1GLastBlockCost; + } + } + return curCost; +} + +void SparseAttnSharedkvMetadataCpuKernel::AssignByBlock( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished || !supportFd) { + return; + } + + int64_t curCost = CalcCurBlockCost(assignContext); + + while (IsWithinTolerance( + assignContext.coreCache.costLimit, + curCost / FA_TOLERANCE_RATIO, + assignContext.coreCache.cost + + curCost)) { // (costLimit - curCostOnCore) * FA_TOLERANCE_RATIO > + // curCost;至少分配1块 + 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--; + curCost = CalcCurBlockCost(assignContext); + } +} + +bool SparseAttnSharedkvMetadataCpuKernel::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 SparseAttnSharedkvMetadataCpuKernel::RecordFDInfo( + const SplitContext& splitContext, + const AssignContext& assignContext, + SplitResult& result) { + const SplitInfo& splitInfo = splitContext.splitInfo; + // 需要规约的行是上一个核的切分点所在位置 + uint32_t splitBIdx = + result.bN2End[assignContext.curCoreIdx - 1U] / kvHeadNum_; + uint32_t splitS1GIdx = result.gS1End[assignContext.curCoreIdx - 1U]; + uint32_t s1Size = GetS1SeqSize(splitBIdx); + + // 计算归约数据的FD均衡划分信息 + uint32_t curFdS1gSize = (splitS1GIdx == splitInfo.s1GBaseNum[splitBIdx] - 1U) + ? (s1Size * groupSize_ - 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.curFdDataNum - assignContext.curKvSplitPart; + result.fdRes.fdS2SplitNum[result.numOfFdHead] = assignContext.curKvSplitPart; + result.fdRes.fdMSize[result.numOfFdHead] = curFdS1gSize; + result.numOfFdHead++; +} + +void SparseAttnSharedkvMetadataCpuKernel::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_ * + kvHeadNum_) { // 所有负载全部分配完,设置最后一个核的右开区间,返回 + assignContext.curS1GIdx = 0U; + assignContext.curS2Idx = 0U; + assignContext.isFinished = true; + return; + } + + if (assignContext.curBN2Idx / kvHeadNum_ != assignContext.curBIdx) { + assignContext.curBIdx = assignContext.curBN2Idx / kvHeadNum_; + 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 = + (supportFd) ? assignContext.s1GCache.winS2Start : 0; + } +} + +void SparseAttnSharedkvMetadataCpuKernel::ForceAssign( + const SplitContext& splitContext, + AssignContext& assignContext) { + if (assignContext.isFinished) { + return; + } + + int64_t curCost = CalcCurBlockCost(assignContext); + + 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); +} + +void SparseAttnSharedkvMetadataCpuKernel::AssignBlocksToCore( + const SplitContext& splitContext, + AssignContext& assignContext, + SplitResult& result) { + const CostInfo& costInfo = splitContext.costInfo; + + 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; + // 对之前的归约信息进行记录并清理 + if (IsNeedRecordFDInfo(assignContext, result)) { + RecordFDInfo(splitContext, assignContext, result); + assignContext.curKvSplitPart = 1U; + } + // 更新S2切分信息 + if (assignContext.curS2Idx > assignContext.s1GCache.s2Start && + assignContext.curS2Idx <= assignContext.s1GCache.s2End) { + assignContext.curKvSplitPart++; + } +} + +void SparseAttnSharedkvMetadataCpuKernel::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; + AssignBlocksToCore(splitContext, assignContext, result); + } + result.usedCoreNum = assignContext.curCoreIdx + 1; +} + +void SparseAttnSharedkvMetadataCpuKernel::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]; + } + // 计算每个核处理的load + uint64_t averageLoad = totalFDLoad / aivCoreNum_; + uint32_t curCoreIndex = 0; + for (uint32_t i = 0; i < splitRes.numOfFdHead; i++) { + uint32_t curFDVectorNum = splitRes.fdRes.fdS2SplitNum[i] * + splitRes.fdRes.fdMSize[i] / averageLoad; + uint32_t curAveMSize = splitRes.fdRes.fdMSize[i] / curFDVectorNum; + 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++; + } + } + splitRes.fdRes.fdUsedVecNum = curCoreIndex; +} + +bool SparseAttnSharedkvMetadataCpuKernel::BalanceSchedule( + SplitResult& splitRes) { + SplitContext splitContext(batchSize_); + // 1、划分基本块,统计信息 + CalcSplitInfo(splitContext); + // 全空case + if (splitContext.splitInfo.isKvSeqAllZero) { + splitRes.usedCoreNum = 1U; + splitRes.bN2End[0] = batchSize_ * kvHeadNum_; + 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 SparseAttnSharedkvMetadataCpuKernel::GenMetaData(SplitResult& splitRes) { + optiling::detail::SasMetaData* metaDataPtr = + (optiling::detail::SasMetaData*)metaData_->GetData(); + // FA Metadata Generate + 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]; + // + 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 = "XllmKernelSparseAttnSharedkvMetadata"; +REGISTER_CPU_KERNEL(kernelType, SparseAttnSharedkvMetadataCpuKernel); +} // namespace + +}; // namespace aicpu diff --git a/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_kernel_aicpu/sparse_attn_sharedkv_metadata_aicpu.h b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_kernel_aicpu/sparse_attn_sharedkv_metadata_aicpu.h new file mode 100644 index 0000000000..3c51e42459 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_kernel_aicpu/sparse_attn_sharedkv_metadata_aicpu.h @@ -0,0 +1,384 @@ +/** + * 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_attn_sharedkv_metadata_aicpu.h + * \brief + */ + +#ifndef SPARSE_ATTN_SHAREDKV_METADATA_AICPU_H +#define SPARSE_ATTN_SHAREDKV_METADATA_AICPU_H + +#include +#include +#include + +#include "cpu_context.h" +#include "cpu_kernel.h" +#include "cpu_tensor.h" + +namespace aicpu { + +constexpr int64_t FA_TOLERANCE_RATIO = 2; + +enum BlockType : uint32_t { + WIN_NORMAL_BLOCK = 0, + WIN_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, + 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}; + int64_t maxS1GCost{0}; // 记录所有S1G行中的最大开销 + + 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}; + uint32_t s2Size{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}; + uint32_t winS2Start{0U}; + uint32_t winS2End{0U}; + uint32_t cmpS2Start{0U}; // win部分与cmp部分的切分点 + uint32_t cmpS2End{0U}; + int64_t s1GCost{0}; + int64_t s1GLastBlockCost{0}; + uint32_t s1GBlock{0U}; + int64_t s1GNormalBlockCost{0}; + uint32_t winS1GBlock{0U}; + int64_t winS1GCost{0}; + int64_t winS1GLastBlockCost{0}; + int64_t winS1GNormalBlockCost{0}; + uint32_t cmpS1GBlock{0U}; + int64_t cmpS1GCost{0}; + int64_t cmpS1GLastBlockCost{0}; + int64_t cmpS1GNormalBlockCost{0}; + int64_t cmpS2TailSize{0}; + int64_t winS2TailSize{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 usedCoreNum{0U}; + uint32_t curKvSplitPart{1U}; + uint32_t curFdDataNum{1U}; + + int64_t bN2Cost{0}; + uint32_t bN2Block{0U}; + bool isFinished{false}; + BatchCache batchCache{}; + S1GCache s1GCache{}; + CoreCache coreCache{}; +}; + +class SparseAttnSharedkvMetadataCpuKernel : public CpuKernel { + public: + SparseAttnSharedkvMetadataCpuKernel() = default; + ~SparseAttnSharedkvMetadataCpuKernel() = default; + uint32_t Compute(CpuKernelContext& ctx) override; + + private: + bool Prepare(CpuKernelContext& ctx); + bool ParamsCheck(); + int32_t GetQueryBatchSize(); + int32_t GetKvBatchSize(); + bool CheckSingleParam(); + bool CheckExistence(); + bool CheckConsistency(); + bool CheckFeature(); + bool ParamsInit(); + bool BalanceSchedule(SplitResult& splitRes); + bool GenMetaData(SplitResult& splitRes); + ValidSocVersion ProcessSocVersion(); + // util + uint32_t GetS1SeqSize(uint32_t bIdx); + uint32_t GetS2SeqSize(uint32_t bIdx); + int64_t CalcPreTokenLeftUp(uint32_t s1Size, uint32_t s2Size); + int64_t CalcNextTokenLeftUp(uint32_t s1Size, uint32_t s2Size); + Range CalcS2TokenRange(uint32_t s1GIdx, + const BatchCache& batchCache); + int64_t WinCalcCost(uint32_t basicM, uint32_t basicS2); + int64_t CmpCalcCost(uint32_t basicM, uint32_t basicS2); + void CalcCostTable(uint32_t s1NormalSize, + uint32_t s2NormalSize, + uint32_t s1GTailSize, + uint32_t winS2TailSize, + uint32_t cmpS2TailSize); + + // cache calculation + void CalcBatchCache(uint32_t bIdx, + const SplitContext& splitContext, + BatchCache& batchCache); + void CalcBlockRangeAndTailSize(Range& oriS2TokenRange, + const BatchCache& batchCache, + S1GCache& s1GCache); + void CalcWinS1GCache(S1GCache& s1GCache, const SplitInfo& splitInfo); + void CalcCmpS1GCache(S1GCache& s1GCache, const SplitInfo& splitInfo); + void GatherWinAndCmpCache(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(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); + 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); + void SplitCore(); + + private: + // context for log use + CpuKernelContext* context_ = nullptr; + + // input + Tensor* actSeqLenQ_ = nullptr; + Tensor* actSeqLenOriKv_ = nullptr; + Tensor* actSeqLenCmpKv_ = nullptr; + Tensor* seqUsedQ_ = nullptr; + Tensor* seqUsedKv_ = nullptr; + + // output + Tensor* metaData_ = nullptr; + + // attributes + int32_t batchSize_ = 0; + int32_t querySeqSize_ = 0; + int32_t queryHeadNum_ = 0; + int32_t kvSeqSize_ = 0; + int32_t kvHeadNum_ = 0; + int32_t headDim_ = 0; + int32_t oriTopK_ = 0; + int32_t cmpTopK_ = 0; + int32_t cmpRatio_ = -1; + int32_t oriMaskMode_ = 4; + int32_t cmpMaskMode_ = 3; + int64_t winLeft_ = 127; + int64_t winRight_ = 0; + std::string layoutQuery_ = "BSND"; + std::string layoutKv_ = "PA_ND"; + bool hasOriKv_ = true; + bool hasCmpKv_ = true; + uint32_t aicCoreNum_ = 24U; + uint32_t aivCoreNum_ = 48U; + + // attr + std::string socVersion_ = "ascend910B"; + int64_t preToken_ = 0; // new + int64_t nextToken_ = 0; // new + uint32_t groupSize_ = 0; + uint32_t mBaseSize_ = 0; + uint32_t s2BaseSize_ = 0; + bool isS1G_ = true; + bool isCFA = false; + bool isSCFA = false; + bool supportFd = false; + uint32_t sparseMode_ = 0; + uint32_t attentionMode_ = 1; + BlockCost typeCost_; + + private: + enum class ParamId : uint32_t { + // input + actSeqLenQ = 0, + actSeqLenOriKv = 1, + actSeqLenCmpKv = 2, + seqUsedQ = 3, + seqUsedKv = 4, + // output + metaData = 0, + }; +}; +} // namespace aicpu + +#endif \ No newline at end of file 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 new file mode 100644 index 0000000000..2e94516021 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_attn_sharedkv_metadata/op_kernel_aicpu/sparse_attn_sharedkv_metadata_aicpu.json @@ -0,0 +1,15 @@ +{ + "XllmKernelSparseAttnSharedkvMetadata":{ + "opInfo":{ + "computeCost":"100", + "engine":"DNN_VM_AICPU", + "flagAsync":"False", + "flagPartial":"False", + "functionName":"RunCpuKernel", + "kernelSo":"libxllm_kernel_aicpu.so", + "opKernelLib":"CUSTAICPUKernel", + "userDefined":"True", + "workspaceSize":"100" + } + } +} \ No newline at end of file diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/SOURCE.txt b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/SOURCE.txt new file mode 100644 index 0000000000..6c8662e97f --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/SOURCE.txt @@ -0,0 +1,7 @@ +SparseFlashAttentionLse CANN implementation + +Source: https://gitcode.com/xLLM-AI/xllm_ops +Revision: 8bd2b014c38fec33ecf14dd33e05e8ad792ec5c8 +Directory: xllm_ops/attention/sparse_flash_attention_lse + +Packaged under a private CANN operator type and ACLNN entry points. diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_host/sparse_flash_attention_lse_def.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_host/sparse_flash_attention_lse_def.cpp new file mode 100644 index 0000000000..caf435def1 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_host/sparse_flash_attention_lse_def.cpp @@ -0,0 +1,104 @@ +/** + * 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 sparse_flash_attention_lse_def.cpp + * \brief + */ + +#include "register/op_def_registry.h" + +namespace ops { +class XllmKernelSparseFlashAttentionLse : public OpDef { + public: + explicit XllmKernelSparseFlashAttentionLse(const char* name) : OpDef(name) { + this->Input("query") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("key") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("value") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("sparse_indices") + .ParamType(REQUIRED) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("block_table") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("actual_seq_lengths_query") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("actual_seq_lengths_kv") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("query_rope") + .ParamType(OPTIONAL) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("key_rope") + .ParamType(OPTIONAL) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Output("attention_out") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("softmax_max") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("softmax_sum") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Attr("scale_value").AttrType(REQUIRED).Float(1.0); + this->Attr("sparse_block_size").AttrType(OPTIONAL).Int(1); + this->Attr("layout_query").AttrType(OPTIONAL).String("BSND"); + this->Attr("layout_kv").AttrType(OPTIONAL).String("BSND"); + this->Attr("sparse_mode") + .AttrType(OPTIONAL) + .Int(3); // 3:默认值,只计算下三角 + this->Attr("pre_tokens").AttrType(OPTIONAL).Int(INT64_MAX); + this->Attr("next_tokens").AttrType(OPTIONAL).Int(INT64_MAX); + this->Attr("attention_mode").AttrType(OPTIONAL).Int(2); + 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); + this->AICore().AddConfig("ascend910b", aicore_config); + this->AICore().AddConfig("ascend910_93", aicore_config); + this->AICore().AddConfig("ascend950", aicore_config); + } +}; +OP_ADD(XllmKernelSparseFlashAttentionLse); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_host/sparse_flash_attention_lse_infershape.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_host/sparse_flash_attention_lse_infershape.cpp new file mode 100644 index 0000000000..a73748e081 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_host/sparse_flash_attention_lse_infershape.cpp @@ -0,0 +1,148 @@ +/** + * 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 sparse_flash_attention_lse_proto.cpp + * \brief + */ + +#include +#include + +#include "err/ops_err.h" + +using namespace ge; + +namespace ops { +constexpr size_t QUERY_INPUT_INDEX = 0; +constexpr size_t KEY_INPUT_INDEX = 1; + +constexpr uint32_t DIM_NUM_1 = 1; +constexpr uint32_t DIM_NUM_3 = 3; +constexpr uint32_t DIM_NUM_4 = 4; +constexpr uint32_t DIM_INDEX_0 = 0; +constexpr uint32_t DIM_INDEX_1 = 1; +constexpr uint32_t DIM_INDEX_2 = 2; +constexpr uint32_t DIM_INDEX_3 = 3; +constexpr uint32_t LAYOUT_KEY_ATTR_INDEX = 3; +constexpr uint32_t RETURN_SOFTMAX_LSE_INDEX = 8; + +constexpr uint32_t OUTPUT_INDEX_0 = 0; +constexpr uint32_t OUTPUT_INDEX_1 = 1; +constexpr uint32_t OUTPUT_INDEX_2 = 2; + +ge::graphStatus InferShapeSparseFlashAttentionLse( + gert::InferShapeContext* context) { + OP_CHECK_IF(context == nullptr, + OP_LOGE("XllmKernelSparseFlashAttentionLse", + "InferShapeContext is nullptr"), + return ge::GRAPH_FAILED); + const gert::Shape* queryShape = context->GetInputShape(QUERY_INPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, queryShape); + + const gert::Shape* keyShape = context->GetInputShape(KEY_INPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, keyShape); + + gert::Shape* attentionOutShape = context->GetOutputShape(0); + OP_CHECK_NULL_WITH_CONTEXT(context, attentionOutShape); + *attentionOutShape = *queryShape; + + gert::Shape* softmaxMaxShape = context->GetOutputShape(1); + OP_CHECK_NULL_WITH_CONTEXT(context, softmaxMaxShape); + + gert::Shape* softmaxSumShape = context->GetOutputShape(2); + OP_CHECK_NULL_WITH_CONTEXT(context, softmaxSumShape); + + auto attrs = context->GetAttrs(); + OP_CHECK_NULL_WITH_CONTEXT(context, attrs); + const char* inputLayoutKeyPtr = + attrs->GetAttrPointer(LAYOUT_KEY_ATTR_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, inputLayoutKeyPtr); + std::string inputLayoutKeyPtrStr = std::string(inputLayoutKeyPtr); + const bool* lse_flag = attrs->GetAttrPointer(RETURN_SOFTMAX_LSE_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, lse_flag); + bool return_softmax_lse = (lse_flag != nullptr) ? *lse_flag : false; + + if (return_softmax_lse) { + if (queryShape->GetDimNum() == DIM_NUM_3) { + if (inputLayoutKeyPtrStr == "PA_BSND") { + softmaxMaxShape->SetDimNum(DIM_NUM_3); + softmaxMaxShape->SetDim(DIM_INDEX_0, keyShape->GetDim(DIM_INDEX_2)); + softmaxMaxShape->SetDim(DIM_INDEX_1, queryShape->GetDim(DIM_INDEX_0)); + softmaxMaxShape->SetDim( + DIM_INDEX_2, + queryShape->GetDim(DIM_INDEX_1) / keyShape->GetDim(DIM_INDEX_2)); + + softmaxSumShape->SetDimNum(DIM_NUM_3); + softmaxSumShape->SetDim(DIM_INDEX_0, keyShape->GetDim(DIM_INDEX_2)); + softmaxSumShape->SetDim(DIM_INDEX_1, queryShape->GetDim(DIM_INDEX_0)); + softmaxSumShape->SetDim( + DIM_INDEX_2, + queryShape->GetDim(DIM_INDEX_1) / keyShape->GetDim(DIM_INDEX_2)); + } else { + softmaxMaxShape->SetDimNum(DIM_NUM_3); + softmaxMaxShape->SetDim(DIM_INDEX_0, keyShape->GetDim(DIM_INDEX_1)); + softmaxMaxShape->SetDim(DIM_INDEX_1, queryShape->GetDim(DIM_INDEX_0)); + softmaxMaxShape->SetDim( + DIM_INDEX_2, + queryShape->GetDim(DIM_INDEX_1) / keyShape->GetDim(DIM_INDEX_1)); + + softmaxSumShape->SetDimNum(DIM_NUM_3); + softmaxSumShape->SetDim(DIM_INDEX_0, keyShape->GetDim(DIM_INDEX_1)); + softmaxSumShape->SetDim(DIM_INDEX_1, queryShape->GetDim(DIM_INDEX_0)); + softmaxSumShape->SetDim( + DIM_INDEX_2, + queryShape->GetDim(DIM_INDEX_1) / keyShape->GetDim(DIM_INDEX_1)); + } + } else { + softmaxMaxShape->SetDimNum(DIM_NUM_4); + softmaxMaxShape->SetDim(DIM_INDEX_0, queryShape->GetDim(DIM_INDEX_0)); + softmaxMaxShape->SetDim(DIM_INDEX_1, keyShape->GetDim(DIM_INDEX_2)); + softmaxMaxShape->SetDim(DIM_INDEX_2, queryShape->GetDim(DIM_INDEX_1)); + softmaxMaxShape->SetDim( + DIM_INDEX_3, + queryShape->GetDim(DIM_INDEX_2) / keyShape->GetDim(DIM_INDEX_2)); + + softmaxSumShape->SetDimNum(DIM_NUM_4); + softmaxSumShape->SetDim(DIM_INDEX_0, queryShape->GetDim(DIM_INDEX_0)); + softmaxSumShape->SetDim(DIM_INDEX_1, keyShape->GetDim(DIM_INDEX_2)); + softmaxSumShape->SetDim(DIM_INDEX_2, queryShape->GetDim(DIM_INDEX_1)); + softmaxSumShape->SetDim( + DIM_INDEX_3, + queryShape->GetDim(DIM_INDEX_2) / keyShape->GetDim(DIM_INDEX_2)); + } + } else { + softmaxMaxShape->SetDimNum(DIM_NUM_1); + softmaxMaxShape->SetDim(DIM_INDEX_0, 0); + softmaxSumShape->SetDimNum(DIM_NUM_1); + softmaxSumShape->SetDim(DIM_INDEX_0, 0); + } + + return GRAPH_SUCCESS; +} + +ge::graphStatus InferDataTypeSparseFlashAttentionLse( + gert::InferDataTypeContext* context) { + OP_CHECK_IF(context == nullptr, + OP_LOGE("XllmKernelSparseFlashAttentionLse", + "InferShapeContext is nullptr"), + return ge::GRAPH_FAILED); + const auto inputDataType = context->GetInputDataType(QUERY_INPUT_INDEX); + context->SetOutputDataType(OUTPUT_INDEX_0, inputDataType); + context->SetOutputDataType(OUTPUT_INDEX_1, ge::DT_FLOAT); + context->SetOutputDataType(OUTPUT_INDEX_2, ge::DT_FLOAT); + return ge::GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(XllmKernelSparseFlashAttentionLse) + .InferShape(InferShapeSparseFlashAttentionLse) + .InferDataType(InferDataTypeSparseFlashAttentionLse); +} // namespace ops diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_host/sparse_flash_attention_lse_tiling.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_host/sparse_flash_attention_lse_tiling.cpp new file mode 100644 index 0000000000..1ca200f429 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_host/sparse_flash_attention_lse_tiling.cpp @@ -0,0 +1,2406 @@ +/** + * 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 sparse_flash_attention_lse_tiling.cpp + * \brief + */ + +#include "sparse_flash_attention_lse_tiling.h" + +#include + +#include +#include +#include +#include + +#include "err/ops_err.h" +#include "register/op_def_registry.h" +#include "sparse_flash_attention_lse/op_kernel/sparse_flash_attention_lse_template_tiling_key.h" + +using std::map; +using std::pair; +using std::string; + +using namespace ge; +using namespace AscendC; +namespace optiling { + +constexpr uint32_t PRE_LOAD_NUM = 2; +constexpr uint32_t BLOCK_TABLE_ELEM_BYTE = 4; +constexpr int32_t SPARSE_MODE_BAND = 4; + +static const std::string QUERY_NAME = "query"; +static const std::string KEY_NAME = "key"; +static const std::string VALUE_NAME = "value"; +static const std::string BLOCK_TABLE_NAME = "block_table"; +static const std::string SPARSE_INDICES_NAME = "sparse_indices"; +static const std::string QUERY_ROPE_NAME = "query_rope"; +static const std::string KEY_ROPE_NAME = "key_rope"; +static const std::string ATTEN_OUT_NAME = "attention_out"; +static const std::string SOFTMAX_MAX_NAME = "softmax_max"; +static const std::string SOFTMAX_SUM_NAME = "softmax_sum"; + +const std::map> DTYPE_SUPPORT_MAP = { + {QUERY_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, + {KEY_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, + {VALUE_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, + {QUERY_ROPE_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, + {KEY_ROPE_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, + {ATTEN_OUT_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, + {SOFTMAX_MAX_NAME, {ge::DT_FLOAT}}, + {SOFTMAX_SUM_NAME, {ge::DT_FLOAT}}, + {SPARSE_INDICES_NAME, {ge::DT_INT32}}, + {BLOCK_TABLE_NAME, {ge::DT_INT32}}, +}; + +const std::map> LAYOUT_SUPPORT_MAP = { + {QUERY_NAME, {SFALSELayout::BSND, SFALSELayout::TND}}, + {KEY_NAME, {SFALSELayout::BSND, SFALSELayout::TND, SFALSELayout::PA_BSND}}, + {VALUE_NAME, + {SFALSELayout::BSND, SFALSELayout::TND, SFALSELayout::PA_BSND}}, + {ATTEN_OUT_NAME, {SFALSELayout::BSND, SFALSELayout::TND}}, + {SOFTMAX_MAX_NAME, {SFALSELayout::BNSG, SFALSELayout::NTG}}, + {SOFTMAX_SUM_NAME, {SFALSELayout::BNSG, SFALSELayout::NTG}}, +}; + +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 +}; + +struct SparseFlashAttentionLseCompileInfo { + int64_t core_num; +}; + +static const std::map> SFA_LAYOUT_AXIS_MAP = + { + {SFALSELayout::BSND, {SFAAxis::B, SFAAxis::S, SFAAxis::N, SFAAxis::D}}, + {SFALSELayout::TND, {SFAAxis::T, SFAAxis::N, SFAAxis::D}}, + {SFALSELayout::PA_BSND, + {SFAAxis::Bn, SFAAxis::Bs, SFAAxis::N, SFAAxis::D}}, + {SFALSELayout::BNSG, {SFAAxis::B, SFAAxis::N, SFAAxis::S, SFAAxis::G}}, + {SFALSELayout::NTG, {SFAAxis::N, SFAAxis::T, SFAAxis::G}}, +}; + +static const std::map SFA_LAYOUT_DIM_MAP = { + {SFALSELayout::BSND, DIM_NUM_FOUR}, + {SFALSELayout::TND, DIM_NUM_THREE}, + {SFALSELayout::PA_BSND, DIM_NUM_FOUR}, + {SFALSELayout::BNSG, DIM_NUM_FOUR}, + {SFALSELayout::NTG, DIM_NUM_THREE}, +}; + +static std::string GetShapeStr(gert::Shape shape) { + std::ostringstream oss; + oss << "["; + if (shape.GetDimNum() > 0) { + for (size_t i = 0; i < shape.GetDimNum() - 1; ++i) { + oss << shape.GetDim(i) << ", "; + } + oss << shape.GetDim(shape.GetDimNum() - 1); + } + oss << "]"; + return oss.str(); +} + +static std::string SFADataTypeToSerialString(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( + "XllmKernelSparseFlashAttentionLse", "datatype %d not support", type); + return "UNDEFINED"; + } +} + +string SFALSETensorDesc2String(const gert::StorageShape* shape, + const gert::CompileTimeTensorDesc* tensor) { + if (shape == nullptr || tensor == nullptr) { + return "nil "; + } + + std::ostringstream oss; + oss << "(dtype: " + << ge::TypeUtils::DataTypeToAscendString(tensor->GetDataType()) + .GetString() + << "),"; + oss << "(shape:" << SFAShape2String(shape->GetStorageShape()) << "),"; + oss << "(ori_shape:" << SFAShape2String(shape->GetOriginShape()) << "),"; + oss << "(format: " + << ge::TypeUtils::FormatToAscendString( + static_cast( + ge::GetPrimaryFormat(tensor->GetStorageFormat()))) + .GetString() + << "),"; + oss << "(ori_format: " + << ge::TypeUtils::FormatToAscendString(tensor->GetOriginFormat()) + .GetString() + << ") "; + + return oss.str(); +} + +string SFALSEDebugTilingContext(const gert::TilingContext* context) { + std::ostringstream oss; + for (size_t i = 0; i < context->GetComputeNodeInfo()->GetInputsNum(); ++i) { + oss << "input" << i << ": "; + oss << SFALSETensorDesc2String(context->GetInputShape(i), + context->GetInputDesc(i)); + } + + for (size_t i = 0; i < context->GetComputeNodeInfo()->GetOutputsNum(); ++i) { + oss << "output" << i << ": "; + oss << SFALSETensorDesc2String(context->GetOutputShape(i), + context->GetOutputDesc(i)); + } + return oss.str(); +} + +std::string SFALSELayoutToSerialString(SFALSELayout layout) { + switch (layout) { + case SFALSELayout::BSND: + return "BSND"; + case SFALSELayout::TND: + return "TND"; + case SFALSELayout::PA_BSND: + return "PA_BSND"; + case SFALSELayout::BNSG: + return "BNSG"; + case SFALSELayout::NTG: + return "NTG"; + default: + return "UNKNOWN"; + } +} + +ge::graphStatus SFALSEMlaTiling::SetBlockDim(uint32_t blockDim) const { + context_->SetBlockDim(blockDim); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEMlaTiling::SetTilingKey(uint64_t tilingKey) const { + context_->SetTilingKey(tilingKey); + context_->SetScheduleMode(1); // 1: batchmode模式 + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEMlaTiling::SetWorkspaceSize( + uint64_t workspaceSize) const { + OP_CHECK_IF( + context_->GetWorkspaceSizes(1) == nullptr, + OPS_REPORT_VECTOR_INNER_ERR(context_->GetNodeName(), + "workSpaceSize got from ge is nullptr"), + return ge::GRAPH_FAILED); + size_t* workSpaces = context_->GetWorkspaceSizes(1); + workSpaces[0] = workspaceSize; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEMlaTiling::SetTilingData(TilingDef& tilingData) const { + OP_CHECK_IF(context_->GetRawTilingData() == nullptr, + OPS_REPORT_VECTOR_INNER_ERR( + context_->GetNodeName(), + "RawTilingData got from GE context is nullptr."), + return ge::GRAPH_FAILED); + + tilingData.SaveToBuffer(context_->GetRawTilingData()->GetData(), + context_->GetRawTilingData()->GetCapacity()); + context_->GetRawTilingData()->SetDataSize(tilingData.GetDataSize()); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEMlaTiling::GetPlatformInfo() { + OP_CHECK_IF(sfaInfo_->platformInfo == nullptr, + OPS_REPORT_VECTOR_INNER_ERR(sfaInfo_->opName, + "GetPlatformInfo is nullptr."), + return ge::GRAPH_FAILED); + + auto ascendcPlatform = + platform_ascendc::PlatformAscendC(sfaInfo_->platformInfo); + libapiSize_ = ascendcPlatform.GetLibApiWorkSpaceSize(); + aivNum_ = ascendcPlatform.GetCoreNumAiv(); + aicNum_ = ascendcPlatform.GetCoreNumAic(); + + OP_CHECK_IF(aicNum_ == 0 || aivNum_ == 0, + OPS_REPORT_VECTOR_INNER_ERR(sfaInfo_->opName, + "num of core obtained is 0."), + return GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +void SFALSEMlaTiling::GenTilingKey() { + uint32_t inputQType = static_cast(sfaInfo_->inputQType); + uint32_t inputKvType = static_cast(sfaInfo_->inputKvType); + uint32_t outputType = static_cast(sfaInfo_->outputType); + uint32_t layoutQuery = static_cast(sfaInfo_->qLayout); + uint32_t layoutKV = static_cast(sfaInfo_->kvLayout); + uint32_t pageAttention = 0U; + if (sfaInfo_->kvLayout == SFALSELayout::PA_BSND) { + pageAttention = 1U; + } + + const uint32_t hasRope = + (sfaInfo_->opParamInfo.queryRope.tensor != nullptr) ? 1U : 0U; + tilingKey_ = GET_TPL_TILING_KEY(0U, + pageAttention, + layoutQuery, + layoutKV, + perfMode_ == SFAPerfMode::V_TEMPLATE_MODE, + static_cast(sfaInfo_->gSize > 64), + hasRope); // N1 > 128时核间切G + + OP_LOGI(sfaInfo_->opName, "SFA tilingKey_: %lu.", tilingKey_); +} + +void SFALSEMlaTiling::ZeroTensorProcess() const { + if (sfaInfo_->s2Size == 0) { + /* + * 1024,空tensor场景下,作为默认值完成后续计算 + * 避免matmal tiling softmax tiling异常 + * kernel计算使用真实的seqSize=0, 与actuseq_len流程归一 + */ + sfaInfo_->s2Size = 1024; + } +} + +void SFALSEMlaTiling::InitParams() { + if (sfaInfo_->s2Size != 0 && + sfaInfo_->sparseBlockSize <= 4) { // 4:当前支持范围 + perfMode_ = SFAPerfMode::V_TEMPLATE_MODE; + } else { + perfMode_ = SFAPerfMode::C_TEMPLATE_MODE; + } + + coreNum_ = aicNum_; + + headDimAlign_ = + Align(sfaInfo_->qkHeadDim, BYTE_BLOCK); // 元素个数按照基本块大小对齐 + ZeroTensorProcess(); +} + +void SFALSEMlaTiling::CalcUbBmm() { + uint32_t cubeMSize = sfaInfo_->gSize * sfaInfo_->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按照这个原则分配内存 + + qPreSizeMla_ = sfaInfo_->gSize * (headDimAlign_ + 64U) * sfaInfo_->s1Size; +} + +void SFALSEMlaTiling::CheckUbSpace() { CalcUbBmm(); } + +void SFALSEMlaTiling::CalcInnerSize(uint32_t s2Size) { + sInnerSize_ = 512; // 512:s2默认切分大小 + // FlashDecode时,如果S2的计算量>=256(确保切分后不小于128)但又不足以分2次计算时,则修改sInnerSize_,均分为2份进行计算,确保Nbuffer=2 + if (splitKVFlag_ && sfaInfo_->qLayout != SFALSELayout::TND) { + if (s2Size == 256) { // 256:s2Size的阈值,判断sInnerSize_是否切分 + sInnerSize_ = + 128; // 128:sInnerSize_值为s2Size的一半,均分为2份进行计算, + } else if (s2Size > 256 && + s2Size <= + sInnerSize_) { // 256:s2Size的阈值,判断sInnerSize_是否切分 + sInnerSize_ = (sInnerSize_ + 1) / 2; // 2:减半 + } + } + + sInnerLoopTimes_ = (s2Size + sInnerSize_ - 1) / sInnerSize_; + sInnerSizeTail_ = s2Size - (sInnerLoopTimes_ - 1) * sInnerSize_; + if (sInnerSize_ > s2Size) { + sInnerSize_ = s2Size; + } + sInnerSizeAlign_ = + Align(sInnerSize_, BYTE_BLOCK); // 元素个数按照基本块大小对齐 + + CheckUbSpace(); +} + +void SFALSEMlaTiling::SplitBalanced() { + CalcInnerSize(sfaInfo_->s2Size); + + InnerSplitParams innerSplitParams; + innerSplitParams.s1GBaseSize = sfaInfo_->gSize; + innerSplitParams.s2BaseSize = sInnerSize_; + tilingData_.innerSplitParams.set_mBaseSize(innerSplitParams.s1GBaseSize); + tilingData_.innerSplitParams.set_s2BaseSize(innerSplitParams.s2BaseSize); + + usedCoreNum_ = aicNum_; +} + +void SFALSEMlaTiling::Split() { SplitBalanced(); } + +void SFALSEMlaTiling::FillTilingBaseParamsMla() { + tilingData_.baseParams.set_batchSize(sfaInfo_->bSize); + tilingData_.baseParams.set_seqSize(sfaInfo_->s2Size); + tilingData_.baseParams.set_qSeqSize(sfaInfo_->s1Size); + tilingData_.baseParams.set_blockSize(sfaInfo_->blockSize); + tilingData_.baseParams.set_maxBlockNumPerBatch(sfaInfo_->maxBlockNumPerBatch); + tilingData_.baseParams.set_scaleValue(sfaInfo_->scaleValue); + tilingData_.baseParams.set_nNumOfQInOneGroup(sfaInfo_->n1Size / + sfaInfo_->n2Size); + tilingData_.baseParams.set_actualLenDimsQ(sfaInfo_->actualLenDimsQ); + tilingData_.baseParams.set_actualLenDimsKV(sfaInfo_->actualLenDimsKV); + tilingData_.baseParams.set_outputLayout( + static_cast(sfaInfo_->outLayout)); + tilingData_.baseParams.set_sparseMode(sfaInfo_->sparseMode); + tilingData_.baseParams.set_preTokens(sfaInfo_->preTokens); + tilingData_.baseParams.set_nextTokens(sfaInfo_->nextTokens); + tilingData_.baseParams.set_sparseBlockSize(sfaInfo_->sparseBlockSize); + tilingData_.baseParams.set_sparseBlockCount(sfaInfo_->sparseBlockCount); + tilingData_.baseParams.set_attentionMode(sfaInfo_->attentionMode); + tilingData_.baseParams.set_returnSoftmaxLse(sfaInfo_->returnSoftmaxLse); + tilingData_.baseParams.set_isActualLenDimsNull( + sfaInfo_->actualQSeqLenFlag ? 0U : 1U); + tilingData_.baseParams.set_isActualLenDimsKVNull( + sfaInfo_->actualSeqLenFlag ? 0U : 1U); +} + +// for flash decode +void SFALSEMlaTiling::FillTilingSplitKVMla() { + tilingData_.splitKVParams.set_s2(kvSplitPart_); + + tilingData_.splitKVParams.set_accumOutSize( + aicNum_ * 2 * sfaInfo_->n2Size * mBaseSize_ * + headDimAlign_); // 2:每个核可能有头规约和尾规约,一共两份规约信息 + tilingData_.splitKVParams.set_logSumExpSize( + 2 * aicNum_ * 2 * sfaInfo_->n2Size * + mBaseSize_ * // 2:每个核可能有头规约和尾规约,一共两份规约信息;sum + max + (BYTE_BLOCK / BLOCK_TABLE_ELEM_BYTE)); + + if (!splitKVFlag_) { + tilingData_.splitKVParams.set_s2(0); + } +} + +void SFALSEMlaTiling::FillTilingSingleCoreParamsMla() { + tilingData_.singleCoreParams.set_usedCoreNum(usedCoreNum_); +} + +void SFALSEMlaTiling::FillTilingSingleCoreTensorSizeMla() { + tilingData_.singleCoreTensorSize.set_mmResUbSize(mmResUbSize_); + tilingData_.singleCoreTensorSize.set_bmm2ResUbSize(bmm2ResUbSize_); +} + +void SFALSEMlaTiling::FillTiling() { + FillTilingBaseParamsMla(); + FillTilingSplitKVMla(); + FillTilingSingleCoreParamsMla(); + FillTilingSingleCoreTensorSizeMla(); +} + +uint32_t SFALSEMlaTiling::CalcBalanceFDParamNums( + const uint32_t actCoreNum) const { + return actCoreNum * 2 * sfaInfo_->n2Size * + mBaseSize_; // 2:每个核可能有头规约和尾规约,一共两份规约信息 +} + +void SFALSEMlaTiling::NormalCalcFDWorkSpace(const uint32_t actCoreNum) { + if (splitKVFlag_) { + uint32_t accumOutSize = 0; + uint32_t logSumExpSize = 0; + uint32_t FDParamNums = CalcBalanceFDParamNums( + actCoreNum); // balanceModeFlag_ ? CalcBalanceFDParamNums(actCoreNum) : + // CalcUnbalanceFDParamNums(); + accumOutSize = FDParamNums * headDimAlign_; + logSumExpSize = + 2 * FDParamNums * + (BYTE_BLOCK / + sfaInfo_->blockTypeSize); // log和sum的存储空间一致,共需要2份内存 + workspaceSize_ += (accumOutSize + logSumExpSize) * sfaInfo_->blockTypeSize; + } +} + +void SFALSEMlaTiling::CalcFDWorkSpace(const uint32_t actCoreNum) { + NormalCalcFDWorkSpace(actCoreNum); +} + +void SFALSEMlaTiling::GetWorkspaceSize() { + uint32_t actCoreNum = coreNum_; + if (sfaInfo_->isA5) { + workspaceSize_ = libapiSize_; + constexpr uint32_t TRIPLE_BUFFER_NUM = 3; + constexpr uint32_t S2_BASE_SIZE = 128; // S2轴基本块大小 + constexpr uint32_t D_SIZE = 576; + auto ascendcPlatform = + platform_ascendc::PlatformAscendC(sfaInfo_->platformInfo); + uint32_t aicNum = ascendcPlatform.GetCoreNumAic(); + if (sfaInfo_->gSize > + 64) { // N1大于64时切G,相邻两个cube核处理同一个s2Base + aicNum = aicNum >> 1; + } + workspaceSize_ += + (S2_BASE_SIZE * D_SIZE * GetTypeSize(sfaInfo_->inputQType) * + TRIPLE_BUFFER_NUM * aicNum); + } else { + uint32_t mmResElemSize = 4; // 4:fp32 + uint32_t vec1ResElemSize = 2; // 2:fp16/bf16 + uint32_t bmm2ResElemSize = 4; // 4:fp32 + uint32_t qPreProcResElemSize = 0; // 普通场景不涉及Q预处理 + uint32_t nUpdateElemSize = 4; // 4:int32 + uint32_t softmaxSumElemSize = 4; // 4:int32 + float kvDtypeRatio = 1.0; + + workspaceSize_ = libapiSize_; + uint32_t preLoadNum = 1; + preLoadNum = PRE_LOAD_NUM; + + workspaceSize_ += preLoadNum * (mmResUbSize_ * actCoreNum * mmResElemSize); + workspaceSize_ += + preLoadNum * + static_cast( + static_cast(mmResUbSize_ * actCoreNum * vec1ResElemSize) * + kvDtypeRatio); + workspaceSize_ += + preLoadNum * bmm2ResUbSize_ * actCoreNum * bmm2ResElemSize; + workspaceSize_ += + preLoadNum * + static_cast(static_cast(qPreSizeMla_ * actCoreNum * + qPreProcResElemSize) * + kvDtypeRatio); + workspaceSize_ += preLoadNum * mBaseSize_ * actCoreNum * nUpdateElemSize; + workspaceSize_ += preLoadNum * mBaseSize_ * actCoreNum * softmaxSumElemSize; + // topk BlkSize == 1场景, 需要额外空间缓存离散聚合的值 + // bufNum s2Base D dRope sizeOf(half) + // 4:bufNum 512:s2Base 512:D 64:dRope 2:sizeOf(half) + // kernel 侧 kvMerge 布局仍按 576 行宽寻址, NoPE 时 rope 半区闲置, 避免 + // host/device 不一致 + workspaceSize_ += 4 * 512 * (512 + 64) * 2 * actCoreNum; + // 缓存有效mte2 size的长度 份数 512B对齐的长度 sizeof(int32_t) aiv核数 + workspaceSize_ += + 4 * 128 * 4 * (2 * actCoreNum); // 4:缓存有效mte2 size的长度 128:份数 + // 4:512B对齐的长度 2:aiv核数 + } + + CalcFDWorkSpace(actCoreNum); +} + +void SFALSEMlaTiling::CalcBlockDim() { + auto ascendcPlatform = + platform_ascendc::PlatformAscendC(sfaInfo_->platformInfo); + auto aicNum = usedCoreNum_; + auto aivNum = 2 * usedCoreNum_; + + blockDim_ = ascendcPlatform.CalcTschBlockDim(aivNum, aicNum, aivNum); + OP_LOGI(sfaInfo_->opName, + "SFA block dim: %u aiv Num: %u aic Num: %u.", + blockDim_, + aivNum, + aicNum); +} + +ge::graphStatus SFALSEMlaTiling::DoOpTiling(SFALSETilingInfo* sfaInfo) { + sfaInfo_ = sfaInfo; + if (GetPlatformInfo() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + InitParams(); + Split(); + FillTiling(); + CalcBlockDim(); + GetWorkspaceSize(); + GenTilingKey(); + + if ((SetBlockDim(blockDim_) != ge::GRAPH_SUCCESS) || + (SetTilingKey(tilingKey_) != ge::GRAPH_SUCCESS) || + (SetWorkspaceSize(workspaceSize_) != ge::GRAPH_SUCCESS) || + (SetTilingData(tilingData_) != ge::GRAPH_SUCCESS)) { + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus TilingSparseFlashAttentionLse(gert::TilingContext* context) { + SFALSETilingInfo sfaInfo; + SFALSEInfoParser sfaInfoParser(context); + if (sfaInfoParser.Parse(sfaInfo) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + SFALSETilingCheck tilingChecker(sfaInfo); + if (tilingChecker.Process() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + SFALSEMlaTiling tiling(context); + return tiling.DoOpTiling(&sfaInfo); +} + +ge::graphStatus TilingPrepareForSparseFlashAttentionLse( + gert::TilingParseContext* const context) { + (void)context; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::GetExpectedShape( + gert::Shape& shapeExpected, + const SFALSETilingShapeCompareParam& param, + const SFALSELayout& layout) const { + if (layout == SFALSELayout::BSND) { + shapeExpected = gert::Shape({param.B, param.S, param.N, param.D}); + } else if (layout == SFALSELayout::TND) { + shapeExpected = gert::Shape({param.T, param.N, param.D}); + } else if (layout == SFALSELayout::PA_BSND) { + shapeExpected = gert::Shape({param.Bn, param.Bs, param.N, param.D}); + } else if (layout == SFALSELayout::BNSG) { + shapeExpected = gert::Shape({param.B, param.N, param.S, param.G}); + } else if (layout == SFALSELayout::NTG) { + shapeExpected = gert::Shape({param.N, param.T, param.G}); + } else { + OP_LOGE(opName_, + "layout %s is unsupported", + SFALSELayoutToSerialString(layout).c_str()); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CompareShape( + SFALSETilingShapeCompareParam& param, + const gert::Shape& shape, + const SFALSELayout& layout, + const std::string& name) const { + gert::Shape shapeExpected; + if (GetExpectedShape(shapeExpected, param, layout) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + if (shape.GetDimNum() != shapeExpected.GetDimNum()) { + OP_LOGE(opName_, + "%s dimension is %zu, expected dimension is %zu.", + name.c_str(), + shape.GetDimNum(), + shapeExpected.GetDimNum()); + return ge::GRAPH_FAILED; + } + + for (size_t i = 0; i < shape.GetDimNum(); i++) { + if (shape.GetDim(i) != shapeExpected.GetDim(i)) { + OP_LOGE(opName_, + "%s layout is %s, shape is %s, expected shape is %s.", + name.c_str(), + SFALSELayoutToSerialString(layout).c_str(), + GetShapeStr(shape).c_str(), + GetShapeStr(shapeExpected).c_str()); + return ge::GRAPH_FAILED; + } + } + + return ge::GRAPH_SUCCESS; +} + +void SFALSETilingCheck::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 << SFADataTypeToSerialString(expectDtypeList[i]); + if (i < expectDtypeList.size() - 1) { + oss << ", "; + } + } + OP_LOGE(opName_, + "Tensor %s only supports dtype %s, but got %s", + name.c_str(), + oss.str().c_str(), + SFADataTypeToSerialString(actualDtype).c_str()); +} + +ge::graphStatus SFALSETilingCheck::CheckDtypeSupport( + const gert::CompileTimeTensorDesc* desc, + const std::string& name) const { + if (desc != nullptr) { + const auto& it = DTYPE_SUPPORT_MAP.find(name); + OP_CHECK_IF( + it == DTYPE_SUPPORT_MAP.end(), + OP_LOGE( + opName_, + "%s datatype support list should be specify in DTYPE_SUPPORT_MAP", + name.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; +} + +template +void SFALSETilingCheck::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(opName_, + "%s %s only supports %s, but got %s", + name.c_str(), + subName.c_str(), + oss.str().c_str(), + std::to_string(actualValue).c_str()); +} + +template +void SFALSETilingCheck::LogErrorDimNumSupport( + const std::vector& expectNumberList, + const T& actualValue, + const std::string& name) const { + LogErrorNumberSupport(expectNumberList, actualValue, name, "dimension"); +} + +ge::graphStatus SFALSETilingCheck::CheckDimNumInLayoutSupport( + const SFALSELayout& layout, + const gert::StorageShape* shape, + const std::string& name) const { + const auto& dimIt = SFA_LAYOUT_DIM_MAP.find(layout); + OP_CHECK_IF( + shape->GetStorageShape().GetDimNum() != dimIt->second, + OP_LOGE(opName_, + "When layout is %s, %s dimension should be %zu, but it's %zu", + SFALSELayoutToSerialString(layout).c_str(), + name.c_str(), + dimIt->second, + shape->GetStorageShape().GetDimNum()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::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; +} + +void SFALSETilingCheck::LogErrorLayoutSupport( + const std::vector& expectLayoutList, + const SFALSELayout& actualLayout, + const std::string& name) const { + std::ostringstream oss; + for (size_t i = 0; i < expectLayoutList.size(); ++i) { + oss << SFALSELayoutToSerialString(expectLayoutList[i]); + if (i < expectLayoutList.size() - 1) { + oss << ", "; + } + } + OP_LOGE(opName_, + "Tensor %s only supports layout %s, but got %s", + name.c_str(), + oss.str().c_str(), + SFALSELayoutToSerialString(actualLayout).c_str()); +} + +ge::graphStatus SFALSETilingCheck::CheckLayoutSupport( + const SFALSELayout& actualLayout, + const std::string& name) const { + const auto& it = LAYOUT_SUPPORT_MAP.find(name); + OP_CHECK_IF( + it == LAYOUT_SUPPORT_MAP.end(), + OP_LOGE(opName_, + "%s layout support list should be specify in LAYOUT_SUPPORT_MAP", + name.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; +} + +ge::graphStatus SFALSETilingCheck::CheckSingleParaQuery() const { + const std::vector queryDimNumList = {DIM_NUM_THREE, DIM_NUM_FOUR}; + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(opParamInfo_.query.desc, QUERY_NAME) || + ge::GRAPH_SUCCESS != CheckLayoutSupport(qLayout_, QUERY_NAME) || + ge::GRAPH_SUCCESS != CheckDimNumSupport(opParamInfo_.query.shape, + queryDimNumList, + QUERY_NAME) || + ge::GRAPH_SUCCESS != CheckDimNumInLayoutSupport(qLayout_, + opParamInfo_.query.shape, + QUERY_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckSingleParaKey() const { + const std::vector keyDimNumList = {DIM_NUM_FOUR, DIM_NUM_THREE}; + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.key.desc, KEY_NAME) || + ge::GRAPH_SUCCESS != CheckLayoutSupport(kvLayout_, KEY_NAME) || + ge::GRAPH_SUCCESS != + CheckDimNumSupport(opParamInfo_.key.shape, keyDimNumList, KEY_NAME) || + ge::GRAPH_SUCCESS != CheckDimNumInLayoutSupport( + kvLayout_, opParamInfo_.key.shape, KEY_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckSingleParaNumHeads() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckSingleParaKvHeadNums() const { + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckSingleParaSparseMode() const { + OP_CHECK_IF((*opParamInfo_.sparseMode != 3 && *opParamInfo_.sparseMode != 0), + OP_LOGE(opName_, + "sparseMode must == 0/3, but got: %ld.", + *opParamInfo_.sparseMode), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckSingleParaSparseBlockSize() const { + OP_CHECK_IF( + (*opParamInfo_.sparseBlockSize <= 0 || + *opParamInfo_.sparseBlockSize > 128 || + (static_cast(*opParamInfo_.sparseBlockSize) & + static_cast(*opParamInfo_.sparseBlockSize - 1L)) != 0UL), + OP_LOGE(opName_, + "sparseBlockSize should be be in range [1, 128] and be a power " + "of 2, but got: %ld.", + *opParamInfo_.sparseBlockSize), + return ge::GRAPH_FAILED); + + OP_CHECK_IF( + (npuArch_ == NpuArch::DAV_3510 && *opParamInfo_.sparseBlockSize != 1), + OP_LOGE(opName_, + "when soc version is Ascend950, sparse_block_size only support " + "1, but now is %d.", + *opParamInfo_.sparseBlockSize), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckSingleParaSparseIndices() const { + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(opParamInfo_.sparseIndices.desc, SPARSE_INDICES_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckSingleParaPreTokens() const { + OP_CHECK_IF((*opParamInfo_.preTokens != INT64_MAX), + OP_LOGE(opName_, + "preTokens should be 9223372036854775807, but got: %ld.", + *opParamInfo_.preTokens), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckSingleParaNextTokens() const { + OP_CHECK_IF((*opParamInfo_.nextTokens != INT64_MAX), + OP_LOGE(opName_, + "nextTokens should be 9223372036854775807, but got: %ld.", + *opParamInfo_.nextTokens), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckSinglePara() const { + if (ge::GRAPH_SUCCESS != CheckSingleParaQuery() || + ge::GRAPH_SUCCESS != CheckSingleParaKey() || + ge::GRAPH_SUCCESS != CheckSingleParaSparseIndices() || + ge::GRAPH_SUCCESS != CheckSingleParaNumHeads() || + ge::GRAPH_SUCCESS != CheckSingleParaKvHeadNums() || + ge::GRAPH_SUCCESS != CheckSingleParaSparseMode() || + ge::GRAPH_SUCCESS != CheckSingleParaSparseBlockSize() || + ge::GRAPH_SUCCESS != CheckSingleParaPreTokens() || + ge::GRAPH_SUCCESS != CheckSingleParaNextTokens()) { + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckRopeExistence() { + OP_CHECK_IF((opParamInfo_.queryRope.tensor != nullptr || + opParamInfo_.keyRope.tensor != nullptr) && + *opParamInfo_.attentionMode == 0, + OP_LOGE(opName_, + "In MHA/GQA situation(attentionMode=0), queryRope and " + "keyRope should be null."), + return ge::GRAPH_FAILED); + OP_CHECK_IF(*opParamInfo_.attentionMode != 2, + OP_LOGE(opName_, "attentionMode only support 2."), + return ge::GRAPH_FAILED); + OP_CHECK_IF((opParamInfo_.queryRope.tensor != nullptr && + opParamInfo_.keyRope.tensor == nullptr), + OP_LOGE(opName_, + "KeyRope is null, but queryRope exists, they should be " + "both null or exist."), + return ge::GRAPH_FAILED); + OP_CHECK_IF((opParamInfo_.queryRope.tensor == nullptr && + opParamInfo_.keyRope.tensor != nullptr), + OP_LOGE(opName_, + "QueryRope is null, but keyRope exists, they should be " + "both null or exist."), + return ge::GRAPH_FAILED); + if (opParamInfo_.queryRope.tensor == nullptr) { + // NoPE场景: queryRope/keyRope均为空, 走HAS_ROPE=0的kernel实例化, + // 无需校验rope desc + return ge::GRAPH_SUCCESS; + } + OP_CHECK_IF( + opParamInfo_.keyRope.desc == nullptr || + opParamInfo_.queryRope.desc == nullptr, + OP_LOGE( + opName_, + "In Mla situation, desc of keyRope and queryRope should not be null"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckExists(const void* pointer, + const std::string& name) const { + OP_CHECK_IF(pointer == nullptr, + OP_LOGE(opName_, "%s should not be null", name.c_str()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckNotExists( + const void* pointer, + const std::string& name) const { + OP_CHECK_IF(pointer != nullptr, + OP_LOGE(opName_, "%s should be null", name.c_str()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::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 SFALSETilingCheck::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 SFALSETilingCheck::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; +} + +template +ge::graphStatus SFALSETilingCheck::CheckAttrValueByMap( + std::map>& attrMap) const { + for (auto const& kv : attrMap) { + const std::string& name = kv.first; + const std::pair& pointerValuePair = kv.second; + if (pointerValuePair.first == nullptr) { + OP_LOGE(opName_, "Attr %s should not be nullptr", name.c_str()); + return ge::GRAPH_FAILED; + } + + if (*(pointerValuePair.first) != pointerValuePair.second) { + std::ostringstream ossExpect; + ossExpect << std::to_string(pointerValuePair.second); + std::ostringstream ossActual; + ossActual << std::to_string(*(pointerValuePair.first)); + OP_LOGE(opName_, + "%s value should be %s, but got %s", + name.c_str(), + ossExpect.str().c_str(), + ossActual.str().c_str()); + return ge::GRAPH_FAILED; + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckParaExistenceMlaNoquant() const { + if (kvStorageMode_ != KvStorageMode::PAGE_ATTENTION) { + return ge::GRAPH_SUCCESS; + } + std::map mlaNoquantParamExistMap = { + {"actualSeqLengths", opParamInfo_.actualSeqLengths.tensor}, + {"blockTable", opParamInfo_.blockTable.tensor}, + }; + std::map mlaNoquantParamNotExistMap = {}; + if (CheckExistenceByMap(mlaNoquantParamExistMap, + mlaNoquantParamNotExistMap) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckParaExistenceMla() const { + return CheckParaExistenceMlaNoquant(); +} + +ge::graphStatus SFALSETilingCheck::CheckParaExistence() { + if (ge::GRAPH_SUCCESS != CheckRopeExistence()) { + return ge::GRAPH_FAILED; + } + + return CheckParaExistenceMla(); +} + +ge::graphStatus SFALSETilingCheck::GetActualSeqLenSize( + uint32_t& size, + const gert::Tensor* tensor, + const SFALSELayout& layout, + const std::string& name) const { + if (tensor == nullptr) { + OP_LOGE(opName_, + "when layout of query is %s, %s must be provided.", + SFALSELayoutToSerialString(layout).c_str(), + name.c_str()); + return ge::GRAPH_FAILED; + } + int64_t shapeSize = tensor->GetShapeSize(); + if (shapeSize <= 0) { + OP_LOGE(opName_, + "the shape size of %s is %ld, it should be greater than 0.", + name.c_str(), + shapeSize); + return ge::GRAPH_FAILED; + } + size = static_cast(shapeSize); + return ge::GRAPH_SUCCESS; +} + +void SFALSETilingCheck::SetSFAShapeCompare() { + queryShapeCmp_ = opParamInfo_.query.shape->GetStorageShape(); + topkShapeCmp_ = opParamInfo_.sparseIndices.shape->GetStorageShape(); + keyShapeCmp_ = opParamInfo_.key.shape->GetStorageShape(); + valueShapeCmp_ = opParamInfo_.value.shape->GetStorageShape(); + attenOutShapeCmp_ = opParamInfo_.attenOut.shape->GetStorageShape(); + if (opParamInfo_.queryRope.tensor != nullptr) { + queryRopeShapeCmp_ = opParamInfo_.queryRope.tensor->GetStorageShape(); + } + if (opParamInfo_.keyRope.tensor != nullptr) { + keyRopeShapeCmp_ = opParamInfo_.keyRope.tensor->GetStorageShape(); + } + softmaxMaxShapeCmp_ = opParamInfo_.softmaxMax.shape->GetStorageShape(); + softmaxSumShapeCmp_ = opParamInfo_.softmaxSum.shape->GetStorageShape(); +} + +ge::graphStatus SFALSETilingCheck::CheckBlockTable() const { + if (kvStorageMode_ != KvStorageMode::PAGE_ATTENTION) { + OP_CHECK_IF(opParamInfo_.blockTable.tensor != nullptr, + OP_LOGE(opName_, + "when the layout_kv is %s, %s should be null", + SFALSELayoutToSerialString(kvLayout_).c_str(), + BLOCK_TABLE_NAME.c_str()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; + } + if (ge::GRAPH_SUCCESS != + CheckDtypeSupport(opParamInfo_.blockTable.desc, BLOCK_TABLE_NAME)) { + return ge::GRAPH_FAILED; + } + uint32_t blockTableBatch = + opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(0); + OP_CHECK_IF( + blockTableBatch != bSize_, + OP_LOGE(opName_, + "%s's first dimension(%u) should be equal to batch size(%u)", + BLOCK_TABLE_NAME.c_str(), + blockTableBatch, + bSize_), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckDTypeConsistency( + const ge::DataType& actualDtype, + const ge::DataType& expectDtype, + const std::string& name) const { + if (actualDtype != expectDtype) { + OP_LOGE(opName_, + "%s dtype should be %s, but it's %s.", + name.c_str(), + SFADataTypeToSerialString(expectDtype).c_str(), + SFADataTypeToSerialString(actualDtype).c_str()); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckQRopeShape() { + SFALSETilingShapeCompareParam shapeParams; + shapeParams.B = bSize_; + shapeParams.N = n1Size_; + shapeParams.S = s1Size_; + shapeParams.D = ropeHeadDim_; + shapeParams.T = qTSize_; + return CompareShape( + shapeParams, queryRopeShapeCmp_, qLayout_, QUERY_ROPE_NAME); +} + +ge::graphStatus SFALSETilingCheck::CheckTopkShape() { + SFALSETilingShapeCompareParam shapeParams; + shapeParams.B = bSize_; + shapeParams.N = n2Size_; + shapeParams.S = s1Size_; + shapeParams.D = sparseBlockCount_; + shapeParams.T = qTSize_; + return CompareShape( + shapeParams, topkShapeCmp_, topkLayout_, SPARSE_INDICES_NAME); +} + +ge::graphStatus SFALSETilingCheck::CheckAttenOutShape() { + SFALSETilingShapeCompareParam shapeParams; + shapeParams.B = bSize_; + shapeParams.N = n1Size_; + shapeParams.S = s1Size_; + shapeParams.D = vHeadDim_; + shapeParams.T = qTSize_; + if (CompareShape( + shapeParams, attenOutShapeCmp_, outLayout_, ATTEN_OUT_NAME) != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckSoftmaxMaxShape() { + if (*opParamInfo_.returnSoftmaxLse) { + SFALSETilingShapeCompareParam shapeParams; + shapeParams.B = bSize_; + shapeParams.N = n2Size_; + shapeParams.S = s1Size_; + shapeParams.T = qTSize_; + shapeParams.G = n1Size_ / n2Size_; + if (CompareShape(shapeParams, + softmaxMaxShapeCmp_, + softmaxMaxLayout_, + SOFTMAX_MAX_NAME) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckSoftmaxSumShape() { + if (*opParamInfo_.returnSoftmaxLse) { + SFALSETilingShapeCompareParam shapeParams; + shapeParams.B = bSize_; + shapeParams.N = n2Size_; + shapeParams.S = s1Size_; + shapeParams.D = vHeadDim_; + shapeParams.T = qTSize_; + shapeParams.G = n1Size_ / n2Size_; + if (CompareShape(shapeParams, + softmaxSumShapeCmp_, + softmaxSumLayout_, + SOFTMAX_SUM_NAME) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckAttenOut() { + if (ge::GRAPH_SUCCESS != + CheckDTypeConsistency(opParamInfo_.attenOut.desc->GetDataType(), + inputQType_, + ATTEN_OUT_NAME) || + ge::GRAPH_SUCCESS != CheckAttenOutShape() || + ge::GRAPH_SUCCESS != CheckSoftmaxMaxShape() || + ge::GRAPH_SUCCESS != CheckSoftmaxSumShape()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} +ge::graphStatus SFALSETilingCheck::CheckSoftmaxMax() { + if (*opParamInfo_.returnSoftmaxLse) { + OP_CHECK_IF( + opParamInfo_.softmaxMax.shape->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(opName_, + "When return_softmax_lse is true, SoftmaxMax tensor cannot be " + "empty tensor."), + return ge::GRAPH_FAILED); + // type类型校验 + OP_CHECK_IF(opParamInfo_.softmaxMax.desc->GetDataType() != ge::DT_FLOAT, + OP_LOGE(opName_, "SoftmaxMax's dtype must be FLOAT."), + return ge::GRAPH_FAILED); + // shape和维度校验 + if (ge::GRAPH_SUCCESS != CheckAttenOutShape()) { + return ge::GRAPH_FAILED; + } + } else { + if (opParamInfo_.softmaxMax.shape->GetStorageShape().GetShapeSize() != 0) { + OP_LOGW(opName_, + "When return_softmax_lse is false, SoftmaxMax tensor must be " + "empty tensor."); + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckSoftmaxSum() { + if (*opParamInfo_.returnSoftmaxLse) { + OP_CHECK_IF( + opParamInfo_.softmaxSum.shape->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(opName_, + "When return_softmax_lse is true, softmaxSum tensor cannot be " + "empty tensor."), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.softmaxSum.desc->GetDataType() != ge::DT_FLOAT, + OP_LOGE(opName_, "softmaxSum's dtype must be FLOAT."), + return ge::GRAPH_FAILED); + } else { + if (opParamInfo_.softmaxSum.shape->GetStorageShape().GetShapeSize() != 0) { + OP_LOGW(opName_, + "When return_softmax_lse is false, softmaxSum tensor must be " + "empty tensor."); + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckQRope() { + if (opParamInfo_.queryRope.tensor == nullptr) { + return ge::GRAPH_SUCCESS; + } + if (ge::GRAPH_SUCCESS != + CheckDTypeConsistency(opParamInfo_.queryRope.desc->GetDataType(), + inputQType_, + QUERY_ROPE_NAME) || + ge::GRAPH_SUCCESS != CheckQRopeShape()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckTopK() { + if (ge::GRAPH_SUCCESS != CheckTopkShape()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckVAndKRopeShapeForBatchContinuous() { + SFALSETilingShapeCompareParam shapeParams; + shapeParams.B = bSize_; + shapeParams.N = n2Size_; + shapeParams.S = s2Size_; + shapeParams.T = kvTSize_; + shapeParams.D = qkHeadDim_; + if (CompareShape(shapeParams, keyShapeCmp_, kvLayout_, KEY_NAME) != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + shapeParams.D = vHeadDim_; + if (CompareShape(shapeParams, valueShapeCmp_, kvLayout_, VALUE_NAME) != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + if (opParamInfo_.keyRope.tensor != nullptr) { + shapeParams.D = ropeHeadDim_; + if (CompareShape(shapeParams, keyRopeShapeCmp_, kvLayout_, KEY_ROPE_NAME) != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + } + return ge::GRAPH_SUCCESS; +} + +uint32_t SFALSEMlaTiling::GetTypeSize(ge::DataType dtype) const { + uint32_t typeSize = NUM_BYTES_FLOAT16; + switch (dtype) { + case ge::DT_FLOAT16: + typeSize = NUM_BYTES_FLOAT16; + break; + case ge::DT_BF16: + typeSize = NUM_BYTES_BF16; + break; + default: + typeSize = NUM_BYTES_FLOAT16; + } + return typeSize; +} + +ge::graphStatus SFALSETilingCheck::CheckVAndKRopeShapeForPageAttention() { + int64_t blockNum = keyShapeCmp_.GetDim(0); + OP_CHECK_IF(blockNum <= 0, + OP_LOGE(opName_, + "The first dim(%ld) of key should be greater than 0", + blockNum), + return ge::GRAPH_FAILED); + SFALSETilingShapeCompareParam shapeParams; + shapeParams.Bn = blockNum; + shapeParams.N = n2Size_; + shapeParams.Bs = blockSize_; + shapeParams.D = vHeadDim_; + shapeParams.T = kvTSize_; + if (CompareShape(shapeParams, valueShapeCmp_, kvLayout_, VALUE_NAME) != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + if (opParamInfo_.keyRope.tensor != nullptr) { + shapeParams.D = ropeHeadDim_; + if (CompareShape(shapeParams, keyRopeShapeCmp_, kvLayout_, KEY_ROPE_NAME) != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckVAndKRopeShape() { + if (kvStorageMode_ == KvStorageMode::BATCH_CONTINUOUS) { + return CheckVAndKRopeShapeForBatchContinuous(); + } + + if (kvStorageMode_ == KvStorageMode::PAGE_ATTENTION) { + return CheckVAndKRopeShapeForPageAttention(); + } + + OP_LOGE(opName_, + "storage mode of key and value is %u, it is incorrect.", + static_cast(kvStorageMode_)); + return ge::GRAPH_FAILED; +} + +// NoPE场景(queryRope/keyRope均为空)下仅校验key/value本身, 跳过rope相关校验 +ge::graphStatus SFALSETilingCheck::CheckVAndKShapeWithoutRope() { + if (kvStorageMode_ == KvStorageMode::BATCH_CONTINUOUS) { + SFALSETilingShapeCompareParam shapeParams; + shapeParams.B = bSize_; + shapeParams.N = n2Size_; + shapeParams.S = s2Size_; + shapeParams.T = kvTSize_; + shapeParams.D = qkHeadDim_; + if (CompareShape(shapeParams, keyShapeCmp_, kvLayout_, KEY_NAME) != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + shapeParams.D = vHeadDim_; + if (CompareShape(shapeParams, valueShapeCmp_, kvLayout_, VALUE_NAME) != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; + } + + if (kvStorageMode_ == KvStorageMode::PAGE_ATTENTION) { + int64_t blockNum = keyShapeCmp_.GetDim(0); + OP_CHECK_IF(blockNum <= 0, + OP_LOGE(opName_, + "The first dim(%ld) of key should be greater than 0", + blockNum), + return ge::GRAPH_FAILED); + SFALSETilingShapeCompareParam shapeParams; + shapeParams.Bn = blockNum; + shapeParams.N = n2Size_; + shapeParams.Bs = blockSize_; + shapeParams.D = qkHeadDim_; + shapeParams.T = kvTSize_; + if (CompareShape(shapeParams, keyShapeCmp_, kvLayout_, KEY_NAME) != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + shapeParams.D = vHeadDim_; + if (CompareShape(shapeParams, valueShapeCmp_, kvLayout_, VALUE_NAME) != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; + } + + OP_LOGE(opName_, + "storage mode of key and value is %u, it is incorrect.", + static_cast(kvStorageMode_)); + return ge::GRAPH_FAILED; +} + +ge::graphStatus SFALSETilingCheck::CheckVAndKRope() { + if (ge::GRAPH_SUCCESS != + CheckDTypeConsistency(opParamInfo_.value.desc->GetDataType(), + inputKvType_, + VALUE_NAME) || + ge::GRAPH_SUCCESS != + CheckDTypeConsistency(opParamInfo_.keyRope.desc->GetDataType(), + inputKvType_, + KEY_ROPE_NAME) || + ge::GRAPH_SUCCESS != CheckVAndKRopeShape()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckActualSeqLensQ() { + if (ge::GRAPH_SUCCESS != CheckActualSeqLensQDType() || + ge::GRAPH_SUCCESS != CheckActualSeqLensQShape()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckActualSeqLensQDType() { + if (opParamInfo_.actualSeqLengthsQ.tensor == nullptr) { + return ge::GRAPH_SUCCESS; + } + if (opParamInfo_.actualSeqLengthsQ.desc == nullptr) { + OP_LOGE(opName_, + "actualSeqLengthsQ is not empty," + "but actualSeqLengthsQ's dtype is nullptr."); + return ge::GRAPH_FAILED; + } + if (opParamInfo_.actualSeqLengthsQ.desc->GetDataType() != ge::DT_INT32) { + OP_LOGE(opName_, + "actualSeqLengthsQ's dtype is %s, it should be DT_INT32.", + SFADataTypeToSerialString( + opParamInfo_.actualSeqLengthsQ.desc->GetDataType()) + .c_str()); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckActualSeqLensQShape() { + if (opParamInfo_.actualSeqLengthsQ.tensor == nullptr) { + return ge::GRAPH_SUCCESS; + } + uint32_t shapeSize = 0; + if (GetActualSeqLenSize(shapeSize, + opParamInfo_.actualSeqLengthsQ.tensor, + qLayout_, + "actualSeqLengthsQ") != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + if (shapeSize != bSize_) { + OP_LOGE(opName_, + "actualSeqLengthsQ shape size is %u, it should be equal to batch " + "size[%u]", + shapeSize, + bSize_); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckActualSeqLens() { + if (std::string(opParamInfo_.layoutKV) == "TND" && + opParamInfo_.actualSeqLengths.tensor == nullptr) { + OP_LOGE(opName_, + "when the layout of key and value is TND, " + "the actualSeqLengths of key and value should not be empty."); + return ge::GRAPH_PARAM_INVALID; + } + if (ge::GRAPH_SUCCESS != CheckActualSeqLensDType() || + ge::GRAPH_SUCCESS != CheckActualSeqLensShape()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckActualSeqLensDType() { + if (opParamInfo_.actualSeqLengths.tensor == nullptr) { + return ge::GRAPH_SUCCESS; + } + if (opParamInfo_.actualSeqLengths.desc == nullptr) { + OP_LOGE(opName_, + "actualSeqLengths is not empty," + "but actualSeqLengths's dtype is nullptr."); + return ge::GRAPH_FAILED; + } + if (opParamInfo_.actualSeqLengths.desc->GetDataType() != ge::DT_INT32) { + OP_LOGE(opName_, + "actualSeqLengths's dtype is %s, it should be DT_INT32.", + SFADataTypeToSerialString( + opParamInfo_.actualSeqLengths.desc->GetDataType()) + .c_str()); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckActualSeqLensShape() { + if (opParamInfo_.actualSeqLengths.tensor == nullptr) { + return ge::GRAPH_SUCCESS; + } + uint32_t shapeSize = 0; + if (GetActualSeqLenSize(shapeSize, + opParamInfo_.actualSeqLengths.tensor, + kvLayout_, + "actualSeqLengths") != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + if (shapeSize != bSize_) { + OP_LOGE(opName_, + "actualSeqLengths shape size is %u, it should be equal to batch " + "size[%u].", + shapeSize, + bSize_); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckMultiParaConsistency() { + SetSFAShapeCompare(); + // NoPE场景(queryRope/keyRope均为空)跳过rope相关的shape/dtype一致性校验, + // 但仍需校验key/value + bool hasRope = (opParamInfo_.queryRope.tensor != nullptr); + if ((hasRope && (ge::GRAPH_SUCCESS != CheckVAndKRope() || + ge::GRAPH_SUCCESS != CheckQRope())) || + (!hasRope && + (ge::GRAPH_SUCCESS != + CheckDTypeConsistency(opParamInfo_.value.desc->GetDataType(), + inputKvType_, + VALUE_NAME) || + ge::GRAPH_SUCCESS != CheckVAndKShapeWithoutRope())) || + ge::GRAPH_SUCCESS != CheckTopK() || + ge::GRAPH_SUCCESS != CheckAttenOut() || + ge::GRAPH_SUCCESS != CheckSoftmaxMax() || + ge::GRAPH_SUCCESS != CheckSoftmaxSum() || + ge::GRAPH_SUCCESS != CheckActualSeqLensQ() || + ge::GRAPH_SUCCESS != CheckActualSeqLens() || + ge::GRAPH_SUCCESS != CheckBlockTable()) { + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckFeatureMlaNoQuantShape() const { + OP_CHECK_IF( + bSize_ <= 0, + OP_LOGE( + opName_, "batch_size should be greater than 0, but got %u", bSize_), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(qTSize_ <= 0 && (qLayout_ == SFALSELayout::TND), + OP_LOGE(opName_, + "T_size of query should be greater than 0, but got %u", + qTSize_), + return ge::GRAPH_FAILED); + + OP_CHECK_IF( + n1Size_ <= 0, + OP_LOGE( + opName_, "q_head_num should be greater than 0, but got %u", n1Size_), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(n2Size_ != 1, + OP_LOGE(opName_, "kv_head_num should be 1, but got %u", n2Size_), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(n1Size_ % n2Size_ != 0, + OP_LOGE(opName_, + "q_head_num(%u) must be divisible by kv_head_num(%u)", + n1Size_, + n2Size_), + return ge::GRAPH_FAILED); + + OP_CHECK_IF( + gSize_ < 1 || (gSize_ > 64 && gSize_ != 128), + OP_LOGE( + opName_, "group num should be in 1 ~ 64, 128, but got %u", gSize_), + return ge::GRAPH_FAILED); + + OP_CHECK_IF( + qkHeadDim_ != 512, + OP_LOGE(opName_, "qk_head_dim only support 512, but got %u", qkHeadDim_), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(qkHeadDim_ != vHeadDim_, + OP_LOGE(opName_, + "qk_head_dim[%u] should be equal to v_head_dim[%u]", + qkHeadDim_, + vHeadDim_), + return ge::GRAPH_FAILED); + + // ropeHeadDim必须与rope tensor的存在性绑定: 有rope输入时只允许64维, + // NoPE(无rope输入)时只允许0, + // 防止"tensor非空但D=0"的非法输入通过校验后进入HAS_ROPE=1的kernel按64维越界读取 + const bool hasRope = (opParamInfo_.queryRope.tensor != nullptr); + OP_CHECK_IF( + hasRope && ropeHeadDim_ != 64, + OP_LOGE( + opName_, + "rope_head_dim should be 64 when query_rope is provided, but got %u", + ropeHeadDim_), + return ge::GRAPH_FAILED); + OP_CHECK_IF(!hasRope && ropeHeadDim_ != 0, + OP_LOGE(opName_, + "rope_head_dim should be 0 when query_rope is not " + "provided, but got %u", + ropeHeadDim_), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckFeatureMlaNoQuantLayout() const { + const std::vector layoutSupportList = {"BSND", "TND"}; + std::string layoutQuery = opParamInfo_.layoutQuery; + OP_CHECK_IF(std::find(layoutSupportList.begin(), + layoutSupportList.end(), + layoutQuery) == layoutSupportList.end(), + OP_LOGE(opName_, + "layoutQuery only supports BSND/TND, but got %s", + layoutQuery.c_str()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckFeatureMlaNoQuantDtype() const { + OP_CHECK_IF(inputQType_ != ge::DT_BF16 && inputQType_ != ge::DT_FLOAT16, + OP_LOGE(opName_, + "query dtype only support %s and %s, but got %s", + SFADataTypeToSerialString(ge::DT_BF16).c_str(), + SFADataTypeToSerialString(ge::DT_FLOAT16).c_str(), + SFADataTypeToSerialString(inputQType_).c_str()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckFeatureMlaNoquantPa() const { + if (kvStorageMode_ != KvStorageMode::PAGE_ATTENTION) { + return ge::GRAPH_SUCCESS; + } + + OP_CHECK_IF( + blockSize_ <= 0 || blockSize_ > static_cast(MAX_BLOCK_SIZE), + OP_LOGE(opName_, + "when page attention is enabled, block_size(%d) should be in " + "range (0, %u].", + blockSize_, + MAX_BLOCK_SIZE), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(blockSize_ % 16 > 0, + OP_LOGE(opName_, + "when page attention is enabled, block_size(%d) should " + "be 16-aligned.", + blockSize_), + return ge::GRAPH_FAILED); + + OP_CHECK_IF( + blockSize_ % sparseBlockSize_ > 0, + OP_LOGE(opName_, + "when page attention is enabled, block_size(%d) must be divided " + "by sparse_block_size(%d), but now the remainder is %d.", + blockSize_, + sparseBlockSize_, + blockSize_ % sparseBlockSize_), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckFeatureMlaNoquant() const { + if (ge::GRAPH_SUCCESS != CheckFeatureMlaNoQuantShape() || + ge::GRAPH_SUCCESS != CheckFeatureMlaNoQuantLayout() || + ge::GRAPH_SUCCESS != CheckFeatureMlaNoQuantDtype() || + ge::GRAPH_SUCCESS != CheckFeatureMlaNoquantPa()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSETilingCheck::CheckFeatureMla() const { + return CheckFeatureMlaNoquant(); +} + +ge::graphStatus SFALSETilingCheck::CheckFeature() const { + return CheckFeatureMla(); +} + +void SFALSETilingCheck::Init() { + opName_ = sfaInfo_.opName; + platformInfo_ = sfaInfo_.platformInfo; + opParamInfo_ = sfaInfo_.opParamInfo; + npuArch_ = sfaInfo_.npuArch; + isA5_ = sfaInfo_.isA5; + + bSize_ = sfaInfo_.bSize; + n1Size_ = sfaInfo_.n1Size; + n2Size_ = sfaInfo_.n2Size; + s1Size_ = sfaInfo_.s1Size; + s2Size_ = sfaInfo_.s2Size; + gSize_ = sfaInfo_.gSize; + qkHeadDim_ = sfaInfo_.qkHeadDim; + vHeadDim_ = sfaInfo_.vHeadDim; + ropeHeadDim_ = sfaInfo_.ropeHeadDim; + maxBlockNumPerBatch_ = sfaInfo_.maxBlockNumPerBatch; + qTSize_ = sfaInfo_.qTSize; + kvTSize_ = sfaInfo_.kvTSize; + blockSize_ = sfaInfo_.blockSize; + sparseBlockCount_ = sfaInfo_.sparseBlockCount; + sparseBlockSize_ = sfaInfo_.sparseBlockSize; + + inputQType_ = sfaInfo_.inputQType; + inputKvType_ = sfaInfo_.inputKvType; + inputQRopeType_ = sfaInfo_.inputQRopeType; + inputKRopeType_ = sfaInfo_.inputKRopeType; + outputType_ = sfaInfo_.outputType; + + qLayout_ = sfaInfo_.qLayout; + topkLayout_ = sfaInfo_.topkLayout; + kvLayout_ = sfaInfo_.kvLayout; + outLayout_ = sfaInfo_.outLayout; + softmaxMaxLayout_ = sfaInfo_.softmaxMaxLayout; + softmaxSumLayout_ = sfaInfo_.softmaxSumLayout; + + kvStorageMode_ = sfaInfo_.kvStorageMode; + l2CacheSize_ = sfaInfo_.l2CacheSize; +} + +ge::graphStatus SFALSETilingCheck::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; +} + +bool SFALSEInfoParser::HasAxis(const SFAAxis& axis, + const SFALSELayout& layout, + const gert::Shape& shape) const { + const auto& layoutIt = SFA_LAYOUT_AXIS_MAP.find(layout); + if (layoutIt == SFA_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 = SFA_LAYOUT_DIM_MAP.find(layout); + if (dimIt == SFA_LAYOUT_DIM_MAP.end() || dimIt->second != shape.GetDimNum()) { + return false; + } + return true; +} + +size_t SFALSEInfoParser::GetAxisIdx(const SFAAxis& axis, + const SFALSELayout& layout) const { + const std::vector& axes = SFA_LAYOUT_AXIS_MAP.find(layout)->second; + const auto& axisIt = std::find(axes.begin(), axes.end(), axis); + return std::distance(axes.begin(), axisIt); +} + +uint32_t SFALSEInfoParser::GetAxisNum(const gert::Shape& shape, + const SFAAxis& axis, + const SFALSELayout& layout) const { + return HasAxis(axis, layout, shape) ? shape.GetDim(GetAxisIdx(axis, layout)) + : invalidDimValue_; +} + +ge::graphStatus SFALSEInfoParser::CheckRequiredInOutExistence() const { + OP_CHECK_IF(opParamInfo_.query.shape == nullptr, + OP_LOGE(opName_, "Shape of tensor query is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.query.desc == nullptr, + OP_LOGE(opName_, "Desc of tensor query is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.key.shape == nullptr, + OP_LOGE(opName_, "Shape of tensor k is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.key.desc == nullptr, + OP_LOGE(opName_, "Desc of tensor k is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.value.shape == nullptr, + OP_LOGE(opName_, "Shape of tensor value is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.value.desc == nullptr, + OP_LOGE(opName_, "Desc of tensor value is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.sparseIndices.shape == nullptr, + OP_LOGE(opName_, "Shape of tensor sparseIndices is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.sparseIndices.desc == nullptr, + OP_LOGE(opName_, "Desc of tensor sparseIndices is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.attenOut.shape == nullptr, + OP_LOGE(opName_, "Shape of tensor output is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.attenOut.desc == nullptr, + OP_LOGE(opName_, "Desc of tensor output is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.softmaxMax.shape == nullptr, + OP_LOGE(opName_, "Shape of tensor softmaxMax is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.softmaxMax.desc == nullptr, + OP_LOGE(opName_, "Desc of tensor softmaxMax is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.softmaxSum.shape == nullptr, + OP_LOGE(opName_, "Shape of tensor softmaxSum is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.softmaxSum.desc == nullptr, + OP_LOGE(opName_, "Desc of tensor softmaxSum is nullptr"), + return ge::GRAPH_FAILED); + // queryRope为可选输入(NoPE场景为nullptr), 其存在性在CheckRopeExistence中校验 + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::CheckRequiredAttrExistence() const { + OP_CHECK_IF(opParamInfo_.layoutQuery == nullptr, + OP_LOGE(opName_, "attr layoutQuery is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.layoutKV == nullptr, + OP_LOGE(opName_, "attr layoutKV is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.sparseBlockSize == nullptr, + OP_LOGE(opName_, "attr sparseBlockSize is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.scaleValue == nullptr, + OP_LOGE(opName_, "attr scaleValue is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.sparseMode == nullptr, + OP_LOGE(opName_, "attr sparseMode is nullptr"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::CheckRequiredParaExistence() const { + if (CheckRequiredInOutExistence() != ge::GRAPH_SUCCESS || + CheckRequiredAttrExistence() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetActualSeqLenSize( + uint32_t& size, + const gert::Tensor* tensor, + SFALSELayout& layout, + const std::string& name) const { + if ((tensor == nullptr)) { + OP_LOGE(opName_, + "when layout of query is %s, %s must be provided.", + SFALSELayoutToSerialString(layout).c_str(), + name.c_str()); + return ge::GRAPH_FAILED; + } + int64_t shapeSize = tensor->GetShapeSize(); + if (shapeSize <= 0) { + OP_LOGE(opName_, + "the shape size of %s is %ld, it should be greater than 0.", + name.c_str(), + shapeSize); + return ge::GRAPH_FAILED; + } + size = static_cast(shapeSize); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetActualSeqLenQSize(uint32_t& size) { + return GetActualSeqLenSize(size, + opParamInfo_.actualSeqLengthsQ.tensor, + qLayout_, + "actualSeqLengthsQ"); +} + +ge::graphStatus SFALSEInfoParser::GetOpName() { + if (context_->GetNodeName() == nullptr) { + OP_LOGE("XllmKernelSparseFlashAttentionLse", + "opName got from TilingContext is nullptr"); + return ge::GRAPH_FAILED; + } + opName_ = context_->GetNodeName(); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetNpuInfo() { + platformInfo_ = context_->GetPlatformInfo(); + OP_CHECK_IF( + platformInfo_ == nullptr, + OPS_REPORT_VECTOR_INNER_ERR(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, + OPS_REPORT_VECTOR_INNER_ERR(opName_, "num of core obtained is 0."), + return GRAPH_FAILED); + + npuArch_ = ascendcPlatform.GetCurNpuArch(); + isA5_ = (npuArch_ == NpuArch::DAV_3510); + if (npuArch_ != NpuArch::DAV_2201 && npuArch_ != NpuArch::DAV_3510) { + OPS_REPORT_VECTOR_INNER_ERR(opName_, + "Npu Arch Version[%d] is not support.", + static_cast(npuArch_)); + return GRAPH_FAILED; + } + + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L2, + l2CacheSize_); + + return ge::GRAPH_SUCCESS; +} + +void SFALSEInfoParser::GetOptionalInputParaInfo() { + opParamInfo_.blockTable.tensor = + context_->GetOptionalInputTensor(BLOCK_TABLE_INPUT_INDEX); + opParamInfo_.blockTable.desc = + context_->GetOptionalInputDesc(BLOCK_TABLE_INPUT_INDEX); + opParamInfo_.actualSeqLengthsQ.tensor = + context_->GetOptionalInputTensor(ACT_SEQ_LEN_Q_INPUT_INDEX); + opParamInfo_.actualSeqLengthsQ.desc = + context_->GetOptionalInputDesc(ACT_SEQ_LEN_Q_INPUT_INDEX); + opParamInfo_.actualSeqLengths.tensor = + context_->GetOptionalInputTensor(ACT_SEQ_LEN_KV_INPUT_INDEX); + opParamInfo_.actualSeqLengths.desc = + context_->GetOptionalInputDesc(ACT_SEQ_LEN_KV_INPUT_INDEX); + opParamInfo_.queryRope.tensor = + context_->GetOptionalInputTensor(QUERY_ROPE_INPUT_INDEX); + opParamInfo_.queryRope.desc = + context_->GetOptionalInputDesc(QUERY_ROPE_INPUT_INDEX); + opParamInfo_.keyRope.tensor = + context_->GetOptionalInputTensor(KEY_ROPE_INPUT_INDEX); + opParamInfo_.keyRope.desc = + context_->GetOptionalInputDesc(KEY_ROPE_INPUT_INDEX); +} + +void SFALSEInfoParser::GetInputParaInfo() { + opParamInfo_.query.desc = context_->GetInputDesc(QUERY_INPUT_INDEX); + opParamInfo_.query.shape = context_->GetInputShape(QUERY_INPUT_INDEX); + opParamInfo_.key.desc = context_->GetInputDesc(KEY_INPUT_INDEX); + opParamInfo_.key.shape = context_->GetInputShape(KEY_INPUT_INDEX); + opParamInfo_.value.desc = context_->GetInputDesc(VALUE_INPUT_INDEX); + opParamInfo_.value.shape = context_->GetInputShape(VALUE_INPUT_INDEX); + opParamInfo_.sparseIndices.desc = + context_->GetInputDesc(SPARSE_INDICES_INPUT_INDEX); + opParamInfo_.sparseIndices.shape = + context_->GetInputShape(SPARSE_INDICES_INPUT_INDEX); + GetOptionalInputParaInfo(); +} + +void SFALSEInfoParser::GetOutputParaInfo() { + opParamInfo_.attenOut.desc = context_->GetOutputDesc(OUTPUT_INDEX); + opParamInfo_.attenOut.shape = context_->GetOutputShape(OUTPUT_INDEX); + opParamInfo_.softmaxMax.desc = context_->GetOutputDesc(SOFTMAXMAX_INDEX); + opParamInfo_.softmaxMax.shape = context_->GetOutputShape(SOFTMAXMAX_INDEX); + opParamInfo_.softmaxSum.desc = context_->GetOutputDesc(SOFTMAXSUM_INDEX); + opParamInfo_.softmaxSum.shape = context_->GetOutputShape(SOFTMAXSUM_INDEX); +} + +ge::graphStatus SFALSEInfoParser::GetAttrParaInfo() { + auto attrs = context_->GetAttrs(); + OP_CHECK_IF(attrs == nullptr, + OPS_REPORT_VECTOR_INNER_ERR(context_->GetNodeName(), + "attrs got from ge is nullptr"), + return ge::GRAPH_FAILED); + + opParamInfo_.layoutQuery = attrs->GetStr(LAYOUT_QUERY_ATTR_INDEX); + opParamInfo_.layoutKV = attrs->GetStr(LAYOUT_KV_ATTR_INDEX); + opParamInfo_.sparseBlockSize = + attrs->GetAttrPointer(SPARSE_BLOCK_SIZE_ATTR_INDEX); + opParamInfo_.scaleValue = + attrs->GetAttrPointer(SCALE_VALUE_ATTR_INDEX); + opParamInfo_.sparseMode = + attrs->GetAttrPointer(SPARSE_MODE_ATTR_INDEX); + opParamInfo_.preTokens = + attrs->GetAttrPointer(PRE_TOKENS_ATTR_INDEX); + opParamInfo_.nextTokens = + attrs->GetAttrPointer(NEXT_TOKENS_ATTR_INDEX); + opParamInfo_.attentionMode = + attrs->GetAttrPointer(ATTENTION_MODE_ATTR_INDEX); + opParamInfo_.returnSoftmaxLse = + attrs->GetAttrPointer(RETURN_SOFTMAX_LSE_ATTR_INDEX); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetOpParaInfo() { + GetInputParaInfo(); + GetOutputParaInfo(); + if (ge::GRAPH_SUCCESS != GetAttrParaInfo()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetInOutDataType() { + inputQType_ = opParamInfo_.query.desc->GetDataType(); + inputKvType_ = opParamInfo_.key.desc->GetDataType(); + outputType_ = opParamInfo_.attenOut.desc->GetDataType(); + if (opParamInfo_.queryRope.desc != nullptr) { + inputQRopeType_ = opParamInfo_.queryRope.desc->GetDataType(); + } + if (opParamInfo_.keyRope.desc != nullptr) { + inputKRopeType_ = opParamInfo_.keyRope.desc->GetDataType(); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetBatchSize() { + // 获取B基准值 + // 1、非TND时, 以query的batch_size维度为基准; + // 2、TND时, actual_seq_lens_q必须传入, 以actual_seq_lens_q数组的长度为B轴大小 + if (qLayout_ == SFALSELayout::TND) { + return GetActualSeqLenQSize(bSize_); + } else { // BSND + bSize_ = GetAxisNum(queryShape_, SFAAxis::B, qLayout_); + return ge::GRAPH_SUCCESS; + } +} + +ge::graphStatus SFALSEInfoParser::GetQTSize() { + // 获取query的T基准值 + // 1、非TND时, 以query的batch_size维度为基准; + // 2、TND时, actual_seq_lens_q必须传入, 以actual_seq_lens_q数组的长度为B轴大小 + qTSize_ = (qLayout_ == SFALSELayout::TND) + ? GetAxisNum(queryShape_, SFAAxis::T, qLayout_) + : 0; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetKVTSize() { + // 获取query的T基准值 + // 1、非TND时, 以key的batch_size维度为基准; + // 2、TND时, actual_seq_lens_q必须传入, 以actual_seq_lens_q数组的长度为B轴大小 + kvTSize_ = (kvLayout_ == SFALSELayout::TND) + ? GetAxisNum(keyShape_, SFAAxis::T, kvLayout_) + : 0; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetQkHeadDim() { + // 获取qkHeadDim基准值 + // 以query的D维度为基准 + qkHeadDim_ = GetAxisNum(queryShape_, SFAAxis::D, qLayout_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetS1Size() { + // 获取S1基准值 + // 1、非TND时, 以query的S维度为基准; + // 2、TND时, actual_seq_lens_q必须传入, + // 以actual_seq_lens_q数组中的最大值为基准 + if (qLayout_ == SFALSELayout::TND) { + s1Size_ = GetAxisNum(queryShape_, SFAAxis::T, qLayout_); + return ge::GRAPH_SUCCESS; + } else { // BSND + s1Size_ = GetAxisNum(queryShape_, SFAAxis::S, qLayout_); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetKvStorageMode() { + if (kvLayout_ == SFALSELayout::PA_BSND) { + kvStorageMode_ = KvStorageMode::PAGE_ATTENTION; + } else { + kvStorageMode_ = KvStorageMode::BATCH_CONTINUOUS; + } + // kv存储模式基准值 + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetKvLayout() { + const map layoutKVMap = { + {"BSND", SFALSELayout::BSND}, + {"PA_BSND", SFALSELayout::PA_BSND}, + {"TND", SFALSELayout::TND}}; + + std::string layout(opParamInfo_.layoutKV); + auto it = layoutKVMap.find(layout); + if (it != layoutKVMap.end()) { + kvLayout_ = it->second; + } else { + OP_LOGE(opName_, "layoutKV is %s, it is unsupported.", layout.c_str()); + return ge::GRAPH_FAILED; + } + if (kvLayout_ != SFALSELayout::PA_BSND && qLayout_ != kvLayout_) { + OP_LOGE( + opName_, + "When layoutKV is not PA_BSND, layoutKV must be the same as layoutQ."); + return ge::GRAPH_FAILED; + } + uint32_t keyDimNum = opParamInfo_.key.shape->GetStorageShape().GetDimNum(); + if (kvLayout_ == SFALSELayout::PA_BSND && keyDimNum != 4U) { + OP_LOGE(opName_, + "When layoutKV is PA_BSND, kvDimNum must be 4, but now is %d.", + keyDimNum); + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetS2SizeForBatchContinuous() { + if (kvLayout_ == SFALSELayout::BSND) { // BSND + s2Size_ = GetAxisNum(keyShape_, SFAAxis::S, kvLayout_); + } else if (kvLayout_ == SFALSELayout::TND) { + s2Size_ = GetAxisNum(keyShape_, SFAAxis::T, kvLayout_); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetMaxBlockNumPerBatch() { + if (opParamInfo_.blockTable.tensor == nullptr) { + OP_LOGE(opName_, + "the layout_kv is %s, blockTable must be provided.", + SFALSELayoutToSerialString(kvLayout_).c_str()); + return ge::GRAPH_FAILED; + } + uint32_t dimNum = + opParamInfo_.blockTable.tensor->GetStorageShape().GetDimNum(); + if (dimNum != DIM_NUM_TWO) { + OP_LOGE(opName_, + "the dim num of block_table is %u, it should be %u.", + dimNum, + DIM_NUM_TWO); + return ge::GRAPH_FAILED; + } + if (opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(1) <= 0) { + OP_LOGE(opName_, + "%s's second dimension(%ld) should be greater than 0", + BLOCK_TABLE_NAME.c_str(), + opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(1)); + return ge::GRAPH_FAILED; + } + maxBlockNumPerBatch_ = + opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(1); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetBlockSize() { + blockSize_ = GetAxisNum(keyShape_, SFAAxis::Bs, kvLayout_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetSparseBlockCount() { + sparseBlockCount_ = GetAxisNum(sparseIndicesShape_, SFAAxis::K, qLayout_); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetS2SizeForPageAttention() { + if (GetMaxBlockNumPerBatch() != ge::GRAPH_SUCCESS || + GetBlockSize() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + s2Size_ = maxBlockNumPerBatch_ * blockSize_; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetS2Size() { + // 获取S2基准值 + // 1、BATCH_CONTINUOUS时, 从key的S轴获取 + // 2、PAGE_ATTENTION时, S2 = block_table.dim1 * block_size + if (kvStorageMode_ == KvStorageMode::BATCH_CONTINUOUS) { + return GetS2SizeForBatchContinuous(); + } + return GetS2SizeForPageAttention(); +} + +ge::graphStatus SFALSEInfoParser::GetValueHeadDim() { + // 获取vHeadDim基准值 + // 以value的D维度为基准 + vHeadDim_ = GetAxisNum(valueShape_, SFAAxis::D, kvLayout_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetRopeHeadDim() { + if (opParamInfo_.queryRope.tensor == nullptr) { + // NoPE场景: 无rope输入, ropeHeadDim按0处理 + ropeHeadDim_ = 0; + return ge::GRAPH_SUCCESS; + } + if (queryShape_.GetDimNum() != queryRopeShape_.GetDimNum()) { + OP_LOGE(opName_, + "The dimensions of query and query_rope should be equal, but query " + "has dimension %zu while query_rope has dimension %zu.", + queryShape_.GetDimNum(), + queryRopeShape_.GetDimNum()); + return ge::GRAPH_PARAM_INVALID; + } + ropeHeadDim_ = GetAxisNum(queryRopeShape_, SFAAxis::D, qLayout_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetQueryAndOutLayout() { + // 获取query和attentionOut的Layout基准值 + // layoutQuery: {qLayout, outLayout} + const map> layoutMap = { + {"BSND", {SFALSELayout::BSND, SFALSELayout::BSND}}, + {"TND", {SFALSELayout::TND, SFALSELayout::TND}}, + }; + + std::string layout(opParamInfo_.layoutQuery); + auto it = layoutMap.find(layout); + if (it != layoutMap.end()) { + qLayout_ = it->second.first; + outLayout_ = it->second.second; + } else { + OP_LOGE(opName_, "layoutQuery is %s, it is unsupported.", layout.c_str()); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetTopkLayout() { + topkLayout_ = qLayout_; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetSoftmaxMaxAndSumLayout() { + if (qLayout_ == SFALSELayout::BSND) { + softmaxMaxLayout_ = SFALSELayout::BNSG; + softmaxSumLayout_ = SFALSELayout::BNSG; + } else if (qLayout_ == SFALSELayout::TND) { + softmaxMaxLayout_ = SFALSELayout::NTG; + softmaxSumLayout_ = SFALSELayout::NTG; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetN1Size() { + n1Size_ = GetAxisNum(queryShape_, SFAAxis::N, qLayout_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetN2Size() { + n2Size_ = GetAxisNum(keyShape_, SFAAxis::N, kvLayout_); + return ge::GRAPH_SUCCESS; +} + +void SFALSEInfoParser::SetSFAShape() { + queryShape_ = opParamInfo_.query.shape->GetStorageShape(); + keyShape_ = opParamInfo_.key.shape->GetStorageShape(); + valueShape_ = opParamInfo_.value.shape->GetStorageShape(); + sparseIndicesShape_ = opParamInfo_.sparseIndices.shape->GetStorageShape(); + if (opParamInfo_.queryRope.tensor != nullptr) { + queryRopeShape_ = opParamInfo_.queryRope.tensor->GetStorageShape(); + } +} + +ge::graphStatus SFALSEInfoParser::GetGSize() { + if (n2Size_ != 0) { + gSize_ = n1Size_ / n2Size_; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFALSEInfoParser::GetActualseqInfo() { + maxActualseq_ = static_cast(s2Size_); + if (opParamInfo_.actualSeqLengths.tensor != nullptr) { + actualLenDimsKV_ = opParamInfo_.actualSeqLengths.tensor->GetShapeSize(); + } + if (opParamInfo_.actualSeqLengthsQ.tensor != nullptr) { + actualLenDimsQ_ = opParamInfo_.actualSeqLengthsQ.tensor->GetShapeSize(); + } + return ge::GRAPH_SUCCESS; +} + +void SFALSEInfoParser::GenerateInfo(SFALSETilingInfo& sfaInfo) { + sfaInfo.opName = opName_; + sfaInfo.platformInfo = platformInfo_; + sfaInfo.opParamInfo = opParamInfo_; + sfaInfo.npuArch = npuArch_; + sfaInfo.isA5 = isA5_; + + sfaInfo.bSize = bSize_; + sfaInfo.n1Size = n1Size_; + sfaInfo.n2Size = n2Size_; + sfaInfo.s1Size = s1Size_; + sfaInfo.s2Size = s2Size_; + sfaInfo.gSize = gSize_; + sfaInfo.qkHeadDim = qkHeadDim_; + sfaInfo.vHeadDim = vHeadDim_; + sfaInfo.ropeHeadDim = ropeHeadDim_; + sfaInfo.qTSize = qTSize_; + sfaInfo.kvTSize = kvTSize_; + sfaInfo.sparseBlockSize = *opParamInfo_.sparseBlockSize; + sfaInfo.sparseBlockCount = sparseBlockCount_; + + sfaInfo.inputQType = inputQType_; + sfaInfo.inputKvType = inputKvType_; + sfaInfo.inputQRopeType = inputQRopeType_; + sfaInfo.inputKRopeType = inputKRopeType_; + sfaInfo.outputType = outputType_; + + sfaInfo.kvStorageMode = kvStorageMode_; + sfaInfo.l2CacheSize = l2CacheSize_; + + sfaInfo.totalBlockNum = opParamInfo_.key.shape->GetStorageShape().GetDim(0); + sfaInfo.scaleValue = *opParamInfo_.scaleValue; + sfaInfo.pageAttentionFlag = (kvStorageMode_ == KvStorageMode::PAGE_ATTENTION); + sfaInfo.blockSize = blockSize_; + sfaInfo.blockTypeSize = sizeof(float); + sfaInfo.maxBlockNumPerBatch = maxBlockNumPerBatch_; + + sfaInfo.actualLenDimsQ = actualLenDimsQ_; + sfaInfo.actualLenDimsKV = actualLenDimsKV_; + sfaInfo.maxActualseq = maxActualseq_; + sfaInfo.isSameSeqAllKVTensor = isSameSeqAllKVTensor_; + sfaInfo.isSameActualseq = isSameActualseq_; + + sfaInfo.actualQSeqLenFlag = + (opParamInfo_.actualSeqLengthsQ.tensor != nullptr); + sfaInfo.actualSeqLenFlag = (opParamInfo_.actualSeqLengths.tensor != nullptr); + + sfaInfo.sparseMode = *opParamInfo_.sparseMode; + sfaInfo.preTokens = *opParamInfo_.preTokens; + sfaInfo.nextTokens = *opParamInfo_.nextTokens; + sfaInfo.attentionMode = *opParamInfo_.attentionMode; + sfaInfo.returnSoftmaxLse = *opParamInfo_.returnSoftmaxLse; + + sfaInfo.qLayout = qLayout_; + sfaInfo.topkLayout = topkLayout_; + sfaInfo.kvLayout = kvLayout_; + sfaInfo.outLayout = outLayout_; + sfaInfo.softmaxMaxLayout = softmaxMaxLayout_; + sfaInfo.softmaxSumLayout = softmaxSumLayout_; +} + +ge::graphStatus SFALSEInfoParser::Parse(SFALSETilingInfo& sfaInfo) { + if (context_ == nullptr) { + OP_LOGE("XllmKernelSparseFlashAttentionLse", "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()) { + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != GetInOutDataType() || + ge::GRAPH_SUCCESS != GetQueryAndOutLayout() || + ge::GRAPH_SUCCESS != GetTopkLayout() || + ge::GRAPH_SUCCESS != GetSoftmaxMaxAndSumLayout() || + ge::GRAPH_SUCCESS != GetKvLayout() || + ge::GRAPH_SUCCESS != GetKvStorageMode()) { + return ge::GRAPH_FAILED; + } + + SetSFAShape(); + if (ge::GRAPH_SUCCESS != GetN1Size() || ge::GRAPH_SUCCESS != GetN2Size() || + ge::GRAPH_SUCCESS != GetGSize() || ge::GRAPH_SUCCESS != GetBatchSize() || + ge::GRAPH_SUCCESS != GetQTSize() || ge::GRAPH_SUCCESS != GetKVTSize() || + ge::GRAPH_SUCCESS != GetS1Size() || ge::GRAPH_SUCCESS != GetQkHeadDim() || + ge::GRAPH_SUCCESS != GetS2Size() || + ge::GRAPH_SUCCESS != GetValueHeadDim() || + ge::GRAPH_SUCCESS != GetRopeHeadDim() || + ge::GRAPH_SUCCESS != GetSparseBlockCount()) { + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != GetActualseqInfo()) { + return ge::GRAPH_FAILED; + } + + GenerateInfo(sfaInfo); + return ge::GRAPH_SUCCESS; +} + +IMPL_OP_OPTILING(XllmKernelSparseFlashAttentionLse) + .Tiling(TilingSparseFlashAttentionLse) + .TilingParse( + TilingPrepareForSparseFlashAttentionLse); +} // namespace optiling diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_host/sparse_flash_attention_lse_tiling.h b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_host/sparse_flash_attention_lse_tiling.h new file mode 100644 index 0000000000..504760b4c8 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_host/sparse_flash_attention_lse_tiling.h @@ -0,0 +1,682 @@ +/** + * 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 sparse_flash_attention_lse_tiling.h + * \brief + */ +#ifndef SPARSE_FLASH_ATTENTION_LSE_TILING_H +#define SPARSE_FLASH_ATTENTION_LSE_TILING_H + +#include +#include +#include + +#include + +#include "exe_graph/runtime/tiling_context.h" +#include "register/tilingdata_base.h" + +namespace optiling { +// ------------------算子原型索引常量定义---------------- +// Inputs Index +constexpr uint32_t QUERY_INPUT_INDEX = 0; +constexpr uint32_t KEY_INPUT_INDEX = 1; +constexpr uint32_t VALUE_INPUT_INDEX = 2; +constexpr uint32_t SPARSE_INDICES_INPUT_INDEX = 3; +constexpr uint32_t BLOCK_TABLE_INPUT_INDEX = 4; +constexpr uint32_t ACT_SEQ_LEN_Q_INPUT_INDEX = 5; +constexpr uint32_t ACT_SEQ_LEN_KV_INPUT_INDEX = 6; +constexpr uint32_t QUERY_ROPE_INPUT_INDEX = 7; +constexpr uint32_t KEY_ROPE_INPUT_INDEX = 8; +// Outputs Index +constexpr uint32_t OUTPUT_INDEX = 0; +constexpr uint32_t SOFTMAXMAX_INDEX = 1; +constexpr uint32_t SOFTMAXSUM_INDEX = 2; + +// Attributes Index +constexpr uint32_t SCALE_VALUE_ATTR_INDEX = 0; +constexpr uint32_t SPARSE_BLOCK_SIZE_ATTR_INDEX = 1; +constexpr uint32_t LAYOUT_QUERY_ATTR_INDEX = 2; +constexpr uint32_t LAYOUT_KV_ATTR_INDEX = 3; +constexpr uint32_t SPARSE_MODE_ATTR_INDEX = 4; +constexpr uint32_t PRE_TOKENS_ATTR_INDEX = 5; +constexpr uint32_t NEXT_TOKENS_ATTR_INDEX = 6; +constexpr uint32_t ATTENTION_MODE_ATTR_INDEX = 7; +constexpr uint32_t RETURN_SOFTMAX_LSE_ATTR_INDEX = 8; +// Dim Num +constexpr size_t DIM_NUM_TWO = 2; +constexpr size_t DIM_NUM_THREE = 3; +constexpr size_t DIM_NUM_FOUR = 4; +// 常量 +constexpr uint32_t MAX_BLOCK_SIZE = 1024; +constexpr uint32_t COPYND2NZ_SRC_STRIDE_LIMITATION = 65535; +constexpr uint32_t NUM_BYTES_FLOAT = 4; +constexpr uint32_t NUM_BYTES_FLOAT16 = 2; +constexpr uint32_t NUM_BYTES_BF16 = 2; +constexpr uint32_t BYTE_BLOCK = 32; +const uint32_t SFA_MAX_AIC_CORE_NUM = 26; // 25 + 1 保证数组8字节对齐 + +// ------------------公共定义-------------------------- +enum class SFALSELayout : uint32_t { + BSND = 0, + TND = 1, + PA_BSND = 2, + BNSG = 3, + NTG = 4 +}; + +struct SFALSETilingShapeCompareParam { + int64_t B = 1; + int64_t S = 1; + int64_t N = 1; + int64_t D = 1; + int64_t T = 1; + int64_t G = 1; + // PA + int64_t Bs = 1; + int64_t Bn = 1; +}; + +enum class KvStorageMode : uint32_t { + BATCH_CONTINUOUS = 0, + PAGE_ATTENTION = 1 +}; + +enum class SFAPerfMode : uint32_t { C_TEMPLATE_MODE = 0, V_TEMPLATE_MODE }; + +enum class SFAAxis : 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 + G = 8, +}; + +struct SFARequiredParaInfo { + const gert::CompileTimeTensorDesc* desc; + const gert::StorageShape* shape; +}; + +struct SFAOptionalParaInfo { + const gert::CompileTimeTensorDesc* desc; + const gert::Tensor* tensor; +}; + +// -----------算子Tiling入参结构体定义--------------- +struct SFAParaInfo { + SFARequiredParaInfo query = {nullptr, nullptr}; + SFARequiredParaInfo key = {nullptr, nullptr}; + SFARequiredParaInfo value = {nullptr, nullptr}; + SFARequiredParaInfo sparseIndices = {nullptr, nullptr}; + SFAOptionalParaInfo blockTable = {nullptr, nullptr}; + SFAOptionalParaInfo actualSeqLengthsQ = {nullptr, nullptr}; + SFAOptionalParaInfo actualSeqLengths = {nullptr, nullptr}; + SFAOptionalParaInfo queryRope = {nullptr, nullptr}; + SFAOptionalParaInfo keyRope = {nullptr, nullptr}; + SFARequiredParaInfo attenOut = {nullptr, nullptr}; + SFARequiredParaInfo softmaxMax = {nullptr, nullptr}; + SFARequiredParaInfo softmaxSum = {nullptr, nullptr}; + + const char* layoutQuery = nullptr; + const char* layoutKV = nullptr; + const int64_t* sparseBlockSize = nullptr; + const float* scaleValue = nullptr; + const int64_t* sparseMode = nullptr; + const int64_t* preTokens = nullptr; + const int64_t* nextTokens = nullptr; + const int64_t* attentionMode = nullptr; + const bool* returnSoftmaxLse = nullptr; +}; + +struct InnerSplitParams { + uint32_t s1GBaseSize = 1; + uint32_t s2BaseSize = 1; +}; + +// -----------算子TilingData定义--------------- +BEGIN_TILING_DATA_DEF(SparseFlashAttentionLseBaseParamsMla) +TILING_DATA_FIELD_DEF(uint32_t, batchSize) +TILING_DATA_FIELD_DEF(uint32_t, seqSize) +TILING_DATA_FIELD_DEF(uint32_t, qSeqSize) +TILING_DATA_FIELD_DEF(int64_t, blockSize) +TILING_DATA_FIELD_DEF(uint32_t, maxBlockNumPerBatch) +TILING_DATA_FIELD_DEF(float, scaleValue) +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(uint32_t, outputLayout) +TILING_DATA_FIELD_DEF(uint32_t, sparseMode) +TILING_DATA_FIELD_DEF(int64_t, preTokens) +TILING_DATA_FIELD_DEF(int64_t, nextTokens) +TILING_DATA_FIELD_DEF(uint32_t, attentionMode) +TILING_DATA_FIELD_DEF(uint32_t, returnSoftmaxLse) +TILING_DATA_FIELD_DEF(int64_t, sparseBlockSize) +TILING_DATA_FIELD_DEF(uint32_t, sparseBlockCount) +TILING_DATA_FIELD_DEF(uint32_t, isActualLenDimsNull) +TILING_DATA_FIELD_DEF(uint32_t, isActualLenDimsKVNull) +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(SparseFlashAttentionLseBaseParamsMlaOp, + SparseFlashAttentionLseBaseParamsMla) + +BEGIN_TILING_DATA_DEF(SparseFlashAttentionLseSingleCoreParamsMla) +TILING_DATA_FIELD_DEF(uint32_t, usedCoreNum); +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(SparseFlashAttentionLseSingleCoreParamsMlaOp, + SparseFlashAttentionLseSingleCoreParamsMla) + +BEGIN_TILING_DATA_DEF(SparseFlashAttentionLseSingleCoreTensorSizeMla) +TILING_DATA_FIELD_DEF(uint32_t, mmResUbSize); +TILING_DATA_FIELD_DEF(uint32_t, bmm2ResUbSize); +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(SparseFlashAttentionLseSingleCoreTensorSizeMlaOp, + SparseFlashAttentionLseSingleCoreTensorSizeMla) + +BEGIN_TILING_DATA_DEF(SparseFlashAttentionLseSplitKVParamsMla) +TILING_DATA_FIELD_DEF(uint32_t, s2) // S2切分份数 +TILING_DATA_FIELD_DEF(uint32_t, accumOutSize) // FD workspace +TILING_DATA_FIELD_DEF(uint32_t, logSumExpSize) // FD workspace +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(SparseFlashAttentionLseSplitKVParamsMlaOp, + SparseFlashAttentionLseSplitKVParamsMla) + +// 内切基本块参数 +BEGIN_TILING_DATA_DEF(SparseFlashAttentionLseInnerSplitParams) +TILING_DATA_FIELD_DEF(uint32_t, mBaseSize) +TILING_DATA_FIELD_DEF(uint32_t, s2BaseSize) +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(SparseFlashAttentionLseInnerSplitParamsOp, + SparseFlashAttentionLseInnerSplitParams) + +BEGIN_TILING_DATA_DEF(SparseFlashAttentionLseTilingDataMla) +TILING_DATA_FIELD_DEF_STRUCT(SparseFlashAttentionLseBaseParamsMla, baseParams); +TILING_DATA_FIELD_DEF_STRUCT(SparseFlashAttentionLseSplitKVParamsMla, + splitKVParams); +TILING_DATA_FIELD_DEF_STRUCT(SparseFlashAttentionLseSingleCoreParamsMla, + singleCoreParams); +TILING_DATA_FIELD_DEF_STRUCT(SparseFlashAttentionLseSingleCoreTensorSizeMla, + singleCoreTensorSize); +TILING_DATA_FIELD_DEF_STRUCT(SparseFlashAttentionLseInnerSplitParams, + innerSplitParams); +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(XllmKernelSparseFlashAttentionLse, + SparseFlashAttentionLseTilingDataMla) + +template +inline T Align(T num, T rnd) { + return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd) * (rnd))); +} + +template +std::string SFAShape2String(const T& shape) { + std::ostringstream oss; + oss << "["; + if (shape.GetDimNum() > 0) { + for (size_t i = 0; i < shape.GetDimNum() - 1; ++i) { + oss << shape.GetDim(i) << ", "; + } + oss << shape.GetDim(shape.GetDimNum() - 1); + } + oss << "]"; + return oss.str(); +} + +static std::string GetShapeStr(gert::Shape shape); +static std::string SFADataTypeToSerialString(ge::DataType type); +std::string SFALSETensorDesc2String(const gert::StorageShape* shape, + const gert::CompileTimeTensorDesc* tensor); +std::string SFALSEDebugTilingContext(const gert::TilingContext* context); +std::string SFALSELayoutToSerialString(SFALSELayout layout); + +// -----------算子Tiling入参信息类--------------- +struct SFALSETilingInfo { + const char* opName = nullptr; + fe::PlatFormInfos* platformInfo = nullptr; + SFAParaInfo opParamInfo; + + // Base Param + NpuArch npuArch = NpuArch::DAV_2201; + bool isA5 = false; + 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 vHeadDim = 0; + uint32_t gSize = 0; + uint32_t ropeHeadDim = 0; + uint32_t qTSize = 0; // 仅TND时生效 + uint32_t kvTSize = 0; // 仅TND时生效 + float scaleValue = 0; + uint32_t innerPrecise = 0; + uint32_t l2CacheOffFlag = 0; + int64_t sparseBlockSize = 0; + int64_t sparseBlockCount = 0; + + bool pageAttentionFlag = false; + int64_t blockSize = 0; + uint32_t blockTypeSize = 0; + uint32_t maxBlockNumPerBatch = 0; + uint32_t totalBlockNum = 0; + + uint32_t actualLenDimsQ = 0; + uint32_t maxActualseq = 0; + + bool actualQSeqLenFlag = false; + bool actualSeqLenFlag = false; + bool isSameSeqAllKVTensor = true; + bool isSameActualseq = true; + uint32_t actualLenDimsKV = 0; + std::vector kvListSeqLens{}; + + uint32_t sparseMode = 0; + int64_t preTokens = INT64_MAX; + int64_t nextTokens = INT64_MAX; + uint32_t attentionMode = 2; + bool returnSoftmaxLse = false; + + ge::DataType inputQType = ge::DT_FLOAT16; + ge::DataType inputKvType = ge::DT_FLOAT16; + ge::DataType outputType = ge::DT_FLOAT16; + + KvStorageMode kvStorageMode = KvStorageMode::BATCH_CONTINUOUS; + + SFALSELayout qLayout = SFALSELayout::BSND; + SFALSELayout topkLayout = SFALSELayout::BSND; + SFALSELayout outLayout = SFALSELayout::BSND; + SFALSELayout kvLayout = SFALSELayout::BSND; + SFALSELayout softmaxMaxLayout = SFALSELayout::BNSG; + SFALSELayout softmaxSumLayout = SFALSELayout::BNSG; + + ge::DataType inputQRopeType = ge::DT_FLOAT16; + ge::DataType inputKRopeType = ge::DT_FLOAT16; + + uint64_t l2CacheSize = 0; +}; + +// ---------------算子Tiling类--------------- +class SFALSEMlaTiling { + public: + explicit SFALSEMlaTiling(gert::TilingContext* context) : context_(context) {} + ge::graphStatus DoOpTiling(SFALSETilingInfo* sfaInfo); + + private: + ge::graphStatus SetBlockDim(uint32_t blockDim) const; + ge::graphStatus SetTilingKey(uint64_t tilingKey) const; + ge::graphStatus SetWorkspaceSize(uint64_t workspaceSize) const; + ge::graphStatus SetTilingData(TilingDef& tilingData) const; + gert::TilingContext* context_ = nullptr; + ge::graphStatus GetPlatformInfo(); + void GenTilingKey(); + bool DealSameSeqEachBatch(); + + void ZeroTensorProcess() const; + void InitParams(); + + void Split(); + bool IsBalanceSplitCore(); + + void SplitBalanced(); + void CalcInnerSize(uint32_t s2Size); + + bool IsFlashDecode(uint32_t coreNum); + + void FillTilingBaseParamsMla(); + void FillTilingSplitKVMla(); + + void FillTilingSingleCoreParamsMla(); + void FillTilingSingleCoreTensorSizeMla(); + void FillTiling(); + + void CalcUbBmm(); + void CheckUbSpace(); + void NormalCalcFDWorkSpace(const uint32_t actCoreNum); + void CalcFDWorkSpace(const uint32_t actCoreNum); + void GetWorkspaceSize(); + + uint32_t CalcBalanceFDParamNums(const uint32_t actCoreNum) const; + + void CalcBlockDim(); + + uint32_t GetTypeSize(ge::DataType dtype) const; + + bool balanceModeFlag_ = false; + bool splitKVFlag_ = false; + + uint32_t coreNum_ = 0; + SFAPerfMode perfMode_ = SFAPerfMode::V_TEMPLATE_MODE; + uint32_t kvSplitPart_ = 1; + size_t mmResUbSize_ = 0; + size_t bmm2ResUbSize_ = 0; + size_t qPreSizeMla_ = 0; + uint32_t sInnerLoopTimes_ = 0; + uint32_t sInnerSize_ = 0; + uint32_t sInnerSizeTail_ = 0; + uint32_t sInnerSizeAlign_ = 0; + uint32_t kvSplit_ = 0; + uint32_t usedCoreNum_ = 0; + uint32_t formerCoreNum_ = 0; + uint32_t blockSplitBn2Range_ = 0; + uint32_t tailSplitedBatchRange_ = 0; + + uint32_t aicNum_ = 0; + uint32_t aivNum_ = 0; + size_t libapiSize_ = 0; + + SparseFlashAttentionLseTilingDataMla tilingData_; + uint32_t blockDim_{0}; + uint64_t workspaceSize_{0}; + uint64_t tilingKey_{0}; + + uint32_t headDimAlign_ = 0; + uint32_t mBaseSize_ = 128; + uint32_t mFdBaseSize_ = 8; + + SFALSETilingInfo* sfaInfo_ = nullptr; +}; + +// -----------算子Tiling入参信息解析及Check类--------------- +class SFALSETilingCheck { + public: + explicit SFALSETilingCheck(const SFALSETilingInfo& sfaInfo) + : sfaInfo_(sfaInfo) {}; + ~SFALSETilingCheck() = 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 CheckDtypeSupport(const gert::CompileTimeTensorDesc* desc, + const std::string& name) const; + template + void LogErrorNumberSupport(const std::vector& expectNumberList, + const T& actualValue, + const std::string& name, + const std::string subName) const; + template + void LogErrorDimNumSupport(const std::vector& expectNumberList, + const T& actualValue, + const std::string& name) const; + ge::graphStatus CheckDimNumSupport( + const gert::StorageShape* shape, + const std::vector& expectDimNumList, + const std::string& name) const; + ge::graphStatus CheckDimNumInLayoutSupport(const SFALSELayout& layout, + const gert::StorageShape* shape, + const std::string& name) const; + void LogErrorLayoutSupport(const std::vector& expectLayoutList, + const SFALSELayout& actualLayout, + const std::string& name) const; + ge::graphStatus GetExpectedShape(gert::Shape& shapeExpected, + const SFALSETilingShapeCompareParam& param, + const SFALSELayout& layout) const; + ge::graphStatus CompareShape(SFALSETilingShapeCompareParam& param, + const gert::Shape& shape, + const SFALSELayout& layout, + const std::string& name) const; + ge::graphStatus CheckLayoutSupport(const SFALSELayout& actualLayout, + const std::string& name) const; + ge::graphStatus CheckSingleParaQuery() const; + ge::graphStatus CheckSingleParaKey() const; + ge::graphStatus CheckSingleParaValue() const; + ge::graphStatus CheckSingleParaQueryRope() const; + ge::graphStatus CheckSingleParaKeyRope() const; + ge::graphStatus CheckSingleParaAttenOut() const; + ge::graphStatus CheckSingleParaNumHeads() const; + ge::graphStatus CheckSingleParaKvHeadNums() const; + ge::graphStatus CheckSingleParaLayout() const; + ge::graphStatus CheckSingleParaSparseMode() const; + ge::graphStatus CheckSingleParaSparseBlockSize() const; + ge::graphStatus CheckSingleParaSparseIndices() const; + ge::graphStatus CheckSinglePara() const; + ge::graphStatus CheckMultiParaConsistency() const; + ge::graphStatus CheckRopeExistence(); + 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; + template + ge::graphStatus CheckAttrValueByMap( + std::map>& attrMap) const; + ge::graphStatus CheckParaExistenceMlaNoquant() const; + ge::graphStatus CheckParaExistenceGqaNoquant() const; + ge::graphStatus CheckParaExistenceMla() const; + ge::graphStatus CheckParaExistence(); + ge::graphStatus GetActualSeqLenSize(uint32_t& size, + const gert::Tensor* tensor, + const SFALSELayout& layout, + const std::string& name) const; + void SetSFAShapeCompare(); + ge::graphStatus CheckQRope(); + ge::graphStatus CheckQRopeShape(); + ge::graphStatus CheckVAndKRopeShapeForBatchContinuous(); + ge::graphStatus CheckVAndKRopeShapeForPageAttention(); + ge::graphStatus CheckVAndKRopeShape(); + ge::graphStatus CheckVAndKShapeWithoutRope(); + ge::graphStatus CheckVAndKRope(); + ge::graphStatus CheckTopK(); + ge::graphStatus CheckTopkShape(); + ge::graphStatus CheckBlockTable() const; + ge::graphStatus CheckDTypeConsistency(const ge::DataType& actualDtype, + const ge::DataType& expectDtype, + const std::string& name) const; + + ge::graphStatus CheckAttenOut(); + ge::graphStatus CheckAttenOutShape(); + ge::graphStatus CheckSoftmaxMax(); + ge::graphStatus CheckSoftmaxMaxShape(); + ge::graphStatus CheckSoftmaxSum(); + ge::graphStatus CheckSoftmaxSumShape(); + ge::graphStatus CheckActualSeqLensQ(); + ge::graphStatus CheckActualSeqLensQShape(); + ge::graphStatus CheckActualSeqLensQDType(); + ge::graphStatus CheckActualSeqLens(); + ge::graphStatus CheckActualSeqLensDType(); + ge::graphStatus CheckActualSeqLensShape(); + ge::graphStatus CheckMultiParaConsistency(); + + ge::graphStatus CheckFeatureMlaNoQuantShape() const; + ge::graphStatus CheckFeatureMlaNoQuantLayout() const; + ge::graphStatus CheckFeatureMlaNoQuantDtype() const; + ge::graphStatus CheckFeatureMlaNoquantPa() const; + ge::graphStatus CheckFeatureMlaNoquant() const; + ge::graphStatus CheckFeatureMla() const; + ge::graphStatus CheckFeature() const; + + ge::graphStatus CheckSingleParaPreTokens() const; + ge::graphStatus CheckSingleParaNextTokens() const; + + private: + const char* opName_; + fe::PlatFormInfos* platformInfo_; + SFAParaInfo opParamInfo_; + const SFALSETilingInfo& sfaInfo_; + + 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 qkHeadDim_ = 0; + uint32_t vHeadDim_ = 0; + uint32_t ropeHeadDim_ = 0; + uint32_t qTSize_ = 0; // 仅TND时生效 + uint32_t kvTSize_ = 0; // 仅TND时生效 + KvStorageMode kvStorageMode_ = KvStorageMode::BATCH_CONTINUOUS; + uint32_t sparseBlockCount_ = 0; + int64_t sparseBlockSize_ = 0; + + SFALSELayout qLayout_ = SFALSELayout::BSND; + SFALSELayout topkLayout_ = SFALSELayout::BSND; + SFALSELayout outLayout_ = SFALSELayout::BSND; + SFALSELayout kvLayout_ = SFALSELayout::BSND; + SFALSELayout softmaxMaxLayout_ = SFALSELayout::BNSG; + SFALSELayout softmaxSumLayout_ = SFALSELayout::BNSG; + + uint32_t maxBlockNumPerBatch_ = 0; + int64_t blockSize_ = 0; + + uint32_t aicNum_ = 0; + uint32_t aivNum_ = 0; + NpuArch npuArch_ = NpuArch::DAV_2201; + bool isA5_ = false; + uint64_t l2CacheSize_ = 0; + + ge::DataType inputQType_ = ge::DT_FLOAT16; + ge::DataType inputKvType_ = ge::DT_FLOAT16; + ge::DataType outputType_ = ge::DT_FLOAT16; + ge::DataType inputQRopeType_ = ge::DT_FLOAT16; + ge::DataType inputKRopeType_ = ge::DT_FLOAT16; + + gert::Shape queryShapeCmp_{}; + gert::Shape keyShapeCmp_{}; + gert::Shape valueShapeCmp_{}; + gert::Shape topkShapeCmp_{}; + gert::Shape queryRopeShapeCmp_{}; + gert::Shape keyRopeShapeCmp_{}; + gert::Shape attenOutShapeCmp_{}; + gert::Shape softmaxMaxShapeCmp_{}; + gert::Shape softmaxSumShapeCmp_{}; +}; + +class SFALSEInfoParser { + public: + explicit SFALSEInfoParser(const gert::TilingContext* context) + : context_(context) {} + ~SFALSEInfoParser() = default; + + ge::graphStatus CheckRequiredInOutExistence() const; + ge::graphStatus CheckRequiredAttrExistence() const; + ge::graphStatus CheckRequiredParaExistence() const; + + ge::graphStatus GetActualSeqLenSize(uint32_t& size, + const gert::Tensor* tensor, + SFALSELayout& layout, + const std::string& name) const; + ge::graphStatus GetActualSeqLenQSize(uint32_t& size); + ge::graphStatus GetOpName(); + ge::graphStatus GetNpuInfo(); + void GetOptionalInputParaInfo(); + void GetInputParaInfo(); + void GetOutputParaInfo(); + ge::graphStatus GetAttrParaInfo(); + ge::graphStatus GetKvCache(); + ge::graphStatus GetOpParaInfo(); + + ge::graphStatus GetInOutDataType(); + ge::graphStatus GetBatchSize(); + ge::graphStatus GetQTSize(); + ge::graphStatus GetKVTSize(); + ge::graphStatus GetQkHeadDim(); + ge::graphStatus GetS1Size(); + ge::graphStatus GetKvStorageMode(); + ge::graphStatus GetKvLayout(); + void SetSFAShape(); + ge::graphStatus GetS2SizeForBatchContinuous(); + ge::graphStatus GetMaxBlockNumPerBatch(); + ge::graphStatus GetBlockSize(); + ge::graphStatus GetS2SizeForPageAttention(); + ge::graphStatus GetS2Size(); + ge::graphStatus GetValueHeadDim(); + ge::graphStatus GetRopeHeadDim(); + ge::graphStatus GetQueryAndOutLayout(); + ge::graphStatus GetTopkLayout(); + ge::graphStatus GetSoftmaxMaxAndSumLayout(); + ge::graphStatus GetN1Size(); + ge::graphStatus GetN2Size(); + ge::graphStatus GetGSize(); + ge::graphStatus GetSparseBlockCount(); + ge::graphStatus GetActualseqInfo(); + void GenerateInfo(SFALSETilingInfo& sfaInfo); + ge::graphStatus Parse(SFALSETilingInfo& sfaInfo); + + public: + bool HasAxis(const SFAAxis& axis, + const SFALSELayout& layout, + const gert::Shape& shape) const; + size_t GetAxisIdx(const SFAAxis& axis, const SFALSELayout& layout) const; + uint32_t GetAxisNum(const gert::Shape& shape, + const SFAAxis& axis, + const SFALSELayout& layout) const; + + const gert::TilingContext* context_ = nullptr; + + const char* opName_; + fe::PlatFormInfos* platformInfo_; + SFAParaInfo opParamInfo_; + static constexpr int64_t invalidDimValue_ = + std::numeric_limits::min(); + + 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 qkHeadDim_ = 0; + uint32_t vHeadDim_ = 0; + uint32_t ropeHeadDim_ = 0; + uint32_t qTSize_ = 0; // 仅TND时生效 + uint32_t kvTSize_ = 0; // 仅TND时生效 + KvStorageMode kvStorageMode_ = KvStorageMode::BATCH_CONTINUOUS; + uint32_t sparseBlockCount_ = 0; + + SFALSELayout qLayout_ = SFALSELayout::BSND; + SFALSELayout topkLayout_ = SFALSELayout::BSND; + SFALSELayout outLayout_ = SFALSELayout::BSND; + SFALSELayout kvLayout_ = SFALSELayout::BSND; + SFALSELayout softmaxMaxLayout_ = SFALSELayout::BNSG; + SFALSELayout softmaxSumLayout_ = SFALSELayout::BNSG; + uint32_t maxBlockNumPerBatch_ = 0; + uint32_t blockSize_ = 0; + + NpuArch npuArch_ = NpuArch::DAV_2201; + bool isA5_ = false; + + ge::DataType inputQType_ = ge::DT_FLOAT16; + ge::DataType inputKvType_ = ge::DT_FLOAT16; + ge::DataType outputType_ = ge::DT_FLOAT16; + ge::DataType inputQRopeType_ = ge::DT_FLOAT16; + ge::DataType inputKRopeType_ = ge::DT_FLOAT16; + + uint64_t l2CacheSize_ = 0; + + bool isSameSeqAllKVTensor_ = true; + bool isSameActualseq_ = true; + uint32_t maxActualseq_ = 0; + + uint32_t actualLenDimsQ_ = 0; + uint32_t actualLenDimsKV_ = 0; + + gert::Shape queryShape_{}; + gert::Shape keyShape_{}; + gert::Shape valueShape_{}; + gert::Shape sparseIndicesShape_{}; + gert::Shape queryRopeShape_{}; + gert::Shape keyRopeShape_{}; +}; +} // namespace optiling +#endif // SPARSE_FLASH_ATTENTION_LSE_TILING_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/arch22/sparse_flash_attention_lse_kernel_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/arch22/sparse_flash_attention_lse_kernel_mla.h new file mode 100644 index 0000000000..e448837b11 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/arch22/sparse_flash_attention_lse_kernel_mla.h @@ -0,0 +1,1238 @@ +/** + * 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 sparse_flash_attention_lse_kernel_mla.h + * \brief + */ + +#ifndef SPARSE_FLASH_ATTENTION_LSE_KERNEL_MLA_H +#define SPARSE_FLASH_ATTENTION_LSE_KERNEL_MLA_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_attention_lse/op_kernel/sparse_flash_attention_lse_common.h" +#include "sparse_flash_attention_lse_service_cube_mla.h" +#include "sparse_flash_attention_lse_service_vector_mla.h" + +using namespace matmul; +using AscendC::CacheMode; +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 + uint64_t curActualSeqLen = 0ULL; + uint64_t curActualSeqLenOri = 0ULL; + bool curActSeqLenIsZero = false; + int32_t nextTokensPerBatch = 0; + + uint64_t actS1Size = 1ULL; // TND场景下当前Batch循环处理的S1轴的大小 + uint32_t tndCoreStartKVSplitPos; + bool tndIsS2SplitCore; + + uint32_t gS1Idx = 0U; + uint64_t mBasicSizeTail = 0U; // gS1方向循环的尾基本块大小 +}; + +template +class SparseFlashAttentionLseMla { + public: + // 中间计算数据类型为float,高精度模式 + using T = float; + using Q_T = typename SFAT::queryType; + using KV_T = typename SFAT::kvType; + using OUT_T = typename SFAT::outputType; + using Q_ROPE_T = Q_T; + using K_ROPE_T = KV_T; + using UPDATE_T = T; + using MM1_OUT_T = T; + using MM2_OUT_T = T; + + __aicore__ inline SparseFlashAttentionLseMla(){}; + __aicore__ inline void Init( + __gm__ uint8_t* query, + __gm__ uint8_t* key, + __gm__ uint8_t* value, + __gm__ uint8_t* sparseIndices, + __gm__ uint8_t* actualSeqLengthsQ, + __gm__ uint8_t* actualSeqLengths, + __gm__ uint8_t* blockTable, + __gm__ uint8_t* queryRope, + __gm__ uint8_t* keyRope, + __gm__ uint8_t* attentionOut, + __gm__ uint8_t* softmaxMax, + __gm__ uint8_t* softmaxSum, + __gm__ uint8_t* workspace, + const SparseFlashAttentionLseTilingDataMla* __restrict tiling, + __gm__ uint8_t* gmTiling, + TPipe* tPipe); + + __aicore__ inline void Process(); + + private: + static constexpr bool PAGE_ATTENTION = SFAT::pageAttention; + static constexpr int TEMPLATE_MODE = SFAT::templateMode; + static constexpr bool FLASH_DECODE = SFAT::flashDecode; + static constexpr SFA_LAYOUT LAYOUT_T = SFAT::layout; + static constexpr SFA_LAYOUT KV_LAYOUT_T = SFAT::kvLayout; + + static constexpr uint32_t PRELOAD_NUM = 2; + static constexpr uint32_t N_BUFFER_M_BASIC_SIZE = 256; + static constexpr uint32_t SFA_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 SYNC_C2_V1_FLAG = 4; + static constexpr uint32_t SYNC_V1_NUPDATE_C2_FLAG = 5; + + 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 uint32_t BLOCK_ELEMENT_NUM = + SFAVectorService::BYTE_BLOCK / sizeof(T); + + static constexpr uint64_t kvHeadNum = 1ULL; + static constexpr uint64_t headDim = 512ULL; + static constexpr uint64_t headDimAlign = 512ULL; + static constexpr uint64_t headDimRope = SFAT::hasRope ? 64ULL : 0ULL; + static constexpr uint32_t msdIterNum = 2U; + + static constexpr uint32_t dbWorkspaceRatio = PRELOAD_NUM; + + const SparseFlashAttentionLseTilingDataMla* __restrict tilingData = nullptr; + + TPipe* pipe = nullptr; + + uint64_t mSizeVStart = 0ULL; + int64_t threshold = 0; + uint64_t topKBaseOffset = 0ULL; + uint64_t s2BatchBaseOffset = 0; + uint64_t tensorACoreOffset = 0ULL; + uint64_t tensorBCoreOffset = 0ULL; + uint64_t tensorARopeCoreOffset = 0ULL; + uint64_t tensorBRopeCoreOffset = 0ULL; + uint64_t tensorBOffset = 0ULL; + uint64_t attenOutOffset = 0ULL; + + uint32_t tmpBlockIdx = 0U; + uint32_t aiCoreIdx = 0U; + uint32_t usedCoreNum = 0U; + + __gm__ uint8_t* keyPtr = nullptr; + __gm__ uint8_t* valuePtr = nullptr; + + ConstInfo constInfo{}; + TempLoopInfo tempLoopInfo{}; + + SFAMatmulService matmulService; + SFAVectorService vectorService; + + GlobalTensor queryGm; + GlobalTensor keyGm; + GlobalTensor valueGm; + GlobalTensor qRopeGm; + GlobalTensor kRopeGm; + + GlobalTensor attentionOutGm; + GlobalTensor softmaxMaxGm; + GlobalTensor softmaxSumGm; + GlobalTensor blockTableGm; + GlobalTensor topKGm; + + GlobalTensor actualSeqLengthsQGm; + GlobalTensor actualSeqLengthsKVGm; + + // workspace + GlobalTensor mm1ResGm; + GlobalTensor vec1ResGm; + GlobalTensor mm2ResGm; + GlobalTensor kvMergeGm_; + GlobalTensor kvValidSizeGm_; + + GlobalTensor mm2ResInt32Gm; + GlobalTensor vec2ResGm; + + GlobalTensor accumOutGm; + GlobalTensor lseSumFdGm; + GlobalTensor lseMaxFdGm; + + GlobalTensor lseSumFaGm; + GlobalTensor lseMaxFaGm; + + // ================================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* actualSeqLengths); + __aicore__ inline void InitOutputSingleCore(); + // ================================Process + // functions================================ + __aicore__ inline void ProcessBalance(); + __aicore__ inline void PreloadPipeline( + uint32_t loop, + uint64_t s2Start, + uint64_t s2LoopIdx, + RunInfo extraInfo[SFA_PRELOAD_TASK_CACHE_SIZE], + uint32_t& curTopKIdx, + uint64_t& curOffsetInSparseBlock); + // ================================Offset + // Calc===================================== + __aicore__ inline void GetActualSeqLen(uint32_t bIdx, uint32_t s1Idx = 0); + __aicore__ inline void GetSparseActualSeqLen(uint32_t bIdx, + uint32_t s1Idx, + uint32_t n2Idx); + __aicore__ inline void CalcSinnerTopKBegin(RunInfo& info, + uint32_t& curTopKIdx, + uint64_t& curOffsetInSparseBlock); + __aicore__ inline void UpdateInnerLoopCond(); + __aicore__ inline void DealActSeqLenIsZero(uint32_t bIdx, + uint32_t s1Idx, + uint32_t n2Idx); + __aicore__ inline void CalcParams(uint32_t loop, + uint64_t s2Start, + uint32_t s2LoopIdx, + RunInfo& info); + __aicore__ inline void GetAxisStartIdx(uint32_t bN2EndPrev, + uint32_t gS1EndPrev, + uint32_t s2EndPrev); + __aicore__ inline uint64_t GetBalanceActualSeqLengths( + GlobalTensor& actualSeqLengths, + uint32_t bIdx); + __aicore__ inline uint32_t GetActualSeqLenKV(uint32_t bIdx); + __aicore__ inline void GetBN2Idx(uint32_t bN2Idx, + uint32_t& bIdx, + uint32_t& n2Idx); + __aicore__ inline void UpdateInner(uint32_t& s2End, + uint32_t& curS2End, + uint32_t s1Idx, + bool isEnd); + __aicore__ inline void GetPreNextTokensLeftUp(); + // ================================Mm1============================================== + __aicore__ inline void ComputeMm1(const RunInfo& info); + // ================================Mm2============================================== + __aicore__ inline void ComputeMm2(const RunInfo& info); + __aicore__ inline void Bmm2DataCopyOut(uint64_t attenOutOffset, + LocalTensor& attenOutUb, + uint32_t startRow, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount); + __aicore__ inline void InitAllZeroOutput(uint32_t bIdx, + uint32_t s1Idx, + uint32_t n2Idx); +}; + +template +__aicore__ inline void SparseFlashAttentionLseMla::InitTilingData() { + usedCoreNum = tilingData->singleCoreParams.usedCoreNum; + constInfo.splitKVNum = tilingData->splitKVParams.s2; + constInfo.mmResUbSize = tilingData->singleCoreTensorSize.mmResUbSize; + constInfo.bmm2ResUbSize = tilingData->singleCoreTensorSize.bmm2ResUbSize; + constInfo.vec1ResUbSize = constInfo.mmResUbSize * msdIterNum; + + constInfo.batchSize = tilingData->baseParams.batchSize; + constInfo.qHeadNum = constInfo.gSize = + tilingData->baseParams.nNumOfQInOneGroup; + constInfo.kvSeqSize = tilingData->baseParams.seqSize; + constInfo.qSeqSize = tilingData->baseParams.qSeqSize; + constInfo.maxBlockNumPerBatch = tilingData->baseParams.maxBlockNumPerBatch; + constInfo.kvCacheBlockSize = tilingData->baseParams.blockSize; + constInfo.outputLayout = + static_cast(tilingData->baseParams.outputLayout); + constInfo.mBaseSize = tilingData->innerSplitParams.mBaseSize; + constInfo.s2BaseSize = tilingData->innerSplitParams.s2BaseSize; + constInfo.kvHeadNum = kvHeadNum; + constInfo.headDim = headDim; + constInfo.headDimRope = headDimRope; + constInfo.sparseBlockSize = tilingData->baseParams.sparseBlockSize; + constInfo.sparseBlockCount = tilingData->baseParams.sparseBlockCount; + constInfo.sparseMode = tilingData->baseParams.sparseMode; + constInfo.preTokens = tilingData->baseParams.preTokens; + constInfo.nextTokens = tilingData->baseParams.nextTokens; + constInfo.attentionMode = tilingData->baseParams.attentionMode; + constInfo.returnSoftmaxLse = tilingData->baseParams.returnSoftmaxLse; + + 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.syncC2V1 = SYNC_C2_V1_FLAG; + constInfo.syncV1NupdateC2 = SYNC_V1_NUPDATE_C2_FLAG; +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::InitBuffers() { + if ASCEND_IS_AIV { + vectorService.InitBuffers(pipe); + } else { + matmulService.InitBuffers(pipe); + } +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::InitActualSeqLen( + __gm__ uint8_t* actualSeqLengthsQ, + __gm__ uint8_t* actualSeqLengths) { + constInfo.actualLenDimsQ = tilingData->baseParams.actualLenDimsQ; + constInfo.actualLenDimsKV = tilingData->baseParams.actualLenDimsKV; + if (constInfo.actualLenDimsKV != 0) { + actualSeqLengthsKVGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengths, + constInfo.actualLenDimsKV); + } + if (constInfo.actualLenDimsQ != 0) { + actualSeqLengthsQGm.SetGlobalBuffer((__gm__ int32_t*)actualSeqLengthsQ, + constInfo.actualLenDimsQ); + } +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::InitAllZeroOutput( + uint32_t bIdx, + uint32_t s1Idx, + uint32_t n2Idx) { + if (constInfo.outputLayout == SFA_LAYOUT::TND) { + uint32_t tBase = bIdx == 0 ? 0 : actualSeqLengthsQGm.GetValue(bIdx - 1); + uint32_t s1Count = tempLoopInfo.actS1Size; + + uint64_t attenOutOffset = (tBase + s1Idx) * kvHeadNum * constInfo.gSize * + headDim + // T轴、s1轴偏移 + n2Idx * constInfo.gSize * headDim; // N2轴偏移 + matmul::InitOutput( + attentionOutGm[attenOutOffset], constInfo.gSize * headDim, 0); + if (constInfo.returnSoftmaxLse) { + uint64_t softmaxSumOffset = + n2Idx * actualSeqLengthsQGm.GetValue(constInfo.batchSize - 1) * + constInfo.gSize + + (tBase + s1Idx) * constInfo.gSize; + uint64_t softmaxMaxOffset = softmaxSumOffset; + matmul::InitOutput(softmaxSumGm[softmaxSumOffset], constInfo.gSize, 0); + matmul::InitOutput(softmaxMaxGm[softmaxMaxOffset], constInfo.gSize, 0); + } + } else if (constInfo.outputLayout == SFA_LAYOUT::BSND) { + uint64_t attenOutOffset = + bIdx * constInfo.qSeqSize * kvHeadNum * constInfo.gSize * headDim + + s1Idx * kvHeadNum * constInfo.gSize * headDim + // B轴、S1轴偏移 + n2Idx * constInfo.gSize * headDim; // N2轴偏移 + matmul::InitOutput( + attentionOutGm[attenOutOffset], constInfo.gSize * headDim, 0); + if (constInfo.returnSoftmaxLse) { + uint64_t softmaxSumOffset = + bIdx * kvHeadNum * constInfo.qSeqSize * constInfo.gSize + + n2Idx * constInfo.qSeqSize * constInfo.gSize + + s1Idx * constInfo.gSize; + uint64_t softmaxMaxOffset = softmaxSumOffset; + matmul::InitOutput(softmaxSumGm[softmaxSumOffset], constInfo.gSize, 0); + matmul::InitOutput(softmaxMaxGm[softmaxMaxOffset], constInfo.gSize, 0); + } + } +} + +template +__aicore__ inline void +SparseFlashAttentionLseMla::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 (tmpBlockIdx * singleCoreSize < totalOutputSize && + singleInitOutputSize > 0) { + matmul::InitOutput(attentionOutGm[tmpBlockIdx * singleCoreSize], + singleInitOutputSize, + 0); + } + if (constInfo.returnSoftmaxLse) { + uint64_t totalReturnSoftmaxSize = constInfo.batchSize * + constInfo.kvHeadNum * + constInfo.qSeqSize * constInfo.gSize; + uint64_t singleCoreReturnSoftmaxSize = + (totalReturnSoftmaxSize + (2 * coreNum) - 1) / (2 * coreNum); + uint64_t tailReturnSoftmaxSize = + totalReturnSoftmaxSize - tmpBlockIdx * singleCoreReturnSoftmaxSize; + uint64_t singleInitReturnSoftmaxSize = + tailReturnSoftmaxSize < singleCoreReturnSoftmaxSize + ? tailReturnSoftmaxSize + : singleCoreReturnSoftmaxSize; + if (tmpBlockIdx * singleCoreReturnSoftmaxSize < totalReturnSoftmaxSize && + singleInitReturnSoftmaxSize > 0) { + matmul::InitOutput( + softmaxSumGm[tmpBlockIdx * singleCoreReturnSoftmaxSize], + singleInitReturnSoftmaxSize, + 0); + matmul::InitOutput( + softmaxMaxGm[tmpBlockIdx * singleCoreReturnSoftmaxSize], + singleInitReturnSoftmaxSize, + 0); + } + } + SyncAll(); + } +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::GetActualSeqLen( + uint32_t bIdx, + uint32_t s1Idx) { + tempLoopInfo.curActualSeqLenOri = GetActualSeqLenKV(bIdx); + tempLoopInfo.actS1Size = + GetBalanceActualSeqLengths(actualSeqLengthsQGm, bIdx); +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::GetSparseActualSeqLen( + uint32_t bIdx, + uint32_t s1Idx, + uint32_t n2Idx) { + if (tempLoopInfo.nextTokensPerBatch < 0 && + s1Idx < (-tempLoopInfo.nextTokensPerBatch)) { // 存在行无效 + tempLoopInfo.curActualSeqLen = 0; + return; + } + int64_t threshold = tempLoopInfo.curActualSeqLenOri; + if (constInfo.sparseMode == 3) { + threshold = + static_cast(tempLoopInfo.nextTokensPerBatch) + s1Idx + 1; + } + + tempLoopInfo.curActualSeqLen = + (constInfo.sparseBlockCount * constInfo.sparseBlockSize > threshold) + ? threshold + : constInfo.sparseBlockCount * constInfo.sparseBlockSize; +} + +template +__aicore__ inline uint32_t SparseFlashAttentionLseMla::GetActualSeqLenKV( + uint32_t bIdx) { + if constexpr (KV_LAYOUT_T == SFA_LAYOUT::TND) { + if (bIdx > 0) { + return actualSeqLengthsKVGm.GetValue(bIdx) - + actualSeqLengthsKVGm.GetValue(bIdx - 1); + } else if (bIdx == 0) { + return actualSeqLengthsKVGm.GetValue(0); + } else { + return 0; + } + } else { + if (constInfo.actualLenDimsKV == 0) { + return constInfo.kvSeqSize; + } else if (constInfo.actualLenDimsKV == 1) { + return actualSeqLengthsKVGm.GetValue(0); + } else { + return actualSeqLengthsKVGm.GetValue(bIdx); + } + } +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::DealActSeqLenIsZero( + uint32_t bIdx, + uint32_t s1Idx, + uint32_t n2Idx) { + if ASCEND_IS_AIV { + InitAllZeroOutput(bIdx, s1Idx, n2Idx); + } +} + +template +__aicore__ inline void +SparseFlashAttentionLseMla::GetPreNextTokensLeftUp() { + if (constInfo.sparseMode == 3) { + tempLoopInfo.nextTokensPerBatch = + static_cast(tempLoopInfo.curActualSeqLenOri) - + static_cast(tempLoopInfo.actS1Size); + } +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::UpdateInnerLoopCond() { + if ((tempLoopInfo.curActualSeqLen == 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; + tempLoopInfo.s2LoopTimes = 0; +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::UpdateInner( + uint32_t& s2End, + uint32_t& curS2End, + uint32_t s1Idx, + bool isEnd) { + uint32_t s1BaseSize = 1; + int64_t s1Offset = s1BaseSize * s1Idx; + int64_t s2LastToken = + Min(s1Offset + tempLoopInfo.nextTokensPerBatch + s1BaseSize, + tempLoopInfo.curActualSeqLenOri); + s2LastToken = + Min(constInfo.sparseBlockSize * constInfo.sparseBlockCount, s2LastToken); + curS2End = (s2LastToken + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize; + tempLoopInfo.s2LoopTimes = isEnd ? constInfo.s2End + 1 : curS2End; +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::Init( + __gm__ uint8_t* query, + __gm__ uint8_t* key, + __gm__ uint8_t* value, + __gm__ uint8_t* sparseIndices, + __gm__ uint8_t* actualSeqLengthsQ, + __gm__ uint8_t* actualSeqLengths, + __gm__ uint8_t* blockTable, + __gm__ uint8_t* queryRope, + __gm__ uint8_t* keyRope, + __gm__ uint8_t* attentionOut, + __gm__ uint8_t* softmaxMax, + __gm__ uint8_t* softmaxSum, + __gm__ uint8_t* workspace, + const SparseFlashAttentionLseTilingDataMla* __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(); + InitActualSeqLen(actualSeqLengthsQ, actualSeqLengths); + + // 初始化计算参数 + InitCalcParamsEach(); + pipe = tPipe; + keyPtr = key; + valuePtr = value; + + // init global buffer + queryGm.SetGlobalBuffer((__gm__ Q_T*)query); + keyGm.SetGlobalBuffer((__gm__ KV_T*)keyPtr); + valueGm.SetGlobalBuffer((__gm__ KV_T*)valuePtr); + if constexpr (SFAT::hasRope) { + qRopeGm.SetGlobalBuffer((__gm__ Q_ROPE_T*)queryRope); + kRopeGm.SetGlobalBuffer((__gm__ K_ROPE_T*)keyRope); + } + + attentionOutGm.SetGlobalBuffer((__gm__ OUT_T*)attentionOut); + softmaxMaxGm.SetGlobalBuffer((__gm__ T*)softmaxMax); + softmaxSumGm.SetGlobalBuffer((__gm__ T*)softmaxSum); + if ASCEND_IS_AIV { + if (constInfo.needInit && LAYOUT_T != SFA_LAYOUT::TND) { + InitOutputSingleCore(); + } + } + + if constexpr (PAGE_ATTENTION) { + blockTableGm.SetGlobalBuffer((__gm__ int32_t*)blockTable); + } + topKGm.SetGlobalBuffer((__gm__ int32_t*)sparseIndices); + + // workspace 内存排布 + // |Q--|mm1ResGm(存S)|vec1ResGm(存A1,A2)|mm2ResGm(存O)|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__ KV_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); + mm2ResInt32Gm.SetGlobalBuffer( + reinterpret_cast<__gm__ int32_t*>(mm2ResGm.GetPhyAddr(0))); + + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + // s2 d+rope bufNum + kvMergeGm_.SetGlobalBuffer( + (__gm__ KV_T*)(workspace + offset + + aiCoreIdx * 512 * 576 * 4 * sizeof(KV_T))); + offset += GetBlockNum() * 512 * 576 * 4 * sizeof(KV_T); + + kvValidSizeGm_.SetGlobalBuffer( + (__gm__ int32_t*)(workspace + offset + + (aiCoreIdx * 2) * 128 * 4 * sizeof(int32_t))); + } + + if constexpr (FLASH_DECODE) { + accumOutGm.SetGlobalBuffer((__gm__ float*)(workspace + offset)); + offset = offset + tilingData->splitKVParams.accumOutSize * sizeof(float); + lseSumFdGm.SetGlobalBuffer((__gm__ float*)(workspace + offset)); + lseMaxFdGm.SetGlobalBuffer((__gm__ float*)(workspace + offset) + + tilingData->splitKVParams.logSumExpSize / 2); + offset = offset + tilingData->splitKVParams.logSumExpSize * sizeof(float); + } + + if ASCEND_IS_AIV { + vectorService.InitParams(constInfo, tilingData); + vectorService.InitMm2ResInt32GmGlobalTensor(mm2ResInt32Gm); + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + vectorService.InitVec0GlobalTensor( + kvValidSizeGm_, kvMergeGm_, kRopeGm, keyGm, blockTableGm); + } + vectorService.InitVec1GlobalTensor(mm1ResGm, + vec1ResGm, + actualSeqLengthsQGm, + actualSeqLengthsKVGm, + lseMaxFdGm, + lseSumFdGm, + topKGm, + softmaxMaxGm, + softmaxSumGm); + vectorService.InitVec2GlobalTensor( + accumOutGm, vec2ResGm, mm2ResGm, attentionOutGm); + } + + if ASCEND_IS_AIC { + matmulService.InitParams(constInfo); + matmulService.InitMm1GlobalTensor( + queryGm, qRopeGm, keyGm, kRopeGm, mm1ResGm); + matmulService.InitMm2GlobalTensor( + vec1ResGm, valueGm, mm2ResGm, attentionOutGm); + matmulService.InitPageAttentionInfo(kvMergeGm_, + blockTableGm, + topKGm, + constInfo.kvCacheBlockSize, + constInfo.maxBlockNumPerBatch); + } + // 要在InitParams之后执行 + if (pipe != nullptr) { + InitBuffers(); + } +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::InitCalcParamsEach() { + // 计算总的基本块 + uint32_t totalBaseNum = 0; + uint32_t s1GBaseSize = constInfo.gSize; + uint32_t actBatchS2 = 1; + uint32_t coreNum = GetBlockNum(); + uint32_t currCoreIdx = aiCoreIdx; + uint32_t actBatchS1 = 1; + for (uint32_t bIdx = 0; bIdx < constInfo.batchSize; bIdx++) { + uint32_t actBatchS1 = GetBalanceActualSeqLengths(actualSeqLengthsQGm, bIdx); + if (actBatchS1 < constInfo.qSeqSize) { + constInfo.needInit = true; + } + totalBaseNum += actBatchS1 * actBatchS2; + } + uint32_t avgBaseNum = 1; + if (totalBaseNum > coreNum) { + avgBaseNum = (totalBaseNum + coreNum - 1) / coreNum; + } else { + usedCoreNum = totalBaseNum; + } + if (aiCoreIdx >= usedCoreNum) { + return; + } + // 计算当前核的基本块 + uint32_t accumBaseNum = 0; // 当前累积的基本块数 + uint32_t targetBaseNum = 0; + uint32_t lastValidBIdx = 0; + uint32_t lastValidactBatchS1 = 0; + bool setStart = false; + targetBaseNum = (currCoreIdx + 1) * avgBaseNum; // 计算当前的目标权重 + uint32_t targetStartBaseNum = targetBaseNum - avgBaseNum; + for (uint32_t bN2Idx = 0; bN2Idx < constInfo.batchSize * constInfo.kvHeadNum; + bN2Idx++) { + uint32_t bIdx = bN2Idx / constInfo.kvHeadNum; + actBatchS1 = GetBalanceActualSeqLengths(actualSeqLengthsQGm, bIdx); + for (uint32_t s1GIdx = 0; s1GIdx < actBatchS1; s1GIdx++) { + accumBaseNum += 1; + if (!setStart && accumBaseNum >= targetStartBaseNum) { + constInfo.bN2Start = bN2Idx; + constInfo.gS1Start = s1GIdx; + setStart = true; + } + if (accumBaseNum >= targetBaseNum) { + // 更新当前核的End分核信息 + constInfo.bN2End = bN2Idx; + constInfo.gS1End = s1GIdx; + constInfo.s2End = 0; + constInfo.coreStartKVSplitPos = 0; + if (aiCoreIdx != 0) { + GetAxisStartIdx(constInfo.bN2Start, constInfo.gS1Start, 0); + } + return; + } + } + if ((actBatchS1 > 0) && (actBatchS2 > 0)) { + lastValidBIdx = bIdx; + lastValidactBatchS1 = actBatchS1; + } + } + if (!setStart) { + constInfo.bN2Start = lastValidBIdx; + constInfo.gS1Start = lastValidactBatchS1 - 1; + } + if (accumBaseNum < targetBaseNum) { + // 更新最后一个核的End分核信息 + constInfo.bN2End = lastValidBIdx; + constInfo.gS1End = lastValidactBatchS1 - 1; + constInfo.s2End = 0; + constInfo.coreStartKVSplitPos = 0; + if (aiCoreIdx != 0) { + GetAxisStartIdx(constInfo.bN2Start, constInfo.gS1Start, 0); + } + return; + } +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::Bmm2DataCopyOut( + uint64_t attenOutOffset, + LocalTensor& attenOutUb, + uint32_t startRow, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = dealRowCount; + dataCopyParams.blockLen = actualColumnCount * sizeof(OUT_T); + dataCopyParams.srcStride = + (columnCount - actualColumnCount) / + (SFAVectorService::BYTE_BLOCK / sizeof(OUT_T)); + dataCopyParams.dstStride = 0; + DataCopyPad(attentionOutGm[attenOutOffset + + (mSizeVStart + startRow) * actualColumnCount], + attenOutUb, + dataCopyParams); +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::CalcParams( + uint32_t loop, + uint64_t s2Start, + uint32_t s2LoopIdx, + RunInfo& info) { + info.loop = loop; + info.bIdx = tempLoopInfo.bIdx; + info.gS1Idx = tempLoopInfo.gS1Idx; + info.s2Idx = s2LoopIdx; + info.curSInnerLoopTimes = tempLoopInfo.s2LoopTimes; + + info.tndIsS2SplitCore = tempLoopInfo.tndIsS2SplitCore; + info.tndCoreStartKVSplitPos = tempLoopInfo.tndCoreStartKVSplitPos; + info.isBmm2Output = false; + + info.actS1Size = tempLoopInfo.actS1Size; + + info.actMBaseSize = constInfo.mBaseSize; + uint32_t remainedGS1Size = + tempLoopInfo.actS1Size * constInfo.gSize - tempLoopInfo.gS1Idx; + if (remainedGS1Size <= constInfo.mBaseSize && remainedGS1Size > 0) { + info.actMBaseSize = tempLoopInfo.mBasicSizeTail; + } + + info.isValid = s2LoopIdx < tempLoopInfo.s2LoopTimes; + + if ASCEND_IS_AIV { + info.mSize = info.actMBaseSize; + info.mSizeV = (info.mSize <= 16) ? info.mSize + : (((info.mSize + 15) / 16 + 1) / 2 * 16); + info.mSizeVStart = 0; + if (tmpBlockIdx % 2 == 1) { + info.mSizeVStart = info.mSizeV; + info.mSizeV = info.mSize - info.mSizeV; + } + } + + info.isChangeBatch = false; + + info.isFirstSInnerLoop = s2LoopIdx == s2Start; + if (info.isFirstSInnerLoop) { + tempLoopInfo.bn2IdxInCurCore++; + } + info.isLastS2Loop = s2LoopIdx == tempLoopInfo.s2LoopTimes - 1; + info.bn2IdxInCurCore = tempLoopInfo.bn2IdxInCurCore - 1; + uint64_t actualSeqQPrefixSum; + if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + actualSeqQPrefixSum = + (info.bIdx <= 0) ? 0 : actualSeqLengthsQGm.GetValue(info.bIdx - 1); + } else { + actualSeqQPrefixSum = (info.bIdx <= 0) ? 0 : info.bIdx * constInfo.qSeqSize; + } + info.tndBIdxOffsetForQ = actualSeqQPrefixSum * constInfo.qHeadNum * headDim; + + uint64_t actualSeqKVPrefixSum; + if constexpr (KV_LAYOUT_T == SFA_LAYOUT::TND) { + actualSeqKVPrefixSum = + (info.bIdx <= 0) ? 0 : actualSeqLengthsKVGm.GetValue(info.bIdx - 1); + } else { + actualSeqKVPrefixSum = + (info.bIdx <= 0) ? 0 : info.bIdx * constInfo.kvSeqSize; + } + info.tndBIdxOffsetForKV = + actualSeqKVPrefixSum * constInfo.kvHeadNum * headDim; + + if (info.isFirstSInnerLoop) { + tensorACoreOffset = info.tndBIdxOffsetForQ + info.gS1Idx * headDim; + tensorBCoreOffset = info.tndBIdxOffsetForKV + info.n2Idx * headDim; + if constexpr (SFAT::hasRope) { + uint64_t tndBIdxRopeOffsetForQ = + actualSeqQPrefixSum * constInfo.qHeadNum * headDimRope; + tensorARopeCoreOffset = tndBIdxRopeOffsetForQ + info.gS1Idx * headDimRope; + + uint64_t tndBIdxRopeOffsetForK = + actualSeqKVPrefixSum * constInfo.kvHeadNum * headDimRope; + tensorBRopeCoreOffset = tndBIdxRopeOffsetForK + info.n2Idx * headDimRope; + } + if (constInfo.sparseMode == 3) { + threshold = static_cast(tempLoopInfo.nextTokensPerBatch) + + info.gS1Idx / constInfo.gSize + 1; + } else { + threshold = tempLoopInfo.curActualSeqLenOri; + } + if constexpr (LAYOUT_T == SFA_LAYOUT::BSND) { // B,S1,N2 K + topKBaseOffset = info.bIdx * constInfo.qSeqSize * constInfo.kvHeadNum * + constInfo.sparseBlockCount + + info.gS1Idx / constInfo.gSize * constInfo.kvHeadNum * + constInfo.sparseBlockCount + + info.n2Idx * constInfo.sparseBlockCount; + } else if (LAYOUT_T == SFA_LAYOUT::TND) { // T N2 K + topKBaseOffset = info.tndBIdxOffsetForQ / constInfo.gSize / + constInfo.headDim * constInfo.kvHeadNum * + constInfo.sparseBlockCount + + info.n2Idx * constInfo.sparseBlockCount + + info.gS1Idx / constInfo.gSize * constInfo.kvHeadNum * + constInfo.sparseBlockCount; + } else { // B N2 S1 K + topKBaseOffset = + info.bIdx * constInfo.kvHeadNum * constInfo.qSeqSize * + constInfo.sparseBlockCount + + info.n2Idx * constInfo.qSeqSize * constInfo.sparseBlockCount + + info.gS1Idx / constInfo.gSize * constInfo.sparseBlockCount; + } + } + info.topKBaseOffset = topKBaseOffset; + info.threshold = threshold; + info.tensorAOffset = tensorACoreOffset; + info.tensorARopeOffset = tensorARopeCoreOffset; + info.tensorBOffset = tensorBCoreOffset; + info.tensorBRopeOffset = tensorBRopeCoreOffset; + info.attenOutOffset = tensorACoreOffset; + + uint64_t sInnerOffsetDataSize = info.s2Idx * constInfo.s2BaseSize; + info.s2BatchOffset = s2BatchBaseOffset + sInnerOffsetDataSize; + + info.curActualSeqLenOri = tempLoopInfo.curActualSeqLenOri; + // 计算实际基本块size + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + if (tempLoopInfo.curActualSeqLen > sInnerOffsetDataSize) { + info.actualSingleProcessSInnerSize = + tempLoopInfo.curActualSeqLen - sInnerOffsetDataSize; + info.actualSingleProcessSInnerSize = + info.actualSingleProcessSInnerSize > constInfo.s2BaseSize + ? constInfo.s2BaseSize + : info.actualSingleProcessSInnerSize; + } else { + info.actualSingleProcessSInnerSize = 0; + } + info.actualSingleProcessSInnerSizeAlign = + SFAAlign((uint32_t)info.actualSingleProcessSInnerSize, + (uint32_t)SFAVectorService::BYTE_BLOCK); + } +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::ComputeMm1( + 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; + matmulService.ComputeMm1(info, mSplitInfo); + CrossCoreSetFlag(constInfo.syncC1V1); + } +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::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); + matmulService.ComputeMm2(info, mSplitInfo); + CrossCoreSetFlag(constInfo.syncC2V2); + CrossCoreSetFlag(constInfo.syncC2V1); + } +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::Process() { + if (aiCoreIdx < usedCoreNum) { + if ASCEND_IS_AIV { + vectorService.AllocEventID(); + vectorService.InitSoftmaxDefaultBuffer(); + } else { + matmulService.AllocEventID(); + } + ProcessBalance(); + + if ASCEND_IS_AIV { + vectorService.FreeEventID(); + } else { + matmulService.FreeEventID(); + } + } +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::GetBN2Idx( + uint32_t bN2Idx, + uint32_t& bIdx, + uint32_t& n2Idx) { + bIdx = bN2Idx / kvHeadNum; + n2Idx = bN2Idx % kvHeadNum; +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::ProcessBalance() { + RunInfo extraInfo[SFA_PRELOAD_TASK_CACHE_SIZE]; + uint32_t gloop = 0; + int gS1LoopEnd; + bool globalLoopStart = true; + if ASCEND_IS_AIC { + CrossCoreSetFlag(constInfo.syncC2V1); + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + CrossCoreSetFlag(3); + CrossCoreSetFlag(3); + CrossCoreSetFlag(3); + CrossCoreSetFlag(3); + } + } + for (uint32_t bN2LoopIdx = constInfo.bN2Start; bN2LoopIdx <= constInfo.bN2End; + bN2LoopIdx++) { + GetBN2Idx(bN2LoopIdx, tempLoopInfo.bIdx, tempLoopInfo.n2Idx); + GetActualSeqLen( + tempLoopInfo.bIdx); // 获取actualSeqLength及ActualSeqLengthKV + GetPreNextTokensLeftUp(); + if (tempLoopInfo.actS1Size == 0) { + continue; + } + int gS1SplitNum = + (tempLoopInfo.actS1Size * constInfo.gSize + constInfo.mBaseSize - 1) / + constInfo.mBaseSize; + gS1LoopEnd = + (bN2LoopIdx == constInfo.bN2End) ? constInfo.gS1End : gS1SplitNum - 1; + for (uint32_t gS1LoopIdx = constInfo.gS1Start; gS1LoopIdx <= gS1LoopEnd; + gS1LoopIdx++) { + tempLoopInfo.gS1Idx = gS1LoopIdx * constInfo.mBaseSize; + GetSparseActualSeqLen( + tempLoopInfo.bIdx, + gS1LoopIdx, + tempLoopInfo.n2Idx); // TopK值sparse完后的ActualSeqLengthKV + UpdateInnerLoopCond(); + + if (tempLoopInfo.curActSeqLenIsZero) { + DealActSeqLenIsZero(tempLoopInfo.bIdx, gS1LoopIdx, tempLoopInfo.n2Idx); + } + int s2SplitNum = + (tempLoopInfo.curActualSeqLen + constInfo.s2BaseSize - 1) / + constInfo.s2BaseSize; // S2切分份数 + bool isEnd = + (bN2LoopIdx == constInfo.bN2End) && (gS1LoopIdx == constInfo.gS1End); + tempLoopInfo.s2LoopTimes = s2SplitNum; + // 分核修改后需要打开 + // 当前s2是否被切,决定了输出是否要写到attenOut上 + tempLoopInfo.tndIsS2SplitCore = + ((constInfo.s2Start == 0) && (tempLoopInfo.s2LoopTimes == s2SplitNum)) + ? false + : true; + tempLoopInfo.tndCoreStartKVSplitPos = + globalLoopStart ? constInfo.coreStartKVSplitPos : 0; + uint32_t extraLoop = isEnd ? 2 : 0; + + uint32_t curTopKIdx = 0; + uint64_t curOffsetInSparseBlock = 0; + for (int s2LoopIdx = constInfo.s2Start; + s2LoopIdx < (tempLoopInfo.s2LoopTimes + extraLoop); + s2LoopIdx++) { + // PreloadPipeline loop初始值要求为 PRELOAD_NUM + PreloadPipeline(gloop, + constInfo.s2Start, + s2LoopIdx, + extraInfo, + curTopKIdx, + curOffsetInSparseBlock); + ++gloop; + } + globalLoopStart = false; + constInfo.s2Start = 0; + } + constInfo.gS1Start = 0; + } + if ASCEND_IS_AIV { + CrossCoreWaitFlag(constInfo.syncC2V1); + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + CrossCoreWaitFlag(3); + CrossCoreWaitFlag(3); + CrossCoreWaitFlag(3); + CrossCoreWaitFlag(3); + } + } +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::PreloadPipeline( + uint32_t loop, + uint64_t s2Start, + uint64_t s2LoopIdx, + RunInfo extraInfo[SFA_PRELOAD_TASK_CACHE_SIZE], + uint32_t& curTopKIdx, + uint64_t& curOffsetInSparseBlock) { + RunInfo& extraInfo0 = + extraInfo[loop % SFA_PRELOAD_TASK_CACHE_SIZE]; // 本轮任务 + RunInfo& extraInfo2 = + extraInfo[(loop + 2) % SFA_PRELOAD_TASK_CACHE_SIZE]; // 上一轮任务 + RunInfo& extraInfo1 = + extraInfo[(loop + 1) % SFA_PRELOAD_TASK_CACHE_SIZE]; // 上两轮任务 + + CalcParams(loop, s2Start, s2LoopIdx, extraInfo0); + CalcSinnerTopKBegin(extraInfo0, curTopKIdx, curOffsetInSparseBlock); + + if (extraInfo0.isValid) { + if ASCEND_IS_AIC { + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + CrossCoreWaitFlag(constInfo.syncV0C1); + } + ComputeMm1(extraInfo0); + } else { + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + CrossCoreWaitFlag(3); + vectorService.MergeKv(extraInfo0); + CrossCoreSetFlag( + constInfo.syncV0C1); + } + } + } + if (extraInfo2.isValid) { + if ASCEND_IS_AIV { + vectorService.ProcessVec1L(extraInfo2); + } + if ASCEND_IS_AIC { + ComputeMm2(extraInfo2); + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + CrossCoreSetFlag(3); + } + } + } + if (extraInfo1.isValid) { + if ASCEND_IS_AIV { + vectorService.ProcessVec2L(extraInfo1); + } + extraInfo1.isValid = false; + } +} + +template +__aicore__ inline uint64_t +SparseFlashAttentionLseMla::GetBalanceActualSeqLengths( + GlobalTensor& actualSeqLengths, + uint32_t bIdx) { + if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + if (bIdx > 0) { + return actualSeqLengths.GetValue(bIdx) - + actualSeqLengths.GetValue(bIdx - 1); + } else if (bIdx == 0) { + return actualSeqLengths.GetValue(0); + } else { + return 0; + } + } else { + if (constInfo.actualLenDimsQ == 0) { + return constInfo.qSeqSize; + } else if (constInfo.actualLenDimsQ == 1) { + return actualSeqLengths.GetValue(0); + } else { + return actualSeqLengths.GetValue(bIdx); + } + } +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::GetAxisStartIdx( + uint32_t bN2EndPrev, + uint32_t s1GEndPrev, + uint32_t s2EndPrev) { + uint32_t bEndPrev = bN2EndPrev / kvHeadNum; + uint32_t actualSeqQPrev = + GetBalanceActualSeqLengths(actualSeqLengthsQGm, bEndPrev); + uint32_t s1GPrevBaseNum = + (actualSeqQPrev * constInfo.gSize + constInfo.mBaseSize - 1) / + constInfo.mBaseSize; + constInfo.bN2Start = bN2EndPrev; + constInfo.gS1Start = s1GEndPrev; + + constInfo.s2Start = 0; + if (s1GEndPrev >= s1GPrevBaseNum - 1) { // 上个核把S1G处理完了 + constInfo.gS1Start = 0; + constInfo.bN2Start++; + } else { + constInfo.gS1Start++; + } +} + +template +__aicore__ inline void SparseFlashAttentionLseMla::CalcSinnerTopKBegin( + RunInfo& info, + uint32_t& curTopKIdx, + uint64_t& curOffsetInSparseBlock) + +{ + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + return; + } + + uint64_t thresholdSparseCount = + (info.threshold + constInfo.sparseBlockSize - 1) / + constInfo.sparseBlockSize; + uint64_t validCount = (constInfo.sparseBlockCount > thresholdSparseCount) + ? thresholdSparseCount + : constInfo.sparseBlockCount; + + int32_t sparseIndices = topKGm.GetValue(info.topKBaseOffset + curTopKIdx); + if (sparseIndices == -1 || curTopKIdx == validCount) { + info.actualSingleProcessSInnerSize = 0; + info.actualSingleProcessSInnerSizeAlign = 0; + tempLoopInfo.s2BasicSizeTail = 0; + if (curTopKIdx == 0) { + DealActSeqLenIsZero( + info.bIdx, info.gS1Idx / constInfo.gSize, tempLoopInfo.n2Idx); + } + return; + } + + uint32_t sparseLen = 0; + uint64_t blockBegin = sparseIndices * constInfo.sparseBlockSize; + uint64_t blockEnd = (blockBegin + constInfo.sparseBlockSize > info.threshold) + ? info.threshold + : blockBegin + constInfo.sparseBlockSize; + int32_t blockLen = blockEnd - blockBegin; + sparseLen += (blockLen > static_cast(curOffsetInSparseBlock)) + ? blockLen - curOffsetInSparseBlock + : 0; + + bool firstVaildFlag = false; + if (curTopKIdx > 0) { + info.curTopKIdx = curTopKIdx; + info.curOffsetInSparseBlock = curOffsetInSparseBlock; + } else if (curTopKIdx == 0 && sparseLen > 0) { + info.curTopKIdx = curTopKIdx; + info.curOffsetInSparseBlock = 0; + firstVaildFlag = true; + } + + for (uint64_t topkIdx = curTopKIdx + 1; topkIdx < validCount; topkIdx++) { + int32_t sparseIndices = topKGm.GetValue(info.topKBaseOffset + topkIdx); + if (sparseIndices == -1) { + curTopKIdx = topkIdx; + curOffsetInSparseBlock = 0; + break; + } + uint64_t blockBegin = sparseIndices * constInfo.sparseBlockSize; + if (blockBegin >= info.threshold) { + continue; + } + if (firstVaildFlag == false && curTopKIdx == 0) { + info.curTopKIdx = topkIdx; + info.curOffsetInSparseBlock = 0; + firstVaildFlag = true; + } + uint64_t blockEnd = + (blockBegin + constInfo.sparseBlockSize > info.threshold) + ? info.threshold + : blockBegin + constInfo.sparseBlockSize; + uint64_t blockLen = blockEnd - blockBegin; + sparseLen += blockLen; + if (sparseLen >= constInfo.s2BaseSize) { + curTopKIdx = topkIdx; + curOffsetInSparseBlock = blockLen - (sparseLen - constInfo.s2BaseSize); + sparseLen = constInfo.s2BaseSize; + break; + } + + if (topkIdx == validCount - 1) { + curTopKIdx = validCount; + curOffsetInSparseBlock = 0; + } + } + + info.actualSingleProcessSInnerSize = sparseLen; + info.actualSingleProcessSInnerSizeAlign = + SFAAlign((uint32_t)info.actualSingleProcessSInnerSize, + (uint32_t)SFAVectorService::BYTE_BLOCK); + tempLoopInfo.s2BasicSizeTail = + (sparseLen == constInfo.s2BaseSize) ? 0 : sparseLen; + if (curTopKIdx == 0 && sparseLen == 0) { + DealActSeqLenIsZero( + info.bIdx, info.gS1Idx / constInfo.gSize, tempLoopInfo.n2Idx); + } +} + +#endif // SPARSE_FLASH_ATTENTION_LSE_KERNEL_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/arch22/sparse_flash_attention_lse_service_cube_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/arch22/sparse_flash_attention_lse_service_cube_mla.h new file mode 100644 index 0000000000..65ed7072df --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/arch22/sparse_flash_attention_lse_service_cube_mla.h @@ -0,0 +1,1424 @@ +/** + * 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 sparse_flash_attention_lse_service_cube_mla.h + * \brief use 7 buffer for matmul l1, better pipeline + */ +#ifndef SPARSE_FLASH_ATTENTION_LSE_SERVICE_CUBE_MLA_H +#define SPARSE_FLASH_ATTENTION_LSE_SERVICE_CUBE_MLA_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_attention_lse/op_kernel/sparse_flash_attention_lse_common.h" + +struct PAShape { + uint32_t blockSize; + uint32_t headNum; // 一般为kv的head num,对应n2 + uint32_t headDim; // mla下rope为64,nope为512, 对应d + uint32_t maxblockNumPerBatch; // block table 每一行的最大个数 + uint32_t actHeadDim; // Columns copied in this N tile + uint32_t copyRowNum; // Total rows to copy + uint32_t copyRowNumAlign; +}; + +struct Position { + uint32_t bIdx; + uint32_t n2Idx; + uint32_t s2Idx; + uint32_t dIdx; +}; + +// 场景:query、queryRope、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分 BNBD(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.blockSize * shape.headNum * + shape.headDim; // PA的偏移 + + uint64_t dStride = shape.headDim; + if constexpr (SRC_LAYOUT == SFA_LAYOUT::BSND || + SRC_LAYOUT == SFA_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 +class SFAMatmulService { + public: + // 中间计算数据类型为float, 高精度模式 + using T = float; + using Q_T = typename SFAT::queryType; + using KV_T = typename SFAT::kvType; + using OUT_T = typename SFAT::outputType; + using MM_OUT_T = T; + + __aicore__ inline SFAMatmulService(){}; + __aicore__ inline void InitParams(const ConstInfo& constInfo); + __aicore__ inline void InitMm1GlobalTensor(GlobalTensor queryGm, + GlobalTensor qRopeGm, + GlobalTensor keyGm, + GlobalTensor kRopeGm, + GlobalTensor mm1ResGm); + __aicore__ inline void InitMm2GlobalTensor( + GlobalTensor vec1ResGm, + GlobalTensor valueGm, + GlobalTensor mm2ResGm, + GlobalTensor attentionOutGm); + __aicore__ inline void InitPageAttentionInfo( + const GlobalTensor& kvMergeGm, + GlobalTensor blockTableGm, + GlobalTensor topKGm, + uint32_t blockSize, + uint32_t maxBlockNumPerBatch); + __aicore__ inline void InitBuffers(TPipe* pipe); + __aicore__ inline void UpdateKey(GlobalTensor keyGm); + __aicore__ inline void UpdateValue(GlobalTensor valueGm); + + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + __aicore__ inline void CalcTopKBlockInfo(const RunInfo& info, + uint32_t& curTopKIdx, + uint64_t& curOffsetInSparseBlock, + uint32_t curSeqIdx, + uint32_t& copyRowCnt, + int64_t& idInTopK); + __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 = SFAT::pageAttention; + static constexpr int TEMPLATE_MODE = SFAT::templateMode; + static constexpr bool FLASH_DECODE = SFAT::flashDecode; + static constexpr SFA_LAYOUT LAYOUT_T = SFAT::layout; + static constexpr SFA_LAYOUT KV_LAYOUT_T = SFAT::kvLayout; + static constexpr bool HAS_ROPE = SFAT::hasRope; + // NoPE场景: K轴只有512的nope部分, 无64维rope段 + static constexpr uint32_t HEAD_DIM_ROPE = HAS_ROPE ? 64U : 0U; + + static constexpr uint32_t M_SPLIT_SIZE = 128; // m方向切分 + static constexpr uint32_t N_SPLIT_SIZE = 128; // n方向切分 + static constexpr uint32_t N_WORKSPACE_SIZE = 512; // n方向切分 + + // L1按nope+rope拼接布局使用: NoPE时只有512 nope部分 + static constexpr uint32_t L1_BLOCK_SIZE = + (64 * (512 + HEAD_DIM_ROPE) * sizeof(Q_T)); + static constexpr uint32_t L1_BLOCK_OFFSET = + 64 * (512 + HEAD_DIM_ROPE); // 72K的元素个数(NoPE时为64K) + + 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}; + + uint32_t kvCacheBlockSize = 0; + uint32_t maxBlockNumPerBatch = 0; + 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 qRopeGm; + GlobalTensor keyGm; + GlobalTensor kRopeGm; + GlobalTensor mm1ResGm; + GlobalTensor kvMergeGm_; + + // mm2 + GlobalTensor vec1ResGm; + GlobalTensor valueGm; + GlobalTensor mm2ResGm; + GlobalTensor attentionOutGm; + + // block_table + GlobalTensor blockTableGm; + GlobalTensor topKGm; + + 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 CopyInMm1ARopeToL1(LocalTensor& aL1Tensor, + const RunInfo& info, + uint32_t mSeqIdx, + uint32_t mSizeAct); + __aicore__ inline void CopyInMm1BToL1(LocalTensor& bL1Tensor, + const uint64_t keyGmBaseOffset, + uint32_t copyTotalRowCntAlign, + uint32_t copyStartRowCnt, + uint32_t nActCopyRowCount, + uint32_t headSize); + __aicore__ inline void CopyInMm1BRopeToL1(LocalTensor& bL1Tensor, + const uint64_t keyGmBaseOffset, + uint32_t copyTotalRowCntAlign, + uint32_t copyStartRowCnt, + uint32_t nActCopyRowCount, + uint32_t headSize); + __aicore__ inline void CopyInMm2AToL1(LocalTensor& aL1Tensor, + const RunInfo& info, + uint32_t mSeqIdx, + uint32_t subMSizeAct, + uint32_t nSize, + uint32_t nOffset); + __aicore__ inline void CopyInMm2BToL1(LocalTensor& bL1Tensor, + const uint64_t valueGmBaseOffset, + uint32_t copyTotalRowCntAlign, + uint32_t copyStartRowCnt, + uint32_t nActCopyRowCount, + uint32_t copyStartColumnCount, + uint32_t copyColumnCount); + __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 SFAMatmulService::InitParams( + const ConstInfo& constInfo) { + this->constInfo = constInfo; +} + +template +__aicore__ inline void SFAMatmulService::InitMm1GlobalTensor( + GlobalTensor queryGm, + GlobalTensor qRopeGm, + GlobalTensor keyGm, + GlobalTensor kRopeGm, + GlobalTensor mm1ResGm) { + // mm1 + this->queryGm = queryGm; + this->keyGm = keyGm; + this->mm1ResGm = mm1ResGm; + if constexpr (HAS_ROPE) { + this->qRopeGm = qRopeGm; + this->kRopeGm = kRopeGm; + } +} + +template +__aicore__ inline void SFAMatmulService::InitMm2GlobalTensor( + GlobalTensor vec1ResGm, + GlobalTensor valueGm, + GlobalTensor mm2ResGm, + GlobalTensor attentionOutGm) { + // mm2 + this->vec1ResGm = vec1ResGm; + this->valueGm = valueGm; + this->mm2ResGm = mm2ResGm; + this->attentionOutGm = attentionOutGm; +} + +template +__aicore__ inline void SFAMatmulService::InitPageAttentionInfo( + const GlobalTensor& kvMergeGm, + GlobalTensor blockTableGm, + GlobalTensor topKGm, + uint32_t blockSize, + uint32_t maxBlockNumPerBatch) { + this->blockTableGm = blockTableGm; + this->topKGm = topKGm; + this->kvCacheBlockSize = blockSize; + this->maxBlockNumPerBatch = maxBlockNumPerBatch; + this->kvMergeGm_ = kvMergeGm; +} + +template +__aicore__ inline void SFAMatmulService::InitBuffers(TPipe* pipe) { + pipe->InitBuffer(bufQPL1, L1_BLOCK_SIZE * 4); // (64K + 8K) * 4 + l1QPTensor = bufQPL1.Get(); + pipe->InitBuffer(bufKVL1, L1_BLOCK_SIZE * 3); // (64K + 8K) * 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 SFAMatmulService::UpdateKey( + GlobalTensor keyGm) { + this->keyGm = keyGm; +} + +template +__aicore__ inline void SFAMatmulService::UpdateValue( + GlobalTensor valueGm) { + this->valueGm = valueGm; +} + +template +__aicore__ inline void SFAMatmulService::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 SFAMatmulService::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 SFAMatmulService::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 SFAMatmulService::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 SFAMatmulService::CopyInMm1ARopeToL1( + LocalTensor& l1Tensor, + const RunInfo& info, + uint32_t mSeqIdx, + uint32_t mSizeAct) { + auto srcGm = + qRopeGm[info.tensorARopeOffset + mSeqIdx * constInfo.headDimRope]; + CopyGmToL1( + l1Tensor, srcGm, mSizeAct, constInfo.headDimRope, constInfo.headDimRope); +} + +template +__aicore__ inline void SFAMatmulService::CopyInMm1BToL1( + LocalTensor& bL1Tensor, + const uint64_t keyGmBaseOffset, + uint32_t copyTotalRowCntAlign, + uint32_t copyStartRowCnt, + uint32_t nActCopyRowCount, + uint32_t headSize) { + uint64_t dStride = constInfo.headDim; + if constexpr (KV_LAYOUT_T == SFA_LAYOUT::BSND || + KV_LAYOUT_T == SFA_LAYOUT::TND) { + dStride = constInfo.headDim * constInfo.kvHeadNum; + } + + uint32_t blockElementCnt = 32 / sizeof(KV_T); + + Nd2NzParams mm1Nd2NzParamsForB; + mm1Nd2NzParamsForB.ndNum = 1; + mm1Nd2NzParamsForB.nValue = nActCopyRowCount; + mm1Nd2NzParamsForB.dValue = headSize; + mm1Nd2NzParamsForB.srcDValue = dStride; + mm1Nd2NzParamsForB.dstNzC0Stride = copyTotalRowCntAlign; + mm1Nd2NzParamsForB.dstNzNStride = 1; + mm1Nd2NzParamsForB.srcNdMatrixStride = 0; + mm1Nd2NzParamsForB.dstNzMatrixStride = 0; + DataCopy(bL1Tensor[copyStartRowCnt * blockElementCnt], + keyGm[keyGmBaseOffset], + mm1Nd2NzParamsForB); +} + +template +__aicore__ inline void SFAMatmulService::CopyInMm1BRopeToL1( + LocalTensor& bL1Tensor, + const uint64_t kRopeGmBaseOffset, + uint32_t copyTotalRowCntAlign, + uint32_t copyStartRowCnt, + uint32_t nActCopyRowCount, + uint32_t headSize) { + uint64_t dStride = constInfo.headDimRope; + if constexpr (KV_LAYOUT_T == SFA_LAYOUT::BSND || + KV_LAYOUT_T == SFA_LAYOUT::TND) { + dStride = constInfo.headDimRope * constInfo.kvHeadNum; + } + + uint32_t blockElementCnt = 32 / sizeof(KV_T); + + Nd2NzParams mm1Nd2NzParamsForB; + mm1Nd2NzParamsForB.ndNum = 1; + mm1Nd2NzParamsForB.nValue = nActCopyRowCount; + mm1Nd2NzParamsForB.dValue = headSize; + mm1Nd2NzParamsForB.srcDValue = dStride; + mm1Nd2NzParamsForB.dstNzC0Stride = copyTotalRowCntAlign; + mm1Nd2NzParamsForB.dstNzNStride = 1; + mm1Nd2NzParamsForB.srcNdMatrixStride = 0; + mm1Nd2NzParamsForB.dstNzMatrixStride = 0; + DataCopy(bL1Tensor[copyStartRowCnt * blockElementCnt], + kRopeGm[kRopeGmBaseOffset], + mm1Nd2NzParamsForB); +} + +template +__aicore__ inline void SFAMatmulService::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 SFAMatmulService::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 SFAMatmulService::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 SFAMatmulService::CopyInMm2BToL1( + LocalTensor& bL1Tensor, + const uint64_t valueGmBaseOffset, + uint32_t copyTotalRowCntAlign, + uint32_t copyStartRowCnt, + uint32_t nActCopyRowCount, + uint32_t copyStartColumnCount, + uint32_t copyColumnCount) { + uint64_t step = constInfo.headDim; + if constexpr (KV_LAYOUT_T == SFA_LAYOUT::BSND || + KV_LAYOUT_T == SFA_LAYOUT::TND) { + step = constInfo.headDim * constInfo.kvHeadNum; + } + + uint32_t blockElementCnt = 32 / sizeof(KV_T); + + Nd2NzParams mm1Nd2NzParamsForB; + mm1Nd2NzParamsForB.ndNum = 1; + mm1Nd2NzParamsForB.nValue = nActCopyRowCount; + mm1Nd2NzParamsForB.dValue = copyColumnCount; + mm1Nd2NzParamsForB.srcDValue = step; + mm1Nd2NzParamsForB.dstNzC0Stride = copyTotalRowCntAlign; + mm1Nd2NzParamsForB.dstNzNStride = 1; + mm1Nd2NzParamsForB.srcNdMatrixStride = 0; + mm1Nd2NzParamsForB.dstNzMatrixStride = 0; + DataCopy(bL1Tensor[copyStartRowCnt * blockElementCnt], + valueGm[valueGmBaseOffset + copyStartColumnCount], + mm1Nd2NzParamsForB); +} + +template +__aicore__ inline void SFAMatmulService::CalcTopKBlockInfo( + const RunInfo& info, + uint32_t& curTopKIdx, + uint64_t& curOffsetInSparseBlock, + uint32_t curSeqIdx, + uint32_t& copyRowCnt, + int64_t& idInTopK) { + uint64_t blockBegin = idInTopK * constInfo.sparseBlockSize; + uint64_t blockEnd = (blockBegin + constInfo.sparseBlockSize > info.threshold) + ? info.threshold + : blockBegin + constInfo.sparseBlockSize; + uint64_t blockLen = blockEnd - blockBegin; + if (curOffsetInSparseBlock + copyRowCnt < blockLen) { + curOffsetInSparseBlock += copyRowCnt; + copyRowCnt = blockLen - curOffsetInSparseBlock; + } else { + for (uint64_t topkidx = curTopKIdx + 1; + topkidx < constInfo.sparseBlockCount; + topkidx++) { + int64_t sparseIndices = topKGm.GetValue(info.topKBaseOffset + topkidx); + if (sparseIndices == -1) { + break; + } + + uint64_t blockBegin = sparseIndices * constInfo.sparseBlockSize; + if (blockBegin >= info.threshold) { + continue; + } + uint64_t blockEnd = + (blockBegin + constInfo.sparseBlockSize > info.threshold) + ? info.threshold + : blockBegin + constInfo.sparseBlockSize; + uint64_t blockLen = blockEnd - blockBegin; + curTopKIdx = topkidx; + idInTopK = sparseIndices; + curOffsetInSparseBlock = 0; + copyRowCnt = blockLen; + break; + } + } +} + +template +__aicore__ inline void SFAMatmulService::ComputeMm1( + const RunInfo& info, + const MSplitInfo mSplitInfo) { + // 最外层还需要一层m的循环 + uint32_t mSize = mSplitInfo.nBufferDealM; + uint32_t mL1Size = M_SPLIT_SIZE; + uint32_t mL1SizeAlign = SFAAlign(M_SPLIT_SIZE, 16U); + uint32_t mL1Loops = (mSize + M_SPLIT_SIZE - 1) / M_SPLIT_SIZE; + + uint32_t nSize = info.actualSingleProcessSInnerSize; + uint32_t nL1Size = N_SPLIT_SIZE; + uint32_t nL1SizeAlign = SFAAlign(N_SPLIT_SIZE, 16U); + uint32_t nL1Loops = (nSize + N_SPLIT_SIZE - 1) / N_SPLIT_SIZE; + + uint32_t kL1Size = 288; + uint32_t kL1Loops = 2; // 2 : 576/288, mla专用 这里不考虑d泛化 + uint32_t kL0Size = 96; + uint32_t kL0Loops = 3; // 288 / 96 = 3 kloops + if constexpr (!HAS_ROPE) { + kL1Size = 256; + kL0Size = 128; + kL0Loops = 2; // 256 / 128, 避免 96 无法整除 256 + } + + LocalTensor bL1Tensor; + LocalTensor kRopeTensor; + LocalTensor kTensor; + // ka表示左矩阵4buf选择哪一块buf, kb表示右矩阵3buf选择哪一块buf + uint32_t ka = 0, kb = 0; + + uint32_t curTopKIdx = info.curTopKIdx; + uint64_t curOffsetInSparseBlock = + info.curOffsetInSparseBlock; // sparse Block块内偏移 + uint32_t copyRowCnt = 0; + int64_t idInTopK = topKGm.GetValue(info.topKBaseOffset + curTopKIdx); + + uint32_t curTopKIdxTmp = 0; + uint64_t curOffsetInSparseBlockTmp = 0; + uint32_t copyRowCntTmp = 0; + int64_t idInTopKTmp = 0; + + // L1 切n切k切m + 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 = SFAAlign(nL1Size, 16U); + } + curTopKIdxTmp = curTopKIdx; + curOffsetInSparseBlockTmp = curOffsetInSparseBlock; + copyRowCntTmp = copyRowCnt; + idInTopKTmp = idInTopK; + + for (uint32_t kL1 = 0; kL1 < kL1Loops; + kL1++) { // L1切k, 576/288, 这里不考虑d泛化 + kvL1BufIter++; + uint32_t kb = kvL1BufIter % 3; + WaitFlag(mte21KVIds[kb]); + // 从k当中取当前的块 + bL1Tensor = l1KVTensor[kb * L1_BLOCK_OFFSET]; + // mm1拷贝主流程 + + uint32_t curSeqIdx = info.s2BatchOffset + nL1 * N_SPLIT_SIZE; + uint32_t copyFinishRowCnt = 0; + curTopKIdx = curTopKIdxTmp; + curOffsetInSparseBlock = curOffsetInSparseBlockTmp; + copyRowCnt = copyRowCntTmp; + idInTopK = idInTopKTmp; + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + if (kL1 == 0) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nL1Size; // 行数 + nd2nzPara.dValue = constInfo.headDim >> 1; // constInfo.headDim; + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = nL1SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(bL1Tensor, + kvMergeGm_[info.loop % 4 * N_WORKSPACE_SIZE * 576 + + nL1 * N_SPLIT_SIZE * constInfo.headDim], + nd2nzPara); + if constexpr (HAS_ROPE) { + nd2nzPara.dValue = constInfo.headDimRope >> 1; + nd2nzPara.srcDValue = constInfo.headDimRope; + DataCopy(bL1Tensor[nL1SizeAlign * (constInfo.headDim >> 1)], + kvMergeGm_[info.loop % 4 * N_WORKSPACE_SIZE * 576 + + N_WORKSPACE_SIZE * constInfo.headDim + + nL1 * N_SPLIT_SIZE * constInfo.headDimRope], + nd2nzPara); + } + } else { + LocalTensor kTmpTensor = + bL1Tensor[(constInfo.headDimRope >> 1) * nL1SizeAlign]; + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nL1Size; // 行数 + nd2nzPara.dValue = constInfo.headDim >> 1; // constInfo.headDim; + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = nL1SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(kTmpTensor, + kvMergeGm_[info.loop % 4 * N_WORKSPACE_SIZE * 576 + + (constInfo.headDim >> 1) + + nL1 * N_SPLIT_SIZE * constInfo.headDim], + nd2nzPara); + if constexpr (HAS_ROPE) { + nd2nzPara.dValue = constInfo.headDimRope >> 1; + nd2nzPara.srcDValue = constInfo.headDimRope; + DataCopy(bL1Tensor, + kvMergeGm_[info.loop % 4 * N_WORKSPACE_SIZE * 576 + + N_WORKSPACE_SIZE * constInfo.headDim + + (constInfo.headDimRope >> 1) + + nL1 * N_SPLIT_SIZE * constInfo.headDimRope], + nd2nzPara); + } + } + } else { + while (copyFinishRowCnt < nL1Size) { + CalcTopKBlockInfo(info, + curTopKIdx, + curOffsetInSparseBlock, + curSeqIdx, + copyRowCnt, + idInTopK); + if (copyFinishRowCnt + copyRowCnt > nL1Size) { + copyRowCnt = nL1Size - copyFinishRowCnt; + } + + // BN2轴偏移 + if constexpr (PAGE_ATTENTION) { + Position startPos; + startPos.bIdx = info.bIdx; + startPos.n2Idx = info.n2Idx; + startPos.s2Idx = + idInTopK * constInfo.sparseBlockSize + curOffsetInSparseBlock; + // 256、32等待7buf命名更改 + startPos.dIdx = kL1 * 256; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 + // 右矩阵, s2为k轴, d轴切分 + PAShape shape; + shape.blockSize = kvCacheBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.actHeadDim = 256; + shape.maxblockNumPerBatch = maxBlockNumPerBatch; + shape.copyRowNum = copyRowCnt; + shape.copyRowNumAlign = nL1SizeAlign; + if constexpr (HAS_ROPE) { + Position ropeStartPos = startPos; + ropeStartPos.dIdx = kL1 * 32; + PAShape ropeShape = shape; + ropeShape.headDim = constInfo.headDimRope; + ropeShape.actHeadDim = 32; + if (kL1 == 0) { + kTensor = bL1Tensor[copyFinishRowCnt * 16]; + DataCopyPA( + kTensor, keyGm, blockTableGm, shape, startPos); + kRopeTensor = + bL1Tensor[(nL1SizeAlign * + (BlockAlign(constInfo.headDim) >> 1)) + + copyFinishRowCnt * 16]; + DataCopyPA(kRopeTensor, + kRopeGm, + blockTableGm, + ropeShape, + ropeStartPos); + } else { + kRopeTensor = bL1Tensor[copyFinishRowCnt * 16]; + DataCopyPA(kRopeTensor, + kRopeGm, + blockTableGm, + ropeShape, + ropeStartPos); + LocalTensor kTmpTensor = + bL1Tensor[32 * nL1SizeAlign + copyFinishRowCnt * 16]; + DataCopyPA( + kTmpTensor, keyGm, blockTableGm, shape, startPos); + } + } else { + kTensor = bL1Tensor[copyFinishRowCnt * 16]; + DataCopyPA( + kTensor, keyGm, blockTableGm, shape, startPos); + } + } else { + uint64_t keyOffset = info.tensorBOffset; + if constexpr (KV_LAYOUT_T == SFA_LAYOUT::BSND || + KV_LAYOUT_T == SFA_LAYOUT::TND) { + keyOffset += (idInTopK * constInfo.sparseBlockSize + + curOffsetInSparseBlock) * + constInfo.kvHeadNum * constInfo.headDim; + } else { + keyOffset += (idInTopK * constInfo.sparseBlockSize + + curOffsetInSparseBlock) * + constInfo.headDim; + } + + if constexpr (HAS_ROPE) { + uint64_t kRopeOffset = info.tensorBRopeOffset; + if constexpr (KV_LAYOUT_T == SFA_LAYOUT::BSND || + KV_LAYOUT_T == SFA_LAYOUT::TND) { + kRopeOffset += (idInTopK * constInfo.sparseBlockSize + + curOffsetInSparseBlock) * + constInfo.kvHeadNum * constInfo.headDimRope; + } else { + kRopeOffset += (idInTopK * constInfo.sparseBlockSize + + curOffsetInSparseBlock) * + constInfo.headDimRope; + } + + if (kL1 == 0) { + CopyInMm1BToL1(bL1Tensor, + keyOffset, + nL1SizeAlign, + copyFinishRowCnt, + copyRowCnt, + 256); + kRopeTensor = + bL1Tensor[nL1SizeAlign * + (BlockAlign(constInfo.headDim) >> 1)]; + CopyInMm1BRopeToL1(kRopeTensor, + kRopeOffset, + nL1SizeAlign, + copyFinishRowCnt, + copyRowCnt, + 32); + } else { + kRopeTensor = bL1Tensor; + CopyInMm1BRopeToL1(kRopeTensor, + kRopeOffset + 32, + nL1SizeAlign, + copyFinishRowCnt, + copyRowCnt, + 32); + LocalTensor kTmpTensor = bL1Tensor[nL1SizeAlign * 32]; + CopyInMm1BToL1(kTmpTensor, + keyOffset + 256, + nL1SizeAlign, + copyFinishRowCnt, + copyRowCnt, + 256); + } + } else { + CopyInMm1BToL1(bL1Tensor, + keyOffset + kL1 * 256, + nL1SizeAlign, + copyFinishRowCnt, + copyRowCnt, + 256); + } + } + + // 更新循环变量 + copyFinishRowCnt += copyRowCnt; + curSeqIdx += copyRowCnt; + } + } + + SetFlag(mte21KVIds[kb]); + WaitFlag(mte21KVIds[kb]); + mL1Size = M_SPLIT_SIZE; + mL1SizeAlign = SFAAlign(M_SPLIT_SIZE, 16U); + for (uint32_t mL1 = 0; mL1 < mL1Loops; mL1++) { + uint32_t aL1PaddingSize = + 0; // 用于使左矩阵对齐到尾部, 以保证两块32K内存连续 + if (mL1 == (mL1Loops - 1)) { + // 尾块重新计算size + mL1Size = mSize - (mL1Loops - 1) * M_SPLIT_SIZE; + mL1SizeAlign = SFAAlign(mL1Size, 16U); + // mL1SizeAlign<128 kL1=0时需要偏移, 确保qRope能一半拷贝到当前tensor, + // 一半拷贝到下一个tensor + aL1PaddingSize = (M_SPLIT_SIZE - mL1SizeAlign) * kL1Size; + } + + // 左矩阵L1选择12块还是34块的index, 由m l1 index决定 + // 左矩阵L1选择12块或34块的前一块还是后一块, 由k l1 index决定 + uint32_t mIdx = qpL1BufIter + mL1; + ka = GetQPL1RealIdx(mIdx, kL1); + LocalTensor aL1Tensor = + l1QPTensor[ka * L1_BLOCK_OFFSET + + (1 - kL1) * aL1PaddingSize]; // kL1=0时需要偏移 + if (nL1 == 0) { // mL1=0, mL1=1两次 + if (kL1 == 0) { + WaitFlag(mte21QPIds[ka]); + WaitFlag(mte21QPIds[ka + 1]); + CopyInMm1AToL1(aL1Tensor, + info, + mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, + mL1Size, + 256, + 0); + if constexpr (HAS_ROPE) { + // 由于L1里面是NZ, 这里q rope的偏移为整块q nope切k的后大小, + // 256为headDim的一半 + LocalTensor qRopeTensor = aL1Tensor[mL1SizeAlign * 256]; + CopyInMm1ARopeToL1(qRopeTensor, + info, + mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, + mL1Size); + } + } else { + if constexpr (HAS_ROPE) { + // 32为rope headDim的一半 + LocalTensor qTmpTensor = aL1Tensor[mL1SizeAlign * 32]; + CopyInMm1AToL1(qTmpTensor, + info, + mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, + mL1Size, + 256, + 256); + } else { + CopyInMm1AToL1(aL1Tensor, + 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)); + + // m == 1的时候需要特殊处理 + 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 + + // 输出偏移info.loop % (constInfo.preLoadNum)) * + // mmResUbSize是否在matmul里计算 + 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 SFAMatmulService::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 = SFAAlign(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 + if (nL1 == (nL1Loops - 1)) { + // 尾块 + nL1Size = nSize - (nL1Loops - 1) * N_SPLIT_SIZE; + nL1SizeAlign = SFAAlign(nL1Size, 16U); + } + + // k l1写成一个循环, 和mm1保持一致 + kL1Size = 256; + kL1SizeAlign = SFAAlign(kL1Size, 16U); + + uint32_t curTopKIdx = info.curTopKIdx; + uint64_t curOffsetInSparseBlock = info.curOffsetInSparseBlock; + uint32_t copyRowCnt = 0; + int64_t idInTopK = topKGm.GetValue(info.topKBaseOffset + curTopKIdx); + + for (uint32_t k1 = 0; k1 < kL1Loops; k1++) { // k切L1, 这里套了一层l0来操作 + if (k1 == (kL1Loops - 1)) { + // 尾块 + kL1Size = kSize - (kL1Loops - 1) * 256; + kL1SizeAlign = SFAAlign(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 + if (kL1 == kOffset + kL0Loops - 1) { + // 尾块 + kL0Size = kL1Size - (kL0Loops - 1) * kL0Size; + kL0SizeAlign = SFAAlign(kL0Size, 16U); + } + + uint32_t curSeqIdx = + info.s2BatchOffset + (kL1 - kOffset) * 128 + k1 * 256; + uint32_t copyFinishRowCnt = 0; + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + 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.loop % 4 * N_WORKSPACE_SIZE * 576 + + kL1 * 128 * constInfo.headDim + nL1 * N_SPLIT_SIZE], + nd2nzPara); + } else { + while (copyFinishRowCnt < kL0Size) { + CalcTopKBlockInfo(info, + curTopKIdx, + curOffsetInSparseBlock, + curSeqIdx, + copyRowCnt, + idInTopK); + + if (copyFinishRowCnt + copyRowCnt > kL0Size) { + copyRowCnt = kL0Size - copyFinishRowCnt; + } + + if constexpr (PAGE_ATTENTION) { + Position startPos; + startPos.bIdx = info.bIdx; + startPos.n2Idx = info.n2Idx; + startPos.s2Idx = + idInTopK * constInfo.sparseBlockSize + curOffsetInSparseBlock; + startPos.dIdx = + nL1 * N_SPLIT_SIZE; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 + // 右矩阵, s2为k轴, d轴切分 + PAShape shape; + shape.blockSize = kvCacheBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.actHeadDim = nL1Size; + shape.maxblockNumPerBatch = maxBlockNumPerBatch; + shape.copyRowNum = copyRowCnt; + shape.copyRowNumAlign = kL0SizeAlign; + subvTensor = bL1Tensor[(kL1 - kOffset) * 128 * N_SPLIT_SIZE + + copyFinishRowCnt * 16]; + DataCopyPA( + subvTensor, valueGm, blockTableGm, shape, startPos); + } else { + uint64_t valueOffset = info.tensorBOffset; + if constexpr (KV_LAYOUT_T == SFA_LAYOUT::BSND || + KV_LAYOUT_T == SFA_LAYOUT::TND) { + valueOffset += (idInTopK * constInfo.sparseBlockSize + + curOffsetInSparseBlock) * + constInfo.kvHeadNum * constInfo.headDim; + } else { + valueOffset += (idInTopK * constInfo.sparseBlockSize + + curOffsetInSparseBlock) * + constInfo.headDim; + } + + subvTensor = bL1Tensor[(kL1 - kOffset) * 128 * N_SPLIT_SIZE]; + CopyInMm2BToL1(subvTensor, + valueOffset, + kL0SizeAlign, + copyFinishRowCnt, + copyRowCnt, + nL1 * N_SPLIT_SIZE, + nL1Size); + } + // 更新循环变量 + copyFinishRowCnt += copyRowCnt; + curSeqIdx += copyRowCnt; + } + } + } + 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 = SFAAlign(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 = SFAAlign(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; // Select FMATRIX_LEFT. + 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)) { + if (nL1 == 0 && mL1 == 0) { // 第一次Fixpipe前等待 + CrossCoreWaitFlag(constInfo.syncV1NupdateC2); + } + + SetAtomicAdd(); + // 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.bn2IdxInCurCore % (constInfo.preLoadNum)) * + constInfo.bmm2ResUbSize + + mm2Offset], + cL0Tensor, + fixParams); + SetAtomicNone(); + } + + if (mL1Loops == 2) { + cL0BufIter++; + } + } + SetFlag( + mte21KVIds[kb]); // 反向同步, 表示L1已经被mte1消费完 + } + // cL0BufIter已经不在使用 + if (mL1Loops == 1) { + cL0BufIter++; + } + } + qpL1BufIter += mL1Loops; +} + +#endif // SPARSE_FLASH_ATTENTION_LSE_SERVICE_CUBE_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/arch22/sparse_flash_attention_lse_service_vector_mla.h b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/arch22/sparse_flash_attention_lse_service_vector_mla.h new file mode 100644 index 0000000000..f0636f0498 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/arch22/sparse_flash_attention_lse_service_vector_mla.h @@ -0,0 +1,1991 @@ +/** + * 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 sparse_flash_attention_lse_service_vector_mla.h + * \brief + */ +#ifndef SPARSE_FLASH_ATTENTION_LSE_SERVICE_VECTOR_MLA_H +#define SPARSE_FLASH_ATTENTION_LSE_SERVICE_VECTOR_MLA_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_attention_lse/op_kernel/sparse_flash_attention_lse_common.h" + +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +template +class SFAVectorService { + public: + // 中间计算数据类型为float,高精度模式 + using T = float; + using KV_T = typename SFAT::kvType; + using OUT_T = typename SFAT::outputType; + using UPDATE_T = T; + using MM1_OUT_T = float; + using MM2_OUT_T = float; + + __aicore__ inline SFAVectorService(){}; + __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 SparseFlashAttentionLseTilingDataMla* __restrict tilingData); + __aicore__ inline void InitMm2ResInt32GmGlobalTensor( + GlobalTensor mm2ResInt32Gm); + __aicore__ inline void InitVec0GlobalTensor( + const GlobalTensor& kvValidSizeGm, + const GlobalTensor& kvMergeGm, + const GlobalTensor& keyRopeGm, + const GlobalTensor& keyGm, + const GlobalTensor& blkTableGm); + __aicore__ inline void InitVec1GlobalTensor( + GlobalTensor mm1ResGm, + GlobalTensor vec1ResGm, + GlobalTensor actualSeqLengthsQGm, + GlobalTensor actualSeqLengthsKVGm, + GlobalTensor lseMaxFdGm, + GlobalTensor lseSumFdGm, + GlobalTensor topKGm, + GlobalTensor softmaxMaxGm, + GlobalTensor softmaxSumGm); + __aicore__ inline void InitVec2GlobalTensor( + GlobalTensor accumOutGm, + GlobalTensor vec2ResGm, + GlobalTensor mm2ResGm, + GlobalTensor attentionOutGm); + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + __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 void MergeKv(const RunInfo& runInfo); + __aicore__ inline int64_t GetKeyGmOffset(int64_t realS2Idx, + const RunInfo& runInfo, + int64_t s2IdLimit); + __aicore__ inline int64_t GetKeyRopeGmOffset(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 SetInfInBlk(const LocalTensor& mmResUb, + uint32_t dealRowCount, + uint32_t columnCount, + uint64_t startId, + uint64_t endId); + __aicore__ inline void SetMidInf(const LocalTensor& mmResUb, + uint32_t dealRowCount, + uint32_t columnCount, + uint64_t startId, + uint64_t endId); + __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 AmlaVecCompute(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 ProcessAmlaNupdate(const RunInfo& info, + const MSplitInfo& mSplitInfo); + __aicore__ inline void ComputeLogSumExpAndCopyToGm( + const RunInfo& info, + const MSplitInfo& mSplitInfo, + LocalTensor& softmaxSumUb, + LocalTensor& softmaxMaxUb); + __aicore__ inline void CopyFALseToGm(const RunInfo& info, + const MSplitInfo& mSplitInfo, + LocalTensor& softmaxSumUb, + LocalTensor& softmaxMaxUb); + __aicore__ inline void SetBmm2FirstSInnerBias(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 GetConfusionTransposeTiling( + int64_t numR, + int64_t numC, + const uint32_t stackBufferSize, + const uint32_t typeSize, + ConfusionTransposeTiling& tiling); + + // 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 = SFAT::pageAttention; + static constexpr int TEMPLATE_MODE = SFAT::templateMode; + static constexpr bool FLASH_DECODE = SFAT::flashDecode; + static constexpr SFA_LAYOUT LAYOUT_T = SFAT::layout; + static constexpr SFA_LAYOUT KV_LAYOUT_T = SFAT::kvLayout; + static constexpr bool HAS_ROPE = SFAT::hasRope; + // kvMergeGm_每个核缓存布局: 512行nope + (有rope时)512行rope, NoPE时无rope半区 + static constexpr uint64_t MERGE_ROPE_REGION_OFFSET = + HAS_ROPE ? 512ULL * 512ULL : 0ULL; + + static constexpr uint64_t MERGE_CACHE_GM_BUF_NUM = 4; + 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_INPUT_V0BUF_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); // 32768/4=8096 + static constexpr uint32_t BLOCK_ELEMENT_NUM = + BYTE_BLOCK / sizeof(T); // 32/4=8 + static constexpr T FLOAT_E_SCALAR = 8388608; + static constexpr T LN2 = 0.6931471805599453094172; + static constexpr T RECIP_OF_LN2 = 1 / LN2; + static constexpr T SOFTMAX_MIN_NUM = -2e38; + + const SparseFlashAttentionLseTilingDataMla* __restrict tilingData; + + uint32_t pingpongFlag = 0U; + ConstInfo constInfo = {}; + + GlobalTensor mm2ResInt32Gm; + GlobalTensor mm1ResGm; + GlobalTensor vec1ResGm; + GlobalTensor lseSumFdGm; + GlobalTensor lseMaxFdGm; + GlobalTensor softmaxMaxGm; + GlobalTensor softmaxSumGm; + + GlobalTensor actualSeqLengthsQGm; + GlobalTensor actualSeqLengthsKVGm; + GlobalTensor vec2ResGm; + GlobalTensor mm2ResGm; + GlobalTensor accumOutGm; + GlobalTensor attentionOutGm; + GlobalTensor blkTableGm_; + + GlobalTensor kvMergeGm_; + GlobalTensor keyRopeGm_; + GlobalTensor keyGm_; + GlobalTensor topkGm_; + GlobalTensor kvValidSizeGm_; + + // ================================Local + // Buffer区==================================== + TBuf<> inputBuff1; // 32K + TBuf<> inputBuff2; // 16K + TBuf<> outputBuff1; // 32K + TBuf<> outputBuff2; // 4K + + TBuf<> tmpBuff1; // 32K + TBuf<> v0ValidSizeBuff; // 8K + + TBuf<> nValueBuff; + TBuf<> cofValueBuff; + TBuf<> aMlaSumBuff; + 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 nValueUb; + LocalTensor cofValueUb; + LocalTensor aMlaSumUb; + LocalTensor softmaxMaxUb; + LocalTensor softmaxSumUb; + LocalTensor softmaxExpUb; + LocalTensor kvMergUb_; + LocalTensor ropeMergUb_; + LocalTensor v0ValidSizeUb_; +}; + +template +__aicore__ inline void SFAVectorService::InitBuffers(TPipe* pipe) { + pipe->InitBuffer(inputBuff1, + ConstInfo::BUFFER_SIZE_BYTE_32K * 2); // 2:pingpong + if constexpr (HAS_ROPE) { + 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(nValueBuff, + ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); + pipe->InitBuffer(cofValueBuff, + ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); + pipe->InitBuffer(aMlaSumBuff, + ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); + + 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); + + nValueUb = nValueBuff.Get(); + cofValueUb = cofValueBuff.Get(); + aMlaSumUb = aMlaSumBuff.Get(); + + softmaxMaxUb = softmaxMaxBuff.Get(); + softmaxSumUb = softmaxSumBuff.Get(); + softmaxExpUb = softmaxExpBuff.Get(); + + softmaxMaxDefaultUb = softmaxMaxDefaultBuff.Get(); + softmaxSumDefaultUb = softmaxSumDefaultBuff.Get(); + + kvMergUb_ = inputBuff1.Get(); + if constexpr (HAS_ROPE) { + ropeMergUb_ = inputBuff2.Get(); + } + + v0ValidSizeUb_ = v0ValidSizeBuff.Get(); +} + +template +__aicore__ inline void SFAVectorService::InitParams( + const struct ConstInfo& constInfo, + const SparseFlashAttentionLseTilingDataMla* __restrict tilingData) { + this->constInfo = constInfo; + this->tilingData = tilingData; +} + +template +__aicore__ inline void SFAVectorService::InitMm2ResInt32GmGlobalTensor( + GlobalTensor mm2ResInt32Gm) { + this->mm2ResInt32Gm = mm2ResInt32Gm; +} + +template +__aicore__ inline void SFAVectorService::InitVec0GlobalTensor( + const GlobalTensor& kvValidSizeGm, + const GlobalTensor& kvMergeGm, + const GlobalTensor& keyRopeGm, + const GlobalTensor& keyGm, + const GlobalTensor& blkTableGm) { + this->kvMergeGm_ = kvMergeGm; + if constexpr (HAS_ROPE) { + this->keyRopeGm_ = keyRopeGm; + } + this->keyGm_ = keyGm; + this->blkTableGm_ = blkTableGm; + this->kvValidSizeGm_ = kvValidSizeGm; +} + +template +__aicore__ inline void SFAVectorService::InitVec1GlobalTensor( + GlobalTensor mm1ResGm, + GlobalTensor vec1ResGm, + GlobalTensor actualSeqLengthsQGm, + GlobalTensor actualSeqLengthsKVGm, + GlobalTensor lseMaxFdGm, + GlobalTensor lseSumFdGm, + GlobalTensor topKGm, + GlobalTensor softmaxMaxGm, + GlobalTensor softmaxSumGm) { + this->mm1ResGm = mm1ResGm; + this->vec1ResGm = vec1ResGm; + this->actualSeqLengthsQGm = actualSeqLengthsQGm; + this->actualSeqLengthsKVGm = actualSeqLengthsKVGm; + this->lseMaxFdGm = lseMaxFdGm; + this->lseSumFdGm = lseSumFdGm; + this->topkGm_ = topKGm; + this->softmaxMaxGm = softmaxMaxGm; + this->softmaxSumGm = softmaxSumGm; +} + +template +__aicore__ inline void SFAVectorService::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 SFAVectorService::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 SFAVectorService::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 SFAVectorService::InitSoftmaxDefaultBuffer() { + Duplicate(softmaxMaxDefaultUb, + SOFTMAX_MIN_NUM, + SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)); + Duplicate(softmaxSumDefaultUb, + ConstInfo::FLOAT_ZERO, + SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)); +} + +template +__aicore__ inline void SFAVectorService::CopyFALseToGm( + const RunInfo& info, + const MSplitInfo& mSplitInfo, + LocalTensor& softmaxSumUb, + LocalTensor& softmaxMaxUb) + +{ + if (mSplitInfo.vecDealM == 0) { + return; + } + uint64_t baseOffset = mSplitInfo.nBufferStartM / 2; + size_t size = mSplitInfo.vecDealM; + + int64_t offset = 0; + if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { // lse layout为N2 T G + uint64_t actualSeqQTotal = + (info.bIdx <= 0) + ? 0 + : actualSeqLengthsQGm.GetValue(constInfo.batchSize - 1); + uint64_t actualSeqQPrefixSum = + (info.bIdx <= 0) ? 0 : actualSeqLengthsQGm.GetValue(info.bIdx - 1); + offset += info.n2Idx * actualSeqQTotal * constInfo.gSize + + (actualSeqQPrefixSum + info.gS1Idx / constInfo.gSize) * + constInfo.gSize + + mSplitInfo.nBufferStartM + mSplitInfo.vecStartM; + } else { + offset += + info.bIdx * constInfo.kvHeadNum * constInfo.qSeqSize * constInfo.gSize + + info.n2Idx * constInfo.qSeqSize * constInfo.gSize + + info.gS1Idx / constInfo.gSize * constInfo.gSize + + mSplitInfo.nBufferStartM + mSplitInfo.vecStartM; + } + + if (info.actualSingleProcessSInnerSize != 0) { + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = 1; + dataCopyParams.blockLen = sizeof(T) * size; + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = 0; + size_t alignedSize = (sizeof(T) * size + 31) / 32 * 32 / sizeof(T); + LocalTensor tmp = outputBuff2.Get(); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + DataCopy(tmp, softmaxMaxUb[baseOffset], alignedSize); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + DataCopyPad(softmaxMaxGm[offset], tmp, dataCopyParams); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + + tmp = outputBuff2.Get(); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + DataCopy(tmp, softmaxSumUb[baseOffset], alignedSize); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + DataCopyPad(softmaxSumGm[offset], tmp, dataCopyParams); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + } else { + matmul::InitOutput(softmaxSumGm[offset], size, ConstInfo::FLOAT_ZERO); + matmul::InitOutput(softmaxMaxGm[offset], size, SOFTMAX_MIN_NUM); + } +} + +template +__aicore__ inline void SFAVectorService::ComputeLogSumExpAndCopyToGm( + const RunInfo& info, + const MSplitInfo& mSplitInfo, + LocalTensor& softmaxSumUb, + LocalTensor& softmaxMaxUb) { + if (mSplitInfo.vecDealM == 0) { + return; + } + uint64_t baseOffset = mSplitInfo.nBufferStartM / 2; + size_t size = mSplitInfo.vecDealM * FP32_BLOCK_ELEMENT_NUM; + uint64_t accumTmpOutNum = CalcAccumOffset(info.bIdx, info.gS1Idx); + uint64_t offset = (accumTmpOutNum * constInfo.kvHeadNum * + constInfo.mBaseSize + // taskoffset + info.tndCoreStartKVSplitPos * constInfo.kvHeadNum * + constInfo.mBaseSize + // 份数offset + mSplitInfo.nBufferStartM + + mSplitInfo.vecStartM) * + FP32_BLOCK_ELEMENT_NUM; // m轴offset + if (info.actualSingleProcessSInnerSize != 0) { + LocalTensor tmp = outputBuff2.Get(); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + Brcb(tmp, softmaxSumUb[baseOffset], (mSplitInfo.vecDealM + 7) / 8, {1, 8}); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + DataCopy(lseSumFdGm[offset], tmp, size); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + + tmp = outputBuff2.Get(); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + Brcb(tmp, softmaxMaxUb[baseOffset], (mSplitInfo.vecDealM + 7) / 8, {1, 8}); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + DataCopy(lseMaxFdGm[offset], tmp, size); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + } else { + matmul::InitOutput(lseSumFdGm[offset], size, ConstInfo::FLOAT_ZERO); + matmul::InitOutput(lseMaxFdGm[offset], size, SOFTMAX_MIN_NUM); + } +} + +template +__aicore__ inline void SFAVectorService::ElewiseCompute( + const RunInfo& info, + const LocalTensor& mmResUb, + uint32_t dealRowCount, + uint32_t columnCount) { + Muls(mmResUb, + mmResUb, + static_cast(tilingData->baseParams.scaleValue), + dealRowCount * columnCount); + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + // v0的无效值判断 + uint64_t s2ValidSizeFirstPart = + v0ValidSizeUb_.GetValue(128 + info.loop % MERGE_CACHE_GM_BUF_NUM); + uint64_t s2ValidSizeSecondPart = + v0ValidSizeUb_.GetValue(256 + info.loop % MERGE_CACHE_GM_BUF_NUM); + + int64_t s2ProcessSize = info.actualSingleProcessSInnerSize; + int64_t s2Pair = CeilDiv(s2ProcessSize, 2L * constInfo.sparseBlockSize); + int64_t s2Mid = CeilDiv(s2Pair, 2L) * 2 * constInfo.sparseBlockSize; + if (s2Mid > s2ProcessSize) { + s2Mid = s2ProcessSize; + } + if (unlikely(s2ValidSizeFirstPart < s2Mid)) { + int64_t s2StartCeilAlign = CeilAlign(s2ValidSizeFirstPart, 8); + int64_t s2MidFloorAlign = s2Mid / 8 * 8; + // 场景一 s2Mid > s2ValidSizeFirstPart + oneBlk + // 可以推导出s2StartCeilAlign < s2Mid 第一阶段取到s2StartCeilAlign + // s2StartCeilAlign <= s2MidFloorAlign 第二阶段取到s2MidFloorAlign + // 场景二 s2Mid <= s2ValidSizeFirstPart + oneBlk + // 可以推导出 s2StartCeilAlign >= s2Mid 第一阶段取到mid + // s2StartCeilAlign > s2MidFloorAlign 第二阶段取到s2StartCeilAlign + SetInfInBlk(mmResUb, + dealRowCount, + columnCount, + s2ValidSizeFirstPart, + s2StartCeilAlign >= s2Mid ? s2Mid : s2StartCeilAlign); + SetMidInf(mmResUb, + dealRowCount, + columnCount, + s2StartCeilAlign, + s2MidFloorAlign); + SetInfInBlk(mmResUb, + dealRowCount, + columnCount, + s2StartCeilAlign <= s2MidFloorAlign ? s2MidFloorAlign + : s2StartCeilAlign, + s2Mid); + } + if (unlikely(s2ValidSizeSecondPart < s2ProcessSize - s2Mid)) { + // 场景一 s2Mid + s2ValidSizeSecondPart > s2ProcessSize + oneBlk + // 可以推导出 s2StartCeilAlign < s2ProcessSize + // 第一阶段取到s2StartCeilAlign s2StartCeilAlign <= s2EndFloorAlign + // 第二阶段取到s2EndFloorAlign 场景二 s2Mid + s2ValidSizeSecondPart <= + // s2ProcessSize + oneBlk 可以推导出 s2StartCeilAlign >= s2ProcessSize + // 第一阶段取到s2ProcessSize s2StartCeilAlign > s2EndFloorAlign + // 第二阶段取到s2StartCeilAlign + int64_t s2StartCeilAlign = CeilAlign(s2Mid + s2ValidSizeSecondPart, 8); + int64_t s2EndFloorAlign = s2ProcessSize / 8 * 8; + SetInfInBlk( + mmResUb, + dealRowCount, + columnCount, + s2Mid + s2ValidSizeSecondPart, + s2StartCeilAlign >= s2ProcessSize ? s2ProcessSize : s2StartCeilAlign); + SetMidInf(mmResUb, + dealRowCount, + columnCount, + s2StartCeilAlign, + s2EndFloorAlign); + SetInfInBlk(mmResUb, + dealRowCount, + columnCount, + s2StartCeilAlign <= s2EndFloorAlign ? s2EndFloorAlign + : s2StartCeilAlign, + s2ProcessSize); + } + } +} + +template +__aicore__ inline void SFAVectorService::SetInfInBlk( + const LocalTensor& mmResUb, + uint32_t dealRowCount, + uint32_t columnCount, + uint64_t startId, + uint64_t endId) { + // startId endId + // x x x 0 0 0 x x x + // 从startId到endId部分置-inf, endId、startId为endId一个blk内部的下标 + if (startId >= endId) { + return; + } + + uint64_t startFloorAlignSize = + startId / BLOCK_ELEMENT_NUM * BLOCK_ELEMENT_NUM; + uint64_t notComputePreMaskOneBlk = (1 << (startId - startFloorAlignSize)) - 1; + uint64_t notComputePostMaskOneBlk = + ~((1 << (endId - startFloorAlignSize)) - 1); + uint64_t notComputeMaskOneBlk = + notComputePreMaskOneBlk ^ notComputePostMaskOneBlk; + + uint64_t maskOneBlk = ~notComputeMaskOneBlk; + uint64_t mask[1] = {maskOneBlk}; + for (int i = 1; i < 8; i++) { + mask[0] = mask[0] | (maskOneBlk << (i * 8)); + } + for (uint64_t rowId = 0; rowId < dealRowCount; rowId += 8) { + Duplicate(mmResUb[rowId * columnCount + startFloorAlignSize], + SOFTMAX_MIN_NUM, + mask, + 1, + CeilDiv(columnCount, 8), + 0); + } +} + +template +__aicore__ inline void SFAVectorService::SetMidInf( + const LocalTensor& mmResUb, + uint32_t dealRowCount, + uint32_t columnCount, + uint64_t startId, + uint64_t endId) { + if (startId >= endId) { + return; + } + // startId endId + // 0 ... 0 + // 从startId到endId部分置-inf, startId、endId为32B对齐的下标 + for (uint64_t rowId = 0; rowId < dealRowCount; rowId++) { + Duplicate(mmResUb[rowId * columnCount + startId], + SOFTMAX_MIN_NUM, + endId - startId); + } +} + +template +__aicore__ inline void SFAVectorService::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; + 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 = SFAAlign(dealRowCount, FP32_BLOCK_ELEMENT_NUM); + DataCopy(softmaxSumUb[softmaxOutOffset], inSumTensor, dealRowCountAlign); + PipeBarrier(); + DataCopy(softmaxMaxUb[softmaxOutOffset], inMaxTensor, dealRowCountAlign); + } +} + +template +__aicore__ inline void SFAVectorService::AmlaVecCompute( + const RunInfo& info, + const MSplitInfo& mSplitInfo, + LocalTensor& mmResUb, + LocalTensor& softmaxTmpUb, + uint32_t startRow, + uint32_t dealRowCount, + uint32_t columnCount, + uint32_t actualColumnCount) { + uint32_t baseOffset = mSplitInfo.nBufferStartM / 2 + startRow; + uint32_t calCount = dealRowCount; + uint32_t outIdx = info.loop % (constInfo.preLoadNum); + uint32_t softmaxOutOffset = + outIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset; + // compute n(i) + LocalTensor nTmp = softmaxTmpUb.template ReinterpretCast(); + LocalTensor nUpdateTmp = nTmp[SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)]; + Muls(nTmp, + softmaxMaxUb[softmaxOutOffset], + ((T)(-1.0)) * RECIP_OF_LN2, + calCount); + + PipeBarrier(); + Cast(nTmp, nTmp, RoundMode::CAST_ROUND, calCount); + PipeBarrier(); + + uint32_t prOutIdx = (info.loop - 1) % (constInfo.preLoadNum); + uint32_t PreSoftmaxOutOffset = + prOutIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset; + // n(i) - n(i-1) + if (info.isFirstSInnerLoop) { + Duplicate(nUpdateTmp, ConstInfo::FLOAT_ZERO, calCount); // n1=n0 + } else { + Sub(nUpdateTmp, nTmp, nValueUb[PreSoftmaxOutOffset], calCount); + } + PipeBarrier(); + // update n(i), DataCopy not support when calCount is not align 32B, so use + // Adds + Adds(nValueUb[softmaxOutOffset], nTmp, ConstInfo::FLOAT_ZERO, calCount); + PipeBarrier(); + + // update softmax res + LocalTensor nUpdateTmp2 = nTmp[2 * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)]; + LocalTensor nTmp_KvT = nTmp[3 * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)] + .template ReinterpretCast(); + LocalTensor tmpCofUb = nTmp[4 * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)]; + LocalTensor epsUb = nTmp[5 * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)]; + Muls(nUpdateTmp2, softmaxMaxUb[softmaxOutOffset], RECIP_OF_LN2, calCount); + PipeBarrier(); + Add(nTmp, nUpdateTmp2, nTmp, calCount); + PipeBarrier(); + Muls(nTmp, nTmp, LN2, calCount); + PipeBarrier(); + Exp(nTmp, nTmp, calCount); + PipeBarrier(); + Cast(nTmp_KvT, nTmp, RoundMode::CAST_ROUND, calCount); // fp32->fp16/bf16 + PipeBarrier(); + Cast(nUpdateTmp2, + nTmp_KvT, + RoundMode::CAST_NONE, + calCount); // fp16/bf16->fp32 + PipeBarrier(); + if (info.s2Idx + 1 == info.curSInnerLoopTimes) { + Mul(aMlaSumUb[softmaxOutOffset], + softmaxSumUb[softmaxOutOffset], + nUpdateTmp2, + calCount); + } + if (actualColumnCount == 0) { + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + return; + } + LocalTensor nTmp3 = nTmp[6 * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)]; + Brcb(nTmp3, nUpdateTmp2, (dealRowCount + 7) / 8, {1, 8}); + PipeBarrier(); + RowMuls( + mmResUb, mmResUb, nTmp3, dealRowCount, columnCount, actualColumnCount); + + Div(tmpCofUb, nTmp, nUpdateTmp2, calCount); // cof(i)=tmpS32/tmpS16 + if (info.isFirstSInnerLoop) { + Duplicate(cofValueUb[softmaxOutOffset], (T)1.0, calCount); // cof_0=1 + PipeBarrier(); + Div(epsUb, cofValueUb[softmaxOutOffset], tmpCofUb, calCount); // 1 / cof(i) + } else { + PipeBarrier(); + Div(epsUb, + cofValueUb[PreSoftmaxOutOffset], + tmpCofUb, + calCount); // cof(i - 1) / cof(i) + } + PipeBarrier(); + + Adds(cofValueUb[softmaxOutOffset], + tmpCofUb, + ConstInfo::FLOAT_ZERO, + calCount); // store cof(i) + Adds(epsUb, epsUb, (T)(-1.0), calCount); // cof(i - 1) / cof(i) - 1 + PipeBarrier(); + Muls(epsUb, epsUb, (T)1.5, calCount); // (cof(i - 1) - cof(i)) / cof(i) * 1.5 + + Maxs(nUpdateTmp, + nUpdateTmp, + (T)(-30.0), + calCount); // N = max(n(i) - n(i-1), -30) + PipeBarrier(); + Adds(epsUb, epsUb, (T)(0.000001), calCount); + PipeBarrier(); + Add(nUpdateTmp, nUpdateTmp, epsUb, calCount); + PipeBarrier(); + Muls(nUpdateTmp, nUpdateTmp, FLOAT_E_SCALAR, calCount); // N = N * pow(2, 23) + PipeBarrier(); + + // nUpdate int32 out + LocalTensor tmQue = outputBuff2.Get(); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + LocalTensor nInt32Out = tmQue[startRow]; // 缓存nUpdate + + Cast(nInt32Out, nUpdateTmp, RoundMode::CAST_ROUND, dealRowCount); + PipeBarrier(); + + SetFlag(SYNC_OUTPUT_BUF2_FLAG); +} + +template +__aicore__ inline void SFAVectorService::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); + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + if (loopId == 0) { + WaitFlag(0); + } + } + 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(); + AmlaVecCompute(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 SFAVectorService::SetBmm2FirstSInnerBias( + const RunInfo& info, + const MSplitInfo& mSplitInfo) { + uint32_t mSplitSize = 16U; + uint64_t baseoffset = + (info.bn2IdxInCurCore % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + + (mSplitInfo.nBufferStartM + mSplitInfo.vecStartM) * constInfo.headDim; + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + LocalTensor tmpTensor = outputBuff1.Get(); + Duplicate(tmpTensor, + static_cast(394264576), + mSplitSize * + constInfo.headDim); // 394264576 : + // fp32下2^(-80)的二进制表示对应的int32数值 + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + uint32_t loopCount = (mSplitInfo.vecDealM + mSplitSize - 1) / mSplitSize; + for (uint32_t loop = 0; loop < loopCount; loop++) { + DataCopy(mm2ResInt32Gm[baseoffset + loop * mSplitSize * constInfo.headDim], + tmpTensor, + mSplitSize * constInfo.headDim); + } + SetFlag(SYNC_OUTPUT_BUF1_FLAG); +} + +template +__aicore__ inline void SFAVectorService::ProcessAmlaNupdate( + const RunInfo& info, + const MSplitInfo& mSplitInfo) { + if (mSplitInfo.vecDealM == 0) { + return; + } + if (info.isFirstSInnerLoop) { + SetBmm2FirstSInnerBias(info, mSplitInfo); + return; + } + + LocalTensor nUpdateTensor = + outputBuff2.Get(); // shape:1/2*s1*g + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + + constexpr uint32_t dGroupSize = 128U; + constexpr uint32_t mSplitSize = + 64U; // tmpQue size + // 32KB,一次只能处理64个N,最大保存的数据大小:64*128*sizeof(int32) + constexpr uint32_t ONE_BLOCK_SIZE = 32U; // 32B + + uint32_t subMSize = SFAAlign(mSplitInfo.vecDealM, 16U); + uint16_t elementPerBlock = + ONE_BLOCK_SIZE / + sizeof(int32_t); // 单个datablock的元素数,int32_t类型的为32/4=8 + uint32_t loopCount = (subMSize + mSplitSize - 1) / mSplitSize; + uint32_t tailSplitSize = subMSize - (loopCount - 1) * mSplitSize; // 尾块 + + for (uint32_t loop = 0, processMSize = mSplitSize; loop < loopCount; loop++) { + if (loop == (loopCount - 1)) { + processMSize = tailSplitSize; + } + LocalTensor tmpQue = outputBuff1.Get(); + + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + // (m,1)单次brcb扩充成(m,8), 重复16次, 扩充为(m,128) + for (uint32_t i = 0; i < dGroupSize / elementPerBlock; i++) { + Brcb( + tmpQue[i * elementPerBlock], + nUpdateTensor[loop * mSplitSize], + static_cast((processMSize + elementPerBlock - 1) / + elementPerBlock), + {static_cast( + dGroupSize / + elementPerBlock), // 单次迭代内,目的操作数不同datablock间地址步长,单位为datablock + static_cast( + dGroupSize)}); // 相邻迭代间,目的操作数相同datablock地址步长 + } + + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + + uint64_t baseoffset = + (info.bn2IdxInCurCore % constInfo.preLoadNum) * + constInfo.bmm2ResUbSize + + (mSplitInfo.nBufferStartM + mSplitInfo.vecStartM + loop * mSplitSize) * + constInfo.headDim; + + SetAtomicAdd(); + DataCopyParams dataCopyParams; + dataCopyParams.blockCount = static_cast(processMSize); + dataCopyParams.blockLen = + dGroupSize * sizeof(int32_t) / + ONE_BLOCK_SIZE; // 每个block是128个元素,单位为32B + dataCopyParams.srcStride = 0; // 前面一个数据块的尾与后面数据块的头的间隔 + dataCopyParams.dstStride = + static_cast((constInfo.headDim - dGroupSize) * + sizeof(int32_t) / ONE_BLOCK_SIZE); // 单位为32B + for (uint32_t i = 0; i < constInfo.headDim / dGroupSize; + i++) { // 4=512/128 + DataCopy( + mm2ResInt32Gm[baseoffset + i * dGroupSize], tmpQue, dataCopyParams); + } + SetAtomicNone(); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + } + SetFlag(SYNC_OUTPUT_BUF2_FLAG); +} + +template +__aicore__ inline void SFAVectorService::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; + + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = 1; + dataCopyParams.blockLen = 256 * sizeof(int32_t); + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = 0; + DataCopyPadExtParams padParams; + // 额外偏移128个元素,避免不同loop下v0和v1互相影响 + DataCopyPad(v0ValidSizeUb_[128], + kvValidSizeGm_[info.loop % MERGE_CACHE_GM_BUF_NUM * (128 * 2)], + dataCopyParams, + padParams); + SetFlag(0); + if (unlikely(loopCount == 0)) { + // scalar同步影响较大,挪到循环内部进行 + WaitFlag(0); + } + } + 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切换 + } +} + +template +__aicore__ inline void SFAVectorService::GetRealS2Idx( + int64_t s2GmOffset, + int64_t& realS2Idx, + int64_t topkGmBaseOffset, + const RunInfo& runInfo) { + int64_t topkGmIdx = (s2GmOffset + runInfo.s2Idx * constInfo.s2BaseSize) / + constInfo.sparseBlockSize; + if (unlikely(topkGmIdx >= constInfo.sparseBlockCount)) { + realS2Idx = -1; + return; + } + realS2Idx = + topkGm_.GetValue(topkGmBaseOffset + topkGmIdx) * + static_cast(constInfo.sparseBlockSize) + + static_cast((s2GmOffset + runInfo.s2Idx * constInfo.s2BaseSize) % + constInfo.sparseBlockSize); +} + +template +__aicore__ inline int64_t SFAVectorService::GetKeyGmOffset( + int64_t realS2Idx, + const RunInfo& runInfo, + int64_t s2IdLimit) { + if (realS2Idx < 0 || realS2Idx >= s2IdLimit) { + return -1; + } + int64_t realKeyGmOffset = 0; + if constexpr (PAGE_ATTENTION) { + int64_t blkTableIdx = realS2Idx / constInfo.kvCacheBlockSize; + int64_t blkTableOffset = realS2Idx % constInfo.kvCacheBlockSize; + realKeyGmOffset = + blkTableGm_.GetValue(runInfo.bIdx * constInfo.maxBlockNumPerBatch + + blkTableIdx) * + static_cast(constInfo.kvCacheBlockSize) * + static_cast(constInfo.kvHeadNum) + + blkTableOffset; + } else { + realKeyGmOffset = (runInfo.tensorBOffset + + realS2Idx * constInfo.kvHeadNum * constInfo.headDim) / + constInfo.headDim; + } + return realKeyGmOffset; +} + +template +__aicore__ inline int64_t SFAVectorService::GetKeyRopeGmOffset( + int64_t realS2Idx, + const RunInfo& runInfo, + int64_t s2IdLimit) { + if constexpr (!HAS_ROPE) { + return -1; + } else { + if (realS2Idx < 0 || realS2Idx >= s2IdLimit) { + return -1; + } + int64_t realKeyRopeGmOffset = 0; + realKeyRopeGmOffset = + (runInfo.tensorBRopeOffset + + realS2Idx * constInfo.kvHeadNum * constInfo.headDimRope) / + constInfo.headDimRope; + return realKeyRopeGmOffset; + } +} + +template +__aicore__ inline void SFAVectorService::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; + DataCopyPad(kvMergUb_[mergeMte3Idx % 2 * 32 * 512 + + (mte2Size - mte3Size) * constInfo.headDim], + keyGm_[keyBNBOffset * constInfo.headDim], + intriParams, + padParams); + if constexpr (HAS_ROPE) { + intriParams.blockLen = validS2Count * constInfo.headDimRope * sizeof(KV_T); + DataCopyPad(ropeMergUb_[mergeMte3Idx % 2 * 32 * 64 + + (mte2Size - mte3Size) * constInfo.headDimRope], + keyRopeGm_[keyBNBOffset * constInfo.headDimRope], + intriParams, + padParams); + } + mte2Size += validS2Count; +} + +template +__aicore__ inline void SFAVectorService::CopyInKv( + int64_t& mte2Size, + int64_t mte3Size, + int64_t mergeMte3Idx, + int64_t realS2Idx1, + int64_t realS2Idx2, + const RunInfo& runInfo) { + int64_t s2IdLimit = runInfo.curActualSeqLenOri; + if (constInfo.sparseMode == 3) { + s2IdLimit = runInfo.curActualSeqLenOri - runInfo.actS1Size + + runInfo.gS1Idx / constInfo.gSize + 1; + } + + 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; + int64_t keyRopeSrcStride = 0; + if constexpr (PAGE_ATTENTION) { + int64_t blkTableSrcStride = + ((keyOffset1 > keyOffset2 ? (keyOffset1 - keyOffset2) + : (keyOffset2 - keyOffset1)) - + constInfo.sparseBlockSize); + keySrcStride = blkTableSrcStride * constInfo.headDim * sizeof(KV_T); + if constexpr (HAS_ROPE) { + keyRopeSrcStride = + blkTableSrcStride * constInfo.headDimRope * sizeof(KV_T); + } + } else { + keySrcStride = ((keyOffset1 > keyOffset2 ? (keyOffset1 - keyOffset2) + : (keyOffset2 - keyOffset1)) - + constInfo.sparseBlockSize) * + constInfo.headDim * sizeof(KV_T); + if constexpr (HAS_ROPE) { + int64_t keyRopeOffset1 = + GetKeyRopeGmOffset(realS2Idx1, runInfo, s2IdLimit); + int64_t keyRopeOffset2 = + GetKeyRopeGmOffset(realS2Idx2, runInfo, s2IdLimit); + keyRopeSrcStride = ((keyRopeOffset1 > keyRopeOffset2 + ? (keyRopeOffset1 - keyRopeOffset2) + : (keyRopeOffset2 - keyRopeOffset1)) - + constInfo.sparseBlockSize) * + constInfo.headDimRope * sizeof(KV_T); + } + } + + if (unlikely(keySrcStride >= INT32_MAX || keySrcStride < 0 || + (HAS_ROPE && !PAGE_ATTENTION && + (keyRopeSrcStride >= INT32_MAX || keyRopeSrcStride < 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; + + int64_t startGmOffset = keyOffset1 > -1 ? keyOffset1 : keyOffset2; + if (keyOffset2 > -1 && keyOffset2 < keyOffset1) { + startGmOffset = keyOffset2; + } + DataCopyPad(kvMergUb_[mergeMte3Idx % 2 * 32 * 512 + + (mte2Size - mte3Size) * constInfo.headDim], + keyGm_[startGmOffset * constInfo.headDim], + intriParams, + padParams); + + if constexpr (HAS_ROPE) { + intriParams.blockLen = + constInfo.sparseBlockSize * constInfo.headDimRope * sizeof(KV_T); + intriParams.dstStride = 0; + intriParams.srcStride = keyRopeSrcStride; + DataCopyPad(ropeMergUb_[mergeMte3Idx % 2 * 32 * 64 + + (mte2Size - mte3Size) * constInfo.headDimRope], + keyRopeGm_[startGmOffset * constInfo.headDimRope], + intriParams, + padParams); + } + mte2Size += + ((keyOffset1 > -1) + (keyOffset2 > -1)) * constInfo.sparseBlockSize; + } +} + +template +__aicore__ inline void SFAVectorService::CopyOutMrgeResult( + int64_t mte2Size, + int64_t mte3Size, + int64_t s2GmStartOffset, + int64_t mergeMte3Idx, + const RunInfo& runInfo) { + if (mte2Size <= mte3Size) { + return; + } + SetFlag(0); + WaitFlag(0); + + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = mte2Size - mte3Size; + dataCopyParams.blockLen = constInfo.headDim * sizeof(KV_T); + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = 0; + + DataCopyPad(kvMergeGm_[runInfo.loop % 4 * 512 * 576 + + (s2GmStartOffset + mte3Size) * constInfo.headDim], + kvMergUb_[mergeMte3Idx % 2 * 32 * 512], + dataCopyParams); + + if constexpr (HAS_ROPE) { + dataCopyParams.blockLen = constInfo.headDimRope * sizeof(KV_T); + DataCopyPad( + kvMergeGm_[runInfo.loop % 4 * 512 * 576 + MERGE_ROPE_REGION_OFFSET + + (s2GmStartOffset + mte3Size) * constInfo.headDimRope], + ropeMergUb_[mergeMte3Idx % 2 * 32 * 64], + dataCopyParams); + } +} + +// b s1 k +template +__aicore__ inline void SFAVectorService::MergeKv(const RunInfo& runInfo) { + int64_t s2ProcessSize = runInfo.actualSingleProcessSInnerSize; + int64_t s2Pair = CeilDiv(s2ProcessSize, 2L * constInfo.sparseBlockSize); + int64_t topkGmBaseOffset = 0; + + if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + uint64_t actualSeqQPrefixSum = + (runInfo.bIdx <= 0) ? 0 + : actualSeqLengthsQGm.GetValue(runInfo.bIdx - 1); + topkGmBaseOffset += + (actualSeqQPrefixSum + runInfo.gS1Idx / constInfo.gSize) * + constInfo.kvHeadNum * constInfo.sparseBlockCount + + runInfo.n2Idx * constInfo.sparseBlockCount; + } else { + topkGmBaseOffset += + runInfo.bIdx * constInfo.qSeqSize * constInfo.sparseBlockCount + + runInfo.gS1Idx / constInfo.gSize * constInfo.sparseBlockCount; + } + int64_t mergeMte3Idx = 0; + int64_t mte2Size = 0; + int64_t mte3Size = 0; + int64_t s2IdxArray0 = -1; + int64_t s2IdxArray1 = -1; + bool needWaitMte3ToMte2 = true; + SetFlag(0); + SetFlag(1); + int64_t s2GmStartOffset = + GetSubBlockIdx() == 0 + ? 0 + : CeilDiv(s2Pair, 2L) * 2 * constInfo.sparseBlockSize; + int64_t s2GmLimit = GetSubBlockIdx() == 0 + ? CeilDiv(s2Pair, 2L) * 2 * constInfo.sparseBlockSize + : s2ProcessSize; + if (s2GmLimit > s2ProcessSize) { + s2GmLimit = s2ProcessSize; + } + for (int64_t s2GmOffsetArray = s2GmStartOffset; s2GmOffsetArray < s2GmLimit; + s2GmOffsetArray += 2 * constInfo.sparseBlockSize) { + if (needWaitMte3ToMte2) { + WaitFlag(mergeMte3Idx % 2); + needWaitMte3ToMte2 = false; + } + GetRealS2Idx(s2GmOffsetArray, s2IdxArray0, topkGmBaseOffset, runInfo); + if (unlikely(s2IdxArray0 < 0)) { + CopyOutMrgeResult( + mte2Size, mte3Size, s2GmStartOffset, mergeMte3Idx, runInfo); + SetFlag(mergeMte3Idx % 2); + mergeMte3Idx++; + break; + } + GetRealS2Idx(s2GmOffsetArray + constInfo.sparseBlockSize, + s2IdxArray1, + topkGmBaseOffset, + runInfo); + CopyInKv( + mte2Size, mte3Size, mergeMte3Idx, s2IdxArray0, s2IdxArray1, runInfo); + if ((mte2Size - mte3Size + 2 * constInfo.sparseBlockSize > 32) || + s2GmOffsetArray + 2 * constInfo.sparseBlockSize >= s2GmLimit) { + CopyOutMrgeResult( + mte2Size, mte3Size, s2GmStartOffset, mergeMte3Idx, runInfo); + mte3Size = mte2Size; + SetFlag(mergeMte3Idx % 2); + mergeMte3Idx++; + needWaitMte3ToMte2 = true; + } + } + + if (unlikely(s2GmStartOffset + mte2Size < s2GmLimit)) { + SetFlag(0); + WaitFlag(0); + WaitFlag(mergeMte3Idx & 1); + Duplicate(kvMergUb_, static_cast(0.0), constInfo.headDim); + SetFlag(0); + WaitFlag(0); + + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = 1; + dataCopyParams.blockLen = constInfo.headDim * sizeof(KV_T); + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = 0; + for (int64_t s2GmOffset = s2GmStartOffset + mte2Size; + s2GmOffset < s2GmLimit; + s2GmOffset++) { + DataCopyPad(kvMergeGm_[runInfo.loop % MERGE_CACHE_GM_BUF_NUM * 512 * 576 + + s2GmOffset * constInfo.headDim], + kvMergUb_, + dataCopyParams); + } + if constexpr (HAS_ROPE) { + dataCopyParams.blockLen = constInfo.headDimRope * sizeof(KV_T); + for (int64_t s2GmOffset = s2GmStartOffset + mte2Size; + s2GmOffset < s2GmLimit; + s2GmOffset++) { + DataCopyPad( + kvMergeGm_[runInfo.loop % MERGE_CACHE_GM_BUF_NUM * 512 * 576 + + MERGE_ROPE_REGION_OFFSET + + s2GmOffset * constInfo.headDimRope], + kvMergUb_, + dataCopyParams); + } + } + SetFlag(mergeMte3Idx & 1); + mergeMte3Idx++; + } + WaitFlag(0); + WaitFlag(1); + v0ValidSizeUb_.SetValue(runInfo.loop % MERGE_CACHE_GM_BUF_NUM, mte2Size); + SetFlag(1); + WaitFlag(1); + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = 1; + dataCopyParams.blockLen = 128 * sizeof(int32_t); + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = 0; + DataCopyPad(kvValidSizeGm_[runInfo.loop % MERGE_CACHE_GM_BUF_NUM * (128 * 2) + + GetSubBlockIdx() * 128], + v0ValidSizeUb_, + dataCopyParams); + SetFlag(SYNC_INPUT_V0BUF_FLAG); + WaitFlag(SYNC_INPUT_V0BUF_FLAG); + return; +} + +template +__aicore__ inline void SFAVectorService::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); + CrossCoreWaitFlag(constInfo.syncC2V1); + // add nUpdate to mm2ResGm + if (info.actualSingleProcessSInnerSize != 0) { + ProcessAmlaNupdate(info, mSplitInfo); + CrossCoreSetFlag( + constInfo.syncV1NupdateC2); + } + // move lse for flash decode or FA + if (info.s2Idx == info.curSInnerLoopTimes - 1 && + (constInfo.returnSoftmaxLse || info.tndIsS2SplitCore)) { + uint32_t outIdx = info.loop % (constInfo.preLoadNum); + auto sumTensor = + softmaxSumUb[outIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)]; + auto maxTensor = + softmaxMaxUb[outIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)]; + if (constInfo.returnSoftmaxLse) { + CopyFALseToGm(info, mSplitInfo, sumTensor, maxTensor); + } + if (info.tndIsS2SplitCore) { + if constexpr (FLASH_DECODE) { + ComputeLogSumExpAndCopyToGm(info, mSplitInfo, sumTensor, maxTensor); + } + } + } + } +} + +template +__aicore__ inline uint64_t SFAVectorService::CalcAccumOffset( + uint32_t bN2Idx, + uint32_t gS1Idx) { + return 0; +} + +template +__aicore__ inline void SFAVectorService::ProcessVec2SingleBuf( + const RunInfo& info, + const MSplitInfo& mSplitInfo) { + if (info.s2Idx + 1 != info.curSInnerLoopTimes) { + return; + } + if (mSplitInfo.vecDealM == 0) { + return; + } + + ProcessVec2Inner(info, mSplitInfo, 0, mSplitInfo.vecDealM); +} + +template +__aicore__ inline void SFAVectorService::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 SFAVectorService::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 SFAVectorService::GetConfusionTransposeTiling( + int64_t numR, + int64_t numC, + const uint32_t stackBufferSize, + const uint32_t typeSize, + ConfusionTransposeTiling& tiling) { + (void)stackBufferSize; + uint32_t blockSize = ONE_BLK_SIZE / typeSize; + uint32_t height = numC; + uint32_t width = numR; + uint32_t highBlock = height / BLOCK_CUBE; + uint32_t stride = height * blockSize * typeSize / ONE_BLK_SIZE; + uint32_t repeat = width / blockSize; + + tiling.param0 = blockSize; + tiling.param1 = height; + tiling.param2 = width; + tiling.param3 = highBlock; + tiling.param4 = stride; + tiling.param5 = repeat; +} + +template +__aicore__ inline void SFAVectorService::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 SFAVectorService::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 SFAVectorService::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 SFAVectorService::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 SFAVectorService::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.bn2IdxInCurCore % 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); + + // 将绝对值大于1e10的数置为0 + LocalTensor bmm2ResUb = tmpBuff1.Get(); + bmm2ResUb.SetSize(vec2ComputeSize); + LocalTensor absBmm2ResUb = bmm2ResUb.template ReinterpretCast(); + Abs(absBmm2ResUb, tmpBmm2ResUb, vec2ComputeSize); + PipeBarrier(); + LocalTensor cmpMaskUb = + absBmm2ResUb.template ReinterpretCast(); + CompareScalar(cmpMaskUb, absBmm2ResUb, (T)1e10, CMPMODE::LE, vec2ComputeSize); + PipeBarrier(); + Select(tmpBmm2ResUb, + cmpMaskUb, + tmpBmm2ResUb, + ConstInfo::FLOAT_ZERO, + SELMODE::VSEL_TENSOR_SCALAR_MODE, + vec2ComputeSize); + PipeBarrier(); + uint32_t baseOffset = mSplitInfo.nBufferStartM / 2 + startRow; + uint32_t idx = info.loop % (constInfo.preLoadNum); + LocalTensor tmpSumUb = + v0ValidSizeBuff.Get()[384]; // sumUb用临时内存 16 * 32B = 512B + Brcb(tmpSumUb, + aMlaSumUb[idx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset], + (dealRowCount + 7) / 8, + {1, 8}); + PipeBarrier(); + RowDivs(bmm2ResUb, + tmpBmm2ResUb, + tmpSumUb, + dealRowCount, + columnCount, + actualColumnCount); + PipeBarrier(); + SetFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); + Bmm2ResCopyOut( + info, bmm2ResUb, mStart, dealRowCount, columnCount, actualColumnCount); +} + +template +__aicore__ inline void SFAVectorService::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 SFAVectorService::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); + } + } + } +} + +#endif // SPARSE_FLASH_ATTENTION_LSE_SERVICE_VECTOR_MLA_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/sparse_flash_attention_lse_common.h b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/sparse_flash_attention_lse_common.h new file mode 100644 index 0000000000..4c5df8be58 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/sparse_flash_attention_lse_common.h @@ -0,0 +1,216 @@ +/** + * 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 sparse_flash_attention_lse_common.h + * \brief + */ + +#ifndef SPARSE_FLASH_ATTENTION_LSE_COMMON_H +#define SPARSE_FLASH_ATTENTION_LSE_COMMON_H + +#include "kernel_operator.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" +#include "sparse_flash_attention_lse_template_tiling_key.h" + +using namespace AscendC; +// 将isCheckTiling设置为false, 输入输出的max&sum&exp的shape为(m, 1) +constexpr SoftmaxConfig SFA_SOFTMAX_FLASHV2_CFG_WITHOUT_BRC = { + false, + 0, + 0, + SoftmaxMode::SOFTMAX_OUTPUT_WITHOUT_BRC}; + +enum class SFA_LAYOUT { + BSND = 0, + TND = 1, + PA_BSND = 2, +}; + +template +struct SFAType { + using queryType = Q_T; + using kvType = KV_T; + using outputType = OUT_T; + static constexpr bool flashDecode = FLASH_DECODE; + static constexpr SFA_LAYOUT layout = LAYOUT_T; + static constexpr SFA_LAYOUT kvLayout = KV_LAYOUT_T; + static constexpr int templateMode = TEMPLATE_MODE; + static constexpr bool pageAttention = (KV_LAYOUT_T == SFA_LAYOUT::PA_BSND); + static constexpr bool hasRope = HAS_ROPE; +}; + +// ================================Util +// functions================================== +template +__aicore__ inline T SFAAlign(T num, T 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 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 RunInfo { + uint32_t loop; + uint32_t bIdx; + uint32_t gIdx; + uint32_t s1Idx; + uint32_t s2Idx; + uint32_t bn2IdxInCurCore; + uint32_t curSInnerLoopTimes; + uint64_t tndBIdxOffsetForQ; + uint64_t tndBIdxOffsetForKV; + uint64_t tensorAOffset; + uint64_t tensorBOffset; + uint64_t tensorARopeOffset; + uint64_t tensorBRopeOffset; + uint64_t attenOutOffset; + uint64_t attenMaskOffset; + uint64_t topKBaseOffset; + uint32_t actualSingleProcessSInnerSize; + uint32_t actualSingleProcessSInnerSizeAlign; + bool isFirstSInnerLoop; + bool isChangeBatch; + uint32_t s2BatchOffset; + uint32_t gSize; + uint32_t s1Size; + uint32_t s2Size; + uint32_t mSize; + uint32_t mSizeV; + uint32_t mSizeVStart; + uint32_t tndIsS2SplitCore; + uint32_t tndCoreStartKVSplitPos; + bool isBmm2Output; + bool isValid = false; + + static constexpr uint32_t n2Idx = 0; + uint64_t actS1Size = 1; + uint64_t curActualSeqLenOri = 0ULL; + + uint32_t gS1Idx; + uint64_t actS2Size = 1; + uint32_t actMBaseSize; + bool isLastS2Loop; + int32_t nextTokensPerBatch = 0; + int64_t threshold; + uint32_t curTopKIdx = 0; + uint64_t curOffsetInSparseBlock = 0; +}; + +struct ConstInfo { + // CUBE与VEC核间同步的模式 + static constexpr uint32_t SFA_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 syncV1NupdateC2 = 0U; + uint32_t syncV0C1 = 0U; + uint32_t syncC1V1 = 0U; + uint32_t syncV1C2 = 0U; + uint32_t syncC2V2 = 0U; + uint32_t syncC2V1 = 0U; + + uint32_t mmResUbSize = 0U; // Matmul1输出结果GM上的大小 + uint32_t vec1ResUbSize = 0U; // Vector1输出结果GM上的大小 + uint32_t bmm2ResUbSize = 0U; // Matmul2输出结果GM上的大小 + uint64_t batchSize = 0ULL; + uint64_t gSize = 0ULL; + uint64_t qHeadNum = 0ULL; + uint64_t kvHeadNum; + uint64_t headDim; + uint64_t headDimRope; + uint64_t kvSeqSize = 0ULL; // kv最大S长度 + uint64_t qSeqSize = 1ULL; // q最大S长度 + int64_t kvCacheBlockSize = 0; // PA场景的block size + uint32_t maxBlockNumPerBatch = 0; // PA场景的最大单batch block number + uint32_t splitKVNum = 0U; // S2核间切分的切分份数 + SFA_LAYOUT outputLayout; // 输出的Transpose格式 + uint32_t sparseMode = 0; + int64_t preTokens = INT64_MAX; + int64_t nextTokens = INT64_MAX; + uint32_t attentionMode = 2; + bool returnSoftmaxLse = false; + bool needInit = false; + + // 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 的维度 + + // 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; +}; + +struct MSplitInfo { + uint32_t nBufferIdx = 0U; + uint32_t nBufferStartM = 0U; + uint32_t nBufferDealM = 0U; + uint32_t vecStartM = 0U; + uint32_t vecDealM = 0U; +}; + +#endif // SPARSE_FLASH_ATTENTION_LSE_COMMON_H diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/sparse_flash_attention_lse_template_tiling_key.h b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/sparse_flash_attention_lse_template_tiling_key.h new file mode 100644 index 0000000000..6837a39245 --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/sparse_flash_attention_lse_template_tiling_key.h @@ -0,0 +1,253 @@ +/** + * 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 sparse_flash_attention_lse_template_tiling_key.h + * \brief + */ + +#ifndef SPARSE_FLASH_ATTENTION_LSE_TEMPLATE_TILING_KEY_H +#define SPARSE_FLASH_ATTENTION_LSE_TEMPLATE_TILING_KEY_H + +#include "ascendc/host_api/tiling/template_argument.h" + +#define SFA_LAYOUT_BSND 0 +#define SFA_LAYOUT_TND 1 +#define SFA_LAYOUT_PA_BSND 2 + +#define ASCENDC_TPL_4_BW 4 + +#define C_TEMPLATE 0 +#define V_TEMPLATE 1 + +// 模板参数支持的范围定义 +// HAS_ROPE 追加在末尾, 低位编码与原 6 参一致; HAS_ROPE=0 时 tiling key +// 数值等于旧 key +ASCENDC_TPL_ARGS_DECL(XllmKernelSparseFlashAttentionLse, // 算子OpType + ASCENDC_TPL_BOOL_DECL(FLASH_DECODE, 0, 1), + ASCENDC_TPL_BOOL_DECL(PAGE_ATTENTION, 0, 1), + ASCENDC_TPL_UINT_DECL(LAYOUT_T, + ASCENDC_TPL_4_BW, + ASCENDC_TPL_UI_LIST, + SFA_LAYOUT_BSND, + SFA_LAYOUT_TND), + ASCENDC_TPL_UINT_DECL(KV_LAYOUT_T, + ASCENDC_TPL_4_BW, + ASCENDC_TPL_UI_LIST, + SFA_LAYOUT_BSND, + SFA_LAYOUT_TND, + SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_DECL(TEMPLATE_MODE, + ASCENDC_TPL_4_BW, + ASCENDC_TPL_UI_LIST, + C_TEMPLATE, + V_TEMPLATE), + ASCENDC_TPL_BOOL_DECL(IS_SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_DECL(HAS_ROPE, 0, 1), ); + +// 支持的模板参数组合 +// 用于调用GET_TPL_TILING_KEY获取TilingKey时,接口内部校验TilingKey是否合法 +// 现有条目仅追加 HAS_ROPE=1 (rope 路径); 下方新增每组 HAS_ROPE=0 (NoPE) 变体 +ASCENDC_TPL_SEL( + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SFA_LAYOUT_BSND, + SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, C_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HAS_ROPE, 1), ), + + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SFA_LAYOUT_TND, + SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, C_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HAS_ROPE, 1), ), + + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SFA_LAYOUT_BSND, + SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, V_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HAS_ROPE, 1), ), + + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SFA_LAYOUT_TND, + SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, V_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HAS_ROPE, 1), ), + + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SFA_LAYOUT_BSND, + SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, C_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HAS_ROPE, 1), ), + + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SFA_LAYOUT_TND, + SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, C_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HAS_ROPE, 1), ), + + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SFA_LAYOUT_BSND, + SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, V_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HAS_ROPE, 1), ), + + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SFA_LAYOUT_TND, + SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, V_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HAS_ROPE, 1), ), + + // ---- NoPE 变体 (HAS_ROPE=0), 与上方 8 组 layout/template 一一对应 ---- + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SFA_LAYOUT_BSND, + SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, C_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HAS_ROPE, 0), ), + + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SFA_LAYOUT_TND, + SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, C_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HAS_ROPE, 0), ), + + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SFA_LAYOUT_BSND, + SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, V_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HAS_ROPE, 0), ), + + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SFA_LAYOUT_TND, + SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, V_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HAS_ROPE, 0), ), + + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SFA_LAYOUT_BSND, + SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, C_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HAS_ROPE, 0), ), + + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SFA_LAYOUT_TND, + SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, C_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HAS_ROPE, 0), ), + + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SFA_LAYOUT_BSND, + SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, V_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HAS_ROPE, 0), ), + + ASCENDC_TPL_ARGS_SEL( + ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, + ASCENDC_TPL_UI_LIST, + SFA_LAYOUT_TND, + SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, V_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), + ASCENDC_TPL_BOOL_SEL(HAS_ROPE, 0), ), ); + +#endif // TEMPLATE_TILING_KEY diff --git a/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/xllm_kernel_sparse_flash_attention_lse.cpp b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/xllm_kernel_sparse_flash_attention_lse.cpp new file mode 100644 index 0000000000..813f63279b --- /dev/null +++ b/xllm-kernel/csrc/ascendc/sparse_flash_attention_lse/op_kernel/xllm_kernel_sparse_flash_attention_lse.cpp @@ -0,0 +1,99 @@ +/** + * 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_attention_lse.cpp + * \brief Atlas A2/A3 kernel entry. Ascend 950 / arch35 is not included. + */ + +#include "arch22/sparse_flash_attention_lse_kernel_mla.h" +#include "kernel_operator.h" +#include "sparse_flash_attention_lse_template_tiling_key.h" + +using namespace AscendC; + +#define SFA_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, \ + key, \ + value, \ + sparseIndices, \ + actualSeqLengthsQuery, \ + actualSeqLengthsKV, \ + blocktable, \ + queryRope, \ + keyRope, \ + attentionOut, \ + softmaxMax, \ + softmaxSum, \ + user, \ + tiling_data, \ + tiling, \ + &tPipe); \ + op.Process(); \ + } while (0) + +template +__global__ __aicore__ void xllm_kernel_sparse_flash_attention_lse( + __gm__ uint8_t* query, + __gm__ uint8_t* key, + __gm__ uint8_t* value, + __gm__ uint8_t* sparseIndices, + __gm__ uint8_t* blocktable, + __gm__ uint8_t* actualSeqLengthsQuery, + __gm__ uint8_t* actualSeqLengthsKV, + __gm__ uint8_t* queryRope, + __gm__ uint8_t* keyRope, + __gm__ uint8_t* attentionOut, + __gm__ uint8_t* softmaxMax, + __gm__ uint8_t* softmaxSum, + __gm__ uint8_t* workspace, + __gm__ uint8_t* tiling) { + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); + + TPipe tPipe; + __gm__ uint8_t* user = GetUserWorkspace(workspace); + + if constexpr (ORIG_DTYPE_QUERY == DT_FLOAT16 && + ORIG_DTYPE_KEY == DT_FLOAT16 && + ORIG_DTYPE_ATTENTION_OUT == DT_FLOAT16) { + SFA_OP_IMPL(SparseFlashAttentionLseMla, + SparseFlashAttentionLseTilingDataMla, + half, + half, + half, + FLASH_DECODE, + static_cast(LAYOUT_T), + static_cast(KV_LAYOUT_T), + TEMPLATE_MODE, + static_cast(HAS_ROPE)); + } else { // bf16 + SFA_OP_IMPL(SparseFlashAttentionLseMla, + SparseFlashAttentionLseTilingDataMla, + bfloat16_t, + bfloat16_t, + bfloat16_t, + FLASH_DECODE, + static_cast(LAYOUT_T), + static_cast(KV_LAYOUT_T), + TEMPLATE_MODE, + static_cast(HAS_ROPE)); + } +} diff --git a/xllm-kernel/csrc/npu/sparse_attention.cpp b/xllm-kernel/csrc/npu/sparse_attention.cpp new file mode 100644 index 0000000000..12863aa740 --- /dev/null +++ b/xllm-kernel/csrc/npu/sparse_attention.cpp @@ -0,0 +1,742 @@ +// Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "csrc/ascendc/sparse_attn_sharedkv/op_kernel/sparse_attn_sharedkv_metadata.h" +#include "csrc/npu/ascendc_api.h" +#include "op_plugin/utils/op_api_common_base.h" + +namespace xllm_kernel { +namespace { + +const auto& sparse_attention_apis() { + static const std::array apis{ + std::pair{"aclnnXllmKernelCompressor", + load_ascendc_api("aclnnXllmKernelCompressor", + "aclnnXllmKernelCompressorGetWorkspaceSize")}, + std::pair{"aclnnXllmKernelSparseAttnSharedkv", + load_ascendc_api( + "aclnnXllmKernelSparseAttnSharedkv", + "aclnnXllmKernelSparseAttnSharedkvGetWorkspaceSize")}, + std::pair{ + "aclnnXllmKernelSparseAttnSharedkvMetadata", + load_ascendc_api( + "aclnnXllmKernelSparseAttnSharedkvMetadata", + "aclnnXllmKernelSparseAttnSharedkvMetadataGetWorkspaceSize")}, + std::pair{"aclnnXllmKernelSparseFlashAttentionLse", + load_ascendc_api( + "aclnnXllmKernelSparseFlashAttentionLse", + "aclnnXllmKernelSparseFlashAttentionLseGetWorkspaceSize")}, + }; + return apis; +} + +void GetApiFunc(const char* name, + const char* /*workspace_name*/, + void*& launch, + void*& workspace) { + for (const auto& [api_name, api] : sparse_attention_apis()) { + if (std::string_view(name) == api_name) { + launch = api.launch; + workspace = api.workspace; + return; + } + } + LOG(FATAL) << "Unknown sparse attention ACLNN entry point: " << name; +} + +void prepare_ascendc_sparse_attention() { sparse_attention_apis(); } + +std::tuple +construct_compressor_output_tensor(const torch::Tensor& x, + const torch::Tensor& norm_weight, + const torch::Tensor& rope_sin, + int64_t cmp_ratio, + int64_t coff, + bool enable_grad) { + constexpr int64_t kBatchedRank = 3; + torch::SmallVector cmp_kv_size; + torch::SmallVector wkv_proj_size; + torch::SmallVector softmax_res_size; + torch::SmallVector norm_x_size; + torch::SmallVector norm_rstd_size; + torch::Tensor cmp_kv; + torch::Tensor wkv_proj; + torch::Tensor softmax_res; + torch::Tensor norm_x; + torch::Tensor norm_rstd; + int64_t cmp_s = 0; + if (x.dim() == kBatchedRank) { + cmp_s = (x.size(1) + cmp_ratio - 1) / cmp_ratio; + cmp_kv_size = {x.size(0), cmp_s, norm_weight.size(0)}; + if (enable_grad) { + wkv_proj_size = {x.size(0), x.size(1), coff * norm_weight.size(0)}; + softmax_res_size = { + x.size(0), cmp_s, coff * cmp_ratio, norm_weight.size(0)}; + norm_x_size = {x.size(0), cmp_s, norm_weight.size(0)}; + norm_rstd_size = {x.size(0), cmp_s}; + } + } else { + cmp_s = rope_sin.size(0); + cmp_kv_size = {cmp_s, norm_weight.size(0)}; + if (enable_grad) { + wkv_proj_size = {x.size(0), coff * norm_weight.size(0)}; + softmax_res_size = {cmp_s, coff * cmp_ratio, norm_weight.size(0)}; + norm_x_size = {cmp_s, norm_weight.size(0)}; + norm_rstd_size = {cmp_s}; + } + } + + cmp_kv = torch::zeros(cmp_kv_size, x.options().dtype(x.dtype())); + if (enable_grad) { + wkv_proj = torch::zeros(wkv_proj_size, x.options().dtype(x.dtype())); + softmax_res = torch::zeros(softmax_res_size, x.options().dtype(x.dtype())); + norm_x = torch::zeros(norm_x_size, x.options().dtype(x.dtype())); + norm_rstd = torch::zeros(norm_rstd_size, x.options().dtype(x.dtype())); + } else { + wkv_proj = torch::empty({0}, x.options().dtype(x.dtype())); + softmax_res = torch::empty({0}, x.options().dtype(x.dtype())); + norm_x = torch::empty({0}, x.options().dtype(x.dtype())); + norm_rstd = torch::empty({0}, x.options().dtype(x.dtype())); + } + + return std::tuple( + cmp_kv, wkv_proj, softmax_res, norm_x, norm_rstd); +} + +std::tuple +compressor(const torch::Tensor& x, + const torch::Tensor& wkv, + const torch::Tensor& wgate, + torch::Tensor& kv_state, + torch::Tensor& score_state, + const torch::Tensor& ape, + const torch::Tensor& norm_weight, + const torch::Tensor& rope_sin, + const torch::Tensor& rope_cos, + const std::optional& kv_block_table, + const std::optional& score_block_table, + const std::optional& cu_seqlens, + const std::optional& seqused, + const std::optional& start_pos, + int64_t rope_head_dim, + int64_t cmp_ratio, + int64_t coff, + double norm_eps, + int64_t rotary_mode, + bool enable_grad) { + constexpr int32_t DIM_1 = 1; + constexpr int32_t DIM_2 = 2; + constexpr int32_t DIM_3 = 3; + constexpr int32_t VALUE_0 = 0; + const torch::DeviceGuard guard(x.device()); + int64_t x_dim = x.dim(); + CHECK(x_dim == DIM_2 || x_dim == DIM_3) + << "x dim num[" << x_dim << "] should be 2 or 3"; + + int64_t norm_weight_dim = norm_weight.dim(); + CHECK(norm_weight_dim == DIM_1) + << "norm_weight dim num[" << norm_weight_dim << "] should be 1"; + + int64_t rope_sin_dim = rope_sin.dim(); + CHECK(rope_sin_dim == x_dim) + << "rope_sin dim num[" << rope_sin_dim + << "] should be equal to x dim num[" << x_dim << "]"; + + CHECK(cmp_ratio != VALUE_0) << "cmp_ratio should not be 0"; + + std::tuple + output = construct_compressor_output_tensor( + x, norm_weight, rope_sin, cmp_ratio, coff, enable_grad); + torch::Tensor cmp_kv = std::get<0>(output); + torch::Tensor wkv_proj = std::get<1>(output); + torch::Tensor softmax_res = std::get<2>(output); + torch::Tensor norm_x = std::get<3>(output); + torch::Tensor norm_rstd = std::get<4>(output); + + EXEC_NPU_CMD_EXT(aclnnXllmKernelCompressor, + x, + wkv, + wgate, + kv_state, + score_state, + ape, + norm_weight, + rope_sin, + rope_cos, + kv_block_table, + score_block_table, + cu_seqlens, + seqused, + start_pos, + rope_head_dim, + cmp_ratio, + coff, + norm_eps, + rotary_mode, + enable_grad, + cmp_kv, + wkv_proj, + softmax_res, + norm_x, + norm_rstd); + + return std::tuple( + cmp_kv, wkv_proj, softmax_res, norm_x, norm_rstd); +} + +void check_sparse_attn_sharedkv_shape_and_dtype(const torch::Tensor& q, + std::string_view layout_q, + std::string_view layout_kv) { + TORCH_CHECK(q.dim() >= 1, + "Input tensor q's dim num should be at least 1, actual ", + q.dim(), + "."); + TORCH_CHECK(q.dtype() == torch::kHalf || q.dtype() == torch::kBFloat16, + "q should be FLOAT16 or BFLOAT16."); + TORCH_CHECK(!layout_q.empty(), "layout_q should not be empty."); + TORCH_CHECK(!layout_kv.empty(), "layout_kv should not be empty."); +} + +torch::Tensor construct_sparse_attn_sharedkv_attn_out_tensor( + const torch::Tensor& q) { + return torch::empty(q.sizes(), q.options().dtype(q.dtype())); +} + +torch::Tensor construct_sparse_attn_sharedkv_softmax_lse_tensor( + const torch::Tensor& q, + bool return_softmax_lse) { + if (!return_softmax_lse) { + return torch::empty({0}, q.options().dtype(torch::kFloat)); + } + auto softmax_lse_shape = q.sizes().vec(); + softmax_lse_shape.back() = 1; + return torch::empty(softmax_lse_shape, q.options().dtype(torch::kFloat)); +} + +int64_t get_sparse_attn_sharedkv_kv_stride( + const std::optional& kv) { + if (!kv.has_value() || !kv.value().defined() || kv.value().dim() == 0) { + return 0; + } + return kv.value().stride(0); +} + +std::tuple sparse_attn_sharedkv( + const torch::Tensor& q, + const std::optional& ori_kv, + const std::optional& cmp_kv, + const std::optional& ori_sparse_indices, + const std::optional& cmp_sparse_indices, + const std::optional& ori_block_table, + const std::optional& cmp_block_table, + const std::optional& cu_seqlens_q, + const std::optional& cu_seqlens_ori_kv, + const std::optional& cu_seqlens_cmp_kv, + const std::optional& seqused_q, + const std::optional& seqused_kv, + const std::optional& sinks, + const std::optional& metadata, + double softmax_scale, + int64_t cmp_ratio, + int64_t ori_mask_mode, + int64_t cmp_mask_mode, + int64_t ori_win_left, + int64_t ori_win_right, + std::string_view layout_q, + std::string_view layout_kv, + bool return_softmax_lse) { + const torch::DeviceGuard guard(q.device()); + check_sparse_attn_sharedkv_shape_and_dtype(q, layout_q, layout_kv); + torch::Tensor attn_out = construct_sparse_attn_sharedkv_attn_out_tensor(q); + torch::Tensor softmax_lse = + construct_sparse_attn_sharedkv_softmax_lse_tensor(q, return_softmax_lse); + + std::string layout_q_str = std::string(layout_q); + std::string layout_kv_str = std::string(layout_kv); + auto layout_q_arg = const_cast(layout_q_str.c_str()); + auto layout_kv_arg = const_cast(layout_kv_str.c_str()); + const int64_t ori_kv_stride = get_sparse_attn_sharedkv_kv_stride(ori_kv); + const int64_t cmp_kv_stride = get_sparse_attn_sharedkv_kv_stride(cmp_kv); + + EXEC_NPU_CMD_EXT(aclnnXllmKernelSparseAttnSharedkv, + q, + ori_kv, + cmp_kv, + ori_sparse_indices, + cmp_sparse_indices, + ori_block_table, + cmp_block_table, + cu_seqlens_q, + cu_seqlens_ori_kv, + cu_seqlens_cmp_kv, + seqused_q, + seqused_kv, + sinks, + metadata, + softmax_scale, + cmp_ratio, + ori_mask_mode, + cmp_mask_mode, + ori_kv_stride, + cmp_kv_stride, + ori_win_left, + ori_win_right, + layout_q_arg, + layout_kv_arg, + return_softmax_lse, + attn_out, + softmax_lse); + return std::make_tuple(attn_out, softmax_lse); +} + +auto get_valid_tensor = [](const std::optional& tensor_opt, + torch::Device device) { + return tensor_opt.has_value() + ? tensor_opt + : torch::empty({0}, torch::dtype(torch::kInt32).device(device)); +}; + +torch::Tensor sparse_attn_sharedkv_metadata( + int64_t num_heads_q, + int64_t num_heads_kv, + int64_t head_dim, + const std::optional& cu_seqlens_q, + const std::optional& cu_seqlens_ori_kv, + const std::optional& cu_seqlens_cmp_kv, + const std::optional& seqused_q, + const std::optional& seqused_kv, + int64_t batch_size, + int64_t max_seqlen_q, + int64_t max_seqlen_kv, + int64_t ori_topk, + int64_t cmp_topk, + int64_t cmp_ratio, + int64_t ori_mask_mode, + int64_t cmp_mask_mode, + int64_t ori_win_left, + int64_t ori_win_right, + std::string_view layout_q, + std::string_view layout_kv, + bool has_ori_kv, + bool has_cmp_kv) { + torch::Device output_device(std::string("npu")); + if (cu_seqlens_q.has_value()) { + output_device = cu_seqlens_q.value().device(); + } else if (cu_seqlens_ori_kv.has_value()) { + output_device = cu_seqlens_ori_kv.value().device(); + } else if (cu_seqlens_cmp_kv.has_value()) { + output_device = cu_seqlens_cmp_kv.value().device(); + } else if (seqused_q.has_value()) { + output_device = seqused_q.value().device(); + } else if (seqused_kv.has_value()) { + output_device = seqused_kv.value().device(); + } + + const torch::DeviceGuard guard(output_device); + torch::Tensor output = + torch::zeros({optiling::SAS_META_SIZE}, + torch::dtype(torch::kInt32).device(output_device)); + auto cu_seqlens_q_val = get_valid_tensor(cu_seqlens_q, output_device); + auto cu_seqlens_ori_kv_val = + get_valid_tensor(cu_seqlens_ori_kv, output_device); + auto cu_seqlens_cmp_kv_val = + get_valid_tensor(cu_seqlens_cmp_kv, output_device); + auto seqused_q_val = get_valid_tensor(seqused_q, output_device); + auto seqused_kv_val = get_valid_tensor(seqused_kv, output_device); + + // convert str + std::string layout_q_str = std::string(layout_q); + std::string layout_kv_str = std::string(layout_kv); + char* layout_q_ptr = layout_q_str.data(); + char* layout_kv_ptr = layout_kv_str.data(); + + EXEC_NPU_CMD_EXT(aclnnXllmKernelSparseAttnSharedkvMetadata, + cu_seqlens_q_val, + cu_seqlens_ori_kv_val, + cu_seqlens_cmp_kv_val, + seqused_q_val, + seqused_kv_val, + num_heads_q, + num_heads_kv, + head_dim, + batch_size, + max_seqlen_q, + max_seqlen_kv, + ori_topk, + cmp_topk, + cmp_ratio, + ori_mask_mode, + cmp_mask_mode, + ori_win_left, + ori_win_right, + layout_q_ptr, + layout_kv_ptr, + has_ori_kv, + has_cmp_kv, + output); + + return output; +} + +constexpr int64_t kDim0 = 0; +constexpr int64_t kDim1 = 1; +constexpr int64_t kDim2 = 2; +constexpr int64_t kDim3 = 3; + +void check_sparse_flash_attention_lse_inputs( + const torch::Tensor& query, + const torch::Tensor& key, + const torch::Tensor& value, + const torch::Tensor& sparse_indices, + int64_t sparse_block_size, + const std::string& layout_query, + const std::string& layout_kv) { + TORCH_CHECK(query.numel() > 0, "Tensor query is empty."); + TORCH_CHECK(key.numel() > 0, "Tensor key is empty."); + TORCH_CHECK(value.numel() > 0, "Tensor value is empty."); + TORCH_CHECK(sparse_indices.numel() > 0, "Tensor sparse_indices is empty."); + TORCH_CHECK( + query.dtype() == torch::kFloat16 || query.dtype() == torch::kBFloat16, + "query should be FLOAT16 or BFLOAT16."); + TORCH_CHECK(key.dtype() == query.dtype(), + "key's dtype should be equal to query's dtype."); + TORCH_CHECK(value.dtype() == query.dtype(), + "value's dtype should be equal to query's dtype."); + TORCH_CHECK(sparse_indices.dtype() == torch::kInt32, + "sparse_indices should be INT32."); + TORCH_CHECK(sparse_block_size > 0, + "sparse_block_size should be greater than 0, actual ", + sparse_block_size, + "."); + TORCH_CHECK(layout_query == "BSND" || layout_query == "TND", + "The layout of query only support BSND and TND, but got ", + layout_query); + TORCH_CHECK(!layout_kv.empty(), "layout_kv should not be empty."); +} + +void check_sparse_flash_attention_lse_output(const torch::Tensor& query, + const torch::Tensor& output, + const std::string& layout_query) { + CHECK_EQ(query.dim(), layout_query == "TND" ? 3 : 4); + CHECK_EQ(output.device(), query.device()) + << "attention output must use the query device."; + CHECK_EQ(output.dtype(), query.dtype()) + << "attention output dtype must match query dtype."; + CHECK(output.is_contiguous()) << "attention output must be contiguous."; + CHECK(output.sizes() == query.sizes()) + << "attention output shape must match query shape for layout " + << layout_query; +} + +std::tuple +construct_sparse_flash_attention_lse_outputs(const torch::Tensor& query, + const torch::Tensor& key, + const std::string& layout_query, + const std::string& layout_kv, + bool return_softmax_lse) { + torch::SmallVector output_size; + if (layout_query == "TND") { + TORCH_CHECK(query.dim() == 3, + "When the layout of query is TND, the query dimension must be " + "3, but got ", + query.dim()); + output_size = {query.size(kDim0), query.size(kDim1), query.size(kDim2)}; + } else { + TORCH_CHECK(query.dim() == 4, + "When the layout of query is BSND, the query dimension must " + "be 4, but got ", + query.dim()); + output_size = {query.size(kDim0), + query.size(kDim1), + query.size(kDim2), + query.size(kDim3)}; + } + + torch::Tensor attention_output = + torch::empty(output_size, query.options().dtype(query.dtype())); + torch::SmallVector softmax_size; + if (return_softmax_lse) { + if (query.dim() == 3) { + const int64_t kv_head_num = + layout_kv == "PA_BSND" ? key.size(kDim2) : key.size(kDim1); + softmax_size = { + kv_head_num, + query.size(kDim0), + query.size(kDim1) / kv_head_num, + }; + } else { + softmax_size = { + query.size(kDim0), + key.size(kDim2), + query.size(kDim1), + query.size(kDim2) / key.size(kDim2), + }; + } + } else { + softmax_size = {0}; + } + + torch::Tensor softmax_max = + torch::empty(softmax_size, query.options().dtype(torch::kFloat32)); + torch::Tensor softmax_sum = + torch::empty(softmax_size, query.options().dtype(torch::kFloat32)); + return {attention_output, softmax_max, softmax_sum}; +} + +void run_sparse_flash_attention_lse( + const torch::Tensor& query, + const torch::Tensor& key, + const torch::Tensor& value, + const torch::Tensor& sparse_indices, + const std::optional& block_table, + const std::optional& actual_seq_lengths_query, + const std::optional& actual_seq_lengths_kv, + const std::optional& query_rope, + const std::optional& key_rope, + double scale_value, + int64_t sparse_block_size, + const std::string& layout_query, + const std::string& layout_kv, + int64_t sparse_mode, + int64_t pre_tokens, + int64_t next_tokens, + int64_t attention_mode, + bool return_softmax_lse, + const torch::Tensor& attention_output, + const torch::Tensor& softmax_max, + const torch::Tensor& softmax_sum) { + const torch::DeviceGuard guard(query.device()); + char* query_layout_ptr = const_cast(layout_query.c_str()); + char* kv_layout_ptr = const_cast(layout_kv.c_str()); + EXEC_NPU_CMD_EXT(aclnnXllmKernelSparseFlashAttentionLse, + query, + key, + value, + sparse_indices, + block_table, + actual_seq_lengths_query, + actual_seq_lengths_kv, + query_rope, + key_rope, + scale_value, + sparse_block_size, + query_layout_ptr, + kv_layout_ptr, + sparse_mode, + pre_tokens, + next_tokens, + attention_mode, + return_softmax_lse, + attention_output, + softmax_max, + softmax_sum); +} + +std::tuple +sparse_flash_attention_lse( + const torch::Tensor& query, + const torch::Tensor& key, + const torch::Tensor& value, + const torch::Tensor& sparse_indices, + const std::optional& block_table, + const std::optional& actual_seq_lengths_query, + const std::optional& actual_seq_lengths_kv, + const std::optional& query_rope, + const std::optional& key_rope, + double scale_value, + int64_t sparse_block_size, + std::string_view layout_query, + std::string_view layout_kv, + int64_t sparse_mode, + int64_t pre_tokens, + int64_t next_tokens, + int64_t attention_mode, + bool return_softmax_lse) { + std::string layout_query_str = std::string(layout_query); + std::string layout_kv_str = std::string(layout_kv); + check_sparse_flash_attention_lse_inputs(query, + key, + value, + sparse_indices, + sparse_block_size, + layout_query_str, + layout_kv_str); + auto outputs = construct_sparse_flash_attention_lse_outputs( + query, key, layout_query_str, layout_kv_str, return_softmax_lse); + torch::Tensor attention_output = std::get<0>(outputs); + torch::Tensor softmax_max = std::get<1>(outputs); + torch::Tensor softmax_sum = std::get<2>(outputs); + run_sparse_flash_attention_lse(query, + key, + value, + sparse_indices, + block_table, + actual_seq_lengths_query, + actual_seq_lengths_kv, + query_rope, + key_rope, + scale_value, + sparse_block_size, + layout_query_str, + layout_kv_str, + sparse_mode, + pre_tokens, + next_tokens, + attention_mode, + return_softmax_lse, + attention_output, + softmax_max, + softmax_sum); + return {attention_output, softmax_max, softmax_sum}; +} + +torch::Tensor sparse_flash_attention_lse_out( + const torch::Tensor& query, + const torch::Tensor& key, + const torch::Tensor& value, + const torch::Tensor& sparse_indices, + const std::optional& block_table, + const std::optional& actual_seq_lengths_query, + const std::optional& actual_seq_lengths_kv, + const std::optional& query_rope, + const std::optional& key_rope, + double scale_value, + int64_t sparse_block_size, + std::string_view layout_query, + std::string_view layout_kv, + int64_t sparse_mode, + int64_t pre_tokens, + int64_t next_tokens, + int64_t attention_mode, + bool return_softmax_lse, + torch::Tensor& attention_output) { + const torch::DeviceGuard guard(query.device()); + CHECK(!return_softmax_lse) + << "sparse_flash_attention_lse_out only supports output without LSE"; + std::string layout_query_str = std::string(layout_query); + std::string layout_kv_str = std::string(layout_kv); + check_sparse_flash_attention_lse_inputs(query, + key, + value, + sparse_indices, + sparse_block_size, + layout_query_str, + layout_kv_str); + check_sparse_flash_attention_lse_output( + query, attention_output, layout_query_str); + torch::Tensor empty_lse_max = + torch::empty({0}, query.options().dtype(torch::kFloat32)); + torch::Tensor empty_lse_sum = + torch::empty({0}, query.options().dtype(torch::kFloat32)); + run_sparse_flash_attention_lse(query, + key, + value, + sparse_indices, + block_table, + actual_seq_lengths_query, + actual_seq_lengths_kv, + query_rope, + key_rope, + scale_value, + sparse_block_size, + layout_query_str, + layout_kv_str, + sparse_mode, + pre_tokens, + next_tokens, + attention_mode, + false, + attention_output, + empty_lse_max, + empty_lse_sum); + return attention_output; +} + +} // namespace + +TORCH_LIBRARY_FRAGMENT(xllm_kernel, m) { + m.def("prepare_ascendc_sparse_attention() -> ()", + &prepare_ascendc_sparse_attention); + m.def( + "compressor(Tensor x, Tensor wkv, Tensor wgate, Tensor(a!) kv_state, " + "Tensor(b!) score_state, Tensor ape, Tensor norm_weight, Tensor " + "rope_sin, Tensor rope_cos, Tensor? kv_block_table, Tensor? " + "score_block_table, Tensor? cu_seqlens, Tensor? seqused, Tensor? " + "start_pos, int rope_head_dim, int cmp_ratio, int coff, float " + "norm_eps, int rotary_mode, bool enable_grad) -> (Tensor, Tensor, " + "Tensor, Tensor, Tensor)"); + m.def( + "sparse_attn_sharedkv(Tensor q, Tensor? ori_kv, Tensor? cmp_kv, " + "Tensor? ori_sparse_indices, Tensor? cmp_sparse_indices, Tensor? " + "ori_block_table, Tensor? cmp_block_table, Tensor? cu_seqlens_q, " + "Tensor? cu_seqlens_ori_kv, Tensor? cu_seqlens_cmp_kv, Tensor? " + "seqused_q, Tensor? seqused_kv, Tensor? sinks, Tensor? metadata, " + "float softmax_scale, int cmp_ratio, int ori_mask_mode, int " + "cmp_mask_mode, int ori_win_left, int ori_win_right, str layout_q, " + "str layout_kv, bool return_softmax_lse) -> (Tensor, Tensor)"); + m.def( + "sparse_attn_sharedkv_metadata(int num_heads_q, int num_heads_kv, int " + "head_dim, Tensor? cu_seqlens_q, Tensor? cu_seqlens_ori_kv, Tensor? " + "cu_seqlens_cmp_kv, Tensor? seqused_q, Tensor? seqused_kv, int " + "batch_size, int max_seqlen_q, int max_seqlen_kv, int ori_topk, int " + "cmp_topk, int cmp_ratio, int ori_mask_mode, int cmp_mask_mode, int " + "ori_win_left, int ori_win_right, str layout_q, str layout_kv, bool " + "has_ori_kv, bool has_cmp_kv) -> Tensor", + &sparse_attn_sharedkv_metadata); + m.def( + "sparse_flash_attention_lse(Tensor query, Tensor key, Tensor value, " + "Tensor sparse_indices, Tensor? block_table, Tensor? " + "actual_seq_lengths_query, Tensor? actual_seq_lengths_kv, Tensor? " + "query_rope, Tensor? key_rope, float scale_value, int sparse_block_size, " + "str layout_query, str layout_kv, int sparse_mode, int " + "pre_tokens=9223372036854775807, int next_tokens=9223372036854775807, " + "int attention_mode=2, bool return_softmax_lse=False) -> (Tensor, " + "Tensor, Tensor)"); + m.def( + "sparse_flash_attention_lse_out(Tensor query, Tensor key, Tensor value, " + "Tensor sparse_indices, Tensor? block_table, Tensor? " + "actual_seq_lengths_query, Tensor? actual_seq_lengths_kv, Tensor? " + "query_rope, Tensor? key_rope, float scale_value, int sparse_block_size, " + "str layout_query, str layout_kv, int sparse_mode, int pre_tokens, int " + "next_tokens, int attention_mode, bool return_softmax_lse, Tensor(a!) " + "attention_output) -> Tensor(a!)"); +} + +TORCH_LIBRARY_IMPL(xllm_kernel, PrivateUse1, m) { + m.impl("compressor", TORCH_FN(compressor)); + m.impl("sparse_attn_sharedkv", TORCH_FN(sparse_attn_sharedkv)); + m.impl("sparse_flash_attention_lse", TORCH_FN(sparse_flash_attention_lse)); + m.impl("sparse_flash_attention_lse_out", + TORCH_FN(sparse_flash_attention_lse_out)); +} + +} // namespace xllm_kernel diff --git a/xllm-kernel/python/xllm_kernel/catalog.py b/xllm-kernel/python/xllm_kernel/catalog.py index a4d62fce98..3fc4744ff8 100644 --- a/xllm-kernel/python/xllm_kernel/catalog.py +++ b/xllm-kernel/python/xllm_kernel/catalog.py @@ -67,6 +67,7 @@ def get_prepared(self) -> PreparedKernel: "xllm_kernel.ops.attention.kda", "xllm_kernel.ops.attention.mla", "xllm_kernel.ops.attention.dsa.indexer", + "xllm_kernel.ops.attention.sparse_attention", "xllm_kernel.ops.positional_encoding", ) diff --git a/xllm-kernel/python/xllm_kernel/ops/__init__.py b/xllm-kernel/python/xllm_kernel/ops/__init__.py index 2ec91c0464..7d7ca977ba 100644 --- a/xllm-kernel/python/xllm_kernel/ops/__init__.py +++ b/xllm-kernel/python/xllm_kernel/ops/__init__.py @@ -24,6 +24,13 @@ ) from xllm_kernel.ops.attention.kda import causal_conv1d, causal_conv1d_update_v2 from xllm_kernel.ops.attention.mla import mla_preprocess_v2 +from xllm_kernel.ops.attention.sparse_attention import ( + compressor, + sparse_attn_sharedkv, + sparse_attn_sharedkv_metadata, + sparse_flash_attention_lse, + sparse_flash_attention_lse_out, +) from xllm_kernel.ops.gemm import matmul_ein_sum, matmul_ein_sum_out, quant_matmul_out from xllm_kernel.ops.hyper_connection import hc_post, hc_pre from xllm_kernel.ops.kv_cache import reshape_paged_cache @@ -81,4 +88,9 @@ "scatter_nd_update", "shared_linear_state_indices_out", "silu_and_mul", + "compressor", + "sparse_attn_sharedkv", + "sparse_attn_sharedkv_metadata", + "sparse_flash_attention_lse", + "sparse_flash_attention_lse_out", ] diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/sparse_attention/__init__.py b/xllm-kernel/python/xllm_kernel/ops/attention/sparse_attention/__init__.py new file mode 100644 index 0000000000..82742d09e2 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/sparse_attention/__init__.py @@ -0,0 +1,290 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Packaged compressed KV, shared cache attention and RoPE sparse 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 + +OPERATIONS = tuple( + Operation( + OpContract(name, 1, mutates, aliases, name), + ( + BackendModule( + module="xllm_kernel.ops.attention.sparse_attention.ascendc", + platform=PlatformEnum.NPU, + requires=("torch_npu",), + implementations=(f"npu.ascendc.{name}",), + ), + ), + ) + for name, mutates, aliases in ( + ("compressor", ("kv_state", "score_state"), False), + ("sparse_attn_sharedkv", (), False), + ("sparse_attn_sharedkv_metadata", (), False), + ("sparse_flash_attention_lse", (), False), + ("sparse_flash_attention_lse_out", ("attention_output",), True), + ) +) +( + _COMPRESSOR, + _SPARSE_ATTN_SHAREDKV, + _SPARSE_ATTN_SHAREDKV_METADATA, + _SPARSE_FLASH_ATTENTION_LSE, + _SPARSE_FLASH_ATTENTION_LSE_OUT, +) = OPERATIONS + + +def compressor( + x: torch.Tensor, + wkv: torch.Tensor, + wgate: torch.Tensor, + kv_state: torch.Tensor, + score_state: torch.Tensor, + ape: torch.Tensor, + norm_weight: torch.Tensor, + rope_sin: torch.Tensor, + rope_cos: torch.Tensor, + kv_block_table: torch.Tensor | None, + score_block_table: torch.Tensor | None, + cu_seqlens: torch.Tensor | None, + seqused: torch.Tensor | None, + start_pos: torch.Tensor | None, + rope_head_dim: int, + cmp_ratio: int, + coff: int, + norm_eps: float, + rotary_mode: int, + enable_grad: bool, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Pool KV along the token axis by ``cmp_ratio`` (NSA-style compressor). + + ``kv_state`` and ``score_state`` are updated in place. + + Returns ``(cmp_kv, wkv_proj, softmax_res, norm_x, norm_rstd)``; only + ``cmp_kv`` is consumed by the DSA path. + """ + # C++ moves DSA metadata to the active device before dispatch. Keep this + # adapter deterministic; experimental clone/noalias paths do not belong in + # the public binding. + kv_block_table = kv_block_table.to(x.device) if kv_block_table is not None else None + score_block_table = score_block_table.to(x.device) if score_block_table is not None else None + cu_seqlens = cu_seqlens.to(x.device) if cu_seqlens is not None else None + seqused = seqused.to(x.device) if seqused is not None else None + start_pos = start_pos.to(x.device) if start_pos is not None else None + return _COMPRESSOR.get_prepared().function( + x, + wkv, + wgate, + kv_state, + score_state, + ape, + norm_weight, + rope_sin, + rope_cos, + kv_block_table, + score_block_table, + cu_seqlens, + seqused, + start_pos, + rope_head_dim, + cmp_ratio, + coff, + norm_eps, + rotary_mode, + enable_grad, + ) + + +def sparse_attn_sharedkv( + q: torch.Tensor, + ori_kv: torch.Tensor | None, + cmp_kv: torch.Tensor | None, + ori_sparse_indices: torch.Tensor | None, + cmp_sparse_indices: torch.Tensor | None, + ori_block_table: torch.Tensor | None, + cmp_block_table: torch.Tensor | None, + cu_seqlens_q: torch.Tensor | None, + cu_seqlens_ori_kv: torch.Tensor | None, + cu_seqlens_cmp_kv: torch.Tensor | None, + seqused_q: torch.Tensor | None, + seqused_kv: torch.Tensor | None, + sinks: torch.Tensor | None, + metadata: torch.Tensor | None, + softmax_scale: float, + cmp_ratio: int, + ori_mask_mode: int, + cmp_mask_mode: int, + ori_win_left: int, + ori_win_right: int, + layout_q: str, + layout_kv: str, + return_softmax_lse: bool, +) -> tuple[torch.Tensor, torch.Tensor]: + """Two-stage sparse attention over original and compressed KV.""" + return _SPARSE_ATTN_SHAREDKV.get_prepared().function( + q, + ori_kv, + cmp_kv, + ori_sparse_indices, + cmp_sparse_indices, + ori_block_table, + cmp_block_table, + cu_seqlens_q, + cu_seqlens_ori_kv, + cu_seqlens_cmp_kv, + seqused_q, + seqused_kv, + sinks, + metadata, + softmax_scale, + cmp_ratio, + ori_mask_mode, + cmp_mask_mode, + ori_win_left, + ori_win_right, + layout_q, + layout_kv, + return_softmax_lse, + ) + + +def sparse_attn_sharedkv_metadata( + num_heads_q: int, + num_heads_kv: int, + head_dim: int, + cu_seqlens_q: torch.Tensor | None, + cu_seqlens_ori_kv: torch.Tensor | None, + cu_seqlens_cmp_kv: torch.Tensor | None, + seqused_q: torch.Tensor | None, + seqused_kv: torch.Tensor | None, + batch_size: int, + max_seqlen_q: int, + max_seqlen_kv: int, + ori_topk: int, + cmp_topk: int, + cmp_ratio: int, + ori_mask_mode: int, + cmp_mask_mode: int, + ori_win_left: int, + ori_win_right: int, + layout_q: str, + layout_kv: str, + has_ori_kv: bool, + has_cmp_kv: bool, +) -> torch.Tensor: + """Build the AICPU tiling metadata for :func:`sparse_attn_sharedkv`.""" + return _SPARSE_ATTN_SHAREDKV_METADATA.get_prepared().function( + num_heads_q, + num_heads_kv, + head_dim, + cu_seqlens_q, + cu_seqlens_ori_kv, + cu_seqlens_cmp_kv, + seqused_q, + seqused_kv, + batch_size, + max_seqlen_q, + max_seqlen_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, + ) + + +def sparse_flash_attention_lse( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + sparse_indices: torch.Tensor, + block_table: torch.Tensor | None, + actual_seq_lengths_query: torch.Tensor | None, + actual_seq_lengths_kv: torch.Tensor | None, + query_rope: torch.Tensor | None, + key_rope: torch.Tensor | None, + scale_value: float, + sparse_block_size: int, + layout_query: str, + layout_kv: str, + sparse_mode: int, + pre_tokens: int = 9223372036854775807, + next_tokens: int = 9223372036854775807, + attention_mode: int = 2, + return_softmax_lse: bool = False, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Run the packaged RoPE sparse attention and return optional softmax statistics.""" + return _SPARSE_FLASH_ATTENTION_LSE.get_prepared().function( + query, + key, + value, + sparse_indices, + block_table, + actual_seq_lengths_query, + actual_seq_lengths_kv, + query_rope, + key_rope, + scale_value, + sparse_block_size, + layout_query, + layout_kv, + sparse_mode, + pre_tokens, + next_tokens, + attention_mode, + return_softmax_lse, + ) + + +def sparse_flash_attention_lse_out( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + sparse_indices: torch.Tensor, + block_table: torch.Tensor | None, + actual_seq_lengths_query: torch.Tensor | None, + actual_seq_lengths_kv: torch.Tensor | None, + query_rope: torch.Tensor | None, + key_rope: torch.Tensor | None, + scale_value: float, + sparse_block_size: int, + layout_query: str, + layout_kv: str, + sparse_mode: int, + output: torch.Tensor, +) -> torch.Tensor: + """Run sparse attention directly into a caller-owned output buffer.""" + return _SPARSE_FLASH_ATTENTION_LSE_OUT.get_prepared().function( + query, + key, + value, + sparse_indices, + block_table, + actual_seq_lengths_query, + actual_seq_lengths_kv, + query_rope, + key_rope, + scale_value, + sparse_block_size, + layout_query, + layout_kv, + sparse_mode, + 9223372036854775807, + 9223372036854775807, + 2, + False, + output, + ) diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/sparse_attention/ascendc.py b/xllm-kernel/python/xllm_kernel/ops/attention/sparse_attention/ascendc.py new file mode 100644 index 0000000000..17a0b20917 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/sparse_attention/ascendc.py @@ -0,0 +1,33 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Bind the compressed KV and sparse attention ACLNN entry points.""" + +import torch + +from xllm_kernel import _ascendc_opp # noqa: F401 +from xllm_kernel.ops.attention.sparse_attention import OPERATIONS +from xllm_kernel.platform import PlatformEnum +from xllm_kernel.registry import register_kernel + +torch.ops.xllm_kernel.prepare_ascendc_sparse_attention() + +for operation, domain in zip( + OPERATIONS, + ( + "Project and compress KV while updating paged compressor state.", + "Attend jointly over original and compressed KV.", + "Device tiling metadata for original and compressed KV.", + "Sparse RoPE attention with optional softmax max and sum.", + "Sparse RoPE attention with a caller-owned output.", + ), + strict=True, +): + name = operation.contract.operation + register_kernel( + name=operation.implementations[0], + platform=PlatformEnum.NPU, + execution_modes=("eager", "aclgraph"), + input_domain=domain, + solution="ascendc", + binding="aclnn", + contract=operation.contract, + )(getattr(torch.ops.xllm_kernel, name).default) diff --git a/xllm-kernel/setup.py b/xllm-kernel/setup.py index 8f3fcdd475..5b8477dac3 100644 --- a/xllm-kernel/setup.py +++ b/xllm-kernel/setup.py @@ -66,8 +66,9 @@ def run(self) -> None: if packaged_header.exists(): header = source / component / "op_host/op_api" / f"aclnn_{component}.h" shutil.copy2(header, packaged_header) - metadata_api = source / "quant_lightning_indexer_metadata" / "op_api" - shutil.copy2(metadata_api / "aclnn_quant_lightning_indexer_metadata.h", headers) + for component in ("quant_lightning_indexer_metadata", "sparse_attn_sharedkv_metadata"): + metadata_header = source / component / "op_api" / f"aclnn_{component}.h" + shutil.copy2(metadata_header, headers) chunk_gdn = source / "mega_chunk_gdn/op_host/op_api" shutil.copy2(chunk_gdn / "aclnn_mega_chunk_gdn.h", headers / "aclnn_xllm_kernel_mega_chunk_gdn.h") recurrent_header = headers / "aclnn_xllm_kernel_recurrent_gated_delta_rule.h" @@ -107,6 +108,7 @@ def get_outputs(self) -> list[str]: "csrc/npu/normalization.cpp", "csrc/npu/quant_matmul.cpp", "csrc/npu/reshape_paged_cache.cpp", + "csrc/npu/sparse_attention.cpp", "csrc/npu/sparse_indexing.cpp", ], include_dirs=[ diff --git a/xllm-kernel/test/npu/conftest.py b/xllm-kernel/test/npu/conftest.py index 36dbe7d6ae..e9d95353a7 100644 --- a/xllm-kernel/test/npu/conftest.py +++ b/xllm-kernel/test/npu/conftest.py @@ -43,6 +43,11 @@ def _prepare_kernels() -> None: "causal_conv1d_update_v2", "matmul_ein_sum", "matmul_ein_sum_out", + "compressor", + "sparse_attn_sharedkv", + "sparse_attn_sharedkv_metadata", + "sparse_flash_attention_lse", + "sparse_flash_attention_lse_out", "quant_lightning_indexer", "quant_lightning_indexer_metadata", "scatter_nd_update", diff --git a/xllm-kernel/test/npu/test_sparse_attention_npu.py b/xllm-kernel/test/npu/test_sparse_attention_npu.py new file mode 100644 index 0000000000..52f36fd612 --- /dev/null +++ b/xllm-kernel/test/npu/test_sparse_attention_npu.py @@ -0,0 +1,225 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Numerical and replay checks for the packaged DSA and SFA operators.""" + +import pytest +import torch +from xllm_kernel.ops import ( + compressor, + sparse_attn_sharedkv, + sparse_attn_sharedkv_metadata, + sparse_flash_attention_lse, + sparse_flash_attention_lse_out, +) + + +@pytest.mark.parametrize("graph_mode", [False, True], ids=["eager", "graph"]) +@torch.inference_mode() +def test_compressor_pools_kv_and_writes_tail_state(graph_mode: bool) -> None: + generator = torch.Generator().manual_seed(781) + dtype = torch.float16 + ratio, head_dim, hidden_dim, rope_dim = 128, 512, 1024, 64 + x = (torch.randn(1, ratio + 2, hidden_dim, generator=generator) * 0.1).to(dtype) + x_npu = x.npu() + wkv = (torch.randn(head_dim, hidden_dim, generator=generator) * 0.05).to(dtype) + wgate = torch.zeros_like(wkv) + kv_state = torch.zeros(3, ratio, head_dim, device="npu") + score_state = torch.zeros_like(kv_state) + table = torch.tensor([[1, 2]], dtype=torch.int32).npu() + ape = torch.arange(ratio, dtype=torch.float32)[:, None].expand(-1, head_dim).contiguous() / ratio + cos = torch.zeros(1, 2, rope_dim, dtype=dtype) + sin = torch.ones_like(cos) + args = ( + x_npu, + wkv.npu(), + wgate.npu(), + kv_state, + score_state, + ape.npu(), + torch.ones(head_dim, dtype=dtype).npu(), + sin.npu(), + cos.npu(), + table, + table, + None, + None, + None, + rope_dim, + ratio, + 1, + 1e-6, + 1, + False, + ) + result = compressor(*args) + torch.npu.synchronize() + if graph_mode: + graph = torch.npu.NPUGraph() + with torch.npu.graph(graph): + result = compressor(*args) + + for scale in (1, -1): + live = x * scale + x_npu.copy_(live) + if graph_mode: + graph.replay() + else: + result = compressor(*args) + projection = live.float() @ wkv.float().T + pooled = (projection[0, :ratio] * ape.softmax(dim=0)).sum(dim=0) + norm = pooled * (pooled.square().mean() + 1e-6).rsqrt() + rope_tail = norm[-rope_dim:] + half = rope_dim // 2 + expected = torch.cat((norm[:-rope_dim], -rope_tail[half:], rope_tail[:half])) + torch.testing.assert_close(result[0].cpu()[0, 0].float(), expected, atol=0.025, rtol=0.025) + assert all(buffer.numel() == 0 for buffer in result[1:]) + torch.testing.assert_close(kv_state.cpu()[2, :2], projection[0, ratio:], atol=0.002, rtol=0.02) + torch.testing.assert_close(score_state.cpu()[2, :2], ape[:2], atol=1e-5, rtol=0) + assert torch.count_nonzero(kv_state.cpu()[0]).item() == 0 + + +@pytest.mark.parametrize("ratio", [1, 128], ids=["swa", "compressed"]) +@torch.inference_mode() +def test_shared_kv_metadata_replays_with_live_lengths_and_pages(ratio: int) -> None: + dtype = torch.float16 + heads, head_dim, page_size = 64, 512, 128 + q = torch.zeros(1, 1, heads, head_dim, dtype=dtype).npu() + ori = torch.arange(3, dtype=dtype)[:, None, None, None].expand(3, page_size, 1, head_dim).contiguous() + cmp = torch.full((1, page_size, 1, head_dim), 8, dtype=dtype) + has_cmp = ratio > 1 + ori_npu = ori.npu() + cmp_npu = cmp.npu() if has_cmp else None + ori_table = torch.tensor([[2]], dtype=torch.int32).npu() + cmp_table = torch.zeros_like(ori_table) if has_cmp else None + seq = torch.tensor([page_size], dtype=torch.int32).npu() + sinks = torch.zeros(heads, dtype=torch.float32).npu() + scale = head_dim**-0.5 + + def attend() -> torch.Tensor: + metadata = sparse_attn_sharedkv_metadata( + heads, + 1, + head_dim, + None, + None, + None, + None, + seq, + 1, + 1, + page_size, + 0, + 0, + ratio, + 4, + 3, + page_size - 1, + 0, + "BSND", + "PA_ND", + True, + has_cmp, + ) + assert metadata.shape == (1024,) + assert metadata.dtype == torch.int32 + output, _ = sparse_attn_sharedkv( + q, + ori_npu, + cmp_npu, + None, + None, + ori_table, + cmp_table, + None, + None, + None, + None, + seq, + sinks, + metadata, + scale, + ratio, + 4, + 3, + page_size - 1, + 0, + "BSND", + "PA_ND", + False, + ) + return output + + eager = attend() + expected = (2 * page_size + (8 if has_cmp else 0)) / (page_size + (2 if has_cmp else 1)) + torch.testing.assert_close(eager.cpu(), torch.full(q.shape, expected, dtype=dtype), atol=0.003, rtol=0) + torch.npu.synchronize() + graph = torch.npu.NPUGraph() + with torch.npu.graph(graph): + output = attend() + + for page, length in ((1, page_size), (2, 64)): + ori_table.fill_(page) + seq.fill_(length) + graph.replay() + compressed_tokens = length // ratio if has_cmp else 0 + expected = (page * length + 8 * compressed_tokens) / (length + compressed_tokens + 1) + torch.testing.assert_close(output.cpu(), torch.full(q.shape, expected, dtype=dtype), atol=0.003, rtol=0) + + +@torch.inference_mode() +def test_sparse_attention_lse_matches_reference_and_replays_to_output_buffer() -> None: + generator = torch.Generator().manual_seed(2460) + dtype = torch.bfloat16 + page_size, heads, head_dim, rope_dim = 128, 8, 512, 64 + q = (torch.randn(1, heads, head_dim, generator=generator) * 0.2).to(dtype) + k = (torch.randn(1, page_size, 1, head_dim, generator=generator) * 0.2).to(dtype) + q_rope = (torch.randn(1, heads, rope_dim, generator=generator) * 0.4).to(dtype) + k_rope = (torch.randn(1, page_size, 1, rope_dim, generator=generator) * 0.4).to(dtype) + k_npu = k.npu() + indices = torch.zeros((1, 1, 16), dtype=torch.int32).npu() + table = torch.zeros((1, 1), dtype=torch.int32).npu() + q_seq = torch.tensor([1], dtype=torch.int32).npu() + kv_seq = torch.tensor([page_size], dtype=torch.int32).npu() + scale = head_dim**-0.5 + args = ( + q.npu(), + k_npu, + k_npu, + indices, + table, + q_seq, + kv_seq, + q_rope.npu(), + k_rope.npu(), + scale, + 1, + "TND", + "PA_BSND", + 3, + ) + + def reference(selected: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + keys = k[0, selected, 0].float() + keys_rope = k_rope[0, selected, 0].float() + score = (q[0].float() @ keys.T + q_rope[0].float() @ keys_rope.T) * scale + maximum = score.max(dim=-1).values + total = (score - maximum[:, None]).exp().sum(dim=-1) + output = (score.softmax(dim=-1) @ keys).unsqueeze(0).to(dtype) + return output, maximum.view(1, 1, heads), total.view(1, 1, heads) + + selected = torch.arange(0, 16, dtype=torch.int32) + indices.copy_(selected.view_as(indices)) + actual = sparse_flash_attention_lse(*args, return_softmax_lse=True) + for result, expected in zip(actual, reference(selected.long()), strict=True): + torch.testing.assert_close(result.cpu(), expected, atol=0.008, rtol=0.008) + + output = torch.empty_like(args[0]) + assert sparse_flash_attention_lse_out(*args, output) is output + torch.npu.synchronize() + graph = torch.npu.NPUGraph() + with torch.npu.graph(graph): + assert sparse_flash_attention_lse_out(*args, output) is output + for start in (8, 32, 64): + selected = torch.arange(start, start + 16, dtype=torch.int32) + indices.copy_(selected.view_as(indices)) + graph.replay() + torch.testing.assert_close(output.cpu(), reference(selected.long())[0], atol=0.008, rtol=0.008) diff --git a/xllm-kernel/test/test_operator_preparation.py b/xllm-kernel/test/test_operator_preparation.py index 8677fa1587..ad61410733 100644 --- a/xllm-kernel/test/test_operator_preparation.py +++ b/xllm-kernel/test/test_operator_preparation.py @@ -77,6 +77,11 @@ def find_spec(self, fullname: str, path: Any = None, target: Any = None) -> None ("mega_gdn_decode", ("conv_state", "ssm_state"), False), ("mega_gdn_mtp_decode", ("conv_state", "ssm_state"), False), ("mega_gdn_mtp_decode_varlen", ("conv_state", "ssm_state", "out"), False), + ("compressor", ("kv_state", "score_state"), False), + ("sparse_attn_sharedkv", (), False), + ("sparse_attn_sharedkv_metadata", (), False), + ("sparse_flash_attention_lse", (), False), + ("sparse_flash_attention_lse_out", ("attention_output",), True), ("quant_lightning_indexer", (), False), ("quant_lightning_indexer_metadata", (), False), ("scatter_nd_update", ("value",), False), diff --git a/xllm/python/__init__.py b/xllm/python/__init__.py index 82f9df0868..ed82f13fd8 100644 --- a/xllm/python/__init__.py +++ b/xllm/python/__init__.py @@ -77,6 +77,11 @@ def initialize_runtime() -> None: "l2_norm", "matmul_ein_sum", "matmul_ein_sum_out", + "compressor", + "sparse_attn_sharedkv", + "sparse_attn_sharedkv_metadata", + "sparse_flash_attention_lse", + "sparse_flash_attention_lse_out", "quant_lightning_indexer", "quant_lightning_indexer_metadata", "scatter_nd_update", diff --git a/xllm/python/kernels_npu/dsa.py b/xllm/python/kernels_npu/dsa.py index 781c952b4b..1e19621d03 100644 --- a/xllm/python/kernels_npu/dsa.py +++ b/xllm/python/kernels_npu/dsa.py @@ -12,179 +12,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""NPU DeepSeek-V4 DSA kernels. - -These wrap the AscendC operators registered as ``torch.ops.xllm_ops.*`` by -``core/kernels/npu/npu_ops_library.cpp``. They drive the two-stage sparse -attention (original + compressed KV), the KV compressor, and the quantized -lightning indexer. -""" - -from __future__ import annotations - -import torch - - -def compressor( - x: torch.Tensor, - wkv: torch.Tensor, - wgate: torch.Tensor, - kv_state: torch.Tensor, - score_state: torch.Tensor, - ape: torch.Tensor, - norm_weight: torch.Tensor, - rope_sin: torch.Tensor, - rope_cos: torch.Tensor, - kv_block_table: torch.Tensor | None, - score_block_table: torch.Tensor | None, - cu_seqlens: torch.Tensor | None, - seqused: torch.Tensor | None, - start_pos: torch.Tensor | None, - rope_head_dim: int, - cmp_ratio: int, - coff: int, - norm_eps: float, - rotary_mode: int, - enable_grad: bool, -) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: - """Pool KV along the token axis by ``cmp_ratio`` (NSA-style compressor). - - ``kv_state`` and ``score_state`` are updated in place. - - Returns ``(cmp_kv, wkv_proj, softmax_res, norm_x, norm_rstd)``; only - ``cmp_kv`` is consumed by the DSA path. - """ - # C++ moves DSA metadata to the active device before dispatch. Keep this - # adapter deterministic; experimental clone/noalias paths do not belong in - # the public binding. - kv_block_table = kv_block_table.to(x.device) if kv_block_table is not None else None - score_block_table = score_block_table.to(x.device) if score_block_table is not None else None - cu_seqlens = cu_seqlens.to(x.device) if cu_seqlens is not None else None - seqused = seqused.to(x.device) if seqused is not None else None - start_pos = start_pos.to(x.device) if start_pos is not None else None - return torch.ops.xllm_ops.compressor( - x, - wkv, - wgate, - kv_state, - score_state, - ape, - norm_weight, - rope_sin, - rope_cos, - kv_block_table, - score_block_table, - cu_seqlens, - seqused, - start_pos, - rope_head_dim, - cmp_ratio, - coff, - norm_eps, - rotary_mode, - enable_grad, - ) - - -def sparse_attn_sharedkv( - q: torch.Tensor, - ori_kv: torch.Tensor | None, - cmp_kv: torch.Tensor | None, - ori_sparse_indices: torch.Tensor | None, - cmp_sparse_indices: torch.Tensor | None, - ori_block_table: torch.Tensor | None, - cmp_block_table: torch.Tensor | None, - cu_seqlens_q: torch.Tensor | None, - cu_seqlens_ori_kv: torch.Tensor | None, - cu_seqlens_cmp_kv: torch.Tensor | None, - seqused_q: torch.Tensor | None, - seqused_kv: torch.Tensor | None, - sinks: torch.Tensor | None, - metadata: torch.Tensor | None, - softmax_scale: float, - cmp_ratio: int, - ori_mask_mode: int, - cmp_mask_mode: int, - ori_win_left: int, - ori_win_right: int, - layout_q: str, - layout_kv: str, - return_softmax_lse: bool, -) -> tuple[torch.Tensor, torch.Tensor]: - """Two-stage sparse attention over original and compressed KV.""" - return torch.ops.xllm_ops.sparse_attn_sharedkv( - q, - ori_kv, - cmp_kv, - ori_sparse_indices, - cmp_sparse_indices, - ori_block_table, - cmp_block_table, - cu_seqlens_q, - cu_seqlens_ori_kv, - cu_seqlens_cmp_kv, - seqused_q, - seqused_kv, - sinks, - metadata, - softmax_scale, - cmp_ratio, - ori_mask_mode, - cmp_mask_mode, - ori_win_left, - ori_win_right, - layout_q, - layout_kv, - return_softmax_lse, - ) - - -def sparse_attn_sharedkv_metadata( - num_heads_q: int, - num_heads_kv: int, - head_dim: int, - cu_seqlens_q: torch.Tensor | None, - cu_seqlens_ori_kv: torch.Tensor | None, - cu_seqlens_cmp_kv: torch.Tensor | None, - seqused_q: torch.Tensor | None, - seqused_kv: torch.Tensor | None, - batch_size: int, - max_seqlen_q: int, - max_seqlen_kv: int, - ori_topk: int, - cmp_topk: int, - cmp_ratio: int, - ori_mask_mode: int, - cmp_mask_mode: int, - ori_win_left: int, - ori_win_right: int, - layout_q: str, - layout_kv: str, - has_ori_kv: bool, - has_cmp_kv: bool, -) -> torch.Tensor: - """Build the AICPU tiling metadata for :func:`sparse_attn_sharedkv`.""" - return torch.ops.xllm_ops.sparse_attn_sharedkv_metadata( - num_heads_q, - num_heads_kv, - head_dim, - cu_seqlens_q, - cu_seqlens_ori_kv, - cu_seqlens_cmp_kv, - seqused_q, - seqused_kv, - batch_size, - max_seqlen_q, - max_seqlen_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, - ) +"""DeepSeek-V4 compressed KV and shared sparse attention kernels.""" + +from xllm_kernel.ops.attention.sparse_attention import ( + compressor as compressor, +) +from xllm_kernel.ops.attention.sparse_attention import ( + sparse_attn_sharedkv as sparse_attn_sharedkv, +) +from xllm_kernel.ops.attention.sparse_attention import ( + sparse_attn_sharedkv_metadata as sparse_attn_sharedkv_metadata, +) diff --git a/xllm/python/kernels_npu/sparse_attention.py b/xllm/python/kernels_npu/sparse_attention.py index 5c63911bad..33dcd511e4 100644 --- a/xllm/python/kernels_npu/sparse_attention.py +++ b/xllm/python/kernels_npu/sparse_attention.py @@ -17,6 +17,7 @@ from __future__ import annotations import torch +from xllm_kernel.ops.attention import sparse_attention as _sparse_attention from xllm_kernel.ops.attention.dsa.indexer import ( quant_lightning_indexer as quant_lightning_indexer, ) @@ -399,7 +400,7 @@ def sparse_flash_attention_out( if (query_rope is None) != (key_rope is None): raise ValueError("query_rope and key_rope must both be present or absent") if query_rope is not None and layout_query == "TND" and layout_kv == "PA_BSND" and sparse_mode == 3: - return torch.ops.xllm_ops.sparse_flash_attention_lse_out( + return _sparse_attention.sparse_flash_attention_lse_out( query, key, value, @@ -414,10 +415,6 @@ def sparse_flash_attention_out( layout_query, layout_kv, sparse_mode, - 9223372036854775807, - 9223372036854775807, - 2, - False, output, ) # Keep the allocating entry's backend selection for unsupported out layouts. @@ -460,7 +457,7 @@ def sparse_flash_attention_lse_out( ) -> torch.Tensor: """Run sparse attention directly into a caller-owned output buffer.""" _validate_sparse_attention_output(query, output) - return torch.ops.xllm_ops.sparse_flash_attention_lse_out( + return _sparse_attention.sparse_flash_attention_lse_out( query, key, value, @@ -475,10 +472,6 @@ def sparse_flash_attention_lse_out( layout_query, layout_kv, sparse_mode, - 9223372036854775807, - 9223372036854775807, - 2, - False, output, ) @@ -514,7 +507,7 @@ def sparse_flash_attention_lse( if (query_rope is None) != (key_rope is None): raise ValueError("query_rope and key_rope must both be present or absent") if query_rope is not None: - return torch.ops.xllm_ops.sparse_flash_attention_lse( + return _sparse_attention.sparse_flash_attention_lse( query, key, value, From 5839379da9c22a620495f9e5b5709b7b2cb26e2c Mon Sep 17 00:00:00 2001 From: Xu Zhang Date: Fri, 20 Nov 2026 20:59:04 +0800 Subject: [PATCH 2/3] test: remove sparse attention dispatch tests. --- .../python/test_sparse_attention_dispatch.py | 155 ------------------ 1 file changed, 155 deletions(-) delete mode 100644 tests/python/test_sparse_attention_dispatch.py diff --git a/tests/python/test_sparse_attention_dispatch.py b/tests/python/test_sparse_attention_dispatch.py deleted file mode 100644 index 16b3c5f5d9..0000000000 --- a/tests/python/test_sparse_attention_dispatch.py +++ /dev/null @@ -1,155 +0,0 @@ -# Copyright 2026 The xLLM Authors. -# -# 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. - -"""SFA interface selection and caller-owned output contracts.""" - -from unittest.mock import MagicMock - -import pytest -import torch -from xllm_kernel.ops.attention import sparse_attention as package_attention - -from xllm.python.kernels_npu import sparse_attention - - -@pytest.mark.parametrize("rope", [False, True]) -@pytest.mark.parametrize("entry", ["allocate", "out", "lse"]) -def test_sparse_attention_preserves_backend_and_output_contract( - monkeypatch: pytest.MonkeyPatch, rope: bool, entry: str -) -> None: - query = torch.zeros(2, 4, 8) - key = torch.zeros(1, 16, 1, 8) - indices = torch.zeros(2, 1, 16, dtype=torch.int32) - block_table = torch.zeros(1, 1, dtype=torch.int32) - lengths = torch.tensor([2], dtype=torch.int32) - query_rope = torch.zeros(2, 4, 4) if rope else None - key_rope = torch.zeros(1, 16, 1, 4) if rope else None - expected = (torch.ones_like(query), torch.ones(1, 2, 4), torch.full((1, 2, 4), 2.0)) - custom = MagicMock(return_value=expected) - native = MagicMock(return_value=expected) - - def write_out(*args: object) -> torch.Tensor: - output = args[-1] - output.copy_(expected[0]) - return output - - custom_out = MagicMock(side_effect=write_out) - monkeypatch.setattr(package_attention, "sparse_flash_attention_lse", custom, raising=False) - monkeypatch.setattr(torch.ops.npu, "npu_sparse_flash_attention", native, raising=False) - monkeypatch.setattr(package_attention, "sparse_flash_attention_lse_out", custom_out, raising=False) - args = ( - query, - key, - key, - indices, - block_table, - lengths, - lengths, - query_rope, - key_rope, - 0.125, - 1, - "TND", - "PA_BSND", - 3, - ) - if entry == "lse": - result = sparse_attention.sparse_flash_attention_lse( - *args, pre_tokens=31, next_tokens=7, attention_mode=2, return_softmax_lse=True - ) - assert all(actual is wanted for actual, wanted in zip(result, expected)) - tail = (31, 7, 2, True) - elif entry == "out": - buffer = torch.zeros_like(query) - result = sparse_attention.sparse_flash_attention_out(*args, output=buffer) - assert result is buffer - torch.testing.assert_close(result, expected[0]) - tail = (9223372036854775807, 9223372036854775807, 2, False) - else: - result = sparse_attention.sparse_flash_attention(*args) - assert result is expected[0] - tail = (9223372036854775807, 9223372036854775807, 2, False) - - if entry == "out" and rope: - custom_out.assert_called_once_with(*args, buffer) - custom.assert_not_called() - native.assert_not_called() - elif rope: - custom_out.assert_not_called() - native.assert_not_called() - custom.assert_called_once_with(*args, *tail) - else: - custom_out.assert_not_called() - custom.assert_not_called() - native.assert_called_once_with( - query, - key, - key, - indices, - 0.125, - block_table=block_table, - actual_seq_lengths_query=lengths, - actual_seq_lengths_kv=lengths, - query_rope=None, - key_rope=None, - sparse_block_size=1, - layout_query="TND", - layout_kv="PA_BSND", - sparse_mode=3, - pre_tokens=tail[0], - next_tokens=tail[1], - attention_mode=tail[2], - return_softmax_lse=tail[3], - ) - - -@pytest.mark.parametrize("query_rope", [None, torch.zeros(1)]) -@pytest.mark.parametrize("entry", ["allocate", "out", "lse"]) -def test_partial_rope_pair_is_rejected_before_operator_execution( - monkeypatch: pytest.MonkeyPatch, query_rope: torch.Tensor | None, entry: str -) -> None: - custom = MagicMock() - native = MagicMock() - custom_out = MagicMock() - monkeypatch.setattr(package_attention, "sparse_flash_attention_lse", custom, raising=False) - monkeypatch.setattr(torch.ops.npu, "npu_sparse_flash_attention", native, raising=False) - monkeypatch.setattr(package_attention, "sparse_flash_attention_lse_out", custom_out, raising=False) - tensor = torch.zeros(1) - key_rope = tensor if query_rope is None else None - args = ( - tensor, - tensor, - tensor, - tensor, - None, - None, - None, - query_rope, - key_rope, - 0.125, - 1, - "TND", - "PA_BSND", - 3, - ) - with pytest.raises(ValueError, match="both be present or absent"): - if entry == "out": - sparse_attention.sparse_flash_attention_out(*args, output=torch.empty_like(tensor)) - elif entry == "lse": - sparse_attention.sparse_flash_attention_lse(*args) - else: - sparse_attention.sparse_flash_attention(*args) - custom.assert_not_called() - native.assert_not_called() - custom_out.assert_not_called() From 92dbf5fbe6e9bd93587629dc5cce45e0567e2d38 Mon Sep 17 00:00:00 2001 From: Xu Zhang Date: Fri, 20 Nov 2026 21:06:02 +0800 Subject: [PATCH 3/3] refactor: separate DSA and DeepSeek V4 operators. --- xllm-kernel/python/xllm_kernel/catalog.py | 3 +- .../python/xllm_kernel/ops/__init__.py | 13 +- .../xllm_kernel/ops/attention/dsa/__init__.py | 116 +++++++++++++++++- .../xllm_kernel/ops/attention/dsa/ascendc.py | 30 +++++ .../{sparse_attention => dsv4}/__init__.py | 116 ++---------------- .../{sparse_attention => dsv4}/ascendc.py | 6 +- xllm/python/kernels_npu/dsa.py | 6 +- xllm/python/kernels_npu/sparse_attention.py | 8 +- 8 files changed, 173 insertions(+), 125 deletions(-) create mode 100644 xllm-kernel/python/xllm_kernel/ops/attention/dsa/ascendc.py rename xllm-kernel/python/xllm_kernel/ops/attention/{sparse_attention => dsv4}/__init__.py (60%) rename xllm-kernel/python/xllm_kernel/ops/attention/{sparse_attention => dsv4}/ascendc.py (77%) diff --git a/xllm-kernel/python/xllm_kernel/catalog.py b/xllm-kernel/python/xllm_kernel/catalog.py index 3fc4744ff8..fa43f1ff3a 100644 --- a/xllm-kernel/python/xllm_kernel/catalog.py +++ b/xllm-kernel/python/xllm_kernel/catalog.py @@ -67,7 +67,8 @@ def get_prepared(self) -> PreparedKernel: "xllm_kernel.ops.attention.kda", "xllm_kernel.ops.attention.mla", "xllm_kernel.ops.attention.dsa.indexer", - "xllm_kernel.ops.attention.sparse_attention", + "xllm_kernel.ops.attention.dsv4", + "xllm_kernel.ops.attention.dsa", "xllm_kernel.ops.positional_encoding", ) diff --git a/xllm-kernel/python/xllm_kernel/ops/__init__.py b/xllm-kernel/python/xllm_kernel/ops/__init__.py index 7d7ca977ba..c464dd511b 100644 --- a/xllm-kernel/python/xllm_kernel/ops/__init__.py +++ b/xllm-kernel/python/xllm_kernel/ops/__init__.py @@ -2,11 +2,17 @@ """SDK-free public operator APIs.""" from xllm_kernel.ops.activation import silu_and_mul +from xllm_kernel.ops.attention.dsa import sparse_flash_attention_lse, sparse_flash_attention_lse_out from xllm_kernel.ops.attention.dsa.indexer import ( quant_lightning_indexer, quant_lightning_indexer_metadata, scatter_nd_update, ) +from xllm_kernel.ops.attention.dsv4 import ( + compressor, + sparse_attn_sharedkv, + sparse_attn_sharedkv_metadata, +) from xllm_kernel.ops.attention.fia import get_fused_attention from xllm_kernel.ops.attention.gdn import ( causal_conv1d_qkv_prefill, @@ -24,13 +30,6 @@ ) from xllm_kernel.ops.attention.kda import causal_conv1d, causal_conv1d_update_v2 from xllm_kernel.ops.attention.mla import mla_preprocess_v2 -from xllm_kernel.ops.attention.sparse_attention import ( - compressor, - sparse_attn_sharedkv, - sparse_attn_sharedkv_metadata, - sparse_flash_attention_lse, - sparse_flash_attention_lse_out, -) from xllm_kernel.ops.gemm import matmul_ein_sum, matmul_ein_sum_out, quant_matmul_out from xllm_kernel.ops.hyper_connection import hc_post, hc_pre from xllm_kernel.ops.kv_cache import reshape_paged_cache diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsa/__init__.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsa/__init__.py index 267ff78c5f..6a15408ec3 100644 --- a/xllm-kernel/python/xllm_kernel/ops/attention/dsa/__init__.py +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsa/__init__.py @@ -1,2 +1,116 @@ # Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. -"""DeepSeek sparse attention operators.""" +"""Sparse attention over KV entries selected by the DSA indexer.""" + +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 + +OPERATIONS = tuple( + Operation( + OpContract(name, 1, mutates, aliases, name), + ( + BackendModule( + module="xllm_kernel.ops.attention.dsa.ascendc", + platform=PlatformEnum.NPU, + requires=("torch_npu",), + implementations=(f"npu.ascendc.{name}",), + ), + ), + ) + for name, mutates, aliases in ( + ("sparse_flash_attention_lse", (), False), + ("sparse_flash_attention_lse_out", ("attention_output",), True), + ) +) +_SPARSE_FLASH_ATTENTION_LSE, _SPARSE_FLASH_ATTENTION_LSE_OUT = OPERATIONS + + +def sparse_flash_attention_lse( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + sparse_indices: torch.Tensor, + block_table: torch.Tensor | None, + actual_seq_lengths_query: torch.Tensor | None, + actual_seq_lengths_kv: torch.Tensor | None, + query_rope: torch.Tensor | None, + key_rope: torch.Tensor | None, + scale_value: float, + sparse_block_size: int, + layout_query: str, + layout_kv: str, + sparse_mode: int, + pre_tokens: int = 9223372036854775807, + next_tokens: int = 9223372036854775807, + attention_mode: int = 2, + return_softmax_lse: bool = False, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Run the packaged RoPE sparse attention and return optional softmax statistics.""" + return _SPARSE_FLASH_ATTENTION_LSE.get_prepared().function( + query, + key, + value, + sparse_indices, + block_table, + actual_seq_lengths_query, + actual_seq_lengths_kv, + query_rope, + key_rope, + scale_value, + sparse_block_size, + layout_query, + layout_kv, + sparse_mode, + pre_tokens, + next_tokens, + attention_mode, + return_softmax_lse, + ) + + +def sparse_flash_attention_lse_out( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + sparse_indices: torch.Tensor, + block_table: torch.Tensor | None, + actual_seq_lengths_query: torch.Tensor | None, + actual_seq_lengths_kv: torch.Tensor | None, + query_rope: torch.Tensor | None, + key_rope: torch.Tensor | None, + scale_value: float, + sparse_block_size: int, + layout_query: str, + layout_kv: str, + sparse_mode: int, + output: torch.Tensor, +) -> torch.Tensor: + """Run sparse attention directly into a caller-owned output buffer.""" + return _SPARSE_FLASH_ATTENTION_LSE_OUT.get_prepared().function( + query, + key, + value, + sparse_indices, + block_table, + actual_seq_lengths_query, + actual_seq_lengths_kv, + query_rope, + key_rope, + scale_value, + sparse_block_size, + layout_query, + layout_kv, + sparse_mode, + 9223372036854775807, + 9223372036854775807, + 2, + False, + output, + ) diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/dsa/ascendc.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsa/ascendc.py new file mode 100644 index 0000000000..78dcd81de4 --- /dev/null +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsa/ascendc.py @@ -0,0 +1,30 @@ +# Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. +"""Bind the DSA RoPE sparse attention ACLNN entry points.""" + +import torch + +from xllm_kernel import _ascendc_opp # noqa: F401 +from xllm_kernel.ops.attention.dsa import OPERATIONS +from xllm_kernel.platform import PlatformEnum +from xllm_kernel.registry import register_kernel + +torch.ops.xllm_kernel.prepare_ascendc_sparse_attention() + +for operation, domain in zip( + OPERATIONS, + ( + "Sparse RoPE attention with optional softmax max and sum.", + "Sparse RoPE attention with a caller-owned output.", + ), + strict=True, +): + name = operation.contract.operation + register_kernel( + name=operation.implementations[0], + platform=PlatformEnum.NPU, + execution_modes=("eager", "aclgraph"), + 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/sparse_attention/__init__.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv4/__init__.py similarity index 60% rename from xllm-kernel/python/xllm_kernel/ops/attention/sparse_attention/__init__.py rename to xllm-kernel/python/xllm_kernel/ops/attention/dsv4/__init__.py index 82742d09e2..bb9683b206 100644 --- a/xllm-kernel/python/xllm_kernel/ops/attention/sparse_attention/__init__.py +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv4/__init__.py @@ -1,5 +1,5 @@ # Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. -"""Packaged compressed KV, shared cache attention and RoPE sparse attention.""" +"""DeepSeek V4 KV compression and shared KV attention.""" from __future__ import annotations @@ -14,31 +14,23 @@ OPERATIONS = tuple( Operation( - OpContract(name, 1, mutates, aliases, name), + OpContract(name, 1, mutates, False, name), ( BackendModule( - module="xllm_kernel.ops.attention.sparse_attention.ascendc", + module="xllm_kernel.ops.attention.dsv4.ascendc", platform=PlatformEnum.NPU, requires=("torch_npu",), implementations=(f"npu.ascendc.{name}",), ), ), ) - for name, mutates, aliases in ( - ("compressor", ("kv_state", "score_state"), False), - ("sparse_attn_sharedkv", (), False), - ("sparse_attn_sharedkv_metadata", (), False), - ("sparse_flash_attention_lse", (), False), - ("sparse_flash_attention_lse_out", ("attention_output",), True), + for name, mutates in ( + ("compressor", ("kv_state", "score_state")), + ("sparse_attn_sharedkv", ()), + ("sparse_attn_sharedkv_metadata", ()), ) ) -( - _COMPRESSOR, - _SPARSE_ATTN_SHAREDKV, - _SPARSE_ATTN_SHAREDKV_METADATA, - _SPARSE_FLASH_ATTENTION_LSE, - _SPARSE_FLASH_ATTENTION_LSE_OUT, -) = OPERATIONS +_COMPRESSOR, _SPARSE_ATTN_SHAREDKV, _SPARSE_ATTN_SHAREDKV_METADATA = OPERATIONS def compressor( @@ -67,12 +59,10 @@ def compressor( ``kv_state`` and ``score_state`` are updated in place. - Returns ``(cmp_kv, wkv_proj, softmax_res, norm_x, norm_rstd)``; only - ``cmp_kv`` is consumed by the DSA path. + Returns ``(cmp_kv, wkv_proj, softmax_res, norm_x, norm_rstd)``. The attention + path consumes ``cmp_kv``. """ - # C++ moves DSA metadata to the active device before dispatch. Keep this - # adapter deterministic; experimental clone/noalias paths do not belong in - # the public binding. + # Match the C++ compressor's metadata placement before dispatch. kv_block_table = kv_block_table.to(x.device) if kv_block_table is not None else None score_block_table = score_block_table.to(x.device) if score_block_table is not None else None cu_seqlens = cu_seqlens.to(x.device) if cu_seqlens is not None else None @@ -204,87 +194,3 @@ def sparse_attn_sharedkv_metadata( has_ori_kv, has_cmp_kv, ) - - -def sparse_flash_attention_lse( - query: torch.Tensor, - key: torch.Tensor, - value: torch.Tensor, - sparse_indices: torch.Tensor, - block_table: torch.Tensor | None, - actual_seq_lengths_query: torch.Tensor | None, - actual_seq_lengths_kv: torch.Tensor | None, - query_rope: torch.Tensor | None, - key_rope: torch.Tensor | None, - scale_value: float, - sparse_block_size: int, - layout_query: str, - layout_kv: str, - sparse_mode: int, - pre_tokens: int = 9223372036854775807, - next_tokens: int = 9223372036854775807, - attention_mode: int = 2, - return_softmax_lse: bool = False, -) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - """Run the packaged RoPE sparse attention and return optional softmax statistics.""" - return _SPARSE_FLASH_ATTENTION_LSE.get_prepared().function( - query, - key, - value, - sparse_indices, - block_table, - actual_seq_lengths_query, - actual_seq_lengths_kv, - query_rope, - key_rope, - scale_value, - sparse_block_size, - layout_query, - layout_kv, - sparse_mode, - pre_tokens, - next_tokens, - attention_mode, - return_softmax_lse, - ) - - -def sparse_flash_attention_lse_out( - query: torch.Tensor, - key: torch.Tensor, - value: torch.Tensor, - sparse_indices: torch.Tensor, - block_table: torch.Tensor | None, - actual_seq_lengths_query: torch.Tensor | None, - actual_seq_lengths_kv: torch.Tensor | None, - query_rope: torch.Tensor | None, - key_rope: torch.Tensor | None, - scale_value: float, - sparse_block_size: int, - layout_query: str, - layout_kv: str, - sparse_mode: int, - output: torch.Tensor, -) -> torch.Tensor: - """Run sparse attention directly into a caller-owned output buffer.""" - return _SPARSE_FLASH_ATTENTION_LSE_OUT.get_prepared().function( - query, - key, - value, - sparse_indices, - block_table, - actual_seq_lengths_query, - actual_seq_lengths_kv, - query_rope, - key_rope, - scale_value, - sparse_block_size, - layout_query, - layout_kv, - sparse_mode, - 9223372036854775807, - 9223372036854775807, - 2, - False, - output, - ) diff --git a/xllm-kernel/python/xllm_kernel/ops/attention/sparse_attention/ascendc.py b/xllm-kernel/python/xllm_kernel/ops/attention/dsv4/ascendc.py similarity index 77% rename from xllm-kernel/python/xllm_kernel/ops/attention/sparse_attention/ascendc.py rename to xllm-kernel/python/xllm_kernel/ops/attention/dsv4/ascendc.py index 17a0b20917..88867e4fdc 100644 --- a/xllm-kernel/python/xllm_kernel/ops/attention/sparse_attention/ascendc.py +++ b/xllm-kernel/python/xllm_kernel/ops/attention/dsv4/ascendc.py @@ -1,10 +1,10 @@ # Copyright 2026 The xLLM Authors. Licensed under Apache-2.0. -"""Bind the compressed KV and sparse attention ACLNN entry points.""" +"""Bind the DeepSeek V4 compression and shared KV ACLNN entry points.""" import torch from xllm_kernel import _ascendc_opp # noqa: F401 -from xllm_kernel.ops.attention.sparse_attention import OPERATIONS +from xllm_kernel.ops.attention.dsv4 import OPERATIONS from xllm_kernel.platform import PlatformEnum from xllm_kernel.registry import register_kernel @@ -16,8 +16,6 @@ "Project and compress KV while updating paged compressor state.", "Attend jointly over original and compressed KV.", "Device tiling metadata for original and compressed KV.", - "Sparse RoPE attention with optional softmax max and sum.", - "Sparse RoPE attention with a caller-owned output.", ), strict=True, ): diff --git a/xllm/python/kernels_npu/dsa.py b/xllm/python/kernels_npu/dsa.py index 1e19621d03..0475b44e3c 100644 --- a/xllm/python/kernels_npu/dsa.py +++ b/xllm/python/kernels_npu/dsa.py @@ -14,12 +14,12 @@ """DeepSeek-V4 compressed KV and shared sparse attention kernels.""" -from xllm_kernel.ops.attention.sparse_attention import ( +from xllm_kernel.ops.attention.dsv4 import ( compressor as compressor, ) -from xllm_kernel.ops.attention.sparse_attention import ( +from xllm_kernel.ops.attention.dsv4 import ( sparse_attn_sharedkv as sparse_attn_sharedkv, ) -from xllm_kernel.ops.attention.sparse_attention import ( +from xllm_kernel.ops.attention.dsv4 import ( sparse_attn_sharedkv_metadata as sparse_attn_sharedkv_metadata, ) diff --git a/xllm/python/kernels_npu/sparse_attention.py b/xllm/python/kernels_npu/sparse_attention.py index 33dcd511e4..11cd441d49 100644 --- a/xllm/python/kernels_npu/sparse_attention.py +++ b/xllm/python/kernels_npu/sparse_attention.py @@ -17,7 +17,7 @@ from __future__ import annotations import torch -from xllm_kernel.ops.attention import sparse_attention as _sparse_attention +from xllm_kernel.ops.attention import dsa as _dsa_attention from xllm_kernel.ops.attention.dsa.indexer import ( quant_lightning_indexer as quant_lightning_indexer, ) @@ -400,7 +400,7 @@ def sparse_flash_attention_out( if (query_rope is None) != (key_rope is None): raise ValueError("query_rope and key_rope must both be present or absent") if query_rope is not None and layout_query == "TND" and layout_kv == "PA_BSND" and sparse_mode == 3: - return _sparse_attention.sparse_flash_attention_lse_out( + return _dsa_attention.sparse_flash_attention_lse_out( query, key, value, @@ -457,7 +457,7 @@ def sparse_flash_attention_lse_out( ) -> torch.Tensor: """Run sparse attention directly into a caller-owned output buffer.""" _validate_sparse_attention_output(query, output) - return _sparse_attention.sparse_flash_attention_lse_out( + return _dsa_attention.sparse_flash_attention_lse_out( query, key, value, @@ -507,7 +507,7 @@ def sparse_flash_attention_lse( if (query_rope is None) != (key_rope is None): raise ValueError("query_rope and key_rope must both be present or absent") if query_rope is not None: - return _sparse_attention.sparse_flash_attention_lse( + return _dsa_attention.sparse_flash_attention_lse( query, key, value,